-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
277 lines (247 loc) · 8.37 KB
/
Copy pathscript.js
File metadata and controls
277 lines (247 loc) · 8.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
(function () {
'use strict';
// Public CORS proxy. allorigins is the most boring/stable free option;
// expects the target URL as a query parameter.
const cors_proxy_url = "https://api.allorigins.win/raw?url=";
var _scalarInstance = null;
// State lives in the query string (?url=...) so Scalar can keep using
// location.hash for its own deep-link navigation.
function getParams() {
return new URLSearchParams(window.location.search);
}
function setParams(params) {
var qs = params.toString();
var newUrl = window.location.pathname + (qs ? '?' + qs : '') + window.location.hash;
history.replaceState(null, '', newUrl);
}
function getParam(key) {
return getParams().get(key);
}
function syncToggleLabel() {
var btn = document.getElementById('toggle-form');
if (!btn) return;
btn.textContent = document.body.classList.contains('from_url') ? 'Show form' : 'Hide form';
}
function setStatus(msg, isError) {
var el = document.getElementById('status');
el.textContent = msg || '';
el.classList.toggle('error', !!isError);
}
function renderScalar(config) {
var app = document.getElementById('app');
if (_scalarInstance && typeof _scalarInstance.destroy === 'function') {
try { _scalarInstance.destroy(); } catch (e) { /* ignore */ }
}
app.innerHTML = '';
var fullConfig = Object.assign({
darkMode: false,
forceDarkModeState: 'light'
}, config);
_scalarInstance = Scalar.createApiReference('#app', fullConfig);
setStatus('');
document.body.classList.add('from_url');
syncToggleLabel();
showShareLink();
}
function showShareLink() {
var link = document.getElementById('share-link');
if (link) {
link.hidden = false;
link.href = window.location.href;
}
}
function hideShareLink() {
var link = document.getElementById('share-link');
if (link) link.hidden = true;
}
function createShareUrl(url, cors, file) {
var params = getParams();
if (url) params.set('url', url); else params.delete('url');
if (file) params.set('file', file); else params.delete('file');
if (cors) params.set('cors', 'true'); else params.delete('cors');
setParams(params);
showShareLink();
}
// Browsers cap the URL length around 32 KB; base64 of the file is the dominant
// component. ~24000 base64 chars ≈ 18 KB raw, which keeps the share URL safe.
const MAX_SHAREABLE_BASE64 = 24000;
function loadSelectedFile() {
var input = document.getElementById('myfile');
if (!input.files || !input.files[0]) {
setStatus('No file selected.', true);
return;
}
var reader = new FileReader();
reader.onload = function () {
const result = reader.result.split('base64,')[1];
if (result.length > MAX_SHAREABLE_BASE64) {
// Too big to round-trip via the URL; render but skip the share link.
hideShareLink();
setStatus('File is too large to share via URL; rendering locally only.');
} else {
createShareUrl(null, false, result);
}
loadSpecFromBase64(result);
};
reader.readAsDataURL(input.files[0]);
}
function loadSpecFromBase64(input) {
const bytes = Uint8Array.from(atob(input), c => c.charCodeAt(0));
loadSpecText(new TextDecoder('utf-8').decode(bytes));
}
function loadSpecText(text) {
if (!text) return;
renderScalar({ content: text });
}
// Public CORS proxies sometimes return short plaintext error blobs
// (e.g. "error code: 522") with a 200 status. Reject those before
// handing them to Scalar, which would fail with "Invalid YAML object".
function looksLikeSpec(text) {
if (!text) return false;
var trimmed = text.replace(/^/, '').trim();
if (!trimmed) return false;
if (/^error code:\s*\d+/i.test(trimmed)) return false;
if (trimmed.length < 16) return false;
return true;
}
function fetchText(url) {
return fetch(url).then(function(response) {
if (!response.ok) {
var err = new Error('HTTP ' + response.status);
err.httpStatus = response.status;
throw err;
}
return response.text();
});
}
// Only network/CORS failures are worth retrying via the proxy.
// HTTP error responses (404, 500, …) reached the origin successfully
// and represent a definitive answer.
function isLikelyCorsError(err) {
return !err.httpStatus;
}
function fetchViaProxy(url) {
return fetchText(cors_proxy_url + encodeURIComponent(url))
.then(function(text) {
if (!looksLikeSpec(text)) {
var preview = text ? text.trim().slice(0, 80) : '(empty)';
throw new Error('CORS proxy returned invalid response: ' + preview);
}
return text;
});
}
// Update checkbox + URL params + share link to reflect what was actually used.
function applyUrlState(url, cors) {
document.getElementById('cors-enabled').checked = !!cors;
var params = getParams();
params.set('url', url);
params.delete('file');
if (cors) params.set('cors', 'true'); else params.delete('cors');
setParams(params);
showShareLink();
}
function loadSpecFromUrl(url, cors) {
if (!url) return;
if (cors) {
setStatus('Fetching ' + url + ' via CORS proxy...');
fetchViaProxy(url)
.then(function(text) {
applyUrlState(url, true);
loadSpecText(text);
})
.catch(function(err) {
console.error('Failed to fetch OpenAPI spec via proxy:', err);
setStatus('Failed to fetch via proxy: ' + err.message, true);
});
return;
}
setStatus('Fetching ' + url + '...');
fetchText(url)
.then(function(text) {
if (!looksLikeSpec(text)) throw new Error('Response did not look like a spec');
applyUrlState(url, false);
loadSpecText(text);
})
.catch(function(err) {
if (!isLikelyCorsError(err)) {
console.error('Failed to fetch OpenAPI spec:', err);
setStatus('Failed to fetch: ' + err.message, true);
return;
}
console.warn('Direct fetch failed, retrying via CORS proxy:', err);
setStatus('Direct fetch failed (' + err.message + '); retrying via CORS proxy...');
fetchViaProxy(url)
.then(function(text) {
applyUrlState(url, true);
loadSpecText(text);
})
.catch(function(err2) {
console.error('Failed to fetch OpenAPI spec:', err2);
setStatus('Failed to fetch: ' + err2.message, true);
});
});
}
function loadOpenApi() {
const p_url = getParam('url');
const p_file = getParam('file');
const p_cors = getParam('cors') === 'true';
if (p_cors) {
document.getElementById('cors-enabled').checked = true;
}
if (p_url) {
document.getElementById('specsource').value = p_url;
loadSpecFromUrl(p_url, p_cors);
showShareLink();
} else if (p_file) {
loadSpecFromBase64(p_file);
showShareLink();
}
}
function bindEventListeners() {
document.getElementById('fetch-form').addEventListener('submit', function(e) {
e.preventDefault();
var corsOn = document.getElementById('cors-enabled').checked;
var url = document.getElementById('specsource').value.trim();
if (!url) return;
loadSpecFromUrl(url, corsOn);
});
document.getElementById('load-file').addEventListener('click', loadSelectedFile);
document.getElementById('toggle-form').addEventListener('click', function() {
document.body.classList.toggle('from_url');
syncToggleLabel();
});
document.getElementById('load-text').addEventListener('click', function() {
var text = document.getElementById('spec-text').value.trim();
if (!text) return;
// Pasted text is too big for the URL; clear any url/file params.
var params = getParams();
params.delete('url');
params.delete('file');
params.delete('cors');
setParams(params);
// Pasted text isn't shareable via URL.
hideShareLink();
loadSpecText(text);
});
document.getElementById('reset').addEventListener('click', function() {
document.getElementById('specsource').value = '';
document.getElementById('spec-text').value = '';
document.getElementById('myfile').value = '';
document.getElementById('cors-enabled').checked = false;
hideShareLink();
document.body.classList.remove('from_url');
syncToggleLabel();
setStatus('');
if (_scalarInstance && typeof _scalarInstance.destroy === 'function') {
try { _scalarInstance.destroy(); } catch (e) { /* ignore */ }
}
_scalarInstance = null;
document.getElementById('app').innerHTML = '';
history.replaceState(null, '', window.location.pathname);
});
}
document.addEventListener('DOMContentLoaded', function() {
bindEventListeners();
loadOpenApi();
});
})();