-
Notifications
You must be signed in to change notification settings - Fork 1
/
mod.ts
343 lines (307 loc) · 10.1 KB
/
mod.ts
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import { DeployClient } from "https://crux.land/5KVm9w";
/*******************************************************************************
* # Welcome to the Deno Deploy IDE
*
* By default, you may press `ctrl+s` to copy the contents of this editor
* to the clipboard in the form of a link you can post to your own Deno Deploy
* project to run your very own custom version of this IDE.
*
* Please find all shortcuts under `defaults.shortcuts` below.
*
* This version of the source code was pushed to https://ide.deno.dev magically
* by deno deploy from a commit to
* https://github.com/ca-d/ide/edit/main/mod.ts .
* If you feel adventurous, try deploying your own instance to Deno Deploy,
* generate a deploy token, then try hitting `ctrl+d` on the running website and
* entering your deploy name and deploy token.
*
* For example, https://deploy-editor.deno.dev was deployed by hitting `ctrl+d`
* on that very website and entering `deploy-editor` under "Deploy name" and my
* secret deploy token under "Deploy token", which I'm not going to tell you ;-P
*
* If you want a boring old file version of the typescript source code from this
* editor in order to upload it to github and deploy from there because you're
* feeling reactionary or can't figure out how to get your own Deno Deploy token
* (hint: https://dash.deno.com/account), go ahead and press `ctrl+shift+s` .
* I dare you.
******************************************************************************/
const defaults = <Record<string, string>> {
theme: "solarized_dark",
mode: "typescript",
url: "https://raw.githubusercontent.com/ca-d/ide/main/mod.ts",
format: "data:text/javascript;base64,",
shortcuts: `{
r: reload,
s: copy,
S: download,
o: open,
d: deploy,
}`,
};
function env(key: string): string {
return Deno.env.get(key) ?? defaults[key] ?? "";
}
async function handleSrc(request: Request) {
if (!request.headers.has("X-Deploy-Token")) {
return new Response(
JSON.stringify({ error: "please set 'X-Deploy-Token' header" }),
{
status: 400,
statusText: "Bad Request",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
},
);
}
const deploy = new DeployClient(request.headers.get("X-Deploy-Token")!);
const projects = await deploy.fetchProjects();
const project = await deploy.fetchProject(
projects.find((p) => p.name === request.headers.get("X-Deploy-Name"))!.id,
);
return new Response(project.productionDeployment.url, {
headers: { "Content-Type": "text/plain; charset=utf-8" },
});
}
async function handlePost(request: Request) {
if (!request.headers.has("content-type")) {
return new Response(
JSON.stringify({ error: "please set 'content-type: text/javascript'" }),
{
status: 400,
statusText: "Bad Request",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
},
);
}
const contentType = request.headers.get("content-type")!;
const responseInit = {
headers: {
"Content-Type": "text/javascript; charset=utf-8",
},
};
if (contentType.includes("text/javascript")) {
const text = await request.text();
const url = env("format") + btoa(text);
const deploy = new DeployClient(
request.headers.get("X-Deploy-Token") ?? "INVALID-TOKEN",
);
const projects = await deploy.fetchProjects();
const project = projects.find(
(p) => p.name === request.headers.get("X-Deploy-Name"),
)!;
console.log(project);
await deploy.deploy(project.id, url, true);
return new Response(text, responseInit);
}
return new Response(
JSON.stringify({ error: "please set 'content-type: text/javascript'" }),
{
status: 400,
statusText: "Bad Request",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
},
);
}
const html = `<html>
<head>
<title>ide.deno.dev</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<script type="module"
src="https://unpkg.com/ace-custom-element@latest/dist/index.min.js">
</script>
<ace-editor theme="ace/theme/${env("theme")}"
mode="ace/mode/${env("mode")}"
value="/* ${env("url")} */"
softTabs wrap>
</ace-editor>
<div class="fabs">
<i class="fa down fa-cloud-download-alt"></i>
<i class="fa copy fa-copy"></i>
<i class="fa save fa-file-download"></i>
<i class="fa open fa-external-link-alt"></i>
<i class="fa up fa-cloud-upload-alt"></i>
</div>
<script type="module">
function downloadString(text, fileType, fileName) {
var blob = new Blob([text], { type: fileType });
var a = document.createElement('a');
a.download = fileName;
a.href = URL.createObjectURL(blob);
a.dataset.downloadurl = [fileType, a.download, a.href].join(':');
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500);
}
var editor = document.querySelector('ace-editor');
async function loadURL(url) {
const res = await fetch(url);
const text = await res.text();
if (text) {
console.log('loading', url);
editor.setAttribute('value', text);
}
}
async function reload() {
const deployURLRes = await fetch('/src', {
method: 'GET',
headers: {
'Content-Type': 'text/plain',
'X-Deploy-Token': localStorage.getItem('deploy-token') || 'INVALID-TOKEN',
'X-Deploy-Name': localStorage.getItem('deploy-name') || 'INVALID-NAME'
}
});
const deployURL = await deployURLRes.text();
const deployRes = await fetch(deployURL);
const deployText = await deployRes.text();
if (deployText) {
console.log('deploy', deployURL);
editor.setAttribute('value', deployText);
}
}
async function initEditor() {
await loadURL('${env("url")}');
try {
const clipURL = await navigator.clipboard.readText();
if (clipURL.substring(0,8).includes(':') && !confirm('Load data from URL ' + clipURL.substring(0,30) + '...?')) return;
await loadURL(clipURL);
} catch (e) {
console.log('no clipboard data');
}
}
initEditor();
function deploy() {
const token = localStorage.getItem('deploy-token') ||
window.prompt('Deploy token');
const name = localStorage.getItem('deploy-name') ||
window.prompt('Deploy name');
localStorage.setItem('deploy-token', token);
localStorage.setItem('deploy-name', name);
fetch('/',
{
method: 'POST',
body: editor.value,
headers: {
'Content-Type': 'text/javascript',
'X-Deploy-Token': token,
'X-Deploy-Name': name,
}
}).then(res => res.text().then(alert));
}
function download() {
downloadString(editor.value, 'text/javascript', window.location.hostname +
'.ts');
}
function copy() {
const title = window.location.hostname + '.ts';
const text = editor.value;
const url = '${env("format")}' + btoa(text);
if (navigator.canShare?.()) {
navigator.share({url, text, title});
} else {
navigator.clipboard.writeText(url);
alert('Copied ' + url.substring(0,30) + '...');
}
}
async function open() {
const url = prompt('Load URL');
if (!url) return;
const res = await fetch(url);
const text = await res.text();
editor.setAttribute('value', text)
}
const saveUI = document.querySelector('.save');
const shareUI = document.querySelector('.copy');
const uploadUI = document.querySelector('.up');
const downloadUI = document.querySelector('.down');
const openUI = document.querySelector('.open');
saveUI.addEventListener('click', download);
shareUI.addEventListener('click', copy);
uploadUI.addEventListener('click', deploy);
downloadUI.addEventListener('click', reload);
openUI.addEventListener('click', open);
const shortcuts = ${env("shortcuts")};
document.addEventListener('keydown',
async e => {
if (e.ctrlKey && shortcuts.hasOwnProperty(e.key)) {
e.stopPropagation();
e.preventDefault();
shortcuts[e.key]();
}
},
true
);
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;600&display=swap');
body {
margin: 0px;
scrollbar-width: thin;
}
ace-editor.ace_editor {
width: 100vw;
height: 100vh;
font-size: 1.7vw;
font-family: 'Fira Code';
}
div.fabs {
display: flex;
flex-direction: column;
position: fixed;
bottom: 16px;
right: 16px;
}
div.fabs > * {
margin: auto;
padding: 8px;
font-size: 64px;
color: var(--base1);
transform: scale(0.9);
}
div.fabs > i:hover {
color: var(--base3);
transform: scale(1.1);
}
:root {
--base03: #002b36;
--base02: #073642;
--base01: #586e75;
--base00: #657b83;
--base0: #839496;
--base1: #93a1a1;
--base2: #eee8d5;
--base3: #fdf6e3;
--yellow: #b58900;
--orange: #cb4b16;
--red: #dc322f;
--magenta: #d33682;
--violet: #6c71c4;
--blue: #268bd2;
--cyan: #2aa198;
--green: #859900;
}
</style>
</body>
</html>`;
addEventListener("fetch", (event: FetchEvent) => {
event.respondWith(
event.request.method === "POST"
? handlePost(event.request)
: new URL(event.request.url).pathname.startsWith("/src")
? handleSrc(event.request)
: new Response(html, {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "text/html; charset=UTF-8",
},
}),
);
});