@threadedstack/wmd-web 0.1.38 → 0.1.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/RELEASE.json +26 -17
- package/guest/arm64/Image +1 -1
- package/guest/arm64/Image-4k +1 -1
- package/guest/arm64/initramfs.cpio.gz +0 -0
- package/package.json +3 -3
- package/src/boot.js +93 -11
- package/src/gowasm/boot-setup.js +175 -0
- package/src/gowasm/make-pins-module.mjs +35 -0
- package/src/gowasm/pins-data.js +162 -0
- package/src/gowasm/setup.js +164 -0
- package/src/gowasm/twin-fetch.js +27 -0
- package/src/host/chan-service.js +25 -1
- package/src/host/ckpt.js +78 -0
- package/src/host/csp-reason.js +64 -0
- package/src/host/ctl.js +30 -8
- package/src/host/edge-go.js +94 -4
- package/src/host/gowasm-guard.js +11 -1
- package/src/host/gowasm-worker.js +90 -35
- package/src/host/pinned-fetch.js +436 -0
- package/wmdpack.wasm +0 -0
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
// Pinned files from sources this library does not trust. A caller names the files it needs (a path, the sha256 and the size each must have) and an
|
|
2
|
+
// ordered list of sources; the first source that gives EVERY file with its pinned sha256 and size wins. A source that fails, stalls, is too big or gives
|
|
3
|
+
// a wrong hash is left for the next, with one reason kept per source. Nothing here throws and nothing waits without a limit.
|
|
4
|
+
//
|
|
5
|
+
// Source kinds (the url texts may hold {name}, {version} and {file}, from the package the pins name; {file} is the name without its scope):
|
|
6
|
+
// { kind: 'tgz', url } an npm registry tarball: the body goes through DecompressionStream('gzip') and a small tar reader that picks the pinned
|
|
7
|
+
// paths ('package/<path>') in one pass, bounded by the tarball bound and the pinned sizes
|
|
8
|
+
// { kind: 'file', base } a plain file at <base>/<path> (a mirror, a CDN of the package, the consumer's own copy)
|
|
9
|
+
// { kind: 'url', url } one file at exactly this url (the table of an embedder that serves its own twin, a data: url in tests)
|
|
10
|
+
// A good fetch is kept in Cache Storage of the page's own origin under a key that holds the sha256, read back after a new hash check; a damaged entry
|
|
11
|
+
// is removed; storage that is missing or throws means a fetch each time. Used by the twin's Worker (X6) and shared with X5.
|
|
12
|
+
const hexOf = buf => [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('')
|
|
13
|
+
const sha256Of = async bytes => hexOf(await crypto.subtle.digest('SHA-256', bytes))
|
|
14
|
+
|
|
15
|
+
export const PINNED_CACHE_NAME = 'wmd-gowasm-twin-v1'
|
|
16
|
+
/** The most one pinned file may be when its pin names no size (file sources only; a tar entry's size must be pinned). */
|
|
17
|
+
export const MAX_PINNED_BYTES = 128 * 1024 * 1024
|
|
18
|
+
/** What a tarball may hold beyond the pinned files (headers, the notices, package.json): added to the pinned sizes for both bounds. */
|
|
19
|
+
export const TAR_OVERHEAD = 8 * 1024 * 1024
|
|
20
|
+
export const PINNED_TOTAL_MS = 300_000
|
|
21
|
+
/**
|
|
22
|
+
* X6 default part 5: ONE bound over all the sources of one fetch, taken from the first byte asked for (ms). Each source keeps its own PINNED_TOTAL_MS, but a source
|
|
23
|
+
* gets no more than what is left of this, and when it has passed no further source is asked. The largest twin (Go 1.27.4) is 52.5 MB: one source's 300 s lets a link
|
|
24
|
+
* of 1.4 Mbit/s bring it in; 600 s lets two sources each be tried to their full bound (a first that trickles and a second that works), and a list of three can no
|
|
25
|
+
* longer take 900 s. Past it the twin is off for the machine and the guest compiles.
|
|
26
|
+
*/
|
|
27
|
+
export const PINNED_ALL_MS = 600_000
|
|
28
|
+
// the longest a source may send no byte (and no response headers) before the next source is asked: a slow link still sends bytes, a dead one does not;
|
|
29
|
+
// measured: the never-answering first source cost the twin 30.2 to 30.3 s (cell c, three browsers), the build itself was not held
|
|
30
|
+
export const PINNED_STALL_MS = 30_000
|
|
31
|
+
const PAX_MAX = 8192
|
|
32
|
+
|
|
33
|
+
const originOf = () => {
|
|
34
|
+
const o = globalThis.location && globalThis.location.origin
|
|
35
|
+
return typeof o === 'string' && /^https?:/.test(o) ? o : 'https://wmd.invalid'
|
|
36
|
+
}
|
|
37
|
+
/** The Cache Storage key of a file: a url of the page's own origin that holds the sha256 (never fetched). */
|
|
38
|
+
export const pinnedCacheKey = sha => `${originOf()}/.wmd-gowasm-twin/${String(sha).toLowerCase()}`
|
|
39
|
+
|
|
40
|
+
const schemeOf = u => {
|
|
41
|
+
try {
|
|
42
|
+
return new URL(u).protocol
|
|
43
|
+
} catch {
|
|
44
|
+
return ''
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const label = u => {
|
|
48
|
+
try {
|
|
49
|
+
const x = new URL(u)
|
|
50
|
+
return x.origin === 'null' ? `${x.protocol}${x.pathname.slice(0, 40)}...` : `${x.origin}${x.pathname}`.slice(0, 160)
|
|
51
|
+
} catch {
|
|
52
|
+
return String(u).slice(0, 80)
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const msg = e => (e && e.message) || String(e)
|
|
56
|
+
|
|
57
|
+
/** A url template made of the package the pins name; null when it needs a package there is none of. */
|
|
58
|
+
function expand(t, pkg) {
|
|
59
|
+
if (!/\{(name|version|file)\}/.test(t)) return t
|
|
60
|
+
if (!pkg || typeof pkg.name !== 'string' || typeof pkg.version !== 'string' || !pkg.name || !pkg.version) return null
|
|
61
|
+
return t.replace(/\{name\}/g, pkg.name).replace(/\{version\}/g, pkg.version).replace(/\{file\}/g, pkg.name.replace(/^@[^/]+\//, ''))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
class Fail extends Error {}
|
|
65
|
+
|
|
66
|
+
/** One body, read to its end: bounded in size (cap) and in silence (stallMs); chunks go to `sink`. Throws Fail. */
|
|
67
|
+
async function pump(resp, { cap, stallMs, ctl, sink, progress }) {
|
|
68
|
+
const reader = resp.body.getReader()
|
|
69
|
+
let got = 0
|
|
70
|
+
for (;;) {
|
|
71
|
+
let timer
|
|
72
|
+
const stall = new Promise(r => (timer = setTimeout(() => r({ stalled: true }), stallMs)))
|
|
73
|
+
let step
|
|
74
|
+
try {
|
|
75
|
+
step = await Promise.race([reader.read(), stall])
|
|
76
|
+
} finally {
|
|
77
|
+
clearTimeout(timer)
|
|
78
|
+
}
|
|
79
|
+
if (step.stalled) {
|
|
80
|
+
reader.cancel().catch(() => {})
|
|
81
|
+
ctl.abort()
|
|
82
|
+
throw new Fail(`the source stalled: no data for ${stallMs} ms after ${got} bytes`)
|
|
83
|
+
}
|
|
84
|
+
if (step.done) return got
|
|
85
|
+
got += step.value.byteLength
|
|
86
|
+
if (got > cap) {
|
|
87
|
+
reader.cancel().catch(() => {})
|
|
88
|
+
ctl.abort()
|
|
89
|
+
throw new Fail(`the body is longer than the bound of ${cap} bytes`)
|
|
90
|
+
}
|
|
91
|
+
await sink(step.value)
|
|
92
|
+
if (progress) progress(got)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* X6 default part 5: the response headers wait for no more than the stall bound either (a source that accepts the connection and says nothing used to
|
|
98
|
+
* hold the fetch until the source's whole PINNED_TOTAL_MS).
|
|
99
|
+
*/
|
|
100
|
+
async function fetchHeaders(fetchFn, url, init, stallMs, ctl) {
|
|
101
|
+
let timer
|
|
102
|
+
const stall = new Promise((_, rej) => (timer = setTimeout(() => (ctl.abort(), rej(new Fail(`the source stalled: no answer for ${stallMs} ms`))), stallMs)))
|
|
103
|
+
try {
|
|
104
|
+
return await Promise.race([fetchFn(url, init), stall])
|
|
105
|
+
} finally {
|
|
106
|
+
clearTimeout(timer)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ---- the tar reader ---------------------------------------------------------------------------------------------------------------------
|
|
111
|
+
const field = (h, from, to) => {
|
|
112
|
+
let end = from
|
|
113
|
+
while (end < to && h[end] !== 0) end++
|
|
114
|
+
return new TextDecoder().decode(h.subarray(from, end))
|
|
115
|
+
}
|
|
116
|
+
function parseSize(h) {
|
|
117
|
+
if (h[124] & 0x80) {
|
|
118
|
+
// base-256: only a size that fits 48 bits is read, and anything past the bound is refused by the caller
|
|
119
|
+
let n = 0
|
|
120
|
+
for (let i = 125; i < 136; i++) n = n * 256 + h[i]
|
|
121
|
+
return Number.isSafeInteger(n) ? n : Infinity
|
|
122
|
+
}
|
|
123
|
+
const t = field(h, 124, 136).trim()
|
|
124
|
+
return /^[0-7]+$/.test(t) ? parseInt(t, 8) : NaN
|
|
125
|
+
}
|
|
126
|
+
function checksumOk(h) {
|
|
127
|
+
let sum = 0
|
|
128
|
+
for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i]
|
|
129
|
+
const t = field(h, 148, 156).trim()
|
|
130
|
+
return /^[0-7]+$/.test(t) && parseInt(t, 8) === sum
|
|
131
|
+
}
|
|
132
|
+
const isZero = h => h.every(b => b === 0)
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* An incremental tar reader. feed(chunk) gives bytes in; finish() says whether the archive ended properly. `wants`: [{path, sha256, size}]; an entry
|
|
136
|
+
* named `package/<path>` is kept (its size field must be the pinned size), every other entry is skipped without being held. The total of bytes taken
|
|
137
|
+
* in is bounded by `maxUnpacked`.
|
|
138
|
+
*/
|
|
139
|
+
function tarReader(wants, maxUnpacked) {
|
|
140
|
+
const want = new Map(wants.map(w => [`package/${w.path}`, w]))
|
|
141
|
+
const found = new Map()
|
|
142
|
+
const seen = new Set()
|
|
143
|
+
let buf = new Uint8Array(0)
|
|
144
|
+
let total = 0
|
|
145
|
+
let state = 'header'
|
|
146
|
+
let ended = false
|
|
147
|
+
let cur = null // {name, want, left, pad, data, at, kind}
|
|
148
|
+
let nextName = null
|
|
149
|
+
const append = chunk => {
|
|
150
|
+
if (!buf.length) buf = chunk
|
|
151
|
+
else {
|
|
152
|
+
const n = new Uint8Array(buf.length + chunk.length)
|
|
153
|
+
n.set(buf)
|
|
154
|
+
n.set(chunk, buf.length)
|
|
155
|
+
buf = n
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const nameOf = (h, override) => {
|
|
159
|
+
if (override) return override
|
|
160
|
+
const n = field(h, 0, 100)
|
|
161
|
+
const p = field(h, 257, 263).startsWith('ustar') ? field(h, 345, 500) : ''
|
|
162
|
+
return p ? `${p}/${n}` : n
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
feed(chunk) {
|
|
166
|
+
total += chunk.length
|
|
167
|
+
if (total > maxUnpacked) throw new Fail(`the archive unpacks to more than the bound of ${maxUnpacked} bytes`)
|
|
168
|
+
if (ended) return
|
|
169
|
+
append(chunk)
|
|
170
|
+
for (;;) {
|
|
171
|
+
if (state === 'header') {
|
|
172
|
+
if (buf.length < 512) return
|
|
173
|
+
const h = buf.subarray(0, 512)
|
|
174
|
+
buf = buf.subarray(512)
|
|
175
|
+
if (isZero(h)) {
|
|
176
|
+
ended = true
|
|
177
|
+
buf = new Uint8Array(0)
|
|
178
|
+
return
|
|
179
|
+
}
|
|
180
|
+
if (!checksumOk(h)) throw new Fail('a tar header has a wrong checksum')
|
|
181
|
+
const size = parseSize(h)
|
|
182
|
+
const type = String.fromCharCode(h[156] || 48)
|
|
183
|
+
if (!Number.isFinite(size) || size < 0 || size > maxUnpacked) throw new Fail(`a tar entry's size field (${size}) is beyond the bound`)
|
|
184
|
+
const padN = (512 - (size % 512)) % 512
|
|
185
|
+
if (type === 'x' || type === 'g' || type === 'L') {
|
|
186
|
+
if (size > PAX_MAX) throw new Fail(`a tar ${type === 'L' ? 'long name' : 'extended header'} is longer than ${PAX_MAX} bytes`)
|
|
187
|
+
cur = { kind: type, left: size, pad: padN, data: new Uint8Array(size), at: 0 }
|
|
188
|
+
} else {
|
|
189
|
+
const name = nameOf(h, nextName)
|
|
190
|
+
nextName = null
|
|
191
|
+
const w = want.get(name)
|
|
192
|
+
if (w) {
|
|
193
|
+
if (seen.has(name)) throw new Fail(`${w.path} is in the archive more than once`)
|
|
194
|
+
seen.add(name)
|
|
195
|
+
if (type !== '0') throw new Fail(`${w.path} is not a regular file in the archive`)
|
|
196
|
+
if (size !== w.size) throw new Fail(`${w.path}: the tar size field is ${size}, not the pinned ${w.size}`)
|
|
197
|
+
cur = { kind: 'want', want: w, left: size, pad: padN, data: new Uint8Array(size), at: 0 }
|
|
198
|
+
} else cur = { kind: 'skip', left: size, pad: padN }
|
|
199
|
+
}
|
|
200
|
+
state = 'data'
|
|
201
|
+
}
|
|
202
|
+
if (state === 'data') {
|
|
203
|
+
const n = Math.min(cur.left, buf.length)
|
|
204
|
+
if (cur.data) cur.data.set(buf.subarray(0, n), cur.at)
|
|
205
|
+
cur.at = (cur.at || 0) + n
|
|
206
|
+
cur.left -= n
|
|
207
|
+
buf = buf.subarray(n)
|
|
208
|
+
if (cur.left > 0) return
|
|
209
|
+
state = 'pad'
|
|
210
|
+
}
|
|
211
|
+
if (state === 'pad') {
|
|
212
|
+
const n = Math.min(cur.pad, buf.length)
|
|
213
|
+
cur.pad -= n
|
|
214
|
+
buf = buf.subarray(n)
|
|
215
|
+
if (cur.pad > 0) return
|
|
216
|
+
if (cur.kind === 'want') found.set(cur.want.path, cur.data)
|
|
217
|
+
else if (cur.kind === 'L') nextName = field(cur.data, 0, cur.data.length)
|
|
218
|
+
else if (cur.kind === 'x') {
|
|
219
|
+
const text = new TextDecoder().decode(cur.data)
|
|
220
|
+
let p = 0
|
|
221
|
+
while (p < text.length) {
|
|
222
|
+
const sp = text.indexOf(' ', p)
|
|
223
|
+
const len = Number(text.slice(p, sp))
|
|
224
|
+
if (!(sp > p) || !(len > 0)) break
|
|
225
|
+
const rec = text.slice(sp + 1, p + len - 1)
|
|
226
|
+
const eq = rec.indexOf('=')
|
|
227
|
+
if (eq > 0 && rec.slice(0, eq) === 'path') nextName = rec.slice(eq + 1)
|
|
228
|
+
p += len
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
cur = null
|
|
232
|
+
state = 'header'
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
finish() {
|
|
237
|
+
if (!ended) throw new Fail(state === 'header' && !buf.length ? 'the archive ends early (no end marker)' : 'the archive ends early (inside an entry)')
|
|
238
|
+
const missing = wants.filter(w => !found.has(w.path)).map(w => w.path)
|
|
239
|
+
if (missing.length) throw new Fail(`${missing.join(', ')} not in the archive`)
|
|
240
|
+
return found
|
|
241
|
+
},
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function fromTgz({ url, files, fetchFn, ctl, stallMs, tarballMax, unpackedMax, late, progress }) {
|
|
246
|
+
if (typeof DecompressionStream !== 'function') throw new Fail('this browser has no DecompressionStream')
|
|
247
|
+
const resp = await fetchHeaders(fetchFn, url, { mode: 'cors', credentials: 'omit', cache: 'no-store', redirect: 'follow', signal: ctl.signal }, stallMs, ctl)
|
|
248
|
+
checkResponse(resp, url)
|
|
249
|
+
const declared = Number(resp.headers && resp.headers.get && resp.headers.get('content-length'))
|
|
250
|
+
if (declared > tarballMax) throw new Fail(`the body is longer than the bound of ${tarballMax} bytes (content-length ${declared})`)
|
|
251
|
+
const reader = tarReader(files, unpackedMax)
|
|
252
|
+
const ds = new DecompressionStream('gzip')
|
|
253
|
+
const writer = ds.writable.getWriter()
|
|
254
|
+
let problem = null
|
|
255
|
+
const note = e => {
|
|
256
|
+
if (!problem) problem = e instanceof Fail ? e : new Fail(`the gzip body is damaged: ${msg(e)}`)
|
|
257
|
+
ctl.abort()
|
|
258
|
+
writer.abort(problem).catch(() => {})
|
|
259
|
+
}
|
|
260
|
+
const out = (async () => {
|
|
261
|
+
const r = ds.readable.getReader()
|
|
262
|
+
try {
|
|
263
|
+
for (;;) {
|
|
264
|
+
const s = await r.read()
|
|
265
|
+
if (s.done) return
|
|
266
|
+
reader.feed(s.value)
|
|
267
|
+
}
|
|
268
|
+
} catch (e) {
|
|
269
|
+
note(e)
|
|
270
|
+
}
|
|
271
|
+
})()
|
|
272
|
+
try {
|
|
273
|
+
await pump(resp, { cap: tarballMax, stallMs, ctl, sink: chunk => writer.write(chunk), progress })
|
|
274
|
+
await writer.close()
|
|
275
|
+
} catch (e) {
|
|
276
|
+
note(e)
|
|
277
|
+
}
|
|
278
|
+
await out
|
|
279
|
+
if (problem) throw problem
|
|
280
|
+
if (late()) throw new Fail('the source did not answer in time')
|
|
281
|
+
try {
|
|
282
|
+
return reader.finish()
|
|
283
|
+
} catch (e) {
|
|
284
|
+
if (e instanceof Fail) throw e
|
|
285
|
+
throw new Fail(msg(e))
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function checkResponse(resp, url) {
|
|
290
|
+
if (resp.status !== 200) throw new Fail(`HTTP ${resp.status}`)
|
|
291
|
+
if (resp.url && schemeOf(resp.url) !== schemeOf(url)) throw new Fail(`redirected to another scheme (${schemeOf(resp.url)})`)
|
|
292
|
+
if (!resp.body) throw new Fail('no body')
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function fromFile({ url, file, fetchFn, ctl, stallMs, progress }) {
|
|
296
|
+
const cap = file.size === undefined ? MAX_PINNED_BYTES : file.size
|
|
297
|
+
const resp = await fetchHeaders(fetchFn, url, { mode: 'cors', credentials: 'omit', cache: 'no-store', redirect: 'follow', signal: ctl.signal }, stallMs, ctl)
|
|
298
|
+
checkResponse(resp, url)
|
|
299
|
+
const declared = Number(resp.headers && resp.headers.get && resp.headers.get('content-length'))
|
|
300
|
+
if (declared > cap) throw new Fail(`the body is longer than the pinned ${cap} bytes (content-length ${declared})`)
|
|
301
|
+
const chunks = []
|
|
302
|
+
const got = await pump(resp, { cap, stallMs, ctl, sink: c => void chunks.push(c), progress }).catch(e => {
|
|
303
|
+
if (e instanceof Fail) throw new Fail(e.message.replace('the bound of', 'the pinned').replace(/ bytes$/, ' bytes'))
|
|
304
|
+
throw e
|
|
305
|
+
})
|
|
306
|
+
if (file.size !== undefined && got !== file.size) throw new Fail(`the body is shorter than the pinned ${file.size} bytes (${got})`)
|
|
307
|
+
const out = new Uint8Array(got)
|
|
308
|
+
let at = 0
|
|
309
|
+
for (const c of chunks) (out.set(c, at), (at += c.byteLength))
|
|
310
|
+
return out
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const joinUrl = (base, path) => `${String(base).replace(/\/+$/, '')}/${path}`
|
|
314
|
+
|
|
315
|
+
async function fromCache({ cacheStorage, files, cacheKeyOf }) {
|
|
316
|
+
const got = {}
|
|
317
|
+
let cache = null
|
|
318
|
+
try {
|
|
319
|
+
if (!cacheStorage) return got
|
|
320
|
+
cache = await cacheStorage.open(PINNED_CACHE_NAME)
|
|
321
|
+
} catch {
|
|
322
|
+
return got
|
|
323
|
+
}
|
|
324
|
+
for (const f of files) {
|
|
325
|
+
const key = cacheKeyOf(f.sha256)
|
|
326
|
+
try {
|
|
327
|
+
const hit = await cache.match(key)
|
|
328
|
+
if (!hit) continue
|
|
329
|
+
const bytes = await hit.arrayBuffer()
|
|
330
|
+
if ((f.size === undefined || bytes.byteLength === f.size) && (await sha256Of(bytes)) === String(f.sha256).toLowerCase()) got[f.path] = bytes
|
|
331
|
+
else await cache.delete(key) // damaged or not the file it is named for: gone
|
|
332
|
+
} catch {
|
|
333
|
+
try {
|
|
334
|
+
await cache.delete(key)
|
|
335
|
+
} catch {
|
|
336
|
+
// storage that throws is storage that is not there
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return got
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* @param {object} o
|
|
345
|
+
* @param {{path: string, sha256: string, size?: number}[]} o.files what is needed; a tar entry is 'package/<path>'
|
|
346
|
+
* @param {{name: string, version: string}|null} [o.pkg] the package the pins name (for the {name} {version} {file} of a source)
|
|
347
|
+
* @param {object[]} o.sources ordered: {kind:'tgz', url} | {kind:'file', base} | {kind:'url', url}
|
|
348
|
+
* @returns {Promise<{files: Object<string, ArrayBuffer>, from: Object<string, string>, source: string, reasons: {source: string, why: string}[]} | {error: string, reasons: {source: string, why: string}[]}>}
|
|
349
|
+
*/
|
|
350
|
+
export async function fetchPinned(o) {
|
|
351
|
+
const reasons = []
|
|
352
|
+
try {
|
|
353
|
+
const { files, pkg = null, sources, fetchFn = (...a) => fetch(...a), cacheStorage = globalThis.caches, cacheKeyOf = pinnedCacheKey, timeoutMs = PINNED_TOTAL_MS, stallMs = PINNED_STALL_MS, allMs = PINNED_ALL_MS, onProgress = null, schemes = ['https:', 'http:'] } = o || {}
|
|
354
|
+
if (!Array.isArray(files) || !files.length) return { error: 'no file was asked for', reasons }
|
|
355
|
+
if (!Array.isArray(sources) || !sources.length) return { error: 'no source is named', reasons }
|
|
356
|
+
const have = await fromCache({ cacheStorage, files, cacheKeyOf })
|
|
357
|
+
const from = {}
|
|
358
|
+
for (const p of Object.keys(have)) from[p] = 'cache'
|
|
359
|
+
const missing = files.filter(f => !(f.path in have))
|
|
360
|
+
if (!missing.length) return { files: have, from, source: 'cache', reasons }
|
|
361
|
+
const pinned = files.reduce((n, f) => n + (f.size || 0), 0)
|
|
362
|
+
const began = Date.now()
|
|
363
|
+
let allHit = false
|
|
364
|
+
for (const src of sources) {
|
|
365
|
+
const left = allMs - (Date.now() - began)
|
|
366
|
+
if (left <= 0) {
|
|
367
|
+
allHit = true
|
|
368
|
+
break
|
|
369
|
+
}
|
|
370
|
+
const why = r => (reasons.push({ source: r.source, why: r.why }), null)
|
|
371
|
+
const kind = src && src.kind
|
|
372
|
+
const raw = kind === 'tgz' || kind === 'url' ? src.url : kind === 'file' ? src.base : null
|
|
373
|
+
if (raw === null || typeof raw !== 'string') {
|
|
374
|
+
why({ source: `${kind || 'source'}`, why: 'a source of an unknown kind or with no url' })
|
|
375
|
+
continue
|
|
376
|
+
}
|
|
377
|
+
const text = expand(raw, pkg)
|
|
378
|
+
if (text === null) {
|
|
379
|
+
why({ source: label(raw), why: 'the pins name no package (name and version) for this file, which this source needs' })
|
|
380
|
+
continue
|
|
381
|
+
}
|
|
382
|
+
if (!schemes.includes(schemeOf(text))) {
|
|
383
|
+
why({ source: label(text), why: `not an ${schemes.map(x => x.slice(0, -1)).join('/')} url` })
|
|
384
|
+
continue
|
|
385
|
+
}
|
|
386
|
+
const ctl = new AbortController()
|
|
387
|
+
let isLate = false
|
|
388
|
+
const limit = Math.min(timeoutMs, left)
|
|
389
|
+
const timer = setTimeout(() => ((isLate = true), ctl.abort()), limit)
|
|
390
|
+
const name = `${kind} ${label(text)}`
|
|
391
|
+
try {
|
|
392
|
+
let got = {}
|
|
393
|
+
if (kind === 'tgz') {
|
|
394
|
+
const tarballMax = src.tarballMax ?? o.tarballMax ?? pinned + TAR_OVERHEAD
|
|
395
|
+
const unpackedMax = o.unpackedMax ?? pinned + TAR_OVERHEAD
|
|
396
|
+
if (missing.some(f => !Number.isInteger(f.size))) throw new Fail('a file inside a tarball needs a pinned size')
|
|
397
|
+
const found = await fromTgz({ url: text, files: missing, fetchFn, ctl, stallMs, tarballMax, unpackedMax, late: () => isLate, progress: onProgress })
|
|
398
|
+
for (const [p, b] of found) got[p] = b
|
|
399
|
+
} else {
|
|
400
|
+
for (const f of missing) got[f.path] = await fromFile({ url: kind === 'url' ? text : joinUrl(text, f.path), file: f, fetchFn, ctl, stallMs, progress: onProgress })
|
|
401
|
+
}
|
|
402
|
+
for (const f of missing) {
|
|
403
|
+
const b = got[f.path]
|
|
404
|
+
if (!b) throw new Fail(`${f.path} was not given`)
|
|
405
|
+
const bytes = b instanceof ArrayBuffer ? b : b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)
|
|
406
|
+
const got12 = await sha256Of(bytes)
|
|
407
|
+
if (got12 !== String(f.sha256).toLowerCase()) throw new Fail(`${f.path} does not match its pin (sha256 ${got12.slice(0, 12)}..., pinned ${String(f.sha256).toLowerCase().slice(0, 12)}...)`)
|
|
408
|
+
have[f.path] = bytes
|
|
409
|
+
from[f.path] = name
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
if (cacheStorage) {
|
|
413
|
+
const cache = await cacheStorage.open(PINNED_CACHE_NAME)
|
|
414
|
+
for (const f of missing) await cache.put(cacheKeyOf(f.sha256), new Response(have[f.path], { headers: { 'content-type': 'application/octet-stream' } }))
|
|
415
|
+
}
|
|
416
|
+
} catch {
|
|
417
|
+
// no storage, or no room: the next boot fetches again
|
|
418
|
+
}
|
|
419
|
+
return { files: have, from, source: name, reasons }
|
|
420
|
+
} catch (e) {
|
|
421
|
+
const said = !isLate && !(e instanceof Fail) && typeof o.explain === 'function' ? await o.explain(text, e) : null // fix 10 (F4): the page's policy, when it blocked the source
|
|
422
|
+
const text2 = e instanceof Fail ? e.message : isLate ? `no answer within ${limit} ms` : said || `could not be fetched: ${msg(e)}`
|
|
423
|
+
why({ source: name, why: isLate && !(e instanceof Fail) ? `did not answer within ${limit} ms${limit < timeoutMs ? ' (what is left of the overall bound)' : ''}` : isLate && /stalled|in time/.test(text2) ? text2 : text2 })
|
|
424
|
+
for (const f of missing) delete have[f.path]
|
|
425
|
+
} finally {
|
|
426
|
+
clearTimeout(timer)
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
if (Date.now() - began >= allMs) allHit = true
|
|
430
|
+
if (allHit) reasons.push({ source: 'all sources', why: `the overall bound of ${allMs} ms passed${sources.length > reasons.length ? ' (the sources not asked are left out)' : ''}` })
|
|
431
|
+
const one = reasons.map(r => `${r.source}: ${r.why}`).join('; ')
|
|
432
|
+
return { error: reasons.length === 1 ? reasons[0].why : `no source gave the file: ${one}`, reasons }
|
|
433
|
+
} catch (e) {
|
|
434
|
+
return { error: `the pinned files could not be fetched: ${msg(e)}`, reasons }
|
|
435
|
+
}
|
|
436
|
+
}
|
package/wmdpack.wasm
CHANGED
|
Binary file
|