repl-sdk 1.0.0 → 1.0.2

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.
@@ -1,2133 +0,0 @@
1
- import { wrap } from "comlink";
2
- import { exports } from "resolve.exports";
3
- import { resolve as resolve$2 } from "resolve.imports";
4
- const types = {
5
- "application/andrew-inset": ["ez"],
6
- "application/appinstaller": ["appinstaller"],
7
- "application/applixware": ["aw"],
8
- "application/appx": ["appx"],
9
- "application/appxbundle": ["appxbundle"],
10
- "application/atom+xml": ["atom"],
11
- "application/atomcat+xml": ["atomcat"],
12
- "application/atomdeleted+xml": ["atomdeleted"],
13
- "application/atomsvc+xml": ["atomsvc"],
14
- "application/atsc-dwd+xml": ["dwd"],
15
- "application/atsc-held+xml": ["held"],
16
- "application/atsc-rsat+xml": ["rsat"],
17
- "application/automationml-aml+xml": ["aml"],
18
- "application/automationml-amlx+zip": ["amlx"],
19
- "application/bdoc": ["bdoc"],
20
- "application/calendar+xml": ["xcs"],
21
- "application/ccxml+xml": ["ccxml"],
22
- "application/cdfx+xml": ["cdfx"],
23
- "application/cdmi-capability": ["cdmia"],
24
- "application/cdmi-container": ["cdmic"],
25
- "application/cdmi-domain": ["cdmid"],
26
- "application/cdmi-object": ["cdmio"],
27
- "application/cdmi-queue": ["cdmiq"],
28
- "application/cpl+xml": ["cpl"],
29
- "application/cu-seeme": ["cu"],
30
- "application/cwl": ["cwl"],
31
- "application/dash+xml": ["mpd"],
32
- "application/dash-patch+xml": ["mpp"],
33
- "application/davmount+xml": ["davmount"],
34
- "application/dicom": ["dcm"],
35
- "application/docbook+xml": ["dbk"],
36
- "application/dssc+der": ["dssc"],
37
- "application/dssc+xml": ["xdssc"],
38
- "application/ecmascript": ["ecma"],
39
- "application/emma+xml": ["emma"],
40
- "application/emotionml+xml": ["emotionml"],
41
- "application/epub+zip": ["epub"],
42
- "application/exi": ["exi"],
43
- "application/express": ["exp"],
44
- "application/fdf": ["fdf"],
45
- "application/fdt+xml": ["fdt"],
46
- "application/font-tdpfr": ["pfr"],
47
- "application/geo+json": ["geojson"],
48
- "application/gml+xml": ["gml"],
49
- "application/gpx+xml": ["gpx"],
50
- "application/gxf": ["gxf"],
51
- "application/gzip": ["gz"],
52
- "application/hjson": ["hjson"],
53
- "application/hyperstudio": ["stk"],
54
- "application/inkml+xml": ["ink", "inkml"],
55
- "application/ipfix": ["ipfix"],
56
- "application/its+xml": ["its"],
57
- "application/java-archive": ["jar", "war", "ear"],
58
- "application/java-serialized-object": ["ser"],
59
- "application/java-vm": ["class"],
60
- "application/javascript": ["*js"],
61
- "application/json": ["json", "map"],
62
- "application/json5": ["json5"],
63
- "application/jsonml+json": ["jsonml"],
64
- "application/ld+json": ["jsonld"],
65
- "application/lgr+xml": ["lgr"],
66
- "application/lost+xml": ["lostxml"],
67
- "application/mac-binhex40": ["hqx"],
68
- "application/mac-compactpro": ["cpt"],
69
- "application/mads+xml": ["mads"],
70
- "application/manifest+json": ["webmanifest"],
71
- "application/marc": ["mrc"],
72
- "application/marcxml+xml": ["mrcx"],
73
- "application/mathematica": ["ma", "nb", "mb"],
74
- "application/mathml+xml": ["mathml"],
75
- "application/mbox": ["mbox"],
76
- "application/media-policy-dataset+xml": ["mpf"],
77
- "application/mediaservercontrol+xml": ["mscml"],
78
- "application/metalink+xml": ["metalink"],
79
- "application/metalink4+xml": ["meta4"],
80
- "application/mets+xml": ["mets"],
81
- "application/mmt-aei+xml": ["maei"],
82
- "application/mmt-usd+xml": ["musd"],
83
- "application/mods+xml": ["mods"],
84
- "application/mp21": ["m21", "mp21"],
85
- "application/mp4": ["*mp4", "*mpg4", "mp4s", "m4p"],
86
- "application/msix": ["msix"],
87
- "application/msixbundle": ["msixbundle"],
88
- "application/msword": ["doc", "dot"],
89
- "application/mxf": ["mxf"],
90
- "application/n-quads": ["nq"],
91
- "application/n-triples": ["nt"],
92
- "application/node": ["cjs"],
93
- "application/octet-stream": [
94
- "bin",
95
- "dms",
96
- "lrf",
97
- "mar",
98
- "so",
99
- "dist",
100
- "distz",
101
- "pkg",
102
- "bpk",
103
- "dump",
104
- "elc",
105
- "deploy",
106
- "exe",
107
- "dll",
108
- "deb",
109
- "dmg",
110
- "iso",
111
- "img",
112
- "msi",
113
- "msp",
114
- "msm",
115
- "buffer"
116
- ],
117
- "application/oda": ["oda"],
118
- "application/oebps-package+xml": ["opf"],
119
- "application/ogg": ["ogx"],
120
- "application/omdoc+xml": ["omdoc"],
121
- "application/onenote": [
122
- "onetoc",
123
- "onetoc2",
124
- "onetmp",
125
- "onepkg",
126
- "one",
127
- "onea"
128
- ],
129
- "application/oxps": ["oxps"],
130
- "application/p2p-overlay+xml": ["relo"],
131
- "application/patch-ops-error+xml": ["xer"],
132
- "application/pdf": ["pdf"],
133
- "application/pgp-encrypted": ["pgp"],
134
- "application/pgp-keys": ["asc"],
135
- "application/pgp-signature": ["sig", "*asc"],
136
- "application/pics-rules": ["prf"],
137
- "application/pkcs10": ["p10"],
138
- "application/pkcs7-mime": ["p7m", "p7c"],
139
- "application/pkcs7-signature": ["p7s"],
140
- "application/pkcs8": ["p8"],
141
- "application/pkix-attr-cert": ["ac"],
142
- "application/pkix-cert": ["cer"],
143
- "application/pkix-crl": ["crl"],
144
- "application/pkix-pkipath": ["pkipath"],
145
- "application/pkixcmp": ["pki"],
146
- "application/pls+xml": ["pls"],
147
- "application/postscript": ["ai", "eps", "ps"],
148
- "application/provenance+xml": ["provx"],
149
- "application/pskc+xml": ["pskcxml"],
150
- "application/raml+yaml": ["raml"],
151
- "application/rdf+xml": ["rdf", "owl"],
152
- "application/reginfo+xml": ["rif"],
153
- "application/relax-ng-compact-syntax": ["rnc"],
154
- "application/resource-lists+xml": ["rl"],
155
- "application/resource-lists-diff+xml": ["rld"],
156
- "application/rls-services+xml": ["rs"],
157
- "application/route-apd+xml": ["rapd"],
158
- "application/route-s-tsid+xml": ["sls"],
159
- "application/route-usd+xml": ["rusd"],
160
- "application/rpki-ghostbusters": ["gbr"],
161
- "application/rpki-manifest": ["mft"],
162
- "application/rpki-roa": ["roa"],
163
- "application/rsd+xml": ["rsd"],
164
- "application/rss+xml": ["rss"],
165
- "application/rtf": ["rtf"],
166
- "application/sbml+xml": ["sbml"],
167
- "application/scvp-cv-request": ["scq"],
168
- "application/scvp-cv-response": ["scs"],
169
- "application/scvp-vp-request": ["spq"],
170
- "application/scvp-vp-response": ["spp"],
171
- "application/sdp": ["sdp"],
172
- "application/senml+xml": ["senmlx"],
173
- "application/sensml+xml": ["sensmlx"],
174
- "application/set-payment-initiation": ["setpay"],
175
- "application/set-registration-initiation": ["setreg"],
176
- "application/shf+xml": ["shf"],
177
- "application/sieve": ["siv", "sieve"],
178
- "application/smil+xml": ["smi", "smil"],
179
- "application/sparql-query": ["rq"],
180
- "application/sparql-results+xml": ["srx"],
181
- "application/sql": ["sql"],
182
- "application/srgs": ["gram"],
183
- "application/srgs+xml": ["grxml"],
184
- "application/sru+xml": ["sru"],
185
- "application/ssdl+xml": ["ssdl"],
186
- "application/ssml+xml": ["ssml"],
187
- "application/swid+xml": ["swidtag"],
188
- "application/tei+xml": ["tei", "teicorpus"],
189
- "application/thraud+xml": ["tfi"],
190
- "application/timestamped-data": ["tsd"],
191
- "application/toml": ["toml"],
192
- "application/trig": ["trig"],
193
- "application/ttml+xml": ["ttml"],
194
- "application/ubjson": ["ubj"],
195
- "application/urc-ressheet+xml": ["rsheet"],
196
- "application/urc-targetdesc+xml": ["td"],
197
- "application/voicexml+xml": ["vxml"],
198
- "application/wasm": ["wasm"],
199
- "application/watcherinfo+xml": ["wif"],
200
- "application/widget": ["wgt"],
201
- "application/winhlp": ["hlp"],
202
- "application/wsdl+xml": ["wsdl"],
203
- "application/wspolicy+xml": ["wspolicy"],
204
- "application/xaml+xml": ["xaml"],
205
- "application/xcap-att+xml": ["xav"],
206
- "application/xcap-caps+xml": ["xca"],
207
- "application/xcap-diff+xml": ["xdf"],
208
- "application/xcap-el+xml": ["xel"],
209
- "application/xcap-ns+xml": ["xns"],
210
- "application/xenc+xml": ["xenc"],
211
- "application/xfdf": ["xfdf"],
212
- "application/xhtml+xml": ["xhtml", "xht"],
213
- "application/xliff+xml": ["xlf"],
214
- "application/xml": ["xml", "xsl", "xsd", "rng"],
215
- "application/xml-dtd": ["dtd"],
216
- "application/xop+xml": ["xop"],
217
- "application/xproc+xml": ["xpl"],
218
- "application/xslt+xml": ["*xsl", "xslt"],
219
- "application/xspf+xml": ["xspf"],
220
- "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"],
221
- "application/yang": ["yang"],
222
- "application/yin+xml": ["yin"],
223
- "application/zip": ["zip"],
224
- "application/zip+dotlottie": ["lottie"],
225
- "audio/3gpp": ["*3gpp"],
226
- "audio/aac": ["adts", "aac"],
227
- "audio/adpcm": ["adp"],
228
- "audio/amr": ["amr"],
229
- "audio/basic": ["au", "snd"],
230
- "audio/midi": ["mid", "midi", "kar", "rmi"],
231
- "audio/mobile-xmf": ["mxmf"],
232
- "audio/mp3": ["*mp3"],
233
- "audio/mp4": ["m4a", "mp4a", "m4b"],
234
- "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"],
235
- "audio/ogg": ["oga", "ogg", "spx", "opus"],
236
- "audio/s3m": ["s3m"],
237
- "audio/silk": ["sil"],
238
- "audio/wav": ["wav"],
239
- "audio/wave": ["*wav"],
240
- "audio/webm": ["weba"],
241
- "audio/xm": ["xm"],
242
- "font/collection": ["ttc"],
243
- "font/otf": ["otf"],
244
- "font/ttf": ["ttf"],
245
- "font/woff": ["woff"],
246
- "font/woff2": ["woff2"],
247
- "image/aces": ["exr"],
248
- "image/apng": ["apng"],
249
- "image/avci": ["avci"],
250
- "image/avcs": ["avcs"],
251
- "image/avif": ["avif"],
252
- "image/bmp": ["bmp", "dib"],
253
- "image/cgm": ["cgm"],
254
- "image/dicom-rle": ["drle"],
255
- "image/dpx": ["dpx"],
256
- "image/emf": ["emf"],
257
- "image/fits": ["fits"],
258
- "image/g3fax": ["g3"],
259
- "image/gif": ["gif"],
260
- "image/heic": ["heic"],
261
- "image/heic-sequence": ["heics"],
262
- "image/heif": ["heif"],
263
- "image/heif-sequence": ["heifs"],
264
- "image/hej2k": ["hej2"],
265
- "image/ief": ["ief"],
266
- "image/jaii": ["jaii"],
267
- "image/jais": ["jais"],
268
- "image/jls": ["jls"],
269
- "image/jp2": ["jp2", "jpg2"],
270
- "image/jpeg": ["jpg", "jpeg", "jpe"],
271
- "image/jph": ["jph"],
272
- "image/jphc": ["jhc"],
273
- "image/jpm": ["jpm", "jpgm"],
274
- "image/jpx": ["jpx", "jpf"],
275
- "image/jxl": ["jxl"],
276
- "image/jxr": ["jxr"],
277
- "image/jxra": ["jxra"],
278
- "image/jxrs": ["jxrs"],
279
- "image/jxs": ["jxs"],
280
- "image/jxsc": ["jxsc"],
281
- "image/jxsi": ["jxsi"],
282
- "image/jxss": ["jxss"],
283
- "image/ktx": ["ktx"],
284
- "image/ktx2": ["ktx2"],
285
- "image/pjpeg": ["jfif"],
286
- "image/png": ["png"],
287
- "image/sgi": ["sgi"],
288
- "image/svg+xml": ["svg", "svgz"],
289
- "image/t38": ["t38"],
290
- "image/tiff": ["tif", "tiff"],
291
- "image/tiff-fx": ["tfx"],
292
- "image/webp": ["webp"],
293
- "image/wmf": ["wmf"],
294
- "message/disposition-notification": ["disposition-notification"],
295
- "message/global": ["u8msg"],
296
- "message/global-delivery-status": ["u8dsn"],
297
- "message/global-disposition-notification": ["u8mdn"],
298
- "message/global-headers": ["u8hdr"],
299
- "message/rfc822": ["eml", "mime", "mht", "mhtml"],
300
- "model/3mf": ["3mf"],
301
- "model/gltf+json": ["gltf"],
302
- "model/gltf-binary": ["glb"],
303
- "model/iges": ["igs", "iges"],
304
- "model/jt": ["jt"],
305
- "model/mesh": ["msh", "mesh", "silo"],
306
- "model/mtl": ["mtl"],
307
- "model/obj": ["obj"],
308
- "model/prc": ["prc"],
309
- "model/step": ["step", "stp", "stpnc", "p21", "210"],
310
- "model/step+xml": ["stpx"],
311
- "model/step+zip": ["stpz"],
312
- "model/step-xml+zip": ["stpxz"],
313
- "model/stl": ["stl"],
314
- "model/u3d": ["u3d"],
315
- "model/vrml": ["wrl", "vrml"],
316
- "model/x3d+binary": ["*x3db", "x3dbz"],
317
- "model/x3d+fastinfoset": ["x3db"],
318
- "model/x3d+vrml": ["*x3dv", "x3dvz"],
319
- "model/x3d+xml": ["x3d", "x3dz"],
320
- "model/x3d-vrml": ["x3dv"],
321
- "text/cache-manifest": ["appcache", "manifest"],
322
- "text/calendar": ["ics", "ifb"],
323
- "text/coffeescript": ["coffee", "litcoffee"],
324
- "text/css": ["css"],
325
- "text/csv": ["csv"],
326
- "text/html": ["html", "htm", "shtml"],
327
- "text/jade": ["jade"],
328
- "text/javascript": ["js", "mjs"],
329
- "text/jsx": ["jsx"],
330
- "text/less": ["less"],
331
- "text/markdown": ["md", "markdown"],
332
- "text/mathml": ["mml"],
333
- "text/mdx": ["mdx"],
334
- "text/n3": ["n3"],
335
- "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"],
336
- "text/richtext": ["rtx"],
337
- "text/rtf": ["*rtf"],
338
- "text/sgml": ["sgml", "sgm"],
339
- "text/shex": ["shex"],
340
- "text/slim": ["slim", "slm"],
341
- "text/spdx": ["spdx"],
342
- "text/stylus": ["stylus", "styl"],
343
- "text/tab-separated-values": ["tsv"],
344
- "text/troff": ["t", "tr", "roff", "man", "me", "ms"],
345
- "text/turtle": ["ttl"],
346
- "text/uri-list": ["uri", "uris", "urls"],
347
- "text/vcard": ["vcard"],
348
- "text/vtt": ["vtt"],
349
- "text/wgsl": ["wgsl"],
350
- "text/xml": ["*xml"],
351
- "text/yaml": ["yaml", "yml"],
352
- "video/3gpp": ["3gp", "3gpp"],
353
- "video/3gpp2": ["3g2"],
354
- "video/h261": ["h261"],
355
- "video/h263": ["h263"],
356
- "video/h264": ["h264"],
357
- "video/iso.segment": ["m4s"],
358
- "video/jpeg": ["jpgv"],
359
- "video/jpm": ["*jpm", "*jpgm"],
360
- "video/mj2": ["mj2", "mjp2"],
361
- "video/mp2t": ["ts", "m2t", "m2ts", "mts"],
362
- "video/mp4": ["mp4", "mp4v", "mpg4"],
363
- "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"],
364
- "video/ogg": ["ogv"],
365
- "video/quicktime": ["qt", "mov"],
366
- "video/webm": ["webm"]
367
- };
368
- Object.freeze(types);
369
- var __classPrivateFieldGet = function(receiver, state, kind, f) {
370
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
371
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
372
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
373
- };
374
- var _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions;
375
- class Mime {
376
- constructor(...args) {
377
- _Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
378
- _Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
379
- _Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
380
- for (const arg of args) {
381
- this.define(arg);
382
- }
383
- }
384
- define(typeMap, force = false) {
385
- for (let [type, extensions] of Object.entries(typeMap)) {
386
- type = type.toLowerCase();
387
- extensions = extensions.map((ext) => ext.toLowerCase());
388
- if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
389
- __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
390
- }
391
- const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
392
- let first = true;
393
- for (let extension of extensions) {
394
- const starred = extension.startsWith("*");
395
- extension = starred ? extension.slice(1) : extension;
396
- allExtensions?.add(extension);
397
- if (first) {
398
- __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
399
- }
400
- first = false;
401
- if (starred)
402
- continue;
403
- const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
404
- if (currentType && currentType != type && !force) {
405
- throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
406
- }
407
- __classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
408
- }
409
- }
410
- return this;
411
- }
412
- getType(path) {
413
- if (typeof path !== "string")
414
- return null;
415
- const last = path.replace(/^.*[/\\]/s, "").toLowerCase();
416
- const ext = last.replace(/^.*\./s, "").toLowerCase();
417
- const hasPath = last.length < path.length;
418
- const hasDot = ext.length < last.length - 1;
419
- if (!hasDot && hasPath)
420
- return null;
421
- return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
422
- }
423
- getExtension(type) {
424
- if (typeof type !== "string")
425
- return null;
426
- type = type?.split?.(";")[0];
427
- return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
428
- }
429
- getAllExtensions(type) {
430
- if (typeof type !== "string")
431
- return null;
432
- return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
433
- }
434
- _freeze() {
435
- this.define = () => {
436
- throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
437
- };
438
- Object.freeze(this);
439
- for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
440
- Object.freeze(extensions);
441
- }
442
- return this;
443
- }
444
- _getTestState() {
445
- return {
446
- types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
447
- extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f")
448
- };
449
- }
450
- }
451
- _Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
452
- const mime = new Mime(types)._freeze();
453
- function assert(message, test) {
454
- if (!test) {
455
- throw new Error(message);
456
- }
457
- }
458
- let i = 0;
459
- function nextId() {
460
- i += 1;
461
- return `repl_${i}`;
462
- }
463
- const fakeDomain = "repl.sdk";
464
- const tgzPrefix = "file:///tgz.repl.sdk/";
465
- const unzippedPrefix = "file:///tgz.repl.sdk/unzipped";
466
- function prefix_tgz(url) {
467
- return `${tgzPrefix}${url}`;
468
- }
469
- function isRecord(x) {
470
- return typeof x === "object" && x !== null && !Array.isArray(x);
471
- }
472
- const secretKey = "__repl-sdk__compiler__";
473
- const secret = Symbol.for(secretKey);
474
- function getGlobal() {
475
- const global = (
476
- /** @type {ExtendedWindow} */
477
- globalThis
478
- );
479
- return global;
480
- }
481
- assert(
482
- `There is already an instance of repl-sdk, and there can only be one. Make sure that your dependency graph is correct.`,
483
- !getGlobal()[secret]
484
- );
485
- class Caches {
486
- clear() {
487
- delete getGlobal()[secret];
488
- }
489
- /**
490
- * Cache of resolved modulePaths to their module "value"
491
- *
492
- * @type {{ [modulePath: string]: unknown }}
493
- */
494
- get resolves() {
495
- this.#root.resolves ||= {};
496
- return this.#root.resolves;
497
- }
498
- /**
499
- * Cache of untarred tarballs
500
- *
501
- * @type {Map<string, import('./types.ts').UntarredPackage>}
502
- */
503
- get tarballs() {
504
- this.#root.tarballs ||= /* @__PURE__ */ new Map();
505
- return this.#root.tarballs;
506
- }
507
- /**
508
- * Cache of request resolutions
509
- *
510
- * @type {Map<string, ResolveIdValue>}
511
- */
512
- get resolveId() {
513
- this.#root.resolveId ||= /* @__PURE__ */ new Map();
514
- return this.#root.resolveId;
515
- }
516
- /**
517
- * Cache of request Key to file content string
518
- *
519
- * @type {Map<string, { code: string, ext: string }>}
520
- */
521
- get fileCache() {
522
- this.#root.fileCache ||= /* @__PURE__ */ new Map();
523
- return this.#root.fileCache;
524
- }
525
- /**
526
- * For any key, store a promise for resolving later
527
- *
528
- * @type {Map<string, Promise<unknown>>}
529
- */
530
- get promiseCache() {
531
- this.#root.promiseCache ||= /* @__PURE__ */ new Map();
532
- return this.#root.promiseCache;
533
- }
534
- /**
535
- * @template Return
536
- * @type {(key: string, callback: () => Promise<any>) => Promise<any>}
537
- */
538
- cachedPromise(key, callback) {
539
- const existing = this.promiseCache.get(key);
540
- if (existing) {
541
- return (
542
- /** @type {Promise<Return>} */
543
- existing
544
- );
545
- }
546
- const promise = callback();
547
- this.promiseCache.set(key, promise);
548
- return promise;
549
- }
550
- get requestCache() {
551
- this.#root.requestCache ||= /* @__PURE__ */ new Map();
552
- return this.#root.requestCache;
553
- }
554
- get #root() {
555
- const global = getGlobal();
556
- global[secret] ||= {};
557
- global[secret].caches ||= this;
558
- return global[secret];
559
- }
560
- }
561
- const cache = new Caches();
562
- const externalPackages = [
563
- "@ember/test-helpers",
564
- "@ember/string",
565
- "@ember/test-waiters",
566
- "@ember/render-modifiers",
567
- "@glimmer/component"
568
- ];
569
- function resolve$1(id) {
570
- if (id === "@ember/template-compiler/runtime") {
571
- return `https://esm.sh/*ember-source/dist/packages/@ember/template-compiler/runtime.js`;
572
- }
573
- const isExternalEmber = externalPackages.some((name) => id.startsWith(name));
574
- if (isExternalEmber) {
575
- return `https://esm.sh/*${id}`;
576
- }
577
- if (id.startsWith("@ember")) {
578
- return `https://esm.sh/*ember-source/dist/packages/${id}`;
579
- }
580
- if (id.startsWith("@glimmer")) {
581
- return `https://esm.sh/*ember-source/dist/dependencies/${id}.js`;
582
- }
583
- if (id.startsWith("@embroider/macros")) {
584
- return () => ({
585
- // passthrough, we are not doing dead-code-elimination
586
- /**
587
- * @param {unknown} x
588
- */
589
- macroCondition: (x) => Boolean(x),
590
- // I *could* actually implement this
591
- dependencySatisfies: () => true,
592
- isDevelopingApp: () => true,
593
- getGlobalConfig: () => ({
594
- WarpDrive: {
595
- debug: false,
596
- env: {
597
- DEBUG: false,
598
- TESTING: false,
599
- PRODUCTION: true
600
- },
601
- activeLogging: false,
602
- compatWith: "99.0",
603
- features: {},
604
- deprecations: {},
605
- polyfillUUID: false,
606
- includeDataAdapter: false
607
- }
608
- })
609
- });
610
- }
611
- }
612
- function onUnhandled(e, handle) {
613
- if (!e.reason?.message) return;
614
- let reason = e.reason.message;
615
- if (reason.includes("Stack trace for the update:")) {
616
- reason += " (see console)";
617
- }
618
- handle(reason);
619
- }
620
- const gjs = {
621
- resolve: resolve$1,
622
- onUnhandled,
623
- codemirror: {
624
- lang: async () => {
625
- const { gjs: gjs2 } = await import("codemirror-lang-glimmer-js");
626
- return gjs2();
627
- }
628
- },
629
- compiler: async (...args) => {
630
- const gjs2 = await import("./gjs-CzFzkEFv.js");
631
- return gjs2.compiler(...args);
632
- }
633
- };
634
- const hbs = {
635
- resolve: resolve$1,
636
- onUnhandled,
637
- codemirror: {
638
- lang: async () => {
639
- const { glimmer } = await import("codemirror-lang-glimmer");
640
- return glimmer();
641
- }
642
- },
643
- compiler: async (...args) => {
644
- const hbs2 = await import("./hbs-CuhWjffM.js");
645
- return hbs2.compiler(...args);
646
- }
647
- };
648
- const gmd = {
649
- resolve: resolve$1,
650
- onUnhandled,
651
- codemirror: {
652
- lang: async () => {
653
- const { glimdown } = await import("codemirror-lang-glimdown");
654
- return glimdown();
655
- },
656
- support: async () => {
657
- const { gjs: gjs2 } = await import("codemirror-lang-glimmer-js");
658
- return [gjs2().support];
659
- }
660
- },
661
- compiler: async (...args) => {
662
- const hbs2 = await import("./gmd-D9OXs2v3.js");
663
- return hbs2.compiler(...args);
664
- }
665
- };
666
- const js = {
667
- codemirror: {
668
- lang: async () => {
669
- const { javascript } = await import("@codemirror/lang-javascript");
670
- return javascript();
671
- }
672
- },
673
- compiler: async (config, api) => {
674
- return {
675
- compile: async (text, options) => {
676
- return text;
677
- },
678
- render: async (element, fun, extra, compiler) => {
679
- assert(
680
- `js document must have a function for a default export. Instead received: ${typeof fun}`,
681
- typeof fun === "function"
682
- );
683
- await fun(element);
684
- compiler.announce("info", "Done");
685
- }
686
- };
687
- }
688
- };
689
- function isNotMarkdownLike(lang) {
690
- return lang !== "md" && lang !== "gmd" && lang !== "mdx";
691
- }
692
- function isPreview(meta) {
693
- if (!meta) return false;
694
- return meta.includes("preview");
695
- }
696
- function isBelow(meta) {
697
- if (!meta) return false;
698
- return meta.includes("below");
699
- }
700
- function buildCodeFenceMetaUtils(api) {
701
- const allowedFormats = api.getAllowedFormats().filter(isNotMarkdownLike);
702
- function needsLive(lang, flavor) {
703
- if (!allowedFormats.includes(lang)) return false;
704
- return api.optionsFor(lang, flavor).needsLiveMeta ?? true;
705
- }
706
- function getFlavorFromMeta(meta, lang) {
707
- const flavors = api.getFlavorsFor(lang);
708
- const flavor = meta?.trim().split(" ").find((metum) => flavors.includes(metum));
709
- return flavor;
710
- }
711
- function isLive(meta, lang) {
712
- const flavor = getFlavorFromMeta(meta, lang);
713
- if (!needsLive(lang, flavor)) return true;
714
- if (!meta) return false;
715
- return meta.includes("live");
716
- }
717
- return {
718
- isPreview,
719
- isBelow,
720
- isLive,
721
- needsLive,
722
- allowedFormats,
723
- getFlavorFromMeta
724
- };
725
- }
726
- function filterOptions(options) {
727
- if (!isRecord(options)) {
728
- return { remarkPlugins: [], rehypePlugins: [] };
729
- }
730
- return {
731
- remarkPlugins: (
732
- /** @type {Plugin[]}*/
733
- options?.remarkPlugins || []
734
- ),
735
- rehypePlugins: (
736
- /** @type {Plugin[]}*/
737
- options?.rehypePlugins || []
738
- )
739
- };
740
- }
741
- const md = {
742
- codemirror: {
743
- lang: async () => {
744
- const { glimdown } = await import("codemirror-lang-glimdown");
745
- return glimdown();
746
- }
747
- },
748
- compiler: async (config, api) => {
749
- const { isLive, isPreview: isPreview2, needsLive, allowedFormats, isBelow: isBelow2, getFlavorFromMeta } = buildCodeFenceMetaUtils(api);
750
- const userOptions = filterOptions(
751
- /** @type {Record<string, unknown>} */
752
- config.userOptions?.md || config
753
- );
754
- const { parseMarkdown } = await import(
755
- /* @vite-ignore */
756
- "./parse-aBKk9rfS.js"
757
- );
758
- return {
759
- compile: async (text, options) => {
760
- const compileOptions = filterOptions(options);
761
- const result = await parseMarkdown(text, {
762
- remarkPlugins: [...userOptions.remarkPlugins, ...compileOptions.remarkPlugins],
763
- rehypePlugins: [...userOptions.rehypePlugins, ...compileOptions.rehypePlugins],
764
- isLive,
765
- isPreview: isPreview2,
766
- isBelow: isBelow2,
767
- needsLive,
768
- ALLOWED_FORMATS: allowedFormats,
769
- getFlavorFromMeta
770
- });
771
- const escaped = result.text.replace(/`/g, "\\`");
772
- return { compiled: `export default \`${escaped}\``, ...result };
773
- },
774
- render: async (element, compiled, extra, compiler) => {
775
- element.innerHTML = /** @type {string} */
776
- compiled;
777
- const destroyables = [];
778
- await Promise.all(
779
- /** @type {unknown[]} */
780
- extra.codeBlocks.map(async (info) => {
781
- const infoObj = (
782
- /** @type {Record<string, unknown>} */
783
- info
784
- );
785
- if (!api.canCompile(
786
- /** @type {string} */
787
- infoObj.format,
788
- /** @type {string} */
789
- infoObj.flavor
790
- )) {
791
- return;
792
- }
793
- const flavor = (
794
- /** @type {string} */
795
- infoObj.flavor
796
- );
797
- const subRender = await compiler.compile(
798
- /** @type {string} */
799
- infoObj.format,
800
- /** @type {string} */
801
- infoObj.code,
802
- {
803
- ...compiler.optionsFor(
804
- /** @type {string} */
805
- infoObj.format,
806
- flavor
807
- ),
808
- flavor
809
- }
810
- );
811
- const selector = `#${/** @type {string} */
812
- infoObj.placeholderId}`;
813
- const target = element.querySelector(selector);
814
- assert(
815
- `Could not find placeholder / target element (using selector: \`${selector}\`). Could not render ${/** @type {string} */
816
- infoObj.format} block.`,
817
- target
818
- );
819
- destroyables.push(subRender.destroy);
820
- target.appendChild(subRender.element);
821
- })
822
- );
823
- compiler.announce("info", "Done");
824
- return () => {
825
- for (const subDestroy of destroyables) {
826
- subDestroy();
827
- }
828
- };
829
- }
830
- };
831
- }
832
- };
833
- function parseSpecifier(specifier) {
834
- let name = "";
835
- let version = "";
836
- let path = ".";
837
- const chars = specifier.split("");
838
- const hasScope = chars[0] === "@";
839
- let isVersion = false;
840
- let isPath = false;
841
- let finishedName = false;
842
- let slashCount = 0;
843
- for (let i2 = 0; i2 < chars.length; i2++) {
844
- const char = chars[i2];
845
- if (char === "@" && i2 > 0) {
846
- finishedName = true;
847
- isVersion = true;
848
- continue;
849
- } else if (char === "/") {
850
- slashCount++;
851
- if (hasScope) {
852
- if (slashCount > 1) {
853
- finishedName = true;
854
- }
855
- } else {
856
- finishedName = true;
857
- }
858
- if (finishedName) {
859
- isPath = true;
860
- }
861
- }
862
- if (isVersion && char === "/") {
863
- isVersion = false;
864
- isPath = true;
865
- }
866
- if (isVersion) {
867
- version += char;
868
- } else if (isPath) {
869
- path += char;
870
- } else {
871
- name += char;
872
- }
873
- }
874
- return {
875
- name,
876
- version: version || void 0,
877
- path
878
- };
879
- }
880
- function splitSubPath(importPath) {
881
- const parsed = parseSpecifier(importPath);
882
- return [parsed.name, parsed.path === "." ? "" : parsed.path];
883
- }
884
- function esmSh(versions, importPath, allExternal = false) {
885
- const [name, subPath] = splitSubPath(importPath);
886
- const version = versions[name];
887
- const subPathExport = subPath.length === 0 || subPath.startsWith("/") ? subPath : `/${subPath}`;
888
- const externals = allExternal ? "*" : "";
889
- return version ? `https://esm.sh/${externals}${name}@${version}${subPathExport}` : `https://esm.sh/${externals}${name}${subPathExport}`;
890
- }
891
- const esmsh = {
892
- /**
893
- * @param {Record<string, string>} versions
894
- * @param {string} importPath
895
- */
896
- async import(versions, importPath) {
897
- const url = esmSh(versions, importPath);
898
- return await import(
899
- /* @vite-ignore */
900
- url
901
- );
902
- },
903
- /**
904
- * @param {Record<string, string>} versions
905
- * @param {string[]} deps the names of deps to pull from esm.sh
906
- */
907
- async importAll(versions, deps = []) {
908
- return await Promise.all(
909
- deps.map((dep) => {
910
- return esmsh.import(versions, dep);
911
- })
912
- );
913
- }
914
- };
915
- const mermaid = {
916
- needsLiveMeta: false,
917
- codemirror: {
918
- lang: async () => {
919
- const { mermaid: mermaid2 } = await import("codemirror-lang-mermaid");
920
- return mermaid2();
921
- }
922
- },
923
- compiler: async (config, api) => {
924
- const versions = config.versions;
925
- const { default: mermaid2 } = await api.tryResolve("mermaid", () => {
926
- return esmsh.import(versions, "mermaid");
927
- });
928
- let id = 0;
929
- return {
930
- compile: async (text) => {
931
- return `export default \`${text}\`;`;
932
- },
933
- render: async (element, text, _, compiler) => {
934
- const { svg } = await mermaid2.render("graphDiv" + id++, text);
935
- element.innerHTML = svg;
936
- compiler.announce("info", "Done");
937
- }
938
- };
939
- }
940
- };
941
- const jsx = {
942
- codemirror: {
943
- lang: async () => {
944
- const { javascript } = await import("@codemirror/lang-javascript");
945
- return javascript({ jsx: true });
946
- }
947
- },
948
- resolve: (id) => {
949
- switch (id) {
950
- case "react":
951
- return `https://esm.sh/react`;
952
- case "react-dom/client":
953
- return `https://esm.sh/react-dom/client`;
954
- case "@babel/standalone":
955
- return `https://esm.sh/@babel/standalone`;
956
- }
957
- },
958
- compiler: async (config, api) => {
959
- const [reactDom, babel] = await api.tryResolveAll(["react-dom/client", "@babel/standalone"]);
960
- const { createRoot } = reactDom;
961
- return {
962
- async compile(text) {
963
- const result = babel.transform(text, {
964
- filename: `repl.js`,
965
- presets: [babel.availablePresets.react]
966
- });
967
- return result.code;
968
- },
969
- async render(element, component) {
970
- const root = createRoot(element);
971
- await new Promise((resolve2) => requestAnimationFrame(resolve2));
972
- root.render(component);
973
- await new Promise((resolve2) => requestAnimationFrame(resolve2));
974
- }
975
- };
976
- }
977
- };
978
- const svelte = {
979
- codemirror: {
980
- lang: async () => {
981
- const { svelte: svelte2 } = await import("@replit/codemirror-lang-svelte");
982
- return svelte2();
983
- }
984
- },
985
- /**
986
- * Default config, known to work with how the compiler and render functions are configured.
987
- */
988
- resolve: (id) => {
989
- if (["svelte"].some((x) => id.startsWith(x))) {
990
- return esmSh(
991
- {
992
- svelte: "5.35.7"
993
- },
994
- id,
995
- false
996
- ) + // + '?target=esnext';
997
- "?dev&target=esnext&keep-names";
998
- }
999
- if ([
1000
- "zimmerframe",
1001
- "locate-character",
1002
- "acorn",
1003
- "clsx",
1004
- "magic-string",
1005
- "@ampproject/remapping",
1006
- "@jridgewell/sourcemap-codec",
1007
- "axobject-query",
1008
- "esrap",
1009
- "is-reference",
1010
- "aria-query",
1011
- "@sveltejs/acorn-typescript"
1012
- ].some((x) => id.startsWith(x))) {
1013
- return esmSh({}, id, false);
1014
- }
1015
- },
1016
- compiler: async (config, api) => {
1017
- const [svelte2, compiler] = await api.tryResolveAll(["svelte", "svelte/compiler"]);
1018
- return {
1019
- compile: async (text, options) => {
1020
- const output = await compiler.compile(text, {
1021
- /* this errors if unexpected options are passed */
1022
- generate: "client",
1023
- fragments: "html",
1024
- // Placeholder for now until multiple files are supported
1025
- filename: "repl-sdk.svelte",
1026
- dev: true,
1027
- runes: true
1028
- // experimental: {
1029
- // async: true,
1030
- // },
1031
- });
1032
- return { compiled: output.js.code, css: output.css?.code };
1033
- },
1034
- render: async (element, component, { css }) => {
1035
- const div = document.createElement("div");
1036
- if (css) {
1037
- const style = document.createElement("style");
1038
- style.innerHTML = /** @type {string} */
1039
- css;
1040
- element.appendChild(style);
1041
- }
1042
- element.appendChild(div);
1043
- requestAnimationFrame(() => {
1044
- svelte2.mount(component, {
1045
- target: element,
1046
- props: {
1047
- /* no props */
1048
- }
1049
- });
1050
- api.announce("info", "Done");
1051
- });
1052
- }
1053
- };
1054
- }
1055
- };
1056
- const vue = {
1057
- codemirror: {
1058
- lang: async () => {
1059
- const { vue: vue2 } = await import("@codemirror/lang-vue");
1060
- return vue2();
1061
- }
1062
- },
1063
- /**
1064
- * Default config, known to work with how the compiler and render functions are configured.
1065
- */
1066
- resolve: (id) => {
1067
- switch (id) {
1068
- case "vue":
1069
- return `https://cdn.jsdelivr.net/npm/vue@3.5.16/+esm`;
1070
- case "@vue/repl":
1071
- return `https://cdn.jsdelivr.net/npm/@vue/repl@4.5.1/+esm`;
1072
- }
1073
- },
1074
- compiler: async (config, api) => {
1075
- const [{ createApp }, { compileFile, useStore }] = await api.tryResolveAll([
1076
- "vue",
1077
- "@vue/repl"
1078
- ]);
1079
- const store = useStore();
1080
- return {
1081
- compile: async (text, options) => {
1082
- const output = { js: "", css: "", ssr: "" };
1083
- await compileFile(store, {
1084
- code: text,
1085
- filename: options.fileName,
1086
- language: "vue",
1087
- compiled: output
1088
- });
1089
- return { compiled: output.js, css: output.css };
1090
- },
1091
- render: async (element, component, { css }, compiler) => {
1092
- const div = document.createElement("div");
1093
- const style = document.createElement("style");
1094
- style.innerHTML = /** @type {string} */
1095
- css;
1096
- element.appendChild(div);
1097
- element.appendChild(style);
1098
- createApp(component).mount(div);
1099
- compiler.announce("info", "Done");
1100
- }
1101
- };
1102
- }
1103
- };
1104
- const compilers = {
1105
- hbs: {
1106
- /**
1107
- * ember has historically used a subset of HBS, and then built its own features on top of.
1108
- *
1109
- * It is not "handlebars", but does share a lot of similarities.
1110
- * (and these continue in ember's new gjs and gts formats)
1111
- *
1112
- */
1113
- ember: hbs
1114
- },
1115
- /**
1116
- * Markdown, but every code fense can be a live "Island"
1117
- * if `live` is in the codefence's meta tag and the compiler
1118
- * is registered here, or by the user of repl-sdk.
1119
- */
1120
- md,
1121
- /**
1122
- * Glimmer-flavored Markdown.
1123
- *
1124
- * Like the markdow renderer, but the resulting HTML
1125
- * is a Glimmer Component, rather than just plain HTML.
1126
- *
1127
- * https://emberjs.com
1128
- * https://repl.nullvoxpopuli.com
1129
- * https://kolay.nullvoxpopuli.com
1130
- * https://tutorial.glimdown.com
1131
- * https://limber.glimdown.com
1132
- */
1133
- gmd,
1134
- /**
1135
- * Glimmer-Flavored JavaScript
1136
- *
1137
- * https://emberjs.com
1138
- */
1139
- gjs,
1140
- /**
1141
- * TODO:
1142
- * Glimmer-flavored TypeScript
1143
- *
1144
- * https://emberjs.com
1145
- */
1146
- // gts: ember.gts,
1147
- /**
1148
- * Just vanilla JS.
1149
- */
1150
- js,
1151
- /**
1152
- * JSX is too overloaded to treat one way.
1153
- * We need to split this, and then make folks choose which one to use
1154
- * - jsx-react
1155
- * - jsx-vue
1156
- * - jsx-solid
1157
- * - (etc)
1158
- *
1159
- * This means that as a generic compiler, we can't just have jsx support.
1160
- * And in markdown, we'll need to support choosing which flavor of jsx
1161
- * via meta tags on the codefences.
1162
- *
1163
- * For example:
1164
- * ```jsx solid
1165
- * export default <></>;
1166
- * ```
1167
- *
1168
- * or
1169
- * ```jsx react
1170
- * export default <></>;
1171
- * ```
1172
- */
1173
- jsx: {
1174
- /**
1175
- * https://react.dev/
1176
- */
1177
- react: jsx
1178
- /**
1179
- * TODO:
1180
- * https://www.solidjs.com/
1181
- */
1182
- // solid: solid.jsx,
1183
- },
1184
- /**
1185
- * https://mermaid.js.org/
1186
- */
1187
- mermaid,
1188
- /**
1189
- * https://svelte.dev/
1190
- */
1191
- svelte,
1192
- /**
1193
- * https://vuejs.org/
1194
- */
1195
- vue
1196
- };
1197
- const STABLE_REFERENCE = {
1198
- resolve: () => {
1199
- throw new Error(
1200
- `'resolve' not implemented in STABLE_REFERENCE. Has the Compiler been set up correctly?`
1201
- );
1202
- },
1203
- fetch: async () => {
1204
- throw new Error(
1205
- `'fetch' not implemented in STABLE_REFERENCE. Has the Compiler been set up correctly?`
1206
- );
1207
- }
1208
- };
1209
- globalThis.esmsInitOptions = {
1210
- shimMode: true,
1211
- // skip: [`https://esm.sh`, 'https://jspm.dev/', 'https://cdn.jsdelivr.net/'],
1212
- revokeBlobURLs: true,
1213
- // default false
1214
- mapOverrides: true,
1215
- // default false
1216
- /**
1217
- * @param {string} id
1218
- * @param {string} parentUrl
1219
- * @param {(id: string, parentUrl: string) => string} resolve
1220
- * @returns {string}
1221
- */
1222
- resolve: (id, parentUrl, resolve2) => STABLE_REFERENCE.resolve(id, parentUrl, resolve2),
1223
- // NOTE: may need source hook
1224
- // https://github.com/guybedford/es-module-shims?tab=readme-ov-file#source-hook
1225
- //
1226
- /**
1227
- * @param {string} url
1228
- * @param {RequestInit} options
1229
- * @returns {Promise<Response>}
1230
- */
1231
- fetch: (url, options) => STABLE_REFERENCE.fetch(url, options)
1232
- };
1233
- let requestId = 1;
1234
- function requestKey() {
1235
- return `repl-request-${requestId++}`;
1236
- }
1237
- function getTarRequestId({ to, from }) {
1238
- const request = Request.of({ to, from });
1239
- const key = requestKey();
1240
- cache.requestCache.set(key, request);
1241
- return `${unzippedPrefix}/${key}`;
1242
- }
1243
- class Request {
1244
- static get #idCache() {
1245
- return cache.requestCache;
1246
- }
1247
- /**
1248
- * @param {{ to: string, from?: string }} toFrom
1249
- */
1250
- static of({ to, from }) {
1251
- const isRoot = to.match(/^[A-Za-z@]/);
1252
- const fromId = from?.replace(unzippedPrefix + "/", "");
1253
- const request = Request.fromSpecifier(isRoot ? to : `${to}?from=${fromId}`);
1254
- return request;
1255
- }
1256
- /**
1257
- * @param {string} id
1258
- */
1259
- static fromRequestId(id) {
1260
- const request = Request.#idCache.get(id);
1261
- assert(`Could not find request from id:${id}`, request);
1262
- return request;
1263
- }
1264
- /**
1265
- * @param {string} specifier
1266
- */
1267
- static fromSpecifier(specifier) {
1268
- return new Request(specifier);
1269
- }
1270
- /** @type {string} */
1271
- #to;
1272
- /** @type {Request | undefined} */
1273
- #from;
1274
- /**
1275
- * @private
1276
- * @param {string} specifier
1277
- */
1278
- constructor(specifier) {
1279
- const removedPrefix = specifier.replace(unzippedPrefix, "");
1280
- const [full, query] = removedPrefix.split("?");
1281
- this.original = specifier;
1282
- assert(`Invalid specifier: ${specifier}`, full);
1283
- if (full.startsWith(".") || full.startsWith("#")) {
1284
- if (!query) {
1285
- throw new Error(
1286
- `Missing query, ?from for specifier: ${specifier}. From is required for relative and subpath-imports.`
1287
- );
1288
- }
1289
- }
1290
- this.#to = full;
1291
- if (query) {
1292
- const search = new URLSearchParams(query);
1293
- const fromQp = search.get("from");
1294
- assert(`Missing query, ?from for specifier: ${specifier}`, fromQp);
1295
- const from = Request.fromRequestId(fromQp);
1296
- this.#from = from;
1297
- this.name = from.name;
1298
- this.version = from.version;
1299
- } else {
1300
- const parsed = parseSpecifier(full);
1301
- const { name, version = "latest", path } = parsed;
1302
- this.name = name;
1303
- this.version = version.replace(/\.+$/, "");
1304
- this.#to = path;
1305
- }
1306
- }
1307
- get to() {
1308
- return this.#to;
1309
- }
1310
- get from() {
1311
- return this.#from;
1312
- }
1313
- get key() {
1314
- return `__name__/${this.name}[AT:V]${this.version}/__to__/${this.to}`;
1315
- }
1316
- }
1317
- const CONDITIONS = ["repl", "module", "browser", "import", "default", "development"];
1318
- const resolveCache = /* @__PURE__ */ new Map();
1319
- const AT = "___AT___";
1320
- const fakeProtocol = "repl://";
1321
- function resolvePath(start, target) {
1322
- const base = start.replace(/^@([^/]+)\/([^/]+)/, `${AT}$1___$2`);
1323
- const url = new URL(target, fakeProtocol + fakeDomain + base);
1324
- return url.href.replace(fakeProtocol + fakeDomain, "").replace(AT, "@").replace("___", "/").replace(/^\//, "./");
1325
- }
1326
- function resolve(untarred, request) {
1327
- let answer = void 0;
1328
- const key = request.key;
1329
- if (resolveCache.has(key)) {
1330
- return resolveCache.get(key);
1331
- }
1332
- answer ||= fromImports(untarred, request, answer);
1333
- answer ||= fromInternalImport(untarred, request, answer);
1334
- answer ||= fromExportsString(untarred, request, answer);
1335
- answer ||= fromExports(untarred, request, answer);
1336
- answer ||= fromModule(untarred, request, answer);
1337
- answer ||= fromBrowser(untarred, request, answer);
1338
- answer ||= fromMain(untarred, request, answer);
1339
- answer ||= fromIndex(untarred, request, answer);
1340
- answer ||= fromFallback(untarred, request, answer);
1341
- if (answer) {
1342
- resolveCache.set(key, answer);
1343
- }
1344
- return answer;
1345
- }
1346
- function fromInternalImport(untarred, request, answer) {
1347
- if (answer) return answer;
1348
- if (!request.from) return answer;
1349
- const fromSpecifier = request.from;
1350
- const answerFrom = resolve(untarred, fromSpecifier);
1351
- if (!answerFrom) {
1352
- printError(untarred, fromSpecifier, answer);
1353
- return;
1354
- }
1355
- const inTarFile = resolvePath(
1356
- fromSpecifier.name + "/" + answerFrom.inTarFile,
1357
- request.to
1358
- ).replace(new RegExp(`^${fromSpecifier.name}/`), "");
1359
- const result = checkFile(untarred, inTarFile);
1360
- if (result) {
1361
- return createAnswer(result, request, "internalImport");
1362
- }
1363
- printError(untarred, request, answer);
1364
- }
1365
- function fromExports(untarred, request, answer) {
1366
- if (answer) return answer;
1367
- const exports$1 = untarred.manifest.exports;
1368
- if (!(typeof exports$1 === "object")) return answer;
1369
- const foundArray = exports(untarred.manifest, request.to, {
1370
- conditions: CONDITIONS
1371
- });
1372
- const found = foundArray?.map((f) => checkFile(untarred, f)).find(Boolean);
1373
- if (found) {
1374
- return createAnswer(found, request, "exports");
1375
- }
1376
- }
1377
- function fromImports(untarred, request, answer) {
1378
- if (answer) return answer;
1379
- if (!request.to.startsWith("#")) return answer;
1380
- const imports = untarred.manifest.imports;
1381
- if (!(typeof imports === "object")) return answer;
1382
- const found = resolve$2({ content: untarred.manifest }, request.to, {
1383
- conditions: CONDITIONS
1384
- });
1385
- if (found) {
1386
- return createAnswer(found.replace(/^\.\//, ""), request, "imports");
1387
- }
1388
- }
1389
- function fromExportsString(untarred, request, answer) {
1390
- if (answer) return answer;
1391
- if (!hasExports(untarred)) return answer;
1392
- return checkLegacyEntry(untarred, request, "exports");
1393
- }
1394
- function fromModule(untarred, request, answer) {
1395
- if (answer) return answer;
1396
- if (hasExports(untarred)) return answer;
1397
- return checkLegacyEntry(untarred, request, "module");
1398
- }
1399
- function fromBrowser(untarred, request, answer) {
1400
- if (answer) return answer;
1401
- if (hasExports(untarred)) return answer;
1402
- return checkLegacyEntry(untarred, request, "browser");
1403
- }
1404
- function fromMain(untarred, request, answer) {
1405
- if (answer) return answer;
1406
- if (hasExports(untarred)) return answer;
1407
- return checkLegacyEntry(untarred, request, "main");
1408
- }
1409
- function checkLegacyEntry(untarred, request, entryName) {
1410
- if (request.to !== ".") return;
1411
- const filePath = untarred.manifest[
1412
- /** @type {keyof typeof untarred.manifest} */
1413
- entryName
1414
- ];
1415
- if (!filePath || typeof filePath !== "string") return;
1416
- const result = checkFile(untarred, filePath);
1417
- if (result) {
1418
- return createAnswer(result, request, entryName);
1419
- }
1420
- }
1421
- function fromIndex(untarred, request, answer) {
1422
- if (answer) return answer;
1423
- if (hasExports(untarred)) return answer;
1424
- if (request.to === ".") {
1425
- if (untarred.contents["index.js"]) {
1426
- return {
1427
- inTarFile: "index.js",
1428
- ext: "js",
1429
- from: "index"
1430
- };
1431
- }
1432
- }
1433
- }
1434
- function fromFallback(untarred, request, answer) {
1435
- if (answer) return answer;
1436
- const result = checkFile(untarred, request.to);
1437
- if (result) {
1438
- return createAnswer(result, request, "fallback");
1439
- }
1440
- }
1441
- function checkFile(untarred, filePath) {
1442
- if (!filePath) return;
1443
- for (const prefix of ["", "pkg/"]) {
1444
- const path = prefix + filePath;
1445
- const dotless = prefix + filePath.replace(/^\.\//, "");
1446
- if (untarred.contents[path]) {
1447
- return path;
1448
- }
1449
- if (untarred.contents[dotless]) {
1450
- return dotless;
1451
- }
1452
- }
1453
- }
1454
- function extName(filePath) {
1455
- return filePath.split(".").pop();
1456
- }
1457
- function hasExports(untarred) {
1458
- return Boolean(untarred.manifest.exports);
1459
- }
1460
- function createAnswer(forFile, request, fromMethod) {
1461
- const ext = extName(forFile);
1462
- assert(
1463
- `All files must have an extension. This file (in ${request.name}) did not have an extension: ${forFile}`,
1464
- ext
1465
- );
1466
- return {
1467
- inTarFile: forFile,
1468
- ext,
1469
- from: fromMethod
1470
- };
1471
- }
1472
- function printError(untarred, request, answer) {
1473
- const { name, exports: exports2, main, module, browser } = untarred.manifest;
1474
- console.group(`${name} file info`);
1475
- console.info(`${name} has these files: `, Object.keys(untarred.contents));
1476
- console.info(`We searched for '${request.original}'`);
1477
- console.info(`from: `, { exports: exports2, main, module, browser });
1478
- console.info(`And found: `, answer);
1479
- console.info(`The request was: `, request);
1480
- console.groupEnd();
1481
- debugger;
1482
- throw new Error(`Could not find file for ${request.original}`);
1483
- }
1484
- const worker = new Worker(new URL(
1485
- /* @vite-ignore */
1486
- "/assets/tar-worker-kdkltuRC.js",
1487
- import.meta.url
1488
- ), {
1489
- name: "Tar & NPM Downloader Worker",
1490
- type: "module"
1491
- });
1492
- const com = wrap(worker);
1493
- async function getFromTarball(url) {
1494
- const key = url.replace(unzippedPrefix + "/", "");
1495
- const request = cache.requestCache.get(key);
1496
- assert(`Missing request for ${url}`, request);
1497
- if (cache.fileCache.has(key)) {
1498
- return cache.fileCache.get(key);
1499
- }
1500
- const data = await cache.cachedPromise(key, async () => {
1501
- const untarred2 = await com.getTar(request.name, request.version);
1502
- const answer = resolve(untarred2, request);
1503
- if (!answer) {
1504
- throw new Error(`Could not find file for ${request.original}`);
1505
- }
1506
- return { answer, name: request.name, version: request.version };
1507
- });
1508
- const untarred = await com.getTar(request.name, request.version);
1509
- const result = getFile(untarred, key, data.answer);
1510
- assert(`Missing file for ${url}`, result);
1511
- cache.fileCache.set(key, result);
1512
- return result;
1513
- }
1514
- function getFile(untarred, key, answer) {
1515
- const request = Request.fromRequestId(key);
1516
- if (!answer) {
1517
- printError(untarred, request, answer);
1518
- return;
1519
- }
1520
- const { inTarFile, ext } = answer;
1521
- const code = untarred.contents[inTarFile]?.text;
1522
- if (!code) {
1523
- printError(untarred, request, answer);
1524
- return;
1525
- }
1526
- return { code, ext };
1527
- }
1528
- assert(`There is no document. repl-sdk is meant to be ran in a browser`, globalThis.document);
1529
- const defaultFormats = Object.keys(compilers);
1530
- const defaults = {
1531
- formats: compilers
1532
- };
1533
- class Compiler {
1534
- /** @type {Options} */
1535
- #options;
1536
- /**
1537
- * Options may be passed to the compiler to add to its behavior.
1538
- * @param {Partial<Options>} options
1539
- */
1540
- constructor(options = defaults) {
1541
- this.#options = Object.assign({}, defaults, options);
1542
- STABLE_REFERENCE.resolve = this.#resolve;
1543
- STABLE_REFERENCE.fetch = this.#fetch;
1544
- window.addEventListener("unhandledrejection", this.#handleUnhandledRejection);
1545
- }
1546
- /**
1547
- *
1548
- * @param {HTMLElement} element
1549
- * @param {any} options
1550
- */
1551
- async createEditor(element, { text, format, handleUpdate, extensions }) {
1552
- return cache.cachedPromise("codemirror", async () => {
1553
- const { buildCodemirror } = await import("./codemirror-D4aIVflZ.js");
1554
- return buildCodemirror({
1555
- element,
1556
- text,
1557
- format,
1558
- extensions,
1559
- handleUpdate,
1560
- getLang: async (format2) => {
1561
- const [lang, flavor] = format2.split("|");
1562
- assert(`Could not determine 'lang' from format: ${format2}`, lang);
1563
- const compiler = this.#resolveFormat(lang, flavor);
1564
- const loadLang = compiler.codemirror?.lang;
1565
- assert(
1566
- `The compiler for '${format2}' is missing its configuration for 'codemirror.lang'`,
1567
- loadLang
1568
- );
1569
- return await loadLang();
1570
- },
1571
- getSupport: async (format2) => {
1572
- const [lang, flavor] = format2.split("|");
1573
- assert(`Could not determine 'lang' from format: ${format2}`, lang);
1574
- const compiler = this.#resolveFormat(lang, flavor);
1575
- const loadSupport = compiler.codemirror.support;
1576
- return await loadSupport?.();
1577
- }
1578
- });
1579
- });
1580
- }
1581
- /**
1582
- * @param {PromiseRejectionEvent} e
1583
- */
1584
- #handleUnhandledRejection = (e) => {
1585
- let handled = false;
1586
- for (const onUnhandled2 of this.#compilerOnUnhandled) {
1587
- onUnhandled2(e, (message) => {
1588
- this.#announce("error", message);
1589
- handled = true;
1590
- });
1591
- if (handled) break;
1592
- }
1593
- if (handled) return;
1594
- this.#announce("error", e.reason);
1595
- };
1596
- /**
1597
- * Order of preference
1598
- * 1. manually resolved (from the caller)
1599
- * 2. specified in the compiler config (to use CDN)
1600
- * 3. download tarball from npm
1601
- * or resolve from already downloaded tarball
1602
- *
1603
- * NOTE: when we return a new URL, we want to collapse the parentURI
1604
- * so that we don't get compound query params in nested requests.
1605
- *
1606
- * @param {string} id
1607
- * @param {string} parentUrl
1608
- * @param {(id: string, parentUrl: string) => string} resolve
1609
- * @returns {string}
1610
- */
1611
- #resolve = (id, parentUrl, resolve2) => {
1612
- const vanilla = deCDN(id);
1613
- this.#announce("info", `Loading ${vanilla}`);
1614
- this.#log("[resolve]", id, "from", parentUrl);
1615
- if (this.#options.resolve?.[vanilla]) {
1616
- this.#log(`[resolve] ${vanilla} found in manually specified resolver`);
1617
- return `manual:${vanilla}`;
1618
- }
1619
- for (const compilerResolve of this.#compilerResolvers) {
1620
- const result = compilerResolve(vanilla);
1621
- if (result) {
1622
- this.#log(`[resolve] ${vanilla} found in compiler config at ${result}.`);
1623
- if (typeof result === "function") {
1624
- return `configured:${vanilla}`;
1625
- }
1626
- return result;
1627
- }
1628
- }
1629
- if (parentUrl.startsWith(tgzPrefix) && (id.startsWith(".") || id.startsWith("#"))) {
1630
- const answer = getTarRequestId({ to: id, from: parentUrl });
1631
- return answer;
1632
- }
1633
- if (id.startsWith("https://")) return resolve2(id, parentUrl);
1634
- if (id.startsWith("blob:")) return resolve2(id, parentUrl);
1635
- if (id.startsWith(".")) return resolve2(id, parentUrl);
1636
- if (parentUrl.startsWith("https://") && parentUrl !== location.href)
1637
- return resolve2(id, parentUrl);
1638
- if (parentUrl.startsWith("https://") && parentUrl.startsWith("/"))
1639
- return resolve2(id, parentUrl);
1640
- if (id.startsWith("node:")) {
1641
- this.#log(`Is known node module: ${id}. Grabbing polyfill`);
1642
- if (id === "node:process") return prefix_tgz(`process`);
1643
- if (id === "node:buffer") return prefix_tgz(`buffer`);
1644
- if (id === "node:events") return prefix_tgz(`events`);
1645
- if (id === "node:path") return prefix_tgz(`path-browser`);
1646
- if (id === "node:util") return prefix_tgz(`util-browser`);
1647
- if (id === "node:crypto") return prefix_tgz(`crypto-browserify`);
1648
- if (id === "node:stream") return prefix_tgz(`stream-browserify`);
1649
- if (id === "node:fs") return prefix_tgz(`browserify-fs`);
1650
- }
1651
- this.#log(`[resolve] ${id} not found, deferring to npmjs.com's provided tarball`);
1652
- return getTarRequestId({ to: id, from: parentUrl });
1653
- };
1654
- /**
1655
- * @param {string} url
1656
- * @param {RequestInit} options
1657
- * @returns {Promise<Response>}
1658
- */
1659
- #fetch = async (url, options) => {
1660
- const mimeType = mime.getType(url) ?? "application/javascript";
1661
- this.#log(`[fetch] attempting to fetch: ${url}. Assuming ${mimeType}`);
1662
- if (url.startsWith("manual:")) {
1663
- const name = url.replace(/^manual:/, "");
1664
- this.#log("[fetch] resolved url in manually specified resolver", url);
1665
- const result = await this.#resolveManually(name);
1666
- assert(`Failed to resolve ${name}`, result);
1667
- const blobContent = `const mod = window[Symbol.for('${secretKey}')].resolves?.['${name}'];
1668
-
1669
-
1670
- if (!mod) { throw new Error('Could not resolve \`${name}\`. Does the module exist? ( checked ${url} )') }
1671
-
1672
- ${Object.keys(result).map((exportName) => {
1673
- if (exportName === "default") {
1674
- return `export default mod.default ?? mod;`;
1675
- }
1676
- return `export const ${exportName} = mod.${exportName};`;
1677
- }).join("\n")}
1678
- `;
1679
- const blob = new Blob(Array.from(blobContent), { type: mimeType });
1680
- this.#log(
1681
- `[fetch] returning blob mapping to manually resolved import for ${name}`
1682
- // blobContent
1683
- );
1684
- this.#announce("info", `Loaded ${name}`);
1685
- return new Response(blob);
1686
- }
1687
- if (url.startsWith("configured:")) {
1688
- const name = url.replace(/^configured:/, "");
1689
- this.#log(
1690
- "[fetch] resolved url in a preconfigured (in the compiler config) specified resolver",
1691
- url
1692
- );
1693
- let result;
1694
- for (const compilerResolve of this.#compilerResolvers) {
1695
- const fn = compilerResolve(name);
1696
- if (fn) {
1697
- this.#log(`[fetch] ${name} found in compiler config at ${result}.`);
1698
- result = await fn();
1699
- }
1700
- }
1701
- assert(`Failed to resolve ${name}`, result);
1702
- cache.resolves[name] = result;
1703
- const blobContent = `const mod = window[Symbol.for('${secretKey}')].resolves?.['${name}'];
1704
-
1705
-
1706
- if (!mod) { throw new Error('Could not resolve \`${name}\`. Does the module exist? ( checked ${url} )') }
1707
-
1708
- ${Object.keys(result).map((exportName) => {
1709
- if (exportName === "default") {
1710
- return `export default mod.default ?? mod;`;
1711
- }
1712
- return `export const ${exportName} = mod.${exportName};`;
1713
- }).join("\n")}
1714
- `;
1715
- const blob = new Blob(Array.from(blobContent), { type: mimeType });
1716
- this.#log(
1717
- `[fetch] returning blob mapping to configured resolved import for ${name}`
1718
- // blobContent
1719
- );
1720
- this.#announce("info", `Loaded ${name}`);
1721
- return new Response(blob);
1722
- }
1723
- if (url.startsWith(unzippedPrefix)) {
1724
- this.#log("[fetch] resolved url via tgz resolver", url, options);
1725
- const tarInfo = await getFromTarball(url);
1726
- assert(`Could not find file for ${url}`, tarInfo);
1727
- const { code, ext } = tarInfo;
1728
- const file = await this.#postProcess(code, ext);
1729
- const type = mime.getType(ext);
1730
- return new Response(new Blob([file], { type: type ?? "application/javascript" }));
1731
- }
1732
- if (url.startsWith("https://")) {
1733
- return fetch(url, options);
1734
- }
1735
- this.#log("[fetch] fetching url", url, options);
1736
- const response = await fetch(url, options);
1737
- if (!response.ok) return response;
1738
- const source = await response.text();
1739
- this.#announce("info", `Loaded ${url}`);
1740
- return new Response(new Blob([source], { type: "application/javascript" }));
1741
- };
1742
- /**
1743
- * NOTE: this does not resolve compilers that are not loaded yet.
1744
- * So there would be a bit of a race condition here if different compilers
1745
- * were to have incompatible post-processing handlers.
1746
- *
1747
- * @param {string} text
1748
- * @param {string} ext
1749
- */
1750
- async #postProcess(text, ext) {
1751
- let code = text;
1752
- for (const compiler of this.#compilers) {
1753
- if (compiler.handlers?.[ext]) {
1754
- code = await compiler.handlers[ext](code);
1755
- }
1756
- }
1757
- return code;
1758
- }
1759
- /**
1760
- * @param {string} format
1761
- * @param {string} text
1762
- * @param {{ fileName?: string, flavor?: string, [key: string]: unknown }} [ options ]
1763
- * @returns {Promise<{ element: HTMLElement, destroy: () => void }>}
1764
- */
1765
- async compile(format, text, options = {}) {
1766
- this.#announce("info", `Compiling ${format}`);
1767
- try {
1768
- return await this.#compile(format, text, options);
1769
- } catch (e) {
1770
- const message = e instanceof Error ? e.message : e;
1771
- this.#announce("error", String(message));
1772
- this.#error(e);
1773
- throw e;
1774
- }
1775
- }
1776
- /**
1777
- * @param {string} format
1778
- * @param {string} text
1779
- * @param {{ fileName?: string, flavor?: string, [key: string]: unknown }} [ options ]
1780
- * @returns {Promise<{ element: HTMLElement, destroy: () => void }>}
1781
- */
1782
- async #compile(format, text, options) {
1783
- this.#log("[compile] idempotently installing es-module-shim");
1784
- await import("es-module-shims");
1785
- const opts = { ...options };
1786
- opts.fileName ||= `dynamic.${format}`;
1787
- this.#log("[compile] compiling");
1788
- const compiler = await this.#getCompiler(format, opts.flavor);
1789
- const compiled = await compiler.compile(text, opts);
1790
- let compiledText = 'export default "failed to compile"';
1791
- let extras = { compiled: "" };
1792
- if (typeof compiled === "string") {
1793
- compiledText = compiled;
1794
- extras = { compiled: compiledText };
1795
- } else if (typeof compiled.compiled === "string") {
1796
- const { compiled: text2 } = compiled;
1797
- compiledText = text2;
1798
- extras = compiled;
1799
- } else {
1800
- let value = compiled;
1801
- if ("compiled" in compiled) {
1802
- value = compiled.compiled;
1803
- extras = compiled;
1804
- }
1805
- return this.#render(compiler, value, {
1806
- ...extras,
1807
- compiled: value
1808
- });
1809
- }
1810
- const asBlobUrl = textToBlobUrl(compiledText);
1811
- const { default: defaultExport } = await shimmedImport(
1812
- /* @vite-ignore */
1813
- asBlobUrl
1814
- );
1815
- this.#log("[compile] preparing to render", defaultExport, extras);
1816
- return this.#render(compiler, defaultExport, extras);
1817
- }
1818
- #compilerCache = /* @__PURE__ */ new WeakMap();
1819
- #compilers = /* @__PURE__ */ new Set();
1820
- #compilerResolvers = /* @__PURE__ */ new Set();
1821
- /**
1822
- * @type {Set<(e: PromiseRejectionEvent, handle: (message: string) => void) => void>}
1823
- */
1824
- #compilerOnUnhandled = /* @__PURE__ */ new Set();
1825
- /**
1826
- * @param {string} format
1827
- * @param {string | undefined} flavor
1828
- */
1829
- async #getCompiler(format, flavor) {
1830
- const config = this.#resolveFormat(format, flavor);
1831
- if (this.#compilerCache.has(config)) {
1832
- return this.#compilerCache.get(config);
1833
- }
1834
- if (config.resolve) {
1835
- this.#compilerResolvers.add(config.resolve);
1836
- }
1837
- if (config.onUnhandled) {
1838
- this.#compilerOnUnhandled.add(config.onUnhandled);
1839
- }
1840
- const options = this.optionsFor(format, flavor);
1841
- const compiler = await config.compiler(options, this.#nestedPublicAPI);
1842
- this.#compilerCache.set(config, compiler);
1843
- this.#compilers.add(compiler);
1844
- return compiler;
1845
- }
1846
- /**
1847
- * @param {string} format
1848
- * @param {string | undefined} flavor
1849
- * @returns {import('./types').CompilerConfig}
1850
- */
1851
- #resolveFormat(format, flavor) {
1852
- let config = this.#options.formats[format];
1853
- assert(
1854
- `${format} is not a configured format / extension. The currently configured formats are ${Object.keys(this.#options.formats).join(", ")}`,
1855
- config
1856
- );
1857
- if (flavor && flavor in config) {
1858
- config = /** @type {{ [flavor: string]: CompilerConfig}} */
1859
- config[flavor];
1860
- }
1861
- assert(
1862
- `The config for ${format}${flavor ? ` (using flavor ${flavor})` : ""} is missing the 'compiler' function. It had keys: ${Object.keys(
1863
- /** @type {any} */
1864
- config
1865
- )}. If this is a language with multiple flavors, make sure you specify the flavor.`,
1866
- "compiler" in /** @type {any} */
1867
- config
1868
- );
1869
- return (
1870
- /** @type {import('./types').CompilerConfig} */
1871
- config
1872
- );
1873
- }
1874
- /**
1875
- * @param {string} format
1876
- * @param {string | undefined} flavor
1877
- * @returns {{ [key: string]: unknown }}
1878
- */
1879
- #resolveUserOptions(format, flavor) {
1880
- let config = (
1881
- /** @type {{ [key: string]: unknown }} */
1882
- this.#options.options?.[format]
1883
- );
1884
- if (!config) return {};
1885
- if (flavor && flavor in config) {
1886
- config = /** @type {{ [key: string]: unknown }} */
1887
- config[flavor];
1888
- }
1889
- return config ?? {};
1890
- }
1891
- /**
1892
- * @param {import('./types.ts').Compiler} compiler
1893
- * @param {string} whatToRender
1894
- * @param {{ compiled: string } & Record<string, unknown>} extras
1895
- * @returns {Promise<{ element: HTMLElement, destroy: () => void }>}
1896
- */
1897
- async #render(compiler, whatToRender, extras) {
1898
- this.#announce("info", "Rendering");
1899
- const div = this.#createDiv();
1900
- assert(`Cannot render falsey values. Did compilation succeed?`, whatToRender);
1901
- const destroy = await compiler.render(div, whatToRender, extras, this.#nestedPublicAPI);
1902
- await new Promise((resolve2) => requestAnimationFrame(resolve2));
1903
- return {
1904
- element: div,
1905
- destroy: () => {
1906
- if (destroy) {
1907
- return destroy();
1908
- }
1909
- }
1910
- };
1911
- }
1912
- /**
1913
- * @param {string} format
1914
- * @param {string | undefined} flavor
1915
- */
1916
- optionsFor = (format, flavor) => {
1917
- const { needsLiveMeta } = this.#resolveFormat(format, flavor);
1918
- return {
1919
- needsLiveMeta: (
1920
- /* @type {boolean | undefined} */
1921
- needsLiveMeta ?? true
1922
- ),
1923
- versions: this.#options.versions ?? {},
1924
- ...this.#resolveUserOptions(format, flavor) ?? {}
1925
- };
1926
- };
1927
- static clearCache() {
1928
- cache.clear();
1929
- }
1930
- /**
1931
- * @param {string} name
1932
- * @param {(name?: string) => Promise<undefined | object>} [fallback]
1933
- * @returns {Promise<undefined | object>}
1934
- */
1935
- #resolveManually = async (name, fallback) => {
1936
- const existing = cache.resolves[name];
1937
- if (existing) {
1938
- this.#log("[#resolveManually]", name, "already resolved");
1939
- return existing;
1940
- }
1941
- let result = (
1942
- /** @type {object | undefined} */
1943
- await this.#options.resolve?.[name]
1944
- );
1945
- if (!result) {
1946
- this.#log(`[#resolveManually] Could not resolve ${name}`);
1947
- }
1948
- if (typeof result === "function") {
1949
- if (!result) {
1950
- this.#log(`[#resolveManually] Value for ${name} is a function. Invoking.`);
1951
- }
1952
- result = await result();
1953
- }
1954
- if (fallback) {
1955
- result = await fallback(name);
1956
- }
1957
- cache.resolves[name] ||= await result;
1958
- return result;
1959
- };
1960
- /**
1961
- * @type {import('./types.ts').PublicMethods}
1962
- */
1963
- #nestedPublicAPI = {
1964
- /**
1965
- * @param {'error' | 'info'} type
1966
- * @param {string} message
1967
- * @returns {void}
1968
- */
1969
- announce: (type, message) => this.#announce(type, message),
1970
- /**
1971
- * @param {string} name
1972
- * @param {(name?: string) => Promise<object | undefined>} [fallback]
1973
- * @returns {Promise<object | undefined>}
1974
- */
1975
- tryResolve: async (name, fallback) => {
1976
- const existing = await this.#resolveManually(name, fallback);
1977
- if (existing) {
1978
- this.#log(name, "already resolved");
1979
- return existing;
1980
- }
1981
- const shimmed = await shimmedImport(
1982
- /* vite-ignore */
1983
- name
1984
- );
1985
- return shimmed;
1986
- },
1987
- /**
1988
- * @param {string[]} names
1989
- * @param {(name?: string) => Promise<unknown>} [fallback]
1990
- * @returns {Promise<unknown[]>}
1991
- */
1992
- tryResolveAll: async (names, fallback) => {
1993
- const results = await Promise.all(
1994
- names.map((name) => {
1995
- return this.#nestedPublicAPI.tryResolve(name);
1996
- })
1997
- );
1998
- if (fallback) {
1999
- const morePromises = {};
2000
- for (let i2 = 0; i2 < results.length; i2++) {
2001
- const result = results[i2];
2002
- const name = names[i2];
2003
- if (!result) {
2004
- this.#warn(`Could not load ${name}. Trying fallback.`);
2005
- morePromises[i2] = fallback(name);
2006
- }
2007
- }
2008
- await Promise.all(Object.values(morePromises));
2009
- for (let i2 = 0; i2 < results.length; i2++) {
2010
- results[i2];
2011
- }
2012
- }
2013
- return results;
2014
- },
2015
- /**
2016
- * @param {Parameters<Compiler['compile']>} args
2017
- */
2018
- compile: (...args) => this.compile(...args),
2019
- /**
2020
- * @param {Parameters<Compiler['optionsFor']>} args
2021
- */
2022
- optionsFor: (...args) => this.optionsFor(...args),
2023
- canCompile: (format, flavor) => {
2024
- let config = this.#options.formats[format];
2025
- if (!config) {
2026
- return {
2027
- result: false,
2028
- reason: `${format} is not a configured format / extension. The currently configured formats are ${Object.keys(this.#options.formats).join(", ")}`
2029
- };
2030
- }
2031
- if (flavor && flavor in config) {
2032
- config = /** @type {{ [flavor: string]: CompilerConfig}} */
2033
- config[flavor];
2034
- }
2035
- if (!config) {
2036
- return {
2037
- result: false,
2038
- reason: `${format} for ${flavor} is not a configured format / extension. The currently configured formats are ${Object.keys(this.#options.formats).join(", ")}`
2039
- };
2040
- }
2041
- if ("compiler" in config) {
2042
- return { result: true };
2043
- }
2044
- return {
2045
- result: false,
2046
- reason: `The config for ${format}${flavor ? ` (using flavor ${flavor})` : ""} is missing the 'compiler' function. It had keys: ${Object.keys(config)}. If this is a language with multiple flavors, make sure you specify the flavor.`
2047
- };
2048
- },
2049
- getCompiler: (format, flavor) => this.#getCompiler(format, flavor),
2050
- getAllowedFormats: () => Object.keys(this.#options.formats),
2051
- getFlavorsFor: (format) => {
2052
- const config = this.#options.formats[format];
2053
- if (!config) return [];
2054
- if (typeof config === "function") return [];
2055
- if (typeof config === "object") {
2056
- return Object.keys(config);
2057
- }
2058
- return [];
2059
- }
2060
- };
2061
- #createDiv() {
2062
- const div = document.createElement("div");
2063
- div.setAttribute("data-repl-output", "");
2064
- div.id = nextId();
2065
- return div;
2066
- }
2067
- /**
2068
- * @param {'error' | 'info'} type
2069
- * @param {string} message
2070
- */
2071
- #announce(type, message) {
2072
- if (!this.#options?.on?.log) return;
2073
- this.#options.on.log(type, message);
2074
- }
2075
- /**
2076
- * @param {Parameters<typeof console.debug>} args
2077
- */
2078
- #log(...args) {
2079
- if (this.#options.logging) {
2080
- console.debug(...args);
2081
- }
2082
- }
2083
- /**
2084
- * @param {Parameters<typeof console.warn>} args
2085
- */
2086
- #warn(...args) {
2087
- if (this.#options.logging) {
2088
- console.warn(...args);
2089
- }
2090
- }
2091
- /**
2092
- * @param {Parameters<typeof console.error>} args
2093
- */
2094
- #error(...args) {
2095
- if (this.#options.logging) {
2096
- console.error(...args);
2097
- }
2098
- }
2099
- /**
2100
- * @param {string} message
2101
- */
2102
- announceError(message) {
2103
- this.#announce("error", message);
2104
- }
2105
- }
2106
- function textToBlobUrl(text) {
2107
- const blob = new Blob([text], { type: "text/javascript" });
2108
- const blobUrl = URL.createObjectURL(blob);
2109
- return blobUrl;
2110
- }
2111
- function shimmedImport(...args) {
2112
- if (!globalThis.importShim) {
2113
- throw new Error(`Could not find importShim. Has the REPL been set up correctly?`);
2114
- }
2115
- return globalThis.importShim(...args);
2116
- }
2117
- function deCDN(id) {
2118
- const noQPs = id.split("?")[0];
2119
- return (
2120
- /** @type {string} */
2121
- noQPs
2122
- );
2123
- }
2124
- export {
2125
- Compiler as C,
2126
- assert as a,
2127
- buildCodeFenceMetaUtils as b,
2128
- defaults as c,
2129
- defaultFormats as d,
2130
- isRecord as i,
2131
- nextId as n
2132
- };
2133
- //# sourceMappingURL=index-CUWCqMoD.js.map