This repository has been archived by the owner on Nov 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
63 lines (54 loc) · 1.75 KB
/
index.js
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
const tsTranspiledEvent = new Event('tsTranspiled')
const workerFile = window.URL.createObjectURL(
new Blob(
[
`
importScripts('https://unpkg.com/typescript@latest')
const load = sourceUrl => {
const xhr = XMLHttpRequest
? new XMLHttpRequest()
: ActiveXObject
? new ActiveXObject('Microsoft.XMLHTTP')
: null
if (!xhr) return ''
xhr.open('GET', sourceUrl, false)
xhr.overrideMimeType && xhr.overrideMimeType('text/plain')
xhr.send(null)
return xhr.status == 200 ? xhr.responseText : ''
}
onmessage = ({data: [sourceUrl, sourceCode]}) => {
const raw = sourceCode ? sourceCode : load(sourceUrl)
const transpiled = ts.transpile(raw)
postMessage(transpiled)
}
`,
],
{type: 'text/javascript'},
),
)
window.addEventListener('DOMContentLoaded', async () => {
const scripts = document.getElementsByTagName('script')
let pending = []
for (let i = 0; i < scripts.length; i++) {
if (scripts[i].type === 'text/typescript') {
const {src} = scripts[i]
const innerHtml = src ? null : scripts[i].innerHTML
pending.push(
new Promise(resolve => {
const w = new Worker(workerFile)
w.postMessage([src, innerHtml])
w.onmessage = ({data: transpiled}) => {
const newScript = document.createElement('script')
newScript.innerHTML = `window.addEventListener('tsTranspiled', function() {
${transpiled}
})`
scripts[i].replaceWith(newScript)
resolve()
}
}),
)
}
}
await Promise.all(pending)
window.dispatchEvent(tsTranspiledEvent)
})