@loaders.gl/schema 4.4.0-alpha.2 → 4.4.0-alpha.9

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/dist/dist.dev.js CHANGED
@@ -6,14 +6,14 @@
6
6
  else root['loaders'] = factory();})(globalThis, function () {
7
7
  "use strict";
8
8
  var __exports__ = (() => {
9
- var __create = Object.create;
10
9
  var __defProp = Object.defineProperty;
11
10
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
11
  var __getOwnPropNames = Object.getOwnPropertyNames;
13
- var __getProtoOf = Object.getPrototypeOf;
14
12
  var __hasOwnProp = Object.prototype.hasOwnProperty;
15
- var __commonJS = (cb, mod) => function __require() {
16
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
17
  };
18
18
  var __copyProps = (to, from, except, desc) => {
19
19
  if (from && typeof from === "object" || typeof from === "function") {
@@ -23,27 +23,3760 @@ var __exports__ = (() => {
23
23
  }
24
24
  return to;
25
25
  };
26
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
27
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
- // If the importer is in node compatibility mode or this is not an ESM
29
- // file that has been converted to a CommonJS file using a Babel-
30
- // compatible transform (i.e. "__esModule" has not been set), then set
31
- // "default" to the CommonJS "module.exports" for node compatibility.
32
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
- mod
34
- ));
35
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var __publicField = (obj, key, value) => {
28
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
29
+ return value;
30
+ };
31
+
32
+ // bundle.ts
33
+ var bundle_exports = {};
34
+ __export(bundle_exports, {
35
+ FetchError: () => FetchError,
36
+ JSONLoader: () => JSONLoader,
37
+ NullLoader: () => NullLoader,
38
+ NullWorkerLoader: () => NullWorkerLoader,
39
+ RequestScheduler: () => RequestScheduler,
40
+ _BrowserFileSystem: () => BrowserFileSystem,
41
+ _fetchProgress: () => fetchProgress,
42
+ _selectSource: () => selectSource2,
43
+ _unregisterLoaders: () => _unregisterLoaders,
44
+ assert: () => assert,
45
+ concatenateArrayBuffersAsync: () => concatenateArrayBuffersAsync,
46
+ createDataSource: () => createDataSource,
47
+ document: () => document_,
48
+ encode: () => encode,
49
+ encodeInBatches: () => encodeInBatches,
50
+ encodeSync: () => encodeSync,
51
+ encodeTable: () => encodeTable,
52
+ encodeTableAsText: () => encodeTableAsText,
53
+ encodeTableInBatches: () => encodeTableInBatches,
54
+ encodeText: () => encodeText,
55
+ encodeTextSync: () => encodeTextSync,
56
+ encodeURLtoURL: () => encodeURLtoURL,
57
+ fetchFile: () => fetchFile,
58
+ forEach: () => forEach,
59
+ getLoaderOptions: () => getGlobalLoaderOptions,
60
+ getPathPrefix: () => getPathPrefix,
61
+ global: () => global_,
62
+ isAsyncIterable: () => isAsyncIterable,
63
+ isBrowser: () => isBrowser,
64
+ isIterable: () => isIterable,
65
+ isIterator: () => isIterator,
66
+ isPromise: () => isPromise,
67
+ isPureObject: () => isPureObject,
68
+ isReadableStream: () => isReadableStream,
69
+ isResponse: () => isResponse,
70
+ isWorker: () => isWorker,
71
+ isWritableStream: () => isWritableStream,
72
+ load: () => load,
73
+ loadInBatches: () => loadInBatches,
74
+ makeIterator: () => makeIterator,
75
+ makeLineIterator: () => makeLineIterator,
76
+ makeNumberedLineIterator: () => makeNumberedLineIterator,
77
+ makeStream: () => makeStream,
78
+ makeTextDecoderIterator: () => makeTextDecoderIterator,
79
+ makeTextEncoderIterator: () => makeTextEncoderIterator,
80
+ parse: () => parse,
81
+ parseInBatches: () => parseInBatches,
82
+ parseSync: () => parseSync,
83
+ readArrayBuffer: () => readArrayBuffer,
84
+ registerLoaders: () => registerLoaders,
85
+ resolvePath: () => resolvePath,
86
+ selectLoader: () => selectLoader,
87
+ selectLoaderSync: () => selectLoaderSync,
88
+ self: () => self_,
89
+ setLoaderOptions: () => setGlobalOptions,
90
+ setPathPrefix: () => setPathPrefix,
91
+ window: () => window_
92
+ });
93
+
94
+ // ../loader-utils/src/lib/env-utils/assert.ts
95
+ function assert(condition, message) {
96
+ if (!condition) {
97
+ throw new Error(message || "loader assertion failed.");
98
+ }
99
+ }
100
+
101
+ // ../loader-utils/src/lib/env-utils/globals.ts
102
+ var globals = {
103
+ self: typeof self !== "undefined" && self,
104
+ window: typeof window !== "undefined" && window,
105
+ global: typeof global !== "undefined" && global,
106
+ document: typeof document !== "undefined" && document
107
+ };
108
+ var self_ = globals.self || globals.window || globals.global || {};
109
+ var window_ = globals.window || globals.self || globals.global || {};
110
+ var global_ = globals.global || globals.self || globals.window || {};
111
+ var document_ = globals.document || {};
112
+ var isBrowser = (
113
+ // @ts-ignore process does not exist on browser
114
+ Boolean(typeof process !== "object" || String(process) !== "[object process]" || process.browser)
115
+ );
116
+ var isWorker = typeof importScripts === "function";
117
+ var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
118
+ var nodeVersion = matches && parseFloat(matches[1]) || 0;
119
+
120
+ // ../../node_modules/@probe.gl/env/dist/lib/globals.js
121
+ var window_2 = globalThis;
122
+ var document_2 = globalThis.document || {};
123
+ var process_ = globalThis.process || {};
124
+ var console_ = globalThis.console;
125
+ var navigator_ = globalThis.navigator || {};
126
+
127
+ // ../../node_modules/@probe.gl/env/dist/lib/is-electron.js
128
+ function isElectron(mockUserAgent) {
129
+ if (typeof window !== "undefined" && window.process?.type === "renderer") {
130
+ return true;
131
+ }
132
+ if (typeof process !== "undefined" && Boolean(process.versions?.["electron"])) {
133
+ return true;
134
+ }
135
+ const realUserAgent = typeof navigator !== "undefined" && navigator.userAgent;
136
+ const userAgent = mockUserAgent || realUserAgent;
137
+ return Boolean(userAgent && userAgent.indexOf("Electron") >= 0);
138
+ }
139
+
140
+ // ../../node_modules/@probe.gl/env/dist/lib/is-browser.js
141
+ function isBrowser2() {
142
+ const isNode = (
143
+ // @ts-expect-error
144
+ typeof process === "object" && String(process) === "[object process]" && !process?.browser
145
+ );
146
+ return !isNode || isElectron();
147
+ }
148
+
149
+ // ../../node_modules/@probe.gl/env/dist/index.js
150
+ var VERSION = true ? "4.0.7" : "untranspiled source";
151
+
152
+ // ../../node_modules/@probe.gl/log/dist/utils/local-storage.js
153
+ function getStorage(type) {
154
+ try {
155
+ const storage = window[type];
156
+ const x = "__storage_test__";
157
+ storage.setItem(x, x);
158
+ storage.removeItem(x);
159
+ return storage;
160
+ } catch (e) {
161
+ return null;
162
+ }
163
+ }
164
+ var LocalStorage = class {
165
+ constructor(id, defaultConfig, type = "sessionStorage") {
166
+ this.storage = getStorage(type);
167
+ this.id = id;
168
+ this.config = defaultConfig;
169
+ this._loadConfiguration();
170
+ }
171
+ getConfiguration() {
172
+ return this.config;
173
+ }
174
+ setConfiguration(configuration) {
175
+ Object.assign(this.config, configuration);
176
+ if (this.storage) {
177
+ const serialized = JSON.stringify(this.config);
178
+ this.storage.setItem(this.id, serialized);
179
+ }
180
+ }
181
+ // Get config from persistent store, if available
182
+ _loadConfiguration() {
183
+ let configuration = {};
184
+ if (this.storage) {
185
+ const serializedConfiguration = this.storage.getItem(this.id);
186
+ configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
187
+ }
188
+ Object.assign(this.config, configuration);
189
+ return this;
190
+ }
191
+ };
192
+
193
+ // ../../node_modules/@probe.gl/log/dist/utils/formatters.js
194
+ function formatTime(ms) {
195
+ let formatted;
196
+ if (ms < 10) {
197
+ formatted = `${ms.toFixed(2)}ms`;
198
+ } else if (ms < 100) {
199
+ formatted = `${ms.toFixed(1)}ms`;
200
+ } else if (ms < 1e3) {
201
+ formatted = `${ms.toFixed(0)}ms`;
202
+ } else {
203
+ formatted = `${(ms / 1e3).toFixed(2)}s`;
204
+ }
205
+ return formatted;
206
+ }
207
+ function leftPad(string, length = 8) {
208
+ const padLength = Math.max(length - string.length, 0);
209
+ return `${" ".repeat(padLength)}${string}`;
210
+ }
211
+
212
+ // ../../node_modules/@probe.gl/log/dist/utils/color.js
213
+ var COLOR;
214
+ (function(COLOR2) {
215
+ COLOR2[COLOR2["BLACK"] = 30] = "BLACK";
216
+ COLOR2[COLOR2["RED"] = 31] = "RED";
217
+ COLOR2[COLOR2["GREEN"] = 32] = "GREEN";
218
+ COLOR2[COLOR2["YELLOW"] = 33] = "YELLOW";
219
+ COLOR2[COLOR2["BLUE"] = 34] = "BLUE";
220
+ COLOR2[COLOR2["MAGENTA"] = 35] = "MAGENTA";
221
+ COLOR2[COLOR2["CYAN"] = 36] = "CYAN";
222
+ COLOR2[COLOR2["WHITE"] = 37] = "WHITE";
223
+ COLOR2[COLOR2["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
224
+ COLOR2[COLOR2["BRIGHT_RED"] = 91] = "BRIGHT_RED";
225
+ COLOR2[COLOR2["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
226
+ COLOR2[COLOR2["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
227
+ COLOR2[COLOR2["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
228
+ COLOR2[COLOR2["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
229
+ COLOR2[COLOR2["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
230
+ COLOR2[COLOR2["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
231
+ })(COLOR || (COLOR = {}));
232
+ var BACKGROUND_INCREMENT = 10;
233
+ function getColor(color) {
234
+ if (typeof color !== "string") {
235
+ return color;
236
+ }
237
+ color = color.toUpperCase();
238
+ return COLOR[color] || COLOR.WHITE;
239
+ }
240
+ function addColor(string, color, background) {
241
+ if (!isBrowser2 && typeof string === "string") {
242
+ if (color) {
243
+ const colorCode = getColor(color);
244
+ string = `\x1B[${colorCode}m${string}\x1B[39m`;
245
+ }
246
+ if (background) {
247
+ const colorCode = getColor(background);
248
+ string = `\x1B[${colorCode + BACKGROUND_INCREMENT}m${string}\x1B[49m`;
249
+ }
250
+ }
251
+ return string;
252
+ }
253
+
254
+ // ../../node_modules/@probe.gl/log/dist/utils/autobind.js
255
+ function autobind(obj, predefined = ["constructor"]) {
256
+ const proto = Object.getPrototypeOf(obj);
257
+ const propNames = Object.getOwnPropertyNames(proto);
258
+ const object = obj;
259
+ for (const key of propNames) {
260
+ const value = object[key];
261
+ if (typeof value === "function") {
262
+ if (!predefined.find((name) => key === name)) {
263
+ object[key] = value.bind(obj);
264
+ }
265
+ }
266
+ }
267
+ }
268
+
269
+ // ../../node_modules/@probe.gl/log/dist/utils/assert.js
270
+ function assert2(condition, message) {
271
+ if (!condition) {
272
+ throw new Error(message || "Assertion failed");
273
+ }
274
+ }
275
+
276
+ // ../../node_modules/@probe.gl/log/dist/utils/hi-res-timestamp.js
277
+ function getHiResTimestamp() {
278
+ let timestamp;
279
+ if (isBrowser2() && window_2.performance) {
280
+ timestamp = window_2?.performance?.now?.();
281
+ } else if ("hrtime" in process_) {
282
+ const timeParts = process_?.hrtime?.();
283
+ timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6;
284
+ } else {
285
+ timestamp = Date.now();
286
+ }
287
+ return timestamp;
288
+ }
289
+
290
+ // ../../node_modules/@probe.gl/log/dist/log.js
291
+ var originalConsole = {
292
+ debug: isBrowser2() ? console.debug || console.log : console.log,
293
+ log: console.log,
294
+ info: console.info,
295
+ warn: console.warn,
296
+ error: console.error
297
+ };
298
+ var DEFAULT_LOG_CONFIGURATION = {
299
+ enabled: true,
300
+ level: 0
301
+ };
302
+ function noop() {
303
+ }
304
+ var cache = {};
305
+ var ONCE = { once: true };
306
+ var Log = class {
307
+ constructor({ id } = { id: "" }) {
308
+ this.VERSION = VERSION;
309
+ this._startTs = getHiResTimestamp();
310
+ this._deltaTs = getHiResTimestamp();
311
+ this.userData = {};
312
+ this.LOG_THROTTLE_TIMEOUT = 0;
313
+ this.id = id;
314
+ this.userData = {};
315
+ this._storage = new LocalStorage(`__probe-${this.id}__`, DEFAULT_LOG_CONFIGURATION);
316
+ this.timeStamp(`${this.id} started`);
317
+ autobind(this);
318
+ Object.seal(this);
319
+ }
320
+ set level(newLevel) {
321
+ this.setLevel(newLevel);
322
+ }
323
+ get level() {
324
+ return this.getLevel();
325
+ }
326
+ isEnabled() {
327
+ return this._storage.config.enabled;
328
+ }
329
+ getLevel() {
330
+ return this._storage.config.level;
331
+ }
332
+ /** @return milliseconds, with fractions */
333
+ getTotal() {
334
+ return Number((getHiResTimestamp() - this._startTs).toPrecision(10));
335
+ }
336
+ /** @return milliseconds, with fractions */
337
+ getDelta() {
338
+ return Number((getHiResTimestamp() - this._deltaTs).toPrecision(10));
339
+ }
340
+ /** @deprecated use logLevel */
341
+ set priority(newPriority) {
342
+ this.level = newPriority;
343
+ }
344
+ /** @deprecated use logLevel */
345
+ get priority() {
346
+ return this.level;
347
+ }
348
+ /** @deprecated use logLevel */
349
+ getPriority() {
350
+ return this.level;
351
+ }
352
+ // Configure
353
+ enable(enabled = true) {
354
+ this._storage.setConfiguration({ enabled });
355
+ return this;
356
+ }
357
+ setLevel(level) {
358
+ this._storage.setConfiguration({ level });
359
+ return this;
360
+ }
361
+ /** return the current status of the setting */
362
+ get(setting) {
363
+ return this._storage.config[setting];
364
+ }
365
+ // update the status of the setting
366
+ set(setting, value) {
367
+ this._storage.setConfiguration({ [setting]: value });
368
+ }
369
+ /** Logs the current settings as a table */
370
+ settings() {
371
+ if (console.table) {
372
+ console.table(this._storage.config);
373
+ } else {
374
+ console.log(this._storage.config);
375
+ }
376
+ }
377
+ // Unconditional logging
378
+ assert(condition, message) {
379
+ if (!condition) {
380
+ throw new Error(message || "Assertion failed");
381
+ }
382
+ }
383
+ warn(message) {
384
+ return this._getLogFunction(0, message, originalConsole.warn, arguments, ONCE);
385
+ }
386
+ error(message) {
387
+ return this._getLogFunction(0, message, originalConsole.error, arguments);
388
+ }
389
+ /** Print a deprecation warning */
390
+ deprecated(oldUsage, newUsage) {
391
+ return this.warn(`\`${oldUsage}\` is deprecated and will be removed in a later version. Use \`${newUsage}\` instead`);
392
+ }
393
+ /** Print a removal warning */
394
+ removed(oldUsage, newUsage) {
395
+ return this.error(`\`${oldUsage}\` has been removed. Use \`${newUsage}\` instead`);
396
+ }
397
+ probe(logLevel, message) {
398
+ return this._getLogFunction(logLevel, message, originalConsole.log, arguments, {
399
+ time: true,
400
+ once: true
401
+ });
402
+ }
403
+ log(logLevel, message) {
404
+ return this._getLogFunction(logLevel, message, originalConsole.debug, arguments);
405
+ }
406
+ info(logLevel, message) {
407
+ return this._getLogFunction(logLevel, message, console.info, arguments);
408
+ }
409
+ once(logLevel, message) {
410
+ return this._getLogFunction(logLevel, message, originalConsole.debug || originalConsole.info, arguments, ONCE);
411
+ }
412
+ /** Logs an object as a table */
413
+ table(logLevel, table, columns) {
414
+ if (table) {
415
+ return this._getLogFunction(logLevel, table, console.table || noop, columns && [columns], {
416
+ tag: getTableHeader(table)
417
+ });
418
+ }
419
+ return noop;
420
+ }
421
+ time(logLevel, message) {
422
+ return this._getLogFunction(logLevel, message, console.time ? console.time : console.info);
423
+ }
424
+ timeEnd(logLevel, message) {
425
+ return this._getLogFunction(logLevel, message, console.timeEnd ? console.timeEnd : console.info);
426
+ }
427
+ timeStamp(logLevel, message) {
428
+ return this._getLogFunction(logLevel, message, console.timeStamp || noop);
429
+ }
430
+ group(logLevel, message, opts = { collapsed: false }) {
431
+ const options = normalizeArguments({ logLevel, message, opts });
432
+ const { collapsed } = opts;
433
+ options.method = (collapsed ? console.groupCollapsed : console.group) || console.info;
434
+ return this._getLogFunction(options);
435
+ }
436
+ groupCollapsed(logLevel, message, opts = {}) {
437
+ return this.group(logLevel, message, Object.assign({}, opts, { collapsed: true }));
438
+ }
439
+ groupEnd(logLevel) {
440
+ return this._getLogFunction(logLevel, "", console.groupEnd || noop);
441
+ }
442
+ // EXPERIMENTAL
443
+ withGroup(logLevel, message, func) {
444
+ this.group(logLevel, message)();
445
+ try {
446
+ func();
447
+ } finally {
448
+ this.groupEnd(logLevel)();
449
+ }
450
+ }
451
+ trace() {
452
+ if (console.trace) {
453
+ console.trace();
454
+ }
455
+ }
456
+ // PRIVATE METHODS
457
+ /** Deduces log level from a variety of arguments */
458
+ _shouldLog(logLevel) {
459
+ return this.isEnabled() && this.getLevel() >= normalizeLogLevel(logLevel);
460
+ }
461
+ _getLogFunction(logLevel, message, method, args, opts) {
462
+ if (this._shouldLog(logLevel)) {
463
+ opts = normalizeArguments({ logLevel, message, args, opts });
464
+ method = method || opts.method;
465
+ assert2(method);
466
+ opts.total = this.getTotal();
467
+ opts.delta = this.getDelta();
468
+ this._deltaTs = getHiResTimestamp();
469
+ const tag = opts.tag || opts.message;
470
+ if (opts.once && tag) {
471
+ if (!cache[tag]) {
472
+ cache[tag] = getHiResTimestamp();
473
+ } else {
474
+ return noop;
475
+ }
476
+ }
477
+ message = decorateMessage(this.id, opts.message, opts);
478
+ return method.bind(console, message, ...opts.args);
479
+ }
480
+ return noop;
481
+ }
482
+ };
483
+ Log.VERSION = VERSION;
484
+ function normalizeLogLevel(logLevel) {
485
+ if (!logLevel) {
486
+ return 0;
487
+ }
488
+ let resolvedLevel;
489
+ switch (typeof logLevel) {
490
+ case "number":
491
+ resolvedLevel = logLevel;
492
+ break;
493
+ case "object":
494
+ resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
495
+ break;
496
+ default:
497
+ return 0;
498
+ }
499
+ assert2(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
500
+ return resolvedLevel;
501
+ }
502
+ function normalizeArguments(opts) {
503
+ const { logLevel, message } = opts;
504
+ opts.logLevel = normalizeLogLevel(logLevel);
505
+ const args = opts.args ? Array.from(opts.args) : [];
506
+ while (args.length && args.shift() !== message) {
507
+ }
508
+ switch (typeof logLevel) {
509
+ case "string":
510
+ case "function":
511
+ if (message !== void 0) {
512
+ args.unshift(message);
513
+ }
514
+ opts.message = logLevel;
515
+ break;
516
+ case "object":
517
+ Object.assign(opts, logLevel);
518
+ break;
519
+ default:
520
+ }
521
+ if (typeof opts.message === "function") {
522
+ opts.message = opts.message();
523
+ }
524
+ const messageType = typeof opts.message;
525
+ assert2(messageType === "string" || messageType === "object");
526
+ return Object.assign(opts, { args }, opts.opts);
527
+ }
528
+ function decorateMessage(id, message, opts) {
529
+ if (typeof message === "string") {
530
+ const time = opts.time ? leftPad(formatTime(opts.total)) : "";
531
+ message = opts.time ? `${id}: ${time} ${message}` : `${id}: ${message}`;
532
+ message = addColor(message, opts.color, opts.background);
533
+ }
534
+ return message;
535
+ }
536
+ function getTableHeader(table) {
537
+ for (const key in table) {
538
+ for (const title in table[key]) {
539
+ return title || "untitled";
540
+ }
541
+ }
542
+ return "empty";
543
+ }
544
+
545
+ // ../../node_modules/@probe.gl/log/dist/init.js
546
+ globalThis.probe = {};
547
+
548
+ // ../../node_modules/@probe.gl/log/dist/index.js
549
+ var dist_default = new Log({ id: "@probe.gl/log" });
550
+
551
+ // ../loader-utils/src/lib/log-utils/log.ts
552
+ var VERSION2 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
553
+ var version = VERSION2[0] >= "0" && VERSION2[0] <= "9" ? `v${VERSION2}` : "";
554
+ function createLog() {
555
+ const log2 = new Log({ id: "loaders.gl" });
556
+ globalThis.loaders = globalThis.loaders || {};
557
+ globalThis.loaders.log = log2;
558
+ globalThis.loaders.version = version;
559
+ globalThis.probe = globalThis.probe || {};
560
+ globalThis.probe.loaders = log2;
561
+ return log2;
562
+ }
563
+ var log = createLog();
564
+
565
+ // ../loader-utils/src/lib/javascript-utils/is-type.ts
566
+ var isBoolean = (value) => typeof value === "boolean";
567
+ var isFunction = (value) => typeof value === "function";
568
+ var isObject = (value) => value !== null && typeof value === "object";
569
+ var isPureObject = (value) => isObject(value) && value.constructor === {}.constructor;
570
+ var isSharedArrayBuffer = (value) => typeof SharedArrayBuffer !== "undefined" && value instanceof SharedArrayBuffer;
571
+ var isArrayBufferLike = (value) => isObject(value) && typeof value.byteLength === "number" && typeof value.slice === "function";
572
+ var isPromise = (value) => isObject(value) && "then" in value && isFunction(value.then);
573
+ var isIterable = (value) => Boolean(value) && isFunction(value[Symbol.iterator]);
574
+ var isAsyncIterable = (value) => Boolean(value) && isFunction(value[Symbol.asyncIterator]);
575
+ var isIterator = (value) => Boolean(value) && isFunction(value.next);
576
+ var isResponse = (value) => typeof Response !== "undefined" && value instanceof Response || isObject(value) && isFunction(value.arrayBuffer) && isFunction(value.text) && isFunction(value.json);
577
+ var isBlob = (value) => typeof Blob !== "undefined" && value instanceof Blob;
578
+ var isWritableDOMStream = (value) => isObject(value) && isFunction(value.abort) && isFunction(value.getWriter);
579
+ var isReadableDOMStream = (value) => typeof ReadableStream !== "undefined" && value instanceof ReadableStream || isObject(value) && isFunction(value.tee) && isFunction(value.cancel) && isFunction(value.getReader);
580
+ var isWritableNodeStream = (value) => isObject(value) && isFunction(value.end) && isFunction(value.write) && isBoolean(value.writable);
581
+ var isReadableNodeStream = (value) => isObject(value) && isFunction(value.read) && isFunction(value.pipe) && isBoolean(value.readable);
582
+ var isReadableStream = (value) => isReadableDOMStream(value) || isReadableNodeStream(value);
583
+ var isWritableStream = (value) => isWritableDOMStream(value) || isWritableNodeStream(value);
584
+
585
+ // ../loader-utils/src/lib/option-utils/merge-options.ts
586
+ function mergeOptions(baseOptions, newOptions) {
587
+ return mergeOptionsRecursively(baseOptions || {}, newOptions);
588
+ }
589
+ function mergeOptionsRecursively(baseOptions, newOptions, level = 0) {
590
+ if (level > 3) {
591
+ return newOptions;
592
+ }
593
+ const options = { ...baseOptions };
594
+ for (const [key, newValue] of Object.entries(newOptions)) {
595
+ if (newValue && typeof newValue === "object" && !Array.isArray(newValue)) {
596
+ options[key] = mergeOptionsRecursively(
597
+ options[key] || {},
598
+ newOptions[key],
599
+ level + 1
600
+ );
601
+ } else {
602
+ options[key] = newOptions[key];
603
+ }
604
+ }
605
+ return options;
606
+ }
36
607
 
37
- // external-global-plugin:@loaders.gl/core
38
- var require_core = __commonJS({
39
- "external-global-plugin:@loaders.gl/core"(exports, module) {
40
- module.exports = globalThis.loaders;
608
+ // ../loader-utils/src/lib/module-utils/js-module-utils.ts
609
+ function registerJSModules(modules) {
610
+ globalThis.loaders ||= {};
611
+ globalThis.loaders.modules ||= {};
612
+ Object.assign(globalThis.loaders.modules, modules);
613
+ }
614
+
615
+ // ../worker-utils/src/lib/npm-tag.ts
616
+ var NPM_TAG = "beta";
617
+
618
+ // ../worker-utils/src/lib/env-utils/version.ts
619
+ var warningIssued = false;
620
+ function getVersion() {
621
+ if (!globalThis._loadersgl_?.version) {
622
+ globalThis._loadersgl_ = globalThis._loadersgl_ || {};
623
+ if (typeof __VERSION__ === "undefined" && !warningIssued) {
624
+ console.warn(
625
+ "loaders.gl: The __VERSION__ variable is not injected using babel plugin. Latest unstable workers would be fetched from the CDN."
626
+ );
627
+ globalThis._loadersgl_.version = NPM_TAG;
628
+ warningIssued = true;
629
+ } else {
630
+ globalThis._loadersgl_.version = __VERSION__;
631
+ }
632
+ }
633
+ return globalThis._loadersgl_.version;
634
+ }
635
+ var VERSION3 = getVersion();
636
+
637
+ // ../worker-utils/src/lib/env-utils/assert.ts
638
+ function assert3(condition, message) {
639
+ if (!condition) {
640
+ throw new Error(message || "loaders.gl assertion failed.");
41
641
  }
642
+ }
643
+
644
+ // ../worker-utils/src/lib/env-utils/globals.ts
645
+ var globals2 = {
646
+ self: typeof self !== "undefined" && self,
647
+ window: typeof window !== "undefined" && window,
648
+ global: typeof global !== "undefined" && global,
649
+ document: typeof document !== "undefined" && document
650
+ };
651
+ var self_2 = globals2.self || globals2.window || globals2.global || {};
652
+ var window_3 = globals2.window || globals2.self || globals2.global || {};
653
+ var global_3 = globals2.global || globals2.self || globals2.window || {};
654
+ var document_3 = globals2.document || {};
655
+ var isBrowser3 = (
656
+ // @ts-ignore process.browser
657
+ typeof process !== "object" || String(process) !== "[object process]" || process.browser
658
+ );
659
+ var isMobile = typeof window !== "undefined" && typeof window.orientation !== "undefined";
660
+ var matches2 = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
661
+ var nodeVersion2 = matches2 && parseFloat(matches2[1]) || 0;
662
+
663
+ // ../worker-utils/src/lib/worker-farm/worker-job.ts
664
+ var WorkerJob = class {
665
+ name;
666
+ workerThread;
667
+ isRunning = true;
668
+ /** Promise that resolves when Job is done */
669
+ result;
670
+ _resolve = () => {
671
+ };
672
+ _reject = () => {
673
+ };
674
+ constructor(jobName, workerThread) {
675
+ this.name = jobName;
676
+ this.workerThread = workerThread;
677
+ this.result = new Promise((resolve2, reject) => {
678
+ this._resolve = resolve2;
679
+ this._reject = reject;
680
+ });
681
+ }
682
+ /**
683
+ * Send a message to the job's worker thread
684
+ * @param data any data structure, ideally consisting mostly of transferrable objects
685
+ */
686
+ postMessage(type, payload) {
687
+ this.workerThread.postMessage({
688
+ source: "loaders.gl",
689
+ // Lets worker ignore unrelated messages
690
+ type,
691
+ payload
692
+ });
693
+ }
694
+ /**
695
+ * Call to resolve the `result` Promise with the supplied value
696
+ */
697
+ done(value) {
698
+ assert3(this.isRunning);
699
+ this.isRunning = false;
700
+ this._resolve(value);
701
+ }
702
+ /**
703
+ * Call to reject the `result` Promise with the supplied error
704
+ */
705
+ error(error) {
706
+ assert3(this.isRunning);
707
+ this.isRunning = false;
708
+ this._reject(error);
709
+ }
710
+ };
711
+
712
+ // ../worker-utils/src/lib/node/worker_threads-browser.ts
713
+ var NodeWorker = class {
714
+ terminate() {
715
+ }
716
+ };
717
+
718
+ // ../worker-utils/src/lib/worker-utils/get-loadable-worker-url.ts
719
+ var workerURLCache = /* @__PURE__ */ new Map();
720
+ function getLoadableWorkerURL(props) {
721
+ assert3(props.source && !props.url || !props.source && props.url);
722
+ let workerURL = workerURLCache.get(props.source || props.url);
723
+ if (!workerURL) {
724
+ if (props.url) {
725
+ workerURL = getLoadableWorkerURLFromURL(props.url);
726
+ workerURLCache.set(props.url, workerURL);
727
+ }
728
+ if (props.source) {
729
+ workerURL = getLoadableWorkerURLFromSource(props.source);
730
+ workerURLCache.set(props.source, workerURL);
731
+ }
732
+ }
733
+ assert3(workerURL);
734
+ return workerURL;
735
+ }
736
+ function getLoadableWorkerURLFromURL(url) {
737
+ if (!url.startsWith("http")) {
738
+ return url;
739
+ }
740
+ const workerSource = buildScriptSource(url);
741
+ return getLoadableWorkerURLFromSource(workerSource);
742
+ }
743
+ function getLoadableWorkerURLFromSource(workerSource) {
744
+ const blob = new Blob([workerSource], { type: "application/javascript" });
745
+ return URL.createObjectURL(blob);
746
+ }
747
+ function buildScriptSource(workerUrl) {
748
+ return `try {
749
+ importScripts('${workerUrl}');
750
+ } catch (error) {
751
+ console.error(error);
752
+ throw error;
753
+ }`;
754
+ }
755
+
756
+ // ../worker-utils/src/lib/worker-utils/get-transfer-list.ts
757
+ function getTransferList(object, recursive = true, transfers) {
758
+ const transfersSet = transfers || /* @__PURE__ */ new Set();
759
+ if (!object) {
760
+ } else if (isTransferable(object)) {
761
+ transfersSet.add(object);
762
+ } else if (isTransferable(object.buffer)) {
763
+ transfersSet.add(object.buffer);
764
+ } else if (ArrayBuffer.isView(object)) {
765
+ } else if (recursive && typeof object === "object") {
766
+ for (const key in object) {
767
+ getTransferList(object[key], recursive, transfersSet);
768
+ }
769
+ }
770
+ return transfers === void 0 ? Array.from(transfersSet) : [];
771
+ }
772
+ function isTransferable(object) {
773
+ if (!object) {
774
+ return false;
775
+ }
776
+ if (object instanceof ArrayBuffer) {
777
+ return true;
778
+ }
779
+ if (typeof MessagePort !== "undefined" && object instanceof MessagePort) {
780
+ return true;
781
+ }
782
+ if (typeof ImageBitmap !== "undefined" && object instanceof ImageBitmap) {
783
+ return true;
784
+ }
785
+ if (typeof OffscreenCanvas !== "undefined" && object instanceof OffscreenCanvas) {
786
+ return true;
787
+ }
788
+ return false;
789
+ }
790
+ function getTransferListForWriter(object) {
791
+ if (object === null) {
792
+ return {};
793
+ }
794
+ const clone = Object.assign({}, object);
795
+ Object.keys(clone).forEach((key) => {
796
+ if (typeof object[key] === "object" && !ArrayBuffer.isView(object[key]) && !(object[key] instanceof Array)) {
797
+ clone[key] = getTransferListForWriter(object[key]);
798
+ } else if (typeof clone[key] === "function" || clone[key] instanceof RegExp) {
799
+ clone[key] = {};
800
+ } else {
801
+ clone[key] = object[key];
802
+ }
803
+ });
804
+ return clone;
805
+ }
806
+
807
+ // ../worker-utils/src/lib/worker-farm/worker-thread.ts
808
+ var NOOP = () => {
809
+ };
810
+ var WorkerThread = class {
811
+ name;
812
+ source;
813
+ url;
814
+ terminated = false;
815
+ worker;
816
+ onMessage;
817
+ onError;
818
+ _loadableURL = "";
819
+ /** Checks if workers are supported on this platform */
820
+ static isSupported() {
821
+ return typeof Worker !== "undefined" && isBrowser3 || typeof NodeWorker !== "undefined" && !isBrowser3;
822
+ }
823
+ constructor(props) {
824
+ const { name, source, url } = props;
825
+ assert3(source || url);
826
+ this.name = name;
827
+ this.source = source;
828
+ this.url = url;
829
+ this.onMessage = NOOP;
830
+ this.onError = (error) => console.log(error);
831
+ this.worker = isBrowser3 ? this._createBrowserWorker() : this._createNodeWorker();
832
+ }
833
+ /**
834
+ * Terminate this worker thread
835
+ * @note Can free up significant memory
836
+ */
837
+ destroy() {
838
+ this.onMessage = NOOP;
839
+ this.onError = NOOP;
840
+ this.worker.terminate();
841
+ this.terminated = true;
842
+ }
843
+ get isRunning() {
844
+ return Boolean(this.onMessage);
845
+ }
846
+ /**
847
+ * Send a message to this worker thread
848
+ * @param data any data structure, ideally consisting mostly of transferrable objects
849
+ * @param transferList If not supplied, calculated automatically by traversing data
850
+ */
851
+ postMessage(data, transferList) {
852
+ transferList = transferList || getTransferList(data);
853
+ this.worker.postMessage(data, transferList);
854
+ }
855
+ // PRIVATE
856
+ /**
857
+ * Generate a standard Error from an ErrorEvent
858
+ * @param event
859
+ */
860
+ _getErrorFromErrorEvent(event) {
861
+ let message = "Failed to load ";
862
+ message += `worker ${this.name} from ${this.url}. `;
863
+ if (event.message) {
864
+ message += `${event.message} in `;
865
+ }
866
+ if (event.lineno) {
867
+ message += `:${event.lineno}:${event.colno}`;
868
+ }
869
+ return new Error(message);
870
+ }
871
+ /**
872
+ * Creates a worker thread on the browser
873
+ */
874
+ _createBrowserWorker() {
875
+ this._loadableURL = getLoadableWorkerURL({ source: this.source, url: this.url });
876
+ const worker = new Worker(this._loadableURL, { name: this.name });
877
+ worker.onmessage = (event) => {
878
+ if (!event.data) {
879
+ this.onError(new Error("No data received"));
880
+ } else {
881
+ this.onMessage(event.data);
882
+ }
883
+ };
884
+ worker.onerror = (error) => {
885
+ this.onError(this._getErrorFromErrorEvent(error));
886
+ this.terminated = true;
887
+ };
888
+ worker.onmessageerror = (event) => console.error(event);
889
+ return worker;
890
+ }
891
+ /**
892
+ * Creates a worker thread in node.js
893
+ * @todo https://nodejs.org/api/async_hooks.html#async-resource-worker-pool
894
+ */
895
+ _createNodeWorker() {
896
+ let worker;
897
+ if (this.url) {
898
+ const absolute = this.url.includes(":/") || this.url.startsWith("/");
899
+ const url = absolute ? this.url : `./${this.url}`;
900
+ const type = this.url.endsWith(".ts") || this.url.endsWith(".mjs") ? "module" : "commonjs";
901
+ worker = new NodeWorker(url, { eval: false, type });
902
+ } else if (this.source) {
903
+ worker = new NodeWorker(this.source, { eval: true });
904
+ } else {
905
+ throw new Error("no worker");
906
+ }
907
+ worker.on("message", (data) => {
908
+ this.onMessage(data);
909
+ });
910
+ worker.on("error", (error) => {
911
+ this.onError(error);
912
+ });
913
+ worker.on("exit", (code) => {
914
+ });
915
+ return worker;
916
+ }
917
+ };
918
+
919
+ // ../worker-utils/src/lib/worker-farm/worker-pool.ts
920
+ var WorkerPool = class {
921
+ name = "unnamed";
922
+ source;
923
+ // | Function;
924
+ url;
925
+ maxConcurrency = 1;
926
+ maxMobileConcurrency = 1;
927
+ onDebug = () => {
928
+ };
929
+ reuseWorkers = true;
930
+ props = {};
931
+ jobQueue = [];
932
+ idleQueue = [];
933
+ count = 0;
934
+ isDestroyed = false;
935
+ /** Checks if workers are supported on this platform */
936
+ static isSupported() {
937
+ return WorkerThread.isSupported();
938
+ }
939
+ /**
940
+ * @param processor - worker function
941
+ * @param maxConcurrency - max count of workers
942
+ */
943
+ constructor(props) {
944
+ this.source = props.source;
945
+ this.url = props.url;
946
+ this.setProps(props);
947
+ }
948
+ /**
949
+ * Terminates all workers in the pool
950
+ * @note Can free up significant memory
951
+ */
952
+ destroy() {
953
+ this.idleQueue.forEach((worker) => worker.destroy());
954
+ this.isDestroyed = true;
955
+ }
956
+ setProps(props) {
957
+ this.props = { ...this.props, ...props };
958
+ if (props.name !== void 0) {
959
+ this.name = props.name;
960
+ }
961
+ if (props.maxConcurrency !== void 0) {
962
+ this.maxConcurrency = props.maxConcurrency;
963
+ }
964
+ if (props.maxMobileConcurrency !== void 0) {
965
+ this.maxMobileConcurrency = props.maxMobileConcurrency;
966
+ }
967
+ if (props.reuseWorkers !== void 0) {
968
+ this.reuseWorkers = props.reuseWorkers;
969
+ }
970
+ if (props.onDebug !== void 0) {
971
+ this.onDebug = props.onDebug;
972
+ }
973
+ }
974
+ async startJob(name, onMessage3 = (job, type, data) => job.done(data), onError = (job, error) => job.error(error)) {
975
+ const startPromise = new Promise((onStart) => {
976
+ this.jobQueue.push({ name, onMessage: onMessage3, onError, onStart });
977
+ return this;
978
+ });
979
+ this._startQueuedJob();
980
+ return await startPromise;
981
+ }
982
+ // PRIVATE
983
+ /**
984
+ * Starts first queued job if worker is available or can be created
985
+ * Called when job is started and whenever a worker returns to the idleQueue
986
+ */
987
+ async _startQueuedJob() {
988
+ if (!this.jobQueue.length) {
989
+ return;
990
+ }
991
+ const workerThread = this._getAvailableWorker();
992
+ if (!workerThread) {
993
+ return;
994
+ }
995
+ const queuedJob = this.jobQueue.shift();
996
+ if (queuedJob) {
997
+ this.onDebug({
998
+ message: "Starting job",
999
+ name: queuedJob.name,
1000
+ workerThread,
1001
+ backlog: this.jobQueue.length
1002
+ });
1003
+ const job = new WorkerJob(queuedJob.name, workerThread);
1004
+ workerThread.onMessage = (data) => queuedJob.onMessage(job, data.type, data.payload);
1005
+ workerThread.onError = (error) => queuedJob.onError(job, error);
1006
+ queuedJob.onStart(job);
1007
+ try {
1008
+ await job.result;
1009
+ } catch (error) {
1010
+ console.error(`Worker exception: ${error}`);
1011
+ } finally {
1012
+ this.returnWorkerToQueue(workerThread);
1013
+ }
1014
+ }
1015
+ }
1016
+ /**
1017
+ * Returns a worker to the idle queue
1018
+ * Destroys the worker if
1019
+ * - pool is destroyed
1020
+ * - if this pool doesn't reuse workers
1021
+ * - if maxConcurrency has been lowered
1022
+ * @param worker
1023
+ */
1024
+ returnWorkerToQueue(worker) {
1025
+ const shouldDestroyWorker = (
1026
+ // Workers on Node.js prevent the process from exiting.
1027
+ // Until we figure out how to close them before exit, we always destroy them
1028
+ !isBrowser3 || // If the pool is destroyed, there is no reason to keep the worker around
1029
+ this.isDestroyed || // If the app has disabled worker reuse, any completed workers should be destroyed
1030
+ !this.reuseWorkers || // If concurrency has been lowered, this worker might be surplus to requirements
1031
+ this.count > this._getMaxConcurrency()
1032
+ );
1033
+ if (shouldDestroyWorker) {
1034
+ worker.destroy();
1035
+ this.count--;
1036
+ } else {
1037
+ this.idleQueue.push(worker);
1038
+ }
1039
+ if (!this.isDestroyed) {
1040
+ this._startQueuedJob();
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Returns idle worker or creates new worker if maxConcurrency has not been reached
1045
+ */
1046
+ _getAvailableWorker() {
1047
+ if (this.idleQueue.length > 0) {
1048
+ return this.idleQueue.shift() || null;
1049
+ }
1050
+ if (this.count < this._getMaxConcurrency()) {
1051
+ this.count++;
1052
+ const name = `${this.name.toLowerCase()} (#${this.count} of ${this.maxConcurrency})`;
1053
+ return new WorkerThread({ name, source: this.source, url: this.url });
1054
+ }
1055
+ return null;
1056
+ }
1057
+ _getMaxConcurrency() {
1058
+ return isMobile ? this.maxMobileConcurrency : this.maxConcurrency;
1059
+ }
1060
+ };
1061
+
1062
+ // ../worker-utils/src/lib/worker-farm/worker-farm.ts
1063
+ var DEFAULT_PROPS = {
1064
+ maxConcurrency: 3,
1065
+ maxMobileConcurrency: 1,
1066
+ reuseWorkers: true,
1067
+ onDebug: () => {
1068
+ }
1069
+ };
1070
+ var _WorkerFarm = class {
1071
+ props;
1072
+ workerPools = /* @__PURE__ */ new Map();
1073
+ /** Checks if workers are supported on this platform */
1074
+ static isSupported() {
1075
+ return WorkerThread.isSupported();
1076
+ }
1077
+ /** Get the singleton instance of the global worker farm */
1078
+ static getWorkerFarm(props = {}) {
1079
+ _WorkerFarm._workerFarm = _WorkerFarm._workerFarm || new _WorkerFarm({});
1080
+ _WorkerFarm._workerFarm.setProps(props);
1081
+ return _WorkerFarm._workerFarm;
1082
+ }
1083
+ /** get global instance with WorkerFarm.getWorkerFarm() */
1084
+ constructor(props) {
1085
+ this.props = { ...DEFAULT_PROPS };
1086
+ this.setProps(props);
1087
+ this.workerPools = /* @__PURE__ */ new Map();
1088
+ }
1089
+ /**
1090
+ * Terminate all workers in the farm
1091
+ * @note Can free up significant memory
1092
+ */
1093
+ destroy() {
1094
+ for (const workerPool of this.workerPools.values()) {
1095
+ workerPool.destroy();
1096
+ }
1097
+ this.workerPools = /* @__PURE__ */ new Map();
1098
+ }
1099
+ /**
1100
+ * Set props used when initializing worker pools
1101
+ * @param props
1102
+ */
1103
+ setProps(props) {
1104
+ this.props = { ...this.props, ...props };
1105
+ for (const workerPool of this.workerPools.values()) {
1106
+ workerPool.setProps(this._getWorkerPoolProps());
1107
+ }
1108
+ }
1109
+ /**
1110
+ * Returns a worker pool for the specified worker
1111
+ * @param options - only used first time for a specific worker name
1112
+ * @param options.name - the name of the worker - used to identify worker pool
1113
+ * @param options.url -
1114
+ * @param options.source -
1115
+ * @example
1116
+ * const job = WorkerFarm.getWorkerFarm().getWorkerPool({name, url}).startJob(...);
1117
+ */
1118
+ getWorkerPool(options) {
1119
+ const { name, source, url } = options;
1120
+ let workerPool = this.workerPools.get(name);
1121
+ if (!workerPool) {
1122
+ workerPool = new WorkerPool({
1123
+ name,
1124
+ source,
1125
+ url
1126
+ });
1127
+ workerPool.setProps(this._getWorkerPoolProps());
1128
+ this.workerPools.set(name, workerPool);
1129
+ }
1130
+ return workerPool;
1131
+ }
1132
+ _getWorkerPoolProps() {
1133
+ return {
1134
+ maxConcurrency: this.props.maxConcurrency,
1135
+ maxMobileConcurrency: this.props.maxMobileConcurrency,
1136
+ reuseWorkers: this.props.reuseWorkers,
1137
+ onDebug: this.props.onDebug
1138
+ };
1139
+ }
1140
+ };
1141
+ var WorkerFarm = _WorkerFarm;
1142
+ // singleton
1143
+ __publicField(WorkerFarm, "_workerFarm");
1144
+
1145
+ // ../worker-utils/src/lib/worker-api/get-worker-url.ts
1146
+ function getWorkerName(worker) {
1147
+ const warning = worker.version !== VERSION3 ? ` (worker-utils@${VERSION3})` : "";
1148
+ return `${worker.name}@${worker.version}${warning}`;
1149
+ }
1150
+ function getWorkerURL(worker, options = {}) {
1151
+ const workerOptions = options[worker.id] || {};
1152
+ const workerFile = isBrowser3 ? `${worker.id}-worker.js` : `${worker.id}-worker-node.js`;
1153
+ let url = workerOptions.workerUrl;
1154
+ if (!url && worker.id === "compression") {
1155
+ url = options.workerUrl;
1156
+ }
1157
+ const workerType = options._workerType || options?.core?._workerType;
1158
+ if (workerType === "test") {
1159
+ if (isBrowser3) {
1160
+ url = `modules/${worker.module}/dist/${workerFile}`;
1161
+ } else {
1162
+ url = `modules/${worker.module}/src/workers/${worker.id}-worker-node.ts`;
1163
+ }
1164
+ }
1165
+ if (!url) {
1166
+ let version2 = worker.version;
1167
+ if (version2 === "latest") {
1168
+ version2 = NPM_TAG;
1169
+ }
1170
+ const versionTag = version2 ? `@${version2}` : "";
1171
+ url = `https://unpkg.com/@loaders.gl/${worker.module}${versionTag}/dist/${workerFile}`;
1172
+ }
1173
+ assert3(url);
1174
+ return url;
1175
+ }
1176
+
1177
+ // ../worker-utils/src/lib/worker-api/process-on-worker.ts
1178
+ async function processOnWorker(worker, data, options = {}, context = {}) {
1179
+ const name = getWorkerName(worker);
1180
+ const workerFarm = WorkerFarm.getWorkerFarm(options);
1181
+ const { source } = options;
1182
+ const workerPoolProps = { name, source };
1183
+ if (!source) {
1184
+ workerPoolProps.url = getWorkerURL(worker, options);
1185
+ }
1186
+ const workerPool = workerFarm.getWorkerPool(workerPoolProps);
1187
+ const jobName = options.jobName || worker.name;
1188
+ const job = await workerPool.startJob(
1189
+ jobName,
1190
+ // eslint-disable-next-line
1191
+ onMessage.bind(null, context)
1192
+ );
1193
+ const transferableOptions = getTransferListForWriter(options);
1194
+ job.postMessage("process", { input: data, options: transferableOptions });
1195
+ const result = await job.result;
1196
+ return result.result;
1197
+ }
1198
+ async function onMessage(context, job, type, payload) {
1199
+ switch (type) {
1200
+ case "done":
1201
+ job.done(payload);
1202
+ break;
1203
+ case "error":
1204
+ job.error(new Error(payload.error));
1205
+ break;
1206
+ case "process":
1207
+ const { id, input, options } = payload;
1208
+ try {
1209
+ if (!context.process) {
1210
+ job.postMessage("error", { id, error: "Worker not set up to process on main thread" });
1211
+ return;
1212
+ }
1213
+ const result = await context.process(input, options);
1214
+ job.postMessage("done", { id, result });
1215
+ } catch (error) {
1216
+ const message = error instanceof Error ? error.message : "unknown error";
1217
+ job.postMessage("error", { id, error: message });
1218
+ }
1219
+ break;
1220
+ default:
1221
+ console.warn(`process-on-worker: unknown message ${type}`);
1222
+ }
1223
+ }
1224
+
1225
+ // ../worker-utils/src/lib/worker-api/validate-worker-version.ts
1226
+ function validateWorkerVersion(worker, coreVersion = VERSION3) {
1227
+ assert3(worker, "no worker provided");
1228
+ const workerVersion = worker.version;
1229
+ if (!coreVersion || !workerVersion) {
1230
+ return false;
1231
+ }
1232
+ return true;
1233
+ }
1234
+
1235
+ // ../loader-utils/src/lib/worker-loader-utils/parse-with-worker.ts
1236
+ function canParseWithWorker(loader, options) {
1237
+ if (!WorkerFarm.isSupported()) {
1238
+ return false;
1239
+ }
1240
+ const nodeWorkers = options?._nodeWorkers ?? options?.core?._nodeWorkers;
1241
+ if (!isBrowser3 && !nodeWorkers) {
1242
+ return false;
1243
+ }
1244
+ const useWorkers = options?.worker ?? options?.core?.worker;
1245
+ return Boolean(loader.worker && useWorkers);
1246
+ }
1247
+ async function parseWithWorker(loader, data, options, context, parseOnMainThread) {
1248
+ const name = loader.id;
1249
+ const url = getWorkerURL(loader, options);
1250
+ const workerFarm = WorkerFarm.getWorkerFarm(options?.core);
1251
+ const workerPool = workerFarm.getWorkerPool({ name, url });
1252
+ options = JSON.parse(JSON.stringify(options));
1253
+ context = JSON.parse(JSON.stringify(context || {}));
1254
+ const job = await workerPool.startJob(
1255
+ "process-on-worker",
1256
+ // @ts-expect-error
1257
+ onMessage2.bind(null, parseOnMainThread)
1258
+ // eslint-disable-line @typescript-eslint/no-misused-promises
1259
+ );
1260
+ job.postMessage("process", {
1261
+ // @ts-ignore
1262
+ input: data,
1263
+ options,
1264
+ context
1265
+ });
1266
+ const result = await job.result;
1267
+ return await result.result;
1268
+ }
1269
+ async function onMessage2(parseOnMainThread, job, type, payload) {
1270
+ switch (type) {
1271
+ case "done":
1272
+ job.done(payload);
1273
+ break;
1274
+ case "error":
1275
+ job.error(new Error(payload.error));
1276
+ break;
1277
+ case "process":
1278
+ const { id, input, options } = payload;
1279
+ try {
1280
+ const result = await parseOnMainThread(input, options);
1281
+ job.postMessage("done", { id, result });
1282
+ } catch (error) {
1283
+ const message = error instanceof Error ? error.message : "unknown error";
1284
+ job.postMessage("error", { id, error: message });
1285
+ }
1286
+ break;
1287
+ default:
1288
+ console.warn(`parse-with-worker unknown message ${type}`);
1289
+ }
1290
+ }
1291
+
1292
+ // ../loader-utils/src/lib/worker-loader-utils/encode-with-worker.ts
1293
+ function canEncodeWithWorker(writer, options) {
1294
+ if (!WorkerFarm.isSupported()) {
1295
+ return false;
1296
+ }
1297
+ const nodeWorkers = options?._nodeWorkers ?? options?.core?._nodeWorkers;
1298
+ const useWorkers = options?.worker ?? options?.core?.worker;
1299
+ if (!isBrowser && !nodeWorkers) {
1300
+ return false;
1301
+ }
1302
+ return Boolean(writer.worker && useWorkers);
1303
+ }
1304
+
1305
+ // ../loader-utils/src/lib/binary-utils/array-buffer-utils.ts
1306
+ function compareArrayBuffers(arrayBuffer1, arrayBuffer2, byteLength) {
1307
+ byteLength = byteLength || arrayBuffer1.byteLength;
1308
+ if (arrayBuffer1.byteLength < byteLength || arrayBuffer2.byteLength < byteLength) {
1309
+ return false;
1310
+ }
1311
+ const array1 = new Uint8Array(arrayBuffer1);
1312
+ const array2 = new Uint8Array(arrayBuffer2);
1313
+ for (let i = 0; i < array1.length; ++i) {
1314
+ if (array1[i] !== array2[i]) {
1315
+ return false;
1316
+ }
1317
+ }
1318
+ return true;
1319
+ }
1320
+ function concatenateArrayBuffers(...sources) {
1321
+ return concatenateArrayBuffersFromArray(sources);
1322
+ }
1323
+ function concatenateArrayBuffersFromArray(sources) {
1324
+ const sourceArrays = sources.map(
1325
+ (source2) => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2
1326
+ );
1327
+ const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
1328
+ const result = new Uint8Array(byteLength);
1329
+ let offset = 0;
1330
+ for (const sourceArray of sourceArrays) {
1331
+ result.set(sourceArray, offset);
1332
+ offset += sourceArray.byteLength;
1333
+ }
1334
+ return result.buffer;
1335
+ }
1336
+
1337
+ // ../loader-utils/src/lib/iterators/text-iterators.ts
1338
+ async function* makeTextDecoderIterator(arrayBufferIterator, options = {}) {
1339
+ const textDecoder = new TextDecoder(void 0, options);
1340
+ for await (const arrayBuffer of arrayBufferIterator) {
1341
+ yield typeof arrayBuffer === "string" ? arrayBuffer : textDecoder.decode(arrayBuffer, { stream: true });
1342
+ }
1343
+ }
1344
+ async function* makeTextEncoderIterator(textIterator) {
1345
+ const textEncoder = new TextEncoder();
1346
+ for await (const text of textIterator) {
1347
+ yield typeof text === "string" ? textEncoder.encode(text).buffer : text;
1348
+ }
1349
+ }
1350
+ async function* makeLineIterator(textIterator) {
1351
+ let previous = "";
1352
+ for await (const textChunk of textIterator) {
1353
+ previous += textChunk;
1354
+ let eolIndex;
1355
+ while ((eolIndex = previous.indexOf("\n")) >= 0) {
1356
+ const line = previous.slice(0, eolIndex + 1);
1357
+ previous = previous.slice(eolIndex + 1);
1358
+ yield line;
1359
+ }
1360
+ }
1361
+ if (previous.length > 0) {
1362
+ yield previous;
1363
+ }
1364
+ }
1365
+ async function* makeNumberedLineIterator(lineIterator) {
1366
+ let counter = 1;
1367
+ for await (const line of lineIterator) {
1368
+ yield { counter, line };
1369
+ counter++;
1370
+ }
1371
+ }
1372
+
1373
+ // ../loader-utils/src/lib/iterators/async-iteration.ts
1374
+ async function forEach(iterable, visitor) {
1375
+ const iterator = toAsyncIterator(iterable);
1376
+ while (true) {
1377
+ const { done, value } = await iterator.next();
1378
+ if (done) {
1379
+ if (iterator.return) {
1380
+ iterator.return();
1381
+ }
1382
+ return;
1383
+ }
1384
+ const cancel = visitor(value);
1385
+ if (cancel) {
1386
+ return;
1387
+ }
1388
+ }
1389
+ }
1390
+ async function concatenateArrayBuffersAsync(asyncIterator) {
1391
+ const arrayBuffers = [];
1392
+ for await (const chunk of asyncIterator) {
1393
+ arrayBuffers.push(copyToArrayBuffer(chunk));
1394
+ }
1395
+ return concatenateArrayBuffers(...arrayBuffers);
1396
+ }
1397
+ function copyToArrayBuffer(chunk) {
1398
+ if (chunk instanceof ArrayBuffer) {
1399
+ return chunk;
1400
+ }
1401
+ if (ArrayBuffer.isView(chunk)) {
1402
+ const { buffer, byteOffset, byteLength } = chunk;
1403
+ return copyFromBuffer(buffer, byteOffset, byteLength);
1404
+ }
1405
+ return copyFromBuffer(chunk);
1406
+ }
1407
+ function copyFromBuffer(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
1408
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
1409
+ const copy = new Uint8Array(view.length);
1410
+ copy.set(view);
1411
+ return copy.buffer;
1412
+ }
1413
+ function toAsyncIterator(iterable) {
1414
+ if (typeof iterable[Symbol.asyncIterator] === "function") {
1415
+ return iterable[Symbol.asyncIterator]();
1416
+ }
1417
+ if (typeof iterable[Symbol.iterator] === "function") {
1418
+ const iterator = iterable[Symbol.iterator]();
1419
+ return iteratorToAsyncIterator(iterator);
1420
+ }
1421
+ return iterable;
1422
+ }
1423
+ function iteratorToAsyncIterator(iterator) {
1424
+ return {
1425
+ next(value) {
1426
+ return Promise.resolve(iterator.next(value));
1427
+ },
1428
+ return(value) {
1429
+ if (typeof iterator.return === "function") {
1430
+ return Promise.resolve(iterator.return(value));
1431
+ }
1432
+ return Promise.resolve({ done: true, value });
1433
+ },
1434
+ throw(error) {
1435
+ if (typeof iterator.throw === "function") {
1436
+ return Promise.resolve(iterator.throw(error));
1437
+ }
1438
+ return Promise.reject(error);
1439
+ }
1440
+ };
1441
+ }
1442
+
1443
+ // ../../node_modules/@probe.gl/stats/dist/utils/hi-res-timestamp.js
1444
+ function getHiResTimestamp2() {
1445
+ let timestamp;
1446
+ if (typeof window !== "undefined" && window.performance) {
1447
+ timestamp = window.performance.now();
1448
+ } else if (typeof process !== "undefined" && process.hrtime) {
1449
+ const timeParts = process.hrtime();
1450
+ timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6;
1451
+ } else {
1452
+ timestamp = Date.now();
1453
+ }
1454
+ return timestamp;
1455
+ }
1456
+
1457
+ // ../../node_modules/@probe.gl/stats/dist/lib/stat.js
1458
+ var Stat = class {
1459
+ constructor(name, type) {
1460
+ this.sampleSize = 1;
1461
+ this.time = 0;
1462
+ this.count = 0;
1463
+ this.samples = 0;
1464
+ this.lastTiming = 0;
1465
+ this.lastSampleTime = 0;
1466
+ this.lastSampleCount = 0;
1467
+ this._count = 0;
1468
+ this._time = 0;
1469
+ this._samples = 0;
1470
+ this._startTime = 0;
1471
+ this._timerPending = false;
1472
+ this.name = name;
1473
+ this.type = type;
1474
+ this.reset();
1475
+ }
1476
+ reset() {
1477
+ this.time = 0;
1478
+ this.count = 0;
1479
+ this.samples = 0;
1480
+ this.lastTiming = 0;
1481
+ this.lastSampleTime = 0;
1482
+ this.lastSampleCount = 0;
1483
+ this._count = 0;
1484
+ this._time = 0;
1485
+ this._samples = 0;
1486
+ this._startTime = 0;
1487
+ this._timerPending = false;
1488
+ return this;
1489
+ }
1490
+ setSampleSize(samples) {
1491
+ this.sampleSize = samples;
1492
+ return this;
1493
+ }
1494
+ /** Call to increment count (+1) */
1495
+ incrementCount() {
1496
+ this.addCount(1);
1497
+ return this;
1498
+ }
1499
+ /** Call to decrement count (-1) */
1500
+ decrementCount() {
1501
+ this.subtractCount(1);
1502
+ return this;
1503
+ }
1504
+ /** Increase count */
1505
+ addCount(value) {
1506
+ this._count += value;
1507
+ this._samples++;
1508
+ this._checkSampling();
1509
+ return this;
1510
+ }
1511
+ /** Decrease count */
1512
+ subtractCount(value) {
1513
+ this._count -= value;
1514
+ this._samples++;
1515
+ this._checkSampling();
1516
+ return this;
1517
+ }
1518
+ /** Add an arbitrary timing and bump the count */
1519
+ addTime(time) {
1520
+ this._time += time;
1521
+ this.lastTiming = time;
1522
+ this._samples++;
1523
+ this._checkSampling();
1524
+ return this;
1525
+ }
1526
+ /** Start a timer */
1527
+ timeStart() {
1528
+ this._startTime = getHiResTimestamp2();
1529
+ this._timerPending = true;
1530
+ return this;
1531
+ }
1532
+ /** End a timer. Adds to time and bumps the timing count. */
1533
+ timeEnd() {
1534
+ if (!this._timerPending) {
1535
+ return this;
1536
+ }
1537
+ this.addTime(getHiResTimestamp2() - this._startTime);
1538
+ this._timerPending = false;
1539
+ this._checkSampling();
1540
+ return this;
1541
+ }
1542
+ getSampleAverageCount() {
1543
+ return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
1544
+ }
1545
+ /** Calculate average time / count for the previous window */
1546
+ getSampleAverageTime() {
1547
+ return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
1548
+ }
1549
+ /** Calculate counts per second for the previous window */
1550
+ getSampleHz() {
1551
+ return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1e3) : 0;
1552
+ }
1553
+ getAverageCount() {
1554
+ return this.samples > 0 ? this.count / this.samples : 0;
1555
+ }
1556
+ /** Calculate average time / count */
1557
+ getAverageTime() {
1558
+ return this.samples > 0 ? this.time / this.samples : 0;
1559
+ }
1560
+ /** Calculate counts per second */
1561
+ getHz() {
1562
+ return this.time > 0 ? this.samples / (this.time / 1e3) : 0;
1563
+ }
1564
+ _checkSampling() {
1565
+ if (this._samples === this.sampleSize) {
1566
+ this.lastSampleTime = this._time;
1567
+ this.lastSampleCount = this._count;
1568
+ this.count += this._count;
1569
+ this.time += this._time;
1570
+ this.samples += this._samples;
1571
+ this._time = 0;
1572
+ this._count = 0;
1573
+ this._samples = 0;
1574
+ }
1575
+ }
1576
+ };
1577
+
1578
+ // ../../node_modules/@probe.gl/stats/dist/lib/stats.js
1579
+ var Stats = class {
1580
+ constructor(options) {
1581
+ this.stats = {};
1582
+ this.id = options.id;
1583
+ this.stats = {};
1584
+ this._initializeStats(options.stats);
1585
+ Object.seal(this);
1586
+ }
1587
+ /** Acquire a stat. Create if it doesn't exist. */
1588
+ get(name, type = "count") {
1589
+ return this._getOrCreate({ name, type });
1590
+ }
1591
+ get size() {
1592
+ return Object.keys(this.stats).length;
1593
+ }
1594
+ /** Reset all stats */
1595
+ reset() {
1596
+ for (const stat of Object.values(this.stats)) {
1597
+ stat.reset();
1598
+ }
1599
+ return this;
1600
+ }
1601
+ forEach(fn) {
1602
+ for (const stat of Object.values(this.stats)) {
1603
+ fn(stat);
1604
+ }
1605
+ }
1606
+ getTable() {
1607
+ const table = {};
1608
+ this.forEach((stat) => {
1609
+ table[stat.name] = {
1610
+ time: stat.time || 0,
1611
+ count: stat.count || 0,
1612
+ average: stat.getAverageTime() || 0,
1613
+ hz: stat.getHz() || 0
1614
+ };
1615
+ });
1616
+ return table;
1617
+ }
1618
+ _initializeStats(stats = []) {
1619
+ stats.forEach((stat) => this._getOrCreate(stat));
1620
+ }
1621
+ _getOrCreate(stat) {
1622
+ const { name, type } = stat;
1623
+ let result = this.stats[name];
1624
+ if (!result) {
1625
+ if (stat instanceof Stat) {
1626
+ result = stat;
1627
+ } else {
1628
+ result = new Stat(name, type);
1629
+ }
1630
+ this.stats[name] = result;
1631
+ }
1632
+ return result;
1633
+ }
1634
+ };
1635
+
1636
+ // ../loader-utils/src/lib/request-utils/request-scheduler.ts
1637
+ var STAT_QUEUED_REQUESTS = "Queued Requests";
1638
+ var STAT_ACTIVE_REQUESTS = "Active Requests";
1639
+ var STAT_CANCELLED_REQUESTS = "Cancelled Requests";
1640
+ var STAT_QUEUED_REQUESTS_EVER = "Queued Requests Ever";
1641
+ var STAT_ACTIVE_REQUESTS_EVER = "Active Requests Ever";
1642
+ var DEFAULT_PROPS2 = {
1643
+ id: "request-scheduler",
1644
+ /** Specifies if the request scheduler should throttle incoming requests, mainly for comparative testing. */
1645
+ throttleRequests: true,
1646
+ /** The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit. */
1647
+ maxRequests: 6,
1648
+ /**
1649
+ * Specifies a debounce time, in milliseconds. All requests are queued, until no new requests have
1650
+ * been added to the queue for this amount of time.
1651
+ */
1652
+ debounceTime: 0
1653
+ };
1654
+ var RequestScheduler = class {
1655
+ props;
1656
+ stats;
1657
+ activeRequestCount = 0;
1658
+ /** Tracks the number of active requests and prioritizes/cancels queued requests. */
1659
+ requestQueue = [];
1660
+ requestMap = /* @__PURE__ */ new Map();
1661
+ updateTimer = null;
1662
+ constructor(props = {}) {
1663
+ this.props = { ...DEFAULT_PROPS2, ...props };
1664
+ this.stats = new Stats({ id: this.props.id });
1665
+ this.stats.get(STAT_QUEUED_REQUESTS);
1666
+ this.stats.get(STAT_ACTIVE_REQUESTS);
1667
+ this.stats.get(STAT_CANCELLED_REQUESTS);
1668
+ this.stats.get(STAT_QUEUED_REQUESTS_EVER);
1669
+ this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
1670
+ }
1671
+ /**
1672
+ * Update scheduler props. Preserves active and queued requests.
1673
+ */
1674
+ setProps(props) {
1675
+ if (props.throttleRequests !== void 0) {
1676
+ this.props.throttleRequests = props.throttleRequests;
1677
+ }
1678
+ if (props.maxRequests !== void 0) {
1679
+ this.props.maxRequests = props.maxRequests;
1680
+ }
1681
+ if (props.debounceTime !== void 0) {
1682
+ this.props.debounceTime = props.debounceTime;
1683
+ }
1684
+ }
1685
+ /**
1686
+ * Called by an application that wants to issue a request, without having it deeply queued by the browser
1687
+ *
1688
+ * When the returned promise resolved, it is OK for the application to issue a request.
1689
+ * The promise resolves to an object that contains a `done` method.
1690
+ * When the application's request has completed (or failed), the application must call the `done` function
1691
+ *
1692
+ * @param handle
1693
+ * @param getPriority will be called when request "slots" open up,
1694
+ * allowing the caller to update priority or cancel the request
1695
+ * Highest priority executes first, priority < 0 cancels the request
1696
+ * @returns a promise
1697
+ * - resolves to a object (with a `done` field) when the request can be issued without queueing,
1698
+ * - resolves to `null` if the request has been cancelled (by the callback return < 0).
1699
+ * In this case the application should not issue the request
1700
+ */
1701
+ scheduleRequest(handle, getPriority = () => 0) {
1702
+ if (!this.props.throttleRequests) {
1703
+ return Promise.resolve({ done: () => {
1704
+ } });
1705
+ }
1706
+ if (this.requestMap.has(handle)) {
1707
+ return this.requestMap.get(handle);
1708
+ }
1709
+ const request = { handle, priority: 0, getPriority };
1710
+ const promise = new Promise((resolve2) => {
1711
+ request.resolve = resolve2;
1712
+ return request;
1713
+ });
1714
+ this.requestQueue.push(request);
1715
+ this.requestMap.set(handle, promise);
1716
+ this._issueNewRequests();
1717
+ return promise;
1718
+ }
1719
+ // PRIVATE
1720
+ _issueRequest(request) {
1721
+ const { handle, resolve: resolve2 } = request;
1722
+ let isDone = false;
1723
+ const done = () => {
1724
+ if (!isDone) {
1725
+ isDone = true;
1726
+ this.requestMap.delete(handle);
1727
+ this.activeRequestCount--;
1728
+ this._issueNewRequests();
1729
+ }
1730
+ };
1731
+ this.activeRequestCount++;
1732
+ return resolve2 ? resolve2({ done }) : Promise.resolve({ done });
1733
+ }
1734
+ /** We check requests asynchronously, to prevent multiple updates */
1735
+ _issueNewRequests() {
1736
+ if (this.updateTimer !== null) {
1737
+ clearTimeout(this.updateTimer);
1738
+ }
1739
+ this.updateTimer = setTimeout(() => this._issueNewRequestsAsync(), this.props.debounceTime);
1740
+ }
1741
+ /** Refresh all requests */
1742
+ _issueNewRequestsAsync() {
1743
+ if (this.updateTimer !== null) {
1744
+ clearTimeout(this.updateTimer);
1745
+ }
1746
+ this.updateTimer = null;
1747
+ const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
1748
+ if (freeSlots === 0) {
1749
+ return;
1750
+ }
1751
+ this._updateAllRequests();
1752
+ for (let i = 0; i < freeSlots; ++i) {
1753
+ const request = this.requestQueue.shift();
1754
+ if (request) {
1755
+ this._issueRequest(request);
1756
+ }
1757
+ }
1758
+ }
1759
+ /** Ensure all requests have updated priorities, and that no longer valid requests are cancelled */
1760
+ _updateAllRequests() {
1761
+ const requestQueue = this.requestQueue;
1762
+ for (let i = 0; i < requestQueue.length; ++i) {
1763
+ const request = requestQueue[i];
1764
+ if (!this._updateRequest(request)) {
1765
+ requestQueue.splice(i, 1);
1766
+ this.requestMap.delete(request.handle);
1767
+ i--;
1768
+ }
1769
+ }
1770
+ requestQueue.sort((a, b) => a.priority - b.priority);
1771
+ }
1772
+ /** Update a single request by calling the callback */
1773
+ _updateRequest(request) {
1774
+ request.priority = request.getPriority(request.handle);
1775
+ if (request.priority < 0) {
1776
+ request.resolve(null);
1777
+ return false;
1778
+ }
1779
+ return true;
1780
+ }
1781
+ };
1782
+
1783
+ // ../loader-utils/src/lib/path-utils/file-aliases.ts
1784
+ var pathPrefix = "";
1785
+ var fileAliases = {};
1786
+ function setPathPrefix(prefix) {
1787
+ pathPrefix = prefix;
1788
+ }
1789
+ function getPathPrefix() {
1790
+ return pathPrefix;
1791
+ }
1792
+ function resolvePath(filename2) {
1793
+ for (const alias in fileAliases) {
1794
+ if (filename2.startsWith(alias)) {
1795
+ const replacement = fileAliases[alias];
1796
+ filename2 = filename2.replace(alias, replacement);
1797
+ }
1798
+ }
1799
+ if (!filename2.startsWith("http://") && !filename2.startsWith("https://")) {
1800
+ filename2 = `${pathPrefix}${filename2}`;
1801
+ }
1802
+ return filename2;
1803
+ }
1804
+
1805
+ // ../loader-utils/src/json-loader.ts
1806
+ var VERSION4 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
1807
+ var JSONLoader = {
1808
+ dataType: null,
1809
+ batchType: null,
1810
+ name: "JSON",
1811
+ id: "json",
1812
+ module: "json",
1813
+ version: VERSION4,
1814
+ extensions: ["json", "geojson"],
1815
+ mimeTypes: ["application/json"],
1816
+ category: "json",
1817
+ text: true,
1818
+ parseTextSync,
1819
+ parse: async (arrayBuffer) => parseTextSync(new TextDecoder().decode(arrayBuffer)),
1820
+ options: {}
1821
+ };
1822
+ function parseTextSync(text) {
1823
+ return JSON.parse(text);
1824
+ }
1825
+
1826
+ // ../loader-utils/src/lib/node/buffer.browser.ts
1827
+ function toArrayBuffer(buffer) {
1828
+ return buffer;
1829
+ }
1830
+
1831
+ // ../loader-utils/src/lib/binary-utils/memory-conversion-utils.ts
1832
+ function isBuffer(value) {
1833
+ return value && typeof value === "object" && value.isBuffer;
1834
+ }
1835
+ function toArrayBuffer2(data) {
1836
+ if (isBuffer(data)) {
1837
+ return toArrayBuffer(data);
1838
+ }
1839
+ if (data instanceof ArrayBuffer) {
1840
+ return data;
1841
+ }
1842
+ if (isSharedArrayBuffer(data)) {
1843
+ return copyToArrayBuffer2(data);
1844
+ }
1845
+ if (ArrayBuffer.isView(data)) {
1846
+ const buffer = data.buffer;
1847
+ if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
1848
+ return buffer;
1849
+ }
1850
+ return buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
1851
+ }
1852
+ if (typeof data === "string") {
1853
+ const text = data;
1854
+ const uint8Array = new TextEncoder().encode(text);
1855
+ return uint8Array.buffer;
1856
+ }
1857
+ if (data && typeof data === "object" && data._toArrayBuffer) {
1858
+ return data._toArrayBuffer();
1859
+ }
1860
+ throw new Error("toArrayBuffer");
1861
+ }
1862
+ function ensureArrayBuffer(bufferSource) {
1863
+ if (bufferSource instanceof ArrayBuffer) {
1864
+ return bufferSource;
1865
+ }
1866
+ if (isSharedArrayBuffer(bufferSource)) {
1867
+ return copyToArrayBuffer2(bufferSource);
1868
+ }
1869
+ const { buffer, byteOffset, byteLength } = bufferSource;
1870
+ if (buffer instanceof ArrayBuffer && byteOffset === 0 && byteLength === buffer.byteLength) {
1871
+ return buffer;
1872
+ }
1873
+ return copyToArrayBuffer2(buffer, byteOffset, byteLength);
1874
+ }
1875
+ function copyToArrayBuffer2(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
1876
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
1877
+ const copy = new Uint8Array(view.length);
1878
+ copy.set(view);
1879
+ return copy.buffer;
1880
+ }
1881
+ function toArrayBufferView(data) {
1882
+ if (ArrayBuffer.isView(data)) {
1883
+ return data;
1884
+ }
1885
+ return new Uint8Array(data);
1886
+ }
1887
+
1888
+ // ../loader-utils/src/lib/path-utils/path.ts
1889
+ var path_exports = {};
1890
+ __export(path_exports, {
1891
+ dirname: () => dirname,
1892
+ filename: () => filename,
1893
+ join: () => join,
1894
+ resolve: () => resolve
42
1895
  });
43
1896
 
44
- // bundle.ts
45
- var bundle_exports = {};
46
- __reExport(bundle_exports, __toESM(require_core(), 1));
1897
+ // ../loader-utils/src/lib/path-utils/get-cwd.ts
1898
+ function getCWD() {
1899
+ if (typeof process !== "undefined" && typeof process.cwd !== "undefined") {
1900
+ return process.cwd();
1901
+ }
1902
+ const pathname = window.location?.pathname;
1903
+ return pathname?.slice(0, pathname.lastIndexOf("/") + 1) || "";
1904
+ }
1905
+
1906
+ // ../loader-utils/src/lib/path-utils/path.ts
1907
+ function filename(url) {
1908
+ const slashIndex = url ? url.lastIndexOf("/") : -1;
1909
+ return slashIndex >= 0 ? url.substr(slashIndex + 1) : url;
1910
+ }
1911
+ function dirname(url) {
1912
+ const slashIndex = url ? url.lastIndexOf("/") : -1;
1913
+ return slashIndex >= 0 ? url.substr(0, slashIndex) : "";
1914
+ }
1915
+ function join(...parts) {
1916
+ const separator = "/";
1917
+ parts = parts.map((part, index) => {
1918
+ if (index) {
1919
+ part = part.replace(new RegExp(`^${separator}`), "");
1920
+ }
1921
+ if (index !== parts.length - 1) {
1922
+ part = part.replace(new RegExp(`${separator}$`), "");
1923
+ }
1924
+ return part;
1925
+ });
1926
+ return parts.join(separator);
1927
+ }
1928
+ function resolve(...components) {
1929
+ const paths = [];
1930
+ for (let _i = 0; _i < components.length; _i++) {
1931
+ paths[_i] = components[_i];
1932
+ }
1933
+ let resolvedPath = "";
1934
+ let resolvedAbsolute = false;
1935
+ let cwd;
1936
+ for (let i = paths.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1937
+ let path;
1938
+ if (i >= 0) {
1939
+ path = paths[i];
1940
+ } else {
1941
+ if (cwd === void 0) {
1942
+ cwd = getCWD();
1943
+ }
1944
+ path = cwd;
1945
+ }
1946
+ if (path.length === 0) {
1947
+ continue;
1948
+ }
1949
+ resolvedPath = `${path}/${resolvedPath}`;
1950
+ resolvedAbsolute = path.charCodeAt(0) === SLASH;
1951
+ }
1952
+ resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
1953
+ if (resolvedAbsolute) {
1954
+ return `/${resolvedPath}`;
1955
+ } else if (resolvedPath.length > 0) {
1956
+ return resolvedPath;
1957
+ }
1958
+ return ".";
1959
+ }
1960
+ var SLASH = 47;
1961
+ var DOT = 46;
1962
+ function normalizeStringPosix(path, allowAboveRoot) {
1963
+ let res = "";
1964
+ let lastSlash = -1;
1965
+ let dots = 0;
1966
+ let code;
1967
+ let isAboveRoot = false;
1968
+ for (let i = 0; i <= path.length; ++i) {
1969
+ if (i < path.length) {
1970
+ code = path.charCodeAt(i);
1971
+ } else if (code === SLASH) {
1972
+ break;
1973
+ } else {
1974
+ code = SLASH;
1975
+ }
1976
+ if (code === SLASH) {
1977
+ if (lastSlash === i - 1 || dots === 1) {
1978
+ } else if (lastSlash !== i - 1 && dots === 2) {
1979
+ if (res.length < 2 || !isAboveRoot || res.charCodeAt(res.length - 1) !== DOT || res.charCodeAt(res.length - 2) !== DOT) {
1980
+ if (res.length > 2) {
1981
+ const start = res.length - 1;
1982
+ let j = start;
1983
+ for (; j >= 0; --j) {
1984
+ if (res.charCodeAt(j) === SLASH) {
1985
+ break;
1986
+ }
1987
+ }
1988
+ if (j !== start) {
1989
+ res = j === -1 ? "" : res.slice(0, j);
1990
+ lastSlash = i;
1991
+ dots = 0;
1992
+ isAboveRoot = false;
1993
+ continue;
1994
+ }
1995
+ } else if (res.length === 2 || res.length === 1) {
1996
+ res = "";
1997
+ lastSlash = i;
1998
+ dots = 0;
1999
+ isAboveRoot = false;
2000
+ continue;
2001
+ }
2002
+ }
2003
+ if (allowAboveRoot) {
2004
+ if (res.length > 0) {
2005
+ res += "/..";
2006
+ } else {
2007
+ res = "..";
2008
+ }
2009
+ isAboveRoot = true;
2010
+ }
2011
+ } else {
2012
+ const slice = path.slice(lastSlash + 1, i);
2013
+ if (res.length > 0) {
2014
+ res += `/${slice}`;
2015
+ } else {
2016
+ res = slice;
2017
+ }
2018
+ isAboveRoot = false;
2019
+ }
2020
+ lastSlash = i;
2021
+ dots = 0;
2022
+ } else if (code === DOT && dots !== -1) {
2023
+ ++dots;
2024
+ } else {
2025
+ dots = -1;
2026
+ }
2027
+ }
2028
+ return res;
2029
+ }
2030
+
2031
+ // ../loader-utils/src/lib/files/blob-file.ts
2032
+ var BlobFile = class {
2033
+ handle;
2034
+ size;
2035
+ bigsize;
2036
+ url;
2037
+ constructor(blob) {
2038
+ this.handle = blob instanceof ArrayBuffer ? new Blob([blob]) : blob;
2039
+ this.size = blob instanceof ArrayBuffer ? blob.byteLength : blob.size;
2040
+ this.bigsize = BigInt(this.size);
2041
+ this.url = blob instanceof File ? blob.name : "";
2042
+ }
2043
+ async close() {
2044
+ }
2045
+ async stat() {
2046
+ return {
2047
+ size: this.handle.size,
2048
+ bigsize: BigInt(this.handle.size),
2049
+ isDirectory: false
2050
+ };
2051
+ }
2052
+ async read(start, length) {
2053
+ const arrayBuffer = await this.handle.slice(Number(start), Number(start) + Number(length)).arrayBuffer();
2054
+ return arrayBuffer;
2055
+ }
2056
+ };
2057
+
2058
+ // ../loader-utils/src/lib/files/node-file-facade.ts
2059
+ var NOT_IMPLEMENTED = new Error("Not implemented");
2060
+ var NodeFileFacade = class {
2061
+ handle;
2062
+ size = 0;
2063
+ bigsize = 0n;
2064
+ url = "";
2065
+ constructor(url, flags, mode) {
2066
+ if (globalThis.loaders?.NodeFile) {
2067
+ return new globalThis.loaders.NodeFile(url, flags, mode);
2068
+ }
2069
+ if (isBrowser) {
2070
+ throw new Error("Can't instantiate NodeFile in browser.");
2071
+ }
2072
+ throw new Error("Can't instantiate NodeFile. Make sure to import @loaders.gl/polyfills first.");
2073
+ }
2074
+ /** Read data */
2075
+ async read(start, length) {
2076
+ throw NOT_IMPLEMENTED;
2077
+ }
2078
+ /** Write to file. The number of bytes written will be returned */
2079
+ async write(arrayBuffer, offset, length) {
2080
+ throw NOT_IMPLEMENTED;
2081
+ }
2082
+ /** Get information about file */
2083
+ async stat() {
2084
+ throw NOT_IMPLEMENTED;
2085
+ }
2086
+ /** Truncates the file descriptor. Only available on NodeFile. */
2087
+ async truncate(length) {
2088
+ throw NOT_IMPLEMENTED;
2089
+ }
2090
+ /** Append data to a file. Only available on NodeFile. */
2091
+ async append(data) {
2092
+ throw NOT_IMPLEMENTED;
2093
+ }
2094
+ /** Close the file */
2095
+ async close() {
2096
+ }
2097
+ };
2098
+
2099
+ // ../core/src/lib/fetch/fetch-error.ts
2100
+ var FetchError = class extends Error {
2101
+ constructor(message, info) {
2102
+ super(message);
2103
+ this.reason = info.reason;
2104
+ this.url = info.url;
2105
+ this.response = info.response;
2106
+ }
2107
+ /** A best effort reason for why the fetch failed */
2108
+ reason;
2109
+ /** The URL that failed to load. Empty string if not available. */
2110
+ url;
2111
+ /** The Response object, if any. */
2112
+ response;
2113
+ };
2114
+
2115
+ // ../core/src/lib/utils/mime-type-utils.ts
2116
+ var DATA_URL_PATTERN = /^data:([-\w.]+\/[-\w.+]+)(;|,)/;
2117
+ var MIME_TYPE_PATTERN = /^([-\w.]+\/[-\w.+]+)/;
2118
+ function compareMIMETypes(mimeType1, mimeType2) {
2119
+ if (mimeType1.toLowerCase() === mimeType2.toLowerCase()) {
2120
+ return true;
2121
+ }
2122
+ return false;
2123
+ }
2124
+ function parseMIMEType(mimeString) {
2125
+ const matches3 = MIME_TYPE_PATTERN.exec(mimeString);
2126
+ if (matches3) {
2127
+ return matches3[1];
2128
+ }
2129
+ return mimeString;
2130
+ }
2131
+ function parseMIMETypeFromURL(url) {
2132
+ const matches3 = DATA_URL_PATTERN.exec(url);
2133
+ if (matches3) {
2134
+ return matches3[1];
2135
+ }
2136
+ return "";
2137
+ }
2138
+
2139
+ // ../core/src/lib/utils/url-utils.ts
2140
+ var QUERY_STRING_PATTERN = /\?.*/;
2141
+ function extractQueryString(url) {
2142
+ const matches3 = url.match(QUERY_STRING_PATTERN);
2143
+ return matches3 && matches3[0];
2144
+ }
2145
+ function stripQueryString(url) {
2146
+ return url.replace(QUERY_STRING_PATTERN, "");
2147
+ }
2148
+ function shortenUrlForDisplay(url) {
2149
+ if (url.length < 50) {
2150
+ return url;
2151
+ }
2152
+ const urlEnd = url.slice(url.length - 15);
2153
+ const urlStart = url.substr(0, 32);
2154
+ return `${urlStart}...${urlEnd}`;
2155
+ }
2156
+
2157
+ // ../core/src/lib/utils/resource-utils.ts
2158
+ function getResourceUrl(resource) {
2159
+ if (isResponse(resource)) {
2160
+ return resource.url;
2161
+ }
2162
+ if (isBlob(resource)) {
2163
+ const fileName = "name" in resource ? resource.name : "";
2164
+ return fileName || "";
2165
+ }
2166
+ if (typeof resource === "string") {
2167
+ return resource;
2168
+ }
2169
+ return "";
2170
+ }
2171
+ function getResourceMIMEType(resource) {
2172
+ if (isResponse(resource)) {
2173
+ const contentTypeHeader = resource.headers.get("content-type") || "";
2174
+ const noQueryUrl = stripQueryString(resource.url);
2175
+ return parseMIMEType(contentTypeHeader) || parseMIMETypeFromURL(noQueryUrl);
2176
+ }
2177
+ if (isBlob(resource)) {
2178
+ return resource.type || "";
2179
+ }
2180
+ if (typeof resource === "string") {
2181
+ return parseMIMETypeFromURL(resource);
2182
+ }
2183
+ return "";
2184
+ }
2185
+ function getResourceContentLength(resource) {
2186
+ if (isResponse(resource)) {
2187
+ const response = resource;
2188
+ return response.headers["content-length"] || -1;
2189
+ }
2190
+ if (isBlob(resource)) {
2191
+ const blob = resource;
2192
+ return blob.size;
2193
+ }
2194
+ if (typeof resource === "string") {
2195
+ return resource.length;
2196
+ }
2197
+ if (resource instanceof ArrayBuffer) {
2198
+ return resource.byteLength;
2199
+ }
2200
+ if (ArrayBuffer.isView(resource)) {
2201
+ return resource.byteLength;
2202
+ }
2203
+ return -1;
2204
+ }
2205
+
2206
+ // ../core/src/lib/utils/response-utils.ts
2207
+ async function makeResponse(resource) {
2208
+ if (isResponse(resource)) {
2209
+ return resource;
2210
+ }
2211
+ const headers = {};
2212
+ const contentLength = getResourceContentLength(resource);
2213
+ if (contentLength >= 0) {
2214
+ headers["content-length"] = String(contentLength);
2215
+ }
2216
+ const url = getResourceUrl(resource);
2217
+ const type = getResourceMIMEType(resource);
2218
+ if (type) {
2219
+ headers["content-type"] = type;
2220
+ }
2221
+ const initialDataUrl = await getInitialDataUrl(resource);
2222
+ if (initialDataUrl) {
2223
+ headers["x-first-bytes"] = initialDataUrl;
2224
+ }
2225
+ if (typeof resource === "string") {
2226
+ resource = new TextEncoder().encode(resource);
2227
+ }
2228
+ const response = new Response(resource, { headers });
2229
+ Object.defineProperty(response, "url", { value: url });
2230
+ return response;
2231
+ }
2232
+ async function checkResponse(response) {
2233
+ if (!response.ok) {
2234
+ const error = await getResponseError(response);
2235
+ throw error;
2236
+ }
2237
+ }
2238
+ async function getResponseError(response) {
2239
+ const shortUrl = shortenUrlForDisplay(response.url);
2240
+ let message = `Failed to fetch resource (${response.status}) ${response.statusText}: ${shortUrl}`;
2241
+ message = message.length > 100 ? `${message.slice(0, 100)}...` : message;
2242
+ const info = {
2243
+ reason: response.statusText,
2244
+ url: response.url,
2245
+ response
2246
+ };
2247
+ try {
2248
+ const contentType = response.headers.get("Content-Type");
2249
+ info.reason = !response.bodyUsed && contentType?.includes("application/json") ? await response.json() : await response.text();
2250
+ } catch (error) {
2251
+ }
2252
+ return new FetchError(message, info);
2253
+ }
2254
+ async function getInitialDataUrl(resource) {
2255
+ const INITIAL_DATA_LENGTH = 5;
2256
+ if (typeof resource === "string") {
2257
+ return `data:,${resource.slice(0, INITIAL_DATA_LENGTH)}`;
2258
+ }
2259
+ if (resource instanceof Blob) {
2260
+ const blobSlice = resource.slice(0, 5);
2261
+ return await new Promise((resolve2) => {
2262
+ const reader = new FileReader();
2263
+ reader.onload = (event) => resolve2(event?.target?.result);
2264
+ reader.readAsDataURL(blobSlice);
2265
+ });
2266
+ }
2267
+ if (resource instanceof ArrayBuffer) {
2268
+ const slice = resource.slice(0, INITIAL_DATA_LENGTH);
2269
+ const base64 = arrayBufferToBase64(slice);
2270
+ return `data:base64,${base64}`;
2271
+ }
2272
+ return null;
2273
+ }
2274
+ function arrayBufferToBase64(buffer) {
2275
+ let binary = "";
2276
+ const bytes = new Uint8Array(buffer);
2277
+ for (let i = 0; i < bytes.byteLength; i++) {
2278
+ binary += String.fromCharCode(bytes[i]);
2279
+ }
2280
+ return btoa(binary);
2281
+ }
2282
+
2283
+ // ../core/src/lib/fetch/fetch-file.ts
2284
+ function isNodePath(url) {
2285
+ return !isRequestURL(url) && !isDataURL(url);
2286
+ }
2287
+ function isRequestURL(url) {
2288
+ return url.startsWith("http:") || url.startsWith("https:");
2289
+ }
2290
+ function isDataURL(url) {
2291
+ return url.startsWith("data:");
2292
+ }
2293
+ async function fetchFile(urlOrData, fetchOptions) {
2294
+ if (typeof urlOrData === "string") {
2295
+ const url = resolvePath(urlOrData);
2296
+ if (isNodePath(url)) {
2297
+ if (globalThis.loaders?.fetchNode) {
2298
+ return globalThis.loaders?.fetchNode(url, fetchOptions);
2299
+ }
2300
+ }
2301
+ return await fetch(url, fetchOptions);
2302
+ }
2303
+ return await makeResponse(urlOrData);
2304
+ }
2305
+
2306
+ // ../core/src/lib/fetch/read-array-buffer.ts
2307
+ async function readArrayBuffer(file, start, length) {
2308
+ if (!(file instanceof Blob)) {
2309
+ file = new Blob([file]);
2310
+ }
2311
+ const slice = file.slice(start, start + length);
2312
+ return await readBlob(slice);
2313
+ }
2314
+ async function readBlob(blob) {
2315
+ return await new Promise((resolve2, reject) => {
2316
+ const fileReader = new FileReader();
2317
+ fileReader.onload = (event) => resolve2(event?.target?.result);
2318
+ fileReader.onerror = (error) => reject(error);
2319
+ fileReader.readAsArrayBuffer(blob);
2320
+ });
2321
+ }
2322
+
2323
+ // ../core/src/lib/loader-utils/loggers.ts
2324
+ var probeLog = new Log({ id: "loaders.gl" });
2325
+ var NullLog = class {
2326
+ log() {
2327
+ return () => {
2328
+ };
2329
+ }
2330
+ info() {
2331
+ return () => {
2332
+ };
2333
+ }
2334
+ warn() {
2335
+ return () => {
2336
+ };
2337
+ }
2338
+ error() {
2339
+ return () => {
2340
+ };
2341
+ }
2342
+ };
2343
+ var ConsoleLog = class {
2344
+ console;
2345
+ constructor() {
2346
+ this.console = console;
2347
+ }
2348
+ log(...args) {
2349
+ return this.console.log.bind(this.console, ...args);
2350
+ }
2351
+ info(...args) {
2352
+ return this.console.info.bind(this.console, ...args);
2353
+ }
2354
+ warn(...args) {
2355
+ return this.console.warn.bind(this.console, ...args);
2356
+ }
2357
+ error(...args) {
2358
+ return this.console.error.bind(this.console, ...args);
2359
+ }
2360
+ };
2361
+
2362
+ // ../core/src/lib/loader-utils/option-defaults.ts
2363
+ var DEFAULT_LOADER_OPTIONS = {
2364
+ core: {
2365
+ baseUri: void 0,
2366
+ // baseUri
2367
+ fetch: null,
2368
+ mimeType: void 0,
2369
+ fallbackMimeType: void 0,
2370
+ ignoreRegisteredLoaders: void 0,
2371
+ nothrow: false,
2372
+ log: new ConsoleLog(),
2373
+ // A probe.gl compatible (`log.log()()` syntax) that just logs to console
2374
+ useLocalLibraries: false,
2375
+ CDN: "https://unpkg.com/@loaders.gl",
2376
+ worker: true,
2377
+ // By default, use worker if provided by loader.
2378
+ maxConcurrency: 3,
2379
+ // How many worker instances should be created for each loader.
2380
+ maxMobileConcurrency: 1,
2381
+ // How many worker instances should be created for each loader on mobile devices.
2382
+ reuseWorkers: isBrowser,
2383
+ // By default reuse workers in browser (Node.js refuses to terminate if browsers are running)
2384
+ _nodeWorkers: false,
2385
+ // By default do not support node workers
2386
+ _workerType: "",
2387
+ // 'test' to use locally generated workers
2388
+ limit: 0,
2389
+ _limitMB: 0,
2390
+ batchSize: "auto",
2391
+ batchDebounceMs: 0,
2392
+ metadata: false,
2393
+ // TODO - currently only implemented for parseInBatches, adds initial metadata batch,
2394
+ transforms: []
2395
+ }
2396
+ };
2397
+ var REMOVED_LOADER_OPTIONS = {
2398
+ // baseUri
2399
+ baseUri: "core.baseUri",
2400
+ fetch: "core.fetch",
2401
+ mimeType: "core.mimeType",
2402
+ fallbackMimeType: "core.fallbackMimeType",
2403
+ ignoreRegisteredLoaders: "core.ignoreRegisteredLoaders",
2404
+ nothrow: "core.nothrow",
2405
+ log: "core.log",
2406
+ useLocalLibraries: "core.useLocalLibraries",
2407
+ CDN: "core.CDN",
2408
+ worker: "core.worker",
2409
+ maxConcurrency: "core.maxConcurrency",
2410
+ maxMobileConcurrency: "core.maxMobileConcurrency",
2411
+ reuseWorkers: "core.reuseWorkers",
2412
+ _nodeWorkers: "core.nodeWorkers",
2413
+ _workerType: "core._workerType",
2414
+ _worker: "core._workerType",
2415
+ limit: "core.limit",
2416
+ _limitMB: "core._limitMB",
2417
+ batchSize: "core.batchSize",
2418
+ batchDebounceMs: "core.batchDebounceMs",
2419
+ metadata: "core.metadata",
2420
+ transforms: "core.transforms",
2421
+ // Older deprecations
2422
+ throws: "nothrow",
2423
+ dataType: "(no longer used)",
2424
+ uri: "baseUri",
2425
+ // Warn if fetch options are used on toplevel
2426
+ method: "fetch.method",
2427
+ headers: "fetch.headers",
2428
+ body: "fetch.body",
2429
+ mode: "fetch.mode",
2430
+ credentials: "fetch.credentials",
2431
+ cache: "fetch.cache",
2432
+ redirect: "fetch.redirect",
2433
+ referrer: "fetch.referrer",
2434
+ referrerPolicy: "fetch.referrerPolicy",
2435
+ integrity: "fetch.integrity",
2436
+ keepalive: "fetch.keepalive",
2437
+ signal: "fetch.signal"
2438
+ };
2439
+
2440
+ // ../core/src/lib/loader-utils/option-utils.ts
2441
+ var CORE_LOADER_OPTION_KEYS = [
2442
+ "baseUri",
2443
+ "fetch",
2444
+ "mimeType",
2445
+ "fallbackMimeType",
2446
+ "ignoreRegisteredLoaders",
2447
+ "nothrow",
2448
+ "log",
2449
+ "useLocalLibraries",
2450
+ "CDN",
2451
+ "worker",
2452
+ "maxConcurrency",
2453
+ "maxMobileConcurrency",
2454
+ "reuseWorkers",
2455
+ "_nodeWorkers",
2456
+ "_workerType",
2457
+ "limit",
2458
+ "_limitMB",
2459
+ "batchSize",
2460
+ "batchDebounceMs",
2461
+ "metadata",
2462
+ "transforms"
2463
+ ];
2464
+ function getGlobalLoaderState() {
2465
+ globalThis.loaders = globalThis.loaders || {};
2466
+ const { loaders } = globalThis;
2467
+ if (!loaders._state) {
2468
+ loaders._state = {};
2469
+ }
2470
+ return loaders._state;
2471
+ }
2472
+ function getGlobalLoaderOptions() {
2473
+ const state = getGlobalLoaderState();
2474
+ state.globalOptions = state.globalOptions || {
2475
+ ...DEFAULT_LOADER_OPTIONS,
2476
+ core: { ...DEFAULT_LOADER_OPTIONS.core }
2477
+ };
2478
+ return normalizeLoaderOptions(state.globalOptions);
2479
+ }
2480
+ function setGlobalOptions(options) {
2481
+ const state = getGlobalLoaderState();
2482
+ const globalOptions = getGlobalLoaderOptions();
2483
+ state.globalOptions = normalizeOptionsInternal(globalOptions, options);
2484
+ registerJSModules(options.modules);
2485
+ }
2486
+ function normalizeOptions(options, loader, loaders, url) {
2487
+ loaders = loaders || [];
2488
+ loaders = Array.isArray(loaders) ? loaders : [loaders];
2489
+ validateOptions(options, loaders);
2490
+ return normalizeLoaderOptions(normalizeOptionsInternal(loader, options, url));
2491
+ }
2492
+ function normalizeLoaderOptions(options) {
2493
+ const normalized = cloneLoaderOptions(options);
2494
+ moveDeprecatedTopLevelOptionsToCore(normalized);
2495
+ for (const key of CORE_LOADER_OPTION_KEYS) {
2496
+ if (normalized.core && normalized.core[key] !== void 0) {
2497
+ delete normalized[key];
2498
+ }
2499
+ }
2500
+ if (normalized.core && normalized.core._workerType !== void 0) {
2501
+ delete normalized._worker;
2502
+ }
2503
+ return normalized;
2504
+ }
2505
+ function validateOptions(options, loaders) {
2506
+ validateOptionsObject(options, null, DEFAULT_LOADER_OPTIONS, REMOVED_LOADER_OPTIONS, loaders);
2507
+ for (const loader of loaders) {
2508
+ const idOptions = options && options[loader.id] || {};
2509
+ const loaderOptions = loader.options && loader.options[loader.id] || {};
2510
+ const deprecatedOptions = loader.deprecatedOptions && loader.deprecatedOptions[loader.id] || {};
2511
+ validateOptionsObject(idOptions, loader.id, loaderOptions, deprecatedOptions, loaders);
2512
+ }
2513
+ }
2514
+ function validateOptionsObject(options, id, defaultOptions, deprecatedOptions, loaders) {
2515
+ const loaderName = id || "Top level";
2516
+ const prefix = id ? `${id}.` : "";
2517
+ for (const key in options) {
2518
+ const isSubOptions = !id && isObject(options[key]);
2519
+ const isBaseUriOption = key === "baseUri" && !id;
2520
+ const isWorkerUrlOption = key === "workerUrl" && id;
2521
+ if (!(key in defaultOptions) && !isBaseUriOption && !isWorkerUrlOption) {
2522
+ if (key in deprecatedOptions) {
2523
+ probeLog.warn(
2524
+ `${loaderName} loader option '${prefix}${key}' no longer supported, use '${deprecatedOptions[key]}'`
2525
+ )();
2526
+ } else if (!isSubOptions) {
2527
+ const suggestion = findSimilarOption(key, loaders);
2528
+ probeLog.warn(
2529
+ `${loaderName} loader option '${prefix}${key}' not recognized. ${suggestion}`
2530
+ )();
2531
+ }
2532
+ }
2533
+ }
2534
+ }
2535
+ function findSimilarOption(optionKey, loaders) {
2536
+ const lowerCaseOptionKey = optionKey.toLowerCase();
2537
+ let bestSuggestion = "";
2538
+ for (const loader of loaders) {
2539
+ for (const key in loader.options) {
2540
+ if (optionKey === key) {
2541
+ return `Did you mean '${loader.id}.${key}'?`;
2542
+ }
2543
+ const lowerCaseKey = key.toLowerCase();
2544
+ const isPartialMatch = lowerCaseOptionKey.startsWith(lowerCaseKey) || lowerCaseKey.startsWith(lowerCaseOptionKey);
2545
+ if (isPartialMatch) {
2546
+ bestSuggestion = bestSuggestion || `Did you mean '${loader.id}.${key}'?`;
2547
+ }
2548
+ }
2549
+ }
2550
+ return bestSuggestion;
2551
+ }
2552
+ function normalizeOptionsInternal(loader, options, url) {
2553
+ const loaderDefaultOptions = loader.options || {};
2554
+ const mergedOptions = { ...loaderDefaultOptions };
2555
+ if (loaderDefaultOptions.core) {
2556
+ mergedOptions.core = { ...loaderDefaultOptions.core };
2557
+ }
2558
+ moveDeprecatedTopLevelOptionsToCore(mergedOptions);
2559
+ if (mergedOptions.core?.log === null) {
2560
+ mergedOptions.core = { ...mergedOptions.core, log: new NullLog() };
2561
+ }
2562
+ mergeNestedFields(mergedOptions, normalizeLoaderOptions(getGlobalLoaderOptions()));
2563
+ const userOptions = normalizeLoaderOptions(options);
2564
+ mergeNestedFields(mergedOptions, userOptions);
2565
+ addUrlOptions(mergedOptions, url);
2566
+ addDeprecatedTopLevelOptions(mergedOptions);
2567
+ return mergedOptions;
2568
+ }
2569
+ function mergeNestedFields(mergedOptions, options) {
2570
+ for (const key in options) {
2571
+ if (key in options) {
2572
+ const value = options[key];
2573
+ if (isPureObject(value) && isPureObject(mergedOptions[key])) {
2574
+ mergedOptions[key] = {
2575
+ ...mergedOptions[key],
2576
+ ...options[key]
2577
+ };
2578
+ } else {
2579
+ mergedOptions[key] = options[key];
2580
+ }
2581
+ }
2582
+ }
2583
+ }
2584
+ function addUrlOptions(options, url) {
2585
+ if (!url) {
2586
+ return;
2587
+ }
2588
+ const hasTopLevelBaseUri = options.baseUri !== void 0;
2589
+ const hasCoreBaseUri = options.core?.baseUri !== void 0;
2590
+ if (!hasTopLevelBaseUri && !hasCoreBaseUri) {
2591
+ options.core ||= {};
2592
+ options.core.baseUri = url;
2593
+ }
2594
+ }
2595
+ function cloneLoaderOptions(options) {
2596
+ const clonedOptions = { ...options };
2597
+ if (options.core) {
2598
+ clonedOptions.core = { ...options.core };
2599
+ }
2600
+ return clonedOptions;
2601
+ }
2602
+ function moveDeprecatedTopLevelOptionsToCore(options) {
2603
+ for (const key of CORE_LOADER_OPTION_KEYS) {
2604
+ if (options[key] !== void 0) {
2605
+ const coreOptions = options.core = options.core || {};
2606
+ const coreRecord = coreOptions;
2607
+ if (coreRecord[key] === void 0) {
2608
+ coreRecord[key] = options[key];
2609
+ }
2610
+ }
2611
+ }
2612
+ const workerTypeAlias = options._worker;
2613
+ if (workerTypeAlias !== void 0) {
2614
+ options.core ||= {};
2615
+ if (options.core._workerType === void 0) {
2616
+ options.core._workerType = workerTypeAlias;
2617
+ }
2618
+ }
2619
+ }
2620
+ function addDeprecatedTopLevelOptions(options) {
2621
+ const coreOptions = options.core;
2622
+ if (!coreOptions) {
2623
+ return;
2624
+ }
2625
+ for (const key of CORE_LOADER_OPTION_KEYS) {
2626
+ if (coreOptions[key] !== void 0) {
2627
+ options[key] = coreOptions[key];
2628
+ }
2629
+ }
2630
+ }
2631
+
2632
+ // ../core/src/lib/loader-utils/normalize-loader.ts
2633
+ function isLoaderObject(loader) {
2634
+ if (!loader) {
2635
+ return false;
2636
+ }
2637
+ if (Array.isArray(loader)) {
2638
+ loader = loader[0];
2639
+ }
2640
+ const hasExtensions = Array.isArray(loader?.extensions);
2641
+ return hasExtensions;
2642
+ }
2643
+ function normalizeLoader(loader) {
2644
+ assert(loader, "null loader");
2645
+ assert(isLoaderObject(loader), "invalid loader");
2646
+ let options;
2647
+ if (Array.isArray(loader)) {
2648
+ options = loader[1];
2649
+ loader = loader[0];
2650
+ loader = {
2651
+ ...loader,
2652
+ options: { ...loader.options, ...options }
2653
+ };
2654
+ }
2655
+ if (loader?.parseTextSync || loader?.parseText) {
2656
+ loader.text = true;
2657
+ }
2658
+ if (!loader.text) {
2659
+ loader.binary = true;
2660
+ }
2661
+ return loader;
2662
+ }
2663
+
2664
+ // ../core/src/lib/api/register-loaders.ts
2665
+ var getGlobalLoaderRegistry = () => {
2666
+ const state = getGlobalLoaderState();
2667
+ state.loaderRegistry = state.loaderRegistry || [];
2668
+ return state.loaderRegistry;
2669
+ };
2670
+ function registerLoaders(loaders) {
2671
+ const loaderRegistry = getGlobalLoaderRegistry();
2672
+ loaders = Array.isArray(loaders) ? loaders : [loaders];
2673
+ for (const loader of loaders) {
2674
+ const normalizedLoader = normalizeLoader(loader);
2675
+ if (!loaderRegistry.find((registeredLoader) => normalizedLoader === registeredLoader)) {
2676
+ loaderRegistry.unshift(normalizedLoader);
2677
+ }
2678
+ }
2679
+ }
2680
+ function getRegisteredLoaders() {
2681
+ return getGlobalLoaderRegistry();
2682
+ }
2683
+ function _unregisterLoaders() {
2684
+ const state = getGlobalLoaderState();
2685
+ state.loaderRegistry = [];
2686
+ }
2687
+
2688
+ // ../core/src/lib/api/select-loader.ts
2689
+ var EXT_PATTERN = /\.([^.]+)$/;
2690
+ async function selectLoader(data, loaders = [], options, context) {
2691
+ if (!validHTTPResponse(data)) {
2692
+ return null;
2693
+ }
2694
+ const normalizedOptions = normalizeLoaderOptions(options || {});
2695
+ normalizedOptions.core ||= {};
2696
+ let loader = selectLoaderSync(
2697
+ data,
2698
+ loaders,
2699
+ { ...normalizedOptions, core: { ...normalizedOptions.core, nothrow: true } },
2700
+ context
2701
+ );
2702
+ if (loader) {
2703
+ return loader;
2704
+ }
2705
+ if (isBlob(data)) {
2706
+ data = await data.slice(0, 10).arrayBuffer();
2707
+ loader = selectLoaderSync(data, loaders, normalizedOptions, context);
2708
+ }
2709
+ if (!loader && !normalizedOptions.core.nothrow) {
2710
+ throw new Error(getNoValidLoaderMessage(data));
2711
+ }
2712
+ return loader;
2713
+ }
2714
+ function selectLoaderSync(data, loaders = [], options, context) {
2715
+ if (!validHTTPResponse(data)) {
2716
+ return null;
2717
+ }
2718
+ const normalizedOptions = normalizeLoaderOptions(options || {});
2719
+ normalizedOptions.core ||= {};
2720
+ if (loaders && !Array.isArray(loaders)) {
2721
+ return normalizeLoader(loaders);
2722
+ }
2723
+ let candidateLoaders = [];
2724
+ if (loaders) {
2725
+ candidateLoaders = candidateLoaders.concat(loaders);
2726
+ }
2727
+ if (!normalizedOptions.core.ignoreRegisteredLoaders) {
2728
+ candidateLoaders.push(...getRegisteredLoaders());
2729
+ }
2730
+ normalizeLoaders(candidateLoaders);
2731
+ const loader = selectLoaderInternal(data, candidateLoaders, normalizedOptions, context);
2732
+ if (!loader && !normalizedOptions.core.nothrow) {
2733
+ throw new Error(getNoValidLoaderMessage(data));
2734
+ }
2735
+ return loader;
2736
+ }
2737
+ function selectLoaderInternal(data, loaders, options, context) {
2738
+ const url = getResourceUrl(data);
2739
+ const type = getResourceMIMEType(data);
2740
+ const testUrl = stripQueryString(url) || context?.url;
2741
+ let loader = null;
2742
+ let reason = "";
2743
+ if (options?.core?.mimeType) {
2744
+ loader = findLoaderByMIMEType(loaders, options?.core?.mimeType);
2745
+ reason = `match forced by supplied MIME type ${options?.core?.mimeType}`;
2746
+ }
2747
+ loader = loader || findLoaderByUrl(loaders, testUrl);
2748
+ reason = reason || (loader ? `matched url ${testUrl}` : "");
2749
+ loader = loader || findLoaderByMIMEType(loaders, type);
2750
+ reason = reason || (loader ? `matched MIME type ${type}` : "");
2751
+ loader = loader || findLoaderByInitialBytes(loaders, data);
2752
+ reason = reason || (loader ? `matched initial data ${getFirstCharacters(data)}` : "");
2753
+ if (options?.core?.fallbackMimeType) {
2754
+ loader = loader || findLoaderByMIMEType(loaders, options?.core?.fallbackMimeType);
2755
+ reason = reason || (loader ? `matched fallback MIME type ${type}` : "");
2756
+ }
2757
+ if (reason) {
2758
+ log.log(1, `selectLoader selected ${loader?.name}: ${reason}.`);
2759
+ }
2760
+ return loader;
2761
+ }
2762
+ function validHTTPResponse(data) {
2763
+ if (data instanceof Response) {
2764
+ if (data.status === 204) {
2765
+ return false;
2766
+ }
2767
+ }
2768
+ return true;
2769
+ }
2770
+ function getNoValidLoaderMessage(data) {
2771
+ const url = getResourceUrl(data);
2772
+ const type = getResourceMIMEType(data);
2773
+ let message = "No valid loader found (";
2774
+ message += url ? `${path_exports.filename(url)}, ` : "no url provided, ";
2775
+ message += `MIME type: ${type ? `"${type}"` : "not provided"}, `;
2776
+ const firstCharacters = data ? getFirstCharacters(data) : "";
2777
+ message += firstCharacters ? ` first bytes: "${firstCharacters}"` : "first bytes: not available";
2778
+ message += ")";
2779
+ return message;
2780
+ }
2781
+ function normalizeLoaders(loaders) {
2782
+ for (const loader of loaders) {
2783
+ normalizeLoader(loader);
2784
+ }
2785
+ }
2786
+ function findLoaderByUrl(loaders, url) {
2787
+ const match = url && EXT_PATTERN.exec(url);
2788
+ const extension = match && match[1];
2789
+ return extension ? findLoaderByExtension(loaders, extension) : null;
2790
+ }
2791
+ function findLoaderByExtension(loaders, extension) {
2792
+ extension = extension.toLowerCase();
2793
+ for (const loader of loaders) {
2794
+ for (const loaderExtension of loader.extensions) {
2795
+ if (loaderExtension.toLowerCase() === extension) {
2796
+ return loader;
2797
+ }
2798
+ }
2799
+ }
2800
+ return null;
2801
+ }
2802
+ function findLoaderByMIMEType(loaders, mimeType) {
2803
+ for (const loader of loaders) {
2804
+ if (loader.mimeTypes?.some((mimeType1) => compareMIMETypes(mimeType, mimeType1))) {
2805
+ return loader;
2806
+ }
2807
+ if (compareMIMETypes(mimeType, `application/x.${loader.id}`)) {
2808
+ return loader;
2809
+ }
2810
+ }
2811
+ return null;
2812
+ }
2813
+ function findLoaderByInitialBytes(loaders, data) {
2814
+ if (!data) {
2815
+ return null;
2816
+ }
2817
+ for (const loader of loaders) {
2818
+ if (typeof data === "string") {
2819
+ if (testDataAgainstText(data, loader)) {
2820
+ return loader;
2821
+ }
2822
+ } else if (ArrayBuffer.isView(data)) {
2823
+ if (testDataAgainstBinary(data.buffer, data.byteOffset, loader)) {
2824
+ return loader;
2825
+ }
2826
+ } else if (data instanceof ArrayBuffer) {
2827
+ const byteOffset = 0;
2828
+ if (testDataAgainstBinary(data, byteOffset, loader)) {
2829
+ return loader;
2830
+ }
2831
+ }
2832
+ }
2833
+ return null;
2834
+ }
2835
+ function testDataAgainstText(data, loader) {
2836
+ if (loader.testText) {
2837
+ return loader.testText(data);
2838
+ }
2839
+ const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
2840
+ return tests.some((test) => data.startsWith(test));
2841
+ }
2842
+ function testDataAgainstBinary(data, byteOffset, loader) {
2843
+ const tests = Array.isArray(loader.tests) ? loader.tests : [loader.tests];
2844
+ return tests.some((test) => testBinary(data, byteOffset, loader, test));
2845
+ }
2846
+ function testBinary(data, byteOffset, loader, test) {
2847
+ if (isArrayBufferLike(test)) {
2848
+ return compareArrayBuffers(test, data, test.byteLength);
2849
+ }
2850
+ switch (typeof test) {
2851
+ case "function":
2852
+ return test(ensureArrayBuffer(data));
2853
+ case "string":
2854
+ const magic = getMagicString(data, byteOffset, test.length);
2855
+ return test === magic;
2856
+ default:
2857
+ return false;
2858
+ }
2859
+ }
2860
+ function getFirstCharacters(data, length = 5) {
2861
+ if (typeof data === "string") {
2862
+ return data.slice(0, length);
2863
+ } else if (ArrayBuffer.isView(data)) {
2864
+ return getMagicString(data.buffer, data.byteOffset, length);
2865
+ } else if (data instanceof ArrayBuffer) {
2866
+ const byteOffset = 0;
2867
+ return getMagicString(data, byteOffset, length);
2868
+ }
2869
+ return "";
2870
+ }
2871
+ function getMagicString(arrayBuffer, byteOffset, length) {
2872
+ if (arrayBuffer.byteLength < byteOffset + length) {
2873
+ return "";
2874
+ }
2875
+ const dataView = new DataView(arrayBuffer);
2876
+ let magic = "";
2877
+ for (let i = 0; i < length; i++) {
2878
+ magic += String.fromCharCode(dataView.getUint8(byteOffset + i));
2879
+ }
2880
+ return magic;
2881
+ }
2882
+
2883
+ // ../core/src/iterators/make-iterator/make-string-iterator.ts
2884
+ var DEFAULT_CHUNK_SIZE = 256 * 1024;
2885
+ function* makeStringIterator(string, options) {
2886
+ const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE;
2887
+ let offset = 0;
2888
+ const textEncoder = new TextEncoder();
2889
+ while (offset < string.length) {
2890
+ const chunkLength = Math.min(string.length - offset, chunkSize);
2891
+ const chunk = string.slice(offset, offset + chunkLength);
2892
+ offset += chunkLength;
2893
+ yield ensureArrayBuffer(textEncoder.encode(chunk));
2894
+ }
2895
+ }
2896
+
2897
+ // ../core/src/iterators/make-iterator/make-array-buffer-iterator.ts
2898
+ var DEFAULT_CHUNK_SIZE2 = 256 * 1024;
2899
+ function* makeArrayBufferIterator(arrayBuffer, options = {}) {
2900
+ const { chunkSize = DEFAULT_CHUNK_SIZE2 } = options;
2901
+ let byteOffset = 0;
2902
+ while (byteOffset < arrayBuffer.byteLength) {
2903
+ const chunkByteLength = Math.min(arrayBuffer.byteLength - byteOffset, chunkSize);
2904
+ const chunk = new ArrayBuffer(chunkByteLength);
2905
+ const sourceArray = new Uint8Array(arrayBuffer, byteOffset, chunkByteLength);
2906
+ const chunkArray = new Uint8Array(chunk);
2907
+ chunkArray.set(sourceArray);
2908
+ byteOffset += chunkByteLength;
2909
+ yield chunk;
2910
+ }
2911
+ }
2912
+
2913
+ // ../core/src/iterators/make-iterator/make-blob-iterator.ts
2914
+ var DEFAULT_CHUNK_SIZE3 = 1024 * 1024;
2915
+ async function* makeBlobIterator(blob, options) {
2916
+ const chunkSize = options?.chunkSize || DEFAULT_CHUNK_SIZE3;
2917
+ let offset = 0;
2918
+ while (offset < blob.size) {
2919
+ const end = offset + chunkSize;
2920
+ const chunk = await blob.slice(offset, end).arrayBuffer();
2921
+ offset = end;
2922
+ yield chunk;
2923
+ }
2924
+ }
2925
+
2926
+ // ../core/src/iterators/make-iterator/make-stream-iterator.ts
2927
+ function makeStreamIterator(stream, options) {
2928
+ return isBrowser ? makeBrowserStreamIterator(stream, options) : makeNodeStreamIterator(stream, options);
2929
+ }
2930
+ async function* makeBrowserStreamIterator(stream, options) {
2931
+ const reader = stream.getReader();
2932
+ let nextBatchPromise;
2933
+ try {
2934
+ while (true) {
2935
+ const currentBatchPromise = nextBatchPromise || reader.read();
2936
+ if (options?._streamReadAhead) {
2937
+ nextBatchPromise = reader.read();
2938
+ }
2939
+ const { done, value } = await currentBatchPromise;
2940
+ if (done) {
2941
+ return;
2942
+ }
2943
+ yield toArrayBuffer2(value);
2944
+ }
2945
+ } catch (error) {
2946
+ reader.releaseLock();
2947
+ }
2948
+ }
2949
+ async function* makeNodeStreamIterator(stream, options) {
2950
+ for await (const chunk of stream) {
2951
+ yield toArrayBuffer2(chunk);
2952
+ }
2953
+ }
2954
+
2955
+ // ../core/src/iterators/make-iterator/make-iterator.ts
2956
+ function makeIterator(data, options) {
2957
+ if (typeof data === "string") {
2958
+ return makeStringIterator(data, options);
2959
+ }
2960
+ if (data instanceof ArrayBuffer) {
2961
+ return makeArrayBufferIterator(data, options);
2962
+ }
2963
+ if (isBlob(data)) {
2964
+ return makeBlobIterator(data, options);
2965
+ }
2966
+ if (isReadableStream(data)) {
2967
+ return makeStreamIterator(data, options);
2968
+ }
2969
+ if (isResponse(data)) {
2970
+ const responseBody = data.body;
2971
+ if (!responseBody) {
2972
+ throw new Error("Readable stream not available on Response");
2973
+ }
2974
+ return makeStreamIterator(responseBody, options);
2975
+ }
2976
+ throw new Error("makeIterator");
2977
+ }
2978
+
2979
+ // ../core/src/lib/loader-utils/get-data.ts
2980
+ var ERR_DATA = "Cannot convert supplied data type";
2981
+ function getArrayBufferOrStringFromDataSync(data, loader, options) {
2982
+ if (loader.text && typeof data === "string") {
2983
+ return data;
2984
+ }
2985
+ if (isBuffer(data)) {
2986
+ data = data.buffer;
2987
+ }
2988
+ if (isArrayBufferLike(data)) {
2989
+ const bufferSource = toArrayBufferView(data);
2990
+ if (loader.text && !loader.binary) {
2991
+ const textDecoder = new TextDecoder("utf8");
2992
+ return textDecoder.decode(bufferSource);
2993
+ }
2994
+ return toArrayBuffer2(bufferSource);
2995
+ }
2996
+ throw new Error(ERR_DATA);
2997
+ }
2998
+ async function getArrayBufferOrStringFromData(data, loader, options) {
2999
+ if (typeof data === "string" || isArrayBufferLike(data)) {
3000
+ return getArrayBufferOrStringFromDataSync(data, loader, options);
3001
+ }
3002
+ if (isBlob(data)) {
3003
+ data = await makeResponse(data);
3004
+ }
3005
+ if (isResponse(data)) {
3006
+ await checkResponse(data);
3007
+ return loader.binary ? await data.arrayBuffer() : await data.text();
3008
+ }
3009
+ if (isReadableStream(data)) {
3010
+ data = makeIterator(data, options);
3011
+ }
3012
+ if (isIterable(data) || isAsyncIterable(data)) {
3013
+ return concatenateArrayBuffersAsync(data);
3014
+ }
3015
+ throw new Error(ERR_DATA);
3016
+ }
3017
+ async function getAsyncIterableFromData(data, options) {
3018
+ if (isPromise(data)) {
3019
+ data = await data;
3020
+ }
3021
+ if (isIterator(data)) {
3022
+ return data;
3023
+ }
3024
+ if (isResponse(data)) {
3025
+ await checkResponse(data);
3026
+ const body = await data.body;
3027
+ if (!body) {
3028
+ throw new Error(ERR_DATA);
3029
+ }
3030
+ return makeIterator(body, options);
3031
+ }
3032
+ if (isBlob(data) || isReadableStream(data)) {
3033
+ return makeIterator(data, options);
3034
+ }
3035
+ if (isAsyncIterable(data)) {
3036
+ return data;
3037
+ }
3038
+ if (isIterable(data)) {
3039
+ return data;
3040
+ }
3041
+ return getIterableFromData(data);
3042
+ }
3043
+ function getIterableFromData(data) {
3044
+ if (ArrayBuffer.isView(data)) {
3045
+ return function* oneChunk() {
3046
+ yield toArrayBuffer2(data);
3047
+ }();
3048
+ }
3049
+ if (isArrayBufferLike(data)) {
3050
+ return function* oneChunk() {
3051
+ yield toArrayBuffer2(data);
3052
+ }();
3053
+ }
3054
+ if (isIterator(data)) {
3055
+ return data;
3056
+ }
3057
+ if (isIterable(data)) {
3058
+ return data[Symbol.iterator]();
3059
+ }
3060
+ throw new Error(ERR_DATA);
3061
+ }
3062
+
3063
+ // ../core/src/lib/loader-utils/get-fetch-function.ts
3064
+ function getFetchFunction(options, context) {
3065
+ const globalOptions = getGlobalLoaderOptions();
3066
+ const loaderOptions = options || globalOptions;
3067
+ const fetchOption = loaderOptions.fetch ?? loaderOptions.core?.fetch;
3068
+ if (typeof fetchOption === "function") {
3069
+ return fetchOption;
3070
+ }
3071
+ if (isObject(fetchOption)) {
3072
+ return (url) => fetchFile(url, fetchOption);
3073
+ }
3074
+ if (context?.fetch) {
3075
+ return context?.fetch;
3076
+ }
3077
+ return fetchFile;
3078
+ }
3079
+
3080
+ // ../core/src/lib/loader-utils/loader-context.ts
3081
+ function getLoaderContext(context, options, parentContext) {
3082
+ if (parentContext) {
3083
+ return parentContext;
3084
+ }
3085
+ const newContext = {
3086
+ fetch: getFetchFunction(options, context),
3087
+ ...context
3088
+ };
3089
+ if (newContext.url) {
3090
+ const baseUrl = stripQueryString(newContext.url);
3091
+ newContext.baseUrl = baseUrl;
3092
+ newContext.queryString = extractQueryString(newContext.url);
3093
+ newContext.filename = path_exports.filename(baseUrl);
3094
+ newContext.baseUrl = path_exports.dirname(baseUrl);
3095
+ }
3096
+ if (!Array.isArray(newContext.loaders)) {
3097
+ newContext.loaders = null;
3098
+ }
3099
+ return newContext;
3100
+ }
3101
+ function getLoadersFromContext(loaders, context) {
3102
+ if (loaders && !Array.isArray(loaders)) {
3103
+ return loaders;
3104
+ }
3105
+ let candidateLoaders;
3106
+ if (loaders) {
3107
+ candidateLoaders = Array.isArray(loaders) ? loaders : [loaders];
3108
+ }
3109
+ if (context && context.loaders) {
3110
+ const contextLoaders = Array.isArray(context.loaders) ? context.loaders : [context.loaders];
3111
+ candidateLoaders = candidateLoaders ? [...candidateLoaders, ...contextLoaders] : contextLoaders;
3112
+ }
3113
+ return candidateLoaders && candidateLoaders.length ? candidateLoaders : void 0;
3114
+ }
3115
+
3116
+ // ../core/src/lib/api/parse.ts
3117
+ async function parse(data, loaders, options, context) {
3118
+ if (loaders && !Array.isArray(loaders) && !isLoaderObject(loaders)) {
3119
+ context = void 0;
3120
+ options = loaders;
3121
+ loaders = void 0;
3122
+ }
3123
+ data = await data;
3124
+ options = options || {};
3125
+ const url = getResourceUrl(data);
3126
+ const typedLoaders = loaders;
3127
+ const candidateLoaders = getLoadersFromContext(typedLoaders, context);
3128
+ const loader = await selectLoader(data, candidateLoaders, options);
3129
+ if (!loader) {
3130
+ return null;
3131
+ }
3132
+ const strictOptions = normalizeOptions(options, loader, candidateLoaders, url);
3133
+ context = getLoaderContext(
3134
+ // @ts-expect-error
3135
+ { url, _parse: parse, loaders: candidateLoaders },
3136
+ strictOptions,
3137
+ context || null
3138
+ );
3139
+ return await parseWithLoader(loader, data, strictOptions, context);
3140
+ }
3141
+ async function parseWithLoader(loader, data, options, context) {
3142
+ validateWorkerVersion(loader);
3143
+ options = mergeOptions(loader.options, options);
3144
+ if (isResponse(data)) {
3145
+ const { ok, redirected, status, statusText, type, url } = data;
3146
+ const headers = Object.fromEntries(data.headers.entries());
3147
+ context.response = { headers, ok, redirected, status, statusText, type, url };
3148
+ }
3149
+ data = await getArrayBufferOrStringFromData(data, loader, options);
3150
+ const loaderWithParser = loader;
3151
+ if (loaderWithParser.parseTextSync && typeof data === "string") {
3152
+ return loaderWithParser.parseTextSync(data, options, context);
3153
+ }
3154
+ if (canParseWithWorker(loader, options)) {
3155
+ return await parseWithWorker(loader, data, options, context, parse);
3156
+ }
3157
+ if (loaderWithParser.parseText && typeof data === "string") {
3158
+ return await loaderWithParser.parseText(data, options, context);
3159
+ }
3160
+ if (loaderWithParser.parse) {
3161
+ return await loaderWithParser.parse(data, options, context);
3162
+ }
3163
+ assert3(!loaderWithParser.parseSync);
3164
+ throw new Error(`${loader.id} loader - no parser found and worker is disabled`);
3165
+ }
3166
+
3167
+ // ../core/src/lib/api/parse-sync.ts
3168
+ function parseSync(data, loaders, options, context) {
3169
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3170
+ context = void 0;
3171
+ options = loaders;
3172
+ loaders = void 0;
3173
+ }
3174
+ options = options || {};
3175
+ const typedLoaders = loaders;
3176
+ const candidateLoaders = getLoadersFromContext(typedLoaders, context);
3177
+ const loader = selectLoaderSync(data, candidateLoaders, options);
3178
+ if (!loader) {
3179
+ return null;
3180
+ }
3181
+ const strictOptions = normalizeOptions(options, loader, candidateLoaders);
3182
+ const url = getResourceUrl(data);
3183
+ const parse2 = () => {
3184
+ throw new Error("parseSync called parse (which is async");
3185
+ };
3186
+ context = getLoaderContext(
3187
+ { url, _parseSync: parse2, _parse: parse2, loaders },
3188
+ strictOptions,
3189
+ context || null
3190
+ );
3191
+ return parseWithLoaderSync(loader, data, strictOptions, context);
3192
+ }
3193
+ function parseWithLoaderSync(loader, data, options, context) {
3194
+ data = getArrayBufferOrStringFromDataSync(data, loader, options);
3195
+ if (loader.parseTextSync && typeof data === "string") {
3196
+ return loader.parseTextSync(data, options);
3197
+ }
3198
+ if (loader.parseSync && data instanceof ArrayBuffer) {
3199
+ return loader.parseSync(data, options, context);
3200
+ }
3201
+ throw new Error(
3202
+ `${loader.name} loader: 'parseSync' not supported by this loader, use 'parse' instead. ${context.url || ""}`
3203
+ );
3204
+ }
3205
+
3206
+ // ../schema-utils/src/lib/table/tables/table-accessors.ts
3207
+ function isTable(table) {
3208
+ const shape = typeof table === "object" && table?.shape;
3209
+ switch (shape) {
3210
+ case "array-row-table":
3211
+ case "object-row-table":
3212
+ return Array.isArray(table.data);
3213
+ case "geojson-table":
3214
+ return Array.isArray(table.features);
3215
+ case "columnar-table":
3216
+ return table.data && typeof table.data === "object";
3217
+ case "arrow-table":
3218
+ return Boolean(table?.data?.numRows !== void 0);
3219
+ default:
3220
+ return false;
3221
+ }
3222
+ }
3223
+ function getTableLength(table) {
3224
+ switch (table.shape) {
3225
+ case "array-row-table":
3226
+ case "object-row-table":
3227
+ return table.data.length;
3228
+ case "geojson-table":
3229
+ return table.features.length;
3230
+ case "arrow-table":
3231
+ const arrowTable = table.data;
3232
+ return arrowTable.numRows;
3233
+ case "columnar-table":
3234
+ for (const column of Object.values(table.data)) {
3235
+ return column.length || 0;
3236
+ }
3237
+ return 0;
3238
+ default:
3239
+ throw new Error("table");
3240
+ }
3241
+ }
3242
+
3243
+ // ../schema-utils/src/lib/table/batches/make-table-batch-iterator.ts
3244
+ function makeBatchFromTable(table) {
3245
+ return { ...table, length: getTableLength(table), batchType: "data" };
3246
+ }
3247
+
3248
+ // ../core/src/lib/api/parse-in-batches.ts
3249
+ async function parseInBatches(data, loaders, options, context) {
3250
+ const loaderArray = Array.isArray(loaders) ? loaders : void 0;
3251
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3252
+ context = void 0;
3253
+ options = loaders;
3254
+ loaders = void 0;
3255
+ }
3256
+ data = await data;
3257
+ options = options || {};
3258
+ const url = getResourceUrl(data);
3259
+ const loader = await selectLoader(data, loaders, options);
3260
+ if (!loader) {
3261
+ return [];
3262
+ }
3263
+ const strictOptions = normalizeOptions(options, loader, loaderArray, url);
3264
+ context = getLoaderContext(
3265
+ { url, _parseInBatches: parseInBatches, _parse: parse, loaders: loaderArray },
3266
+ strictOptions,
3267
+ context || null
3268
+ );
3269
+ return await parseWithLoaderInBatches(loader, data, strictOptions, context);
3270
+ }
3271
+ async function parseWithLoaderInBatches(loader, data, options, context) {
3272
+ const outputIterator = await parseToOutputIterator(loader, data, options, context);
3273
+ if (!options?.core?.metadata) {
3274
+ return outputIterator;
3275
+ }
3276
+ const metadataBatch = {
3277
+ shape: "metadata",
3278
+ batchType: "metadata",
3279
+ metadata: {
3280
+ _loader: loader,
3281
+ _context: context
3282
+ },
3283
+ // Populate with some default fields to avoid crashing
3284
+ data: [],
3285
+ bytesUsed: 0
3286
+ };
3287
+ async function* makeMetadataBatchIterator(iterator) {
3288
+ yield metadataBatch;
3289
+ yield* iterator;
3290
+ }
3291
+ return makeMetadataBatchIterator(outputIterator);
3292
+ }
3293
+ async function parseToOutputIterator(loader, data, options, context) {
3294
+ const inputIterator = await getAsyncIterableFromData(data, options);
3295
+ const transformedIterator = await applyInputTransforms(
3296
+ inputIterator,
3297
+ options?.core?.transforms || []
3298
+ );
3299
+ if (loader.parseInBatches) {
3300
+ return loader.parseInBatches(transformedIterator, options, context);
3301
+ }
3302
+ return parseChunkInBatches(transformedIterator, loader, options, context);
3303
+ }
3304
+ async function* parseChunkInBatches(transformedIterator, loader, options, context) {
3305
+ const arrayBuffer = await concatenateArrayBuffersAsync(transformedIterator);
3306
+ const parsedData = await parse(
3307
+ arrayBuffer,
3308
+ loader,
3309
+ // TODO - Hack: supply loaders MIME type to ensure we match it
3310
+ { ...options, core: { ...options?.core, mimeType: loader.mimeTypes[0] } },
3311
+ context
3312
+ );
3313
+ const batch = convertDataToBatch(parsedData, loader);
3314
+ yield batch;
3315
+ }
3316
+ function convertDataToBatch(parsedData, loader) {
3317
+ const batch = isTable(parsedData) ? makeBatchFromTable(parsedData) : {
3318
+ shape: "unknown",
3319
+ batchType: "data",
3320
+ data: parsedData,
3321
+ length: Array.isArray(parsedData) ? parsedData.length : 1
3322
+ };
3323
+ batch.mimeType = loader.mimeTypes[0];
3324
+ return batch;
3325
+ }
3326
+ async function applyInputTransforms(inputIterator, transforms = []) {
3327
+ let iteratorChain = inputIterator;
3328
+ for await (const transformBatches of transforms) {
3329
+ iteratorChain = transformBatches(iteratorChain);
3330
+ }
3331
+ return iteratorChain;
3332
+ }
3333
+
3334
+ // ../core/src/lib/api/load.ts
3335
+ async function load(url, loaders, options, context) {
3336
+ let resolvedLoaders;
3337
+ let resolvedOptions;
3338
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3339
+ resolvedLoaders = [];
3340
+ resolvedOptions = loaders;
3341
+ context = void 0;
3342
+ } else {
3343
+ resolvedLoaders = loaders;
3344
+ resolvedOptions = options;
3345
+ }
3346
+ const fetch2 = getFetchFunction(resolvedOptions);
3347
+ let data = url;
3348
+ if (typeof url === "string") {
3349
+ data = await fetch2(url);
3350
+ }
3351
+ if (isBlob(url)) {
3352
+ data = await fetch2(url);
3353
+ }
3354
+ return Array.isArray(resolvedLoaders) ? await parse(data, resolvedLoaders, resolvedOptions) : await parse(data, resolvedLoaders, resolvedOptions);
3355
+ }
3356
+
3357
+ // ../core/src/lib/api/load-in-batches.ts
3358
+ function loadInBatches(files, loaders, options, context) {
3359
+ let loadersArray;
3360
+ if (!Array.isArray(loaders) && !isLoaderObject(loaders)) {
3361
+ context = void 0;
3362
+ options = loaders;
3363
+ loadersArray = void 0;
3364
+ } else {
3365
+ loadersArray = loaders;
3366
+ }
3367
+ const fetch2 = getFetchFunction(options || {});
3368
+ if (!Array.isArray(files)) {
3369
+ return loadOneFileInBatches(files, loadersArray, options || {}, fetch2);
3370
+ }
3371
+ const promises = files.map(
3372
+ (file) => loadOneFileInBatches(file, loadersArray, options || {}, fetch2)
3373
+ );
3374
+ return promises;
3375
+ }
3376
+ async function loadOneFileInBatches(file, loaders, options, fetch2) {
3377
+ if (typeof file === "string") {
3378
+ const url = file;
3379
+ const response = await fetch2(url);
3380
+ return Array.isArray(loaders) ? await parseInBatches(response, loaders, options) : await parseInBatches(response, loaders, options);
3381
+ }
3382
+ return Array.isArray(loaders) ? await parseInBatches(file, loaders, options) : await parseInBatches(file, loaders, options);
3383
+ }
3384
+
3385
+ // ../core/src/lib/api/encode-table.ts
3386
+ async function encodeTable(data, writer, options) {
3387
+ if (writer.encode) {
3388
+ return await writer.encode(data, options);
3389
+ }
3390
+ if (writer.encodeText) {
3391
+ const text = await writer.encodeText(data, options);
3392
+ return ensureArrayBuffer(new TextEncoder().encode(text));
3393
+ }
3394
+ if (writer.encodeInBatches) {
3395
+ const batches = encodeTableInBatches(data, writer, options);
3396
+ const chunks = [];
3397
+ for await (const batch of batches) {
3398
+ chunks.push(batch);
3399
+ }
3400
+ return concatenateArrayBuffers(...chunks);
3401
+ }
3402
+ throw new Error("Writer could not encode data");
3403
+ }
3404
+ async function encodeTableAsText(data, writer, options) {
3405
+ if (writer.text && writer.encodeText) {
3406
+ return await writer.encodeText(data, options);
3407
+ }
3408
+ if (writer.text) {
3409
+ const arrayBuffer = await encodeTable(data, writer, options);
3410
+ return new TextDecoder().decode(arrayBuffer);
3411
+ }
3412
+ throw new Error(`Writer ${writer.name} could not encode data as text`);
3413
+ }
3414
+ function encodeTableInBatches(data, writer, options) {
3415
+ if (writer.encodeInBatches) {
3416
+ const dataIterator = getIterator(data);
3417
+ return writer.encodeInBatches(dataIterator, options);
3418
+ }
3419
+ throw new Error("Writer could not encode data in batches");
3420
+ }
3421
+ function getIterator(data) {
3422
+ const dataIterator = [{ ...data, start: 0, end: data.length }];
3423
+ return dataIterator;
3424
+ }
3425
+
3426
+ // ../core/src/lib/api/encode.ts
3427
+ async function encode(data, writer, options_) {
3428
+ const globalOptions = getGlobalLoaderOptions();
3429
+ const options = { ...globalOptions, ...options_ };
3430
+ if (writer.encodeURLtoURL) {
3431
+ return encodeWithCommandLineTool(writer, data, options);
3432
+ }
3433
+ if (canEncodeWithWorker(writer, options)) {
3434
+ return await processOnWorker(writer, data, options);
3435
+ }
3436
+ return await writer.encode(data, options);
3437
+ }
3438
+ function encodeSync(data, writer, options) {
3439
+ if (writer.encodeSync) {
3440
+ return writer.encodeSync(data, options);
3441
+ }
3442
+ if (writer.encodeTextSync) {
3443
+ return ensureArrayBuffer(new TextEncoder().encode(writer.encodeTextSync(data, options)));
3444
+ }
3445
+ throw new Error(`Writer ${writer.name} could not synchronously encode data`);
3446
+ }
3447
+ async function encodeText(data, writer, options) {
3448
+ if (writer.encodeText) {
3449
+ return await writer.encodeText(data, options);
3450
+ }
3451
+ if (writer.encodeTextSync) {
3452
+ return writer.encodeTextSync(data, options);
3453
+ }
3454
+ if (writer.text) {
3455
+ const arrayBuffer = await writer.encode(data, options);
3456
+ return new TextDecoder().decode(arrayBuffer);
3457
+ }
3458
+ throw new Error(`Writer ${writer.name} could not encode data as text`);
3459
+ }
3460
+ function encodeTextSync(data, writer, options) {
3461
+ if (writer.encodeTextSync) {
3462
+ return writer.encodeTextSync(data, options);
3463
+ }
3464
+ if (writer.text && writer.encodeSync) {
3465
+ const arrayBuffer = encodeSync(data, writer, options);
3466
+ return new TextDecoder().decode(arrayBuffer);
3467
+ }
3468
+ throw new Error(`Writer ${writer.name} could not encode data as text`);
3469
+ }
3470
+ function encodeInBatches(data, writer, options) {
3471
+ if (writer.encodeInBatches) {
3472
+ const dataIterator = getIterator2(data);
3473
+ return writer.encodeInBatches(dataIterator, options);
3474
+ }
3475
+ throw new Error(`Writer ${writer.name} could not encode in batches`);
3476
+ }
3477
+ async function encodeURLtoURL(inputUrl, outputUrl, writer, options) {
3478
+ inputUrl = resolvePath(inputUrl);
3479
+ outputUrl = resolvePath(outputUrl);
3480
+ if (isBrowser || !writer.encodeURLtoURL) {
3481
+ throw new Error();
3482
+ }
3483
+ const outputFilename = await writer.encodeURLtoURL(inputUrl, outputUrl, options);
3484
+ return outputFilename;
3485
+ }
3486
+ async function encodeWithCommandLineTool(writer, data, options) {
3487
+ if (isBrowser) {
3488
+ throw new Error(`Writer ${writer.name} not supported in browser`);
3489
+ }
3490
+ const tmpInputFilename = getTemporaryFilename("input");
3491
+ const file = new NodeFileFacade(tmpInputFilename, "w");
3492
+ await file.write(data);
3493
+ const tmpOutputFilename = getTemporaryFilename("output");
3494
+ const outputFilename = await encodeURLtoURL(tmpInputFilename, tmpOutputFilename, writer, options);
3495
+ const response = await fetchFile(outputFilename);
3496
+ return response.arrayBuffer();
3497
+ }
3498
+ function getIterator2(data) {
3499
+ const dataIterator = [{ ...data, start: 0, end: data.length }];
3500
+ return dataIterator;
3501
+ }
3502
+ function getTemporaryFilename(filename2) {
3503
+ return `/tmp/${filename2}`;
3504
+ }
3505
+
3506
+ // ../core/src/lib/api/create-data-source.ts
3507
+ function createDataSource(data, sources, options) {
3508
+ const type = options?.core?.type || options.type || "auto";
3509
+ const source = type === "auto" ? selectSource(data, sources) : getSourceOfType(type, sources);
3510
+ if (!source) {
3511
+ throw new Error("Not a valid source type");
3512
+ }
3513
+ return source.createDataSource(data, options);
3514
+ }
3515
+ function selectSource(url, sources) {
3516
+ for (const service of sources) {
3517
+ if (service.testURL && service.testURL(url)) {
3518
+ return service;
3519
+ }
3520
+ }
3521
+ return null;
3522
+ }
3523
+ function getSourceOfType(type, sources) {
3524
+ for (const service of sources) {
3525
+ if (service.type === type) {
3526
+ return service;
3527
+ }
3528
+ }
3529
+ return null;
3530
+ }
3531
+
3532
+ // ../core/src/lib/api/select-source.ts
3533
+ function selectSource2(url, sources, options) {
3534
+ const type = options?.type || "auto";
3535
+ let selectedSource = null;
3536
+ if (type === "auto") {
3537
+ for (const source of sources) {
3538
+ if (typeof url === "string" && source.testURL && source.testURL(url)) {
3539
+ return source;
3540
+ }
3541
+ }
3542
+ } else {
3543
+ selectedSource = getSourceOfType2(type, sources);
3544
+ }
3545
+ if (!selectedSource && !options?.nothrow) {
3546
+ throw new Error("Not a valid image source type");
3547
+ }
3548
+ return selectedSource;
3549
+ }
3550
+ function getSourceOfType2(type, sources) {
3551
+ for (const service of sources) {
3552
+ if (service.type === type) {
3553
+ return service;
3554
+ }
3555
+ }
3556
+ return null;
3557
+ }
3558
+
3559
+ // ../core/src/iterators/make-stream/make-stream.ts
3560
+ function makeStream(source, options) {
3561
+ if (globalThis.loaders.makeNodeStream) {
3562
+ return globalThis.loaders.makeNodeStream(source, options);
3563
+ }
3564
+ const iterator = source[Symbol.asyncIterator] ? source[Symbol.asyncIterator]() : source[Symbol.iterator]();
3565
+ return new ReadableStream(
3566
+ {
3567
+ // Create a byte stream (enables `Response(stream).arrayBuffer()`)
3568
+ // Only supported on Chrome
3569
+ // See: https://developer.mozilla.org/en-US/docs/Web/API/ReadableByteStreamController
3570
+ // @ts-ignore
3571
+ type: "bytes",
3572
+ async pull(controller) {
3573
+ try {
3574
+ const { done, value } = await iterator.next();
3575
+ if (done) {
3576
+ controller.close();
3577
+ } else {
3578
+ controller.enqueue(new Uint8Array(value));
3579
+ }
3580
+ } catch (error) {
3581
+ controller.error(error);
3582
+ }
3583
+ },
3584
+ async cancel() {
3585
+ await iterator?.return?.();
3586
+ }
3587
+ },
3588
+ // options: QueingStrategy<Uint8Array>
3589
+ {
3590
+ // This is bytes, not chunks
3591
+ highWaterMark: 2 ** 24,
3592
+ ...options
3593
+ }
3594
+ );
3595
+ }
3596
+
3597
+ // ../core/src/null-loader.ts
3598
+ var VERSION5 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
3599
+ var NullWorkerLoader = {
3600
+ dataType: null,
3601
+ batchType: null,
3602
+ name: "Null loader",
3603
+ id: "null",
3604
+ module: "core",
3605
+ version: VERSION5,
3606
+ worker: true,
3607
+ mimeTypes: ["application/x.empty"],
3608
+ extensions: ["null"],
3609
+ tests: [() => false],
3610
+ options: {
3611
+ null: {}
3612
+ }
3613
+ };
3614
+ var NullLoader = {
3615
+ dataType: null,
3616
+ batchType: null,
3617
+ name: "Null loader",
3618
+ id: "null",
3619
+ module: "core",
3620
+ version: VERSION5,
3621
+ mimeTypes: ["application/x.empty"],
3622
+ extensions: ["null"],
3623
+ parse: async (arrayBuffer, options, context) => parseSync2(arrayBuffer, options || {}, context),
3624
+ parseSync: parseSync2,
3625
+ parseInBatches: async function* generator(asyncIterator, options, context) {
3626
+ for await (const batch of asyncIterator) {
3627
+ yield parseSync2(batch, options, context);
3628
+ }
3629
+ },
3630
+ tests: [() => false],
3631
+ options: {
3632
+ null: {}
3633
+ }
3634
+ };
3635
+ function parseSync2(arrayBuffer, options, context) {
3636
+ return null;
3637
+ }
3638
+
3639
+ // ../core/src/lib/progress/fetch-progress.ts
3640
+ async function fetchProgress(response, onProgress, onDone = () => {
3641
+ }, onError = () => {
3642
+ }) {
3643
+ response = await response;
3644
+ if (!response.ok) {
3645
+ return response;
3646
+ }
3647
+ const body = response.body;
3648
+ if (!body) {
3649
+ return response;
3650
+ }
3651
+ const contentLength = response.headers.get("content-length") || 0;
3652
+ const totalBytes = contentLength ? parseInt(contentLength) : 0;
3653
+ if (!(totalBytes > 0)) {
3654
+ return response;
3655
+ }
3656
+ if (typeof ReadableStream === "undefined" || !body.getReader) {
3657
+ return response;
3658
+ }
3659
+ const progressStream = new ReadableStream({
3660
+ async start(controller) {
3661
+ const reader = body.getReader();
3662
+ await read(controller, reader, 0, totalBytes, onProgress, onDone, onError);
3663
+ }
3664
+ });
3665
+ return new Response(progressStream);
3666
+ }
3667
+ async function read(controller, reader, loadedBytes, totalBytes, onProgress, onDone, onError) {
3668
+ try {
3669
+ const { done, value } = await reader.read();
3670
+ if (done) {
3671
+ onDone();
3672
+ controller.close();
3673
+ return;
3674
+ }
3675
+ loadedBytes += value.byteLength;
3676
+ const percent = Math.round(loadedBytes / totalBytes * 100);
3677
+ onProgress(percent, { loadedBytes, totalBytes });
3678
+ controller.enqueue(value);
3679
+ await read(controller, reader, loadedBytes, totalBytes, onProgress, onDone, onError);
3680
+ } catch (error) {
3681
+ controller.error(error);
3682
+ onError(error);
3683
+ }
3684
+ }
3685
+
3686
+ // ../core/src/lib/filesystems/browser-filesystem.ts
3687
+ var BrowserFileSystem = class {
3688
+ _fetch;
3689
+ files = {};
3690
+ lowerCaseFiles = {};
3691
+ usedFiles = {};
3692
+ /**
3693
+ * A FileSystem API wrapper around a list of browser 'File' objects
3694
+ * @param files
3695
+ * @param options
3696
+ */
3697
+ constructor(files, options) {
3698
+ this._fetch = options?.fetch || fetch;
3699
+ for (let i = 0; i < files.length; ++i) {
3700
+ const file = files[i];
3701
+ this.files[file.name] = file;
3702
+ this.lowerCaseFiles[file.name.toLowerCase()] = file;
3703
+ this.usedFiles[file.name] = false;
3704
+ }
3705
+ this.fetch = this.fetch.bind(this);
3706
+ }
3707
+ // implements IFileSystem
3708
+ /**
3709
+ * Implementation of fetch against this file system
3710
+ * Delegates to global fetch for http{s}:// or data://
3711
+ */
3712
+ async fetch(path, options) {
3713
+ if (path.includes("://")) {
3714
+ return this._fetch(path, options);
3715
+ }
3716
+ const file = this.files[path];
3717
+ if (!file) {
3718
+ return new Response(path, { status: 400, statusText: "NOT FOUND" });
3719
+ }
3720
+ const headers = new Headers(options?.headers);
3721
+ const range = headers.get("Range");
3722
+ const bytes = range && /bytes=($1)-($2)/.exec(range);
3723
+ if (bytes) {
3724
+ const start = parseInt(bytes[1]);
3725
+ const end = parseInt(bytes[2]);
3726
+ const data = await file.slice(start, end).arrayBuffer();
3727
+ const response2 = new Response(data);
3728
+ Object.defineProperty(response2, "url", { value: path });
3729
+ return response2;
3730
+ }
3731
+ const response = new Response(file);
3732
+ Object.defineProperty(response, "url", { value: path });
3733
+ return response;
3734
+ }
3735
+ /**
3736
+ * List filenames in this filesystem
3737
+ * @param dirname
3738
+ * @returns
3739
+ */
3740
+ async readdir(dirname2) {
3741
+ const files = [];
3742
+ for (const path in this.files) {
3743
+ files.push(path);
3744
+ }
3745
+ return files;
3746
+ }
3747
+ /**
3748
+ * Return information (size) about files in this file system
3749
+ */
3750
+ async stat(path, options) {
3751
+ const file = this.files[path];
3752
+ if (!file) {
3753
+ throw new Error(path);
3754
+ }
3755
+ return { size: file.size };
3756
+ }
3757
+ /**
3758
+ * Just removes the file from the list
3759
+ */
3760
+ async unlink(path) {
3761
+ delete this.files[path];
3762
+ delete this.lowerCaseFiles[path];
3763
+ this.usedFiles[path] = true;
3764
+ }
3765
+ // implements IRandomAccessFileSystem
3766
+ // RANDOM ACCESS
3767
+ async openReadableFile(pathname, flags) {
3768
+ return new BlobFile(this.files[pathname]);
3769
+ }
3770
+ // PRIVATE
3771
+ // Supports case independent paths, and file usage tracking
3772
+ _getFile(path, used) {
3773
+ const file = this.files[path] || this.lowerCaseFiles[path];
3774
+ if (file && used) {
3775
+ this.usedFiles[path] = true;
3776
+ }
3777
+ return file;
3778
+ }
3779
+ };
47
3780
  return __toCommonJS(bundle_exports);
48
3781
  })();
49
3782
  return __exports__;