@loaders.gl/scientific 0.0.0-stage → 5.0.0-alpha.13

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.
Files changed (175) hide show
  1. package/README.md +21 -2
  2. package/dist/index.cjs +4313 -0
  3. package/dist/index.cjs.map +6 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/index.js +8 -0
  7. package/dist/index.js.map +1 -0
  8. package/dist/netcdf/bundled.cjs +1394 -0
  9. package/dist/netcdf/bundled.d.ts +2 -0
  10. package/dist/netcdf/bundled.d.ts.map +1 -0
  11. package/dist/netcdf/bundled.js +5 -0
  12. package/dist/netcdf/bundled.js.map +1 -0
  13. package/dist/netcdf/index.cjs +1394 -0
  14. package/dist/netcdf/index.cjs.map +6 -0
  15. package/dist/netcdf/index.d.ts +7 -0
  16. package/dist/netcdf/index.d.ts.map +1 -0
  17. package/dist/netcdf/index.js +8 -0
  18. package/dist/netcdf/index.js.map +1 -0
  19. package/dist/netcdf/iobuffer/iobuffer.d.ts +253 -0
  20. package/dist/netcdf/iobuffer/iobuffer.d.ts.map +1 -0
  21. package/dist/netcdf/iobuffer/iobuffer.js +450 -0
  22. package/dist/netcdf/iobuffer/iobuffer.js.map +1 -0
  23. package/dist/netcdf/netcdf-format.cjs +39 -0
  24. package/dist/netcdf/netcdf-format.d.ts +11 -0
  25. package/dist/netcdf/netcdf-format.d.ts.map +1 -0
  26. package/dist/netcdf/netcdf-format.js +14 -0
  27. package/dist/netcdf/netcdf-format.js.map +1 -0
  28. package/dist/netcdf/netcdf-loader-with-parser.cjs +995 -0
  29. package/dist/netcdf/netcdf-loader-with-parser.d.ts +60 -0
  30. package/dist/netcdf/netcdf-loader-with-parser.d.ts.map +1 -0
  31. package/dist/netcdf/netcdf-loader-with-parser.js +35 -0
  32. package/dist/netcdf/netcdf-loader-with-parser.js.map +1 -0
  33. package/dist/netcdf/netcdf-loader.cjs +84 -0
  34. package/dist/netcdf/netcdf-loader.d.ts +81 -0
  35. package/dist/netcdf/netcdf-loader.d.ts.map +1 -0
  36. package/dist/netcdf/netcdf-loader.js +41 -0
  37. package/dist/netcdf/netcdf-loader.js.map +1 -0
  38. package/dist/netcdf/netcdf-source-loader-types.cjs +78 -0
  39. package/dist/netcdf/netcdf-source-loader-types.d.ts +28 -0
  40. package/dist/netcdf/netcdf-source-loader-types.d.ts.map +1 -0
  41. package/dist/netcdf/netcdf-source-loader-types.js +32 -0
  42. package/dist/netcdf/netcdf-source-loader-types.js.map +1 -0
  43. package/dist/netcdf/netcdf-source-loader.cjs +1319 -0
  44. package/dist/netcdf/netcdf-source-loader.d.ts +59 -0
  45. package/dist/netcdf/netcdf-source-loader.d.ts.map +1 -0
  46. package/dist/netcdf/netcdf-source-loader.js +421 -0
  47. package/dist/netcdf/netcdf-source-loader.js.map +1 -0
  48. package/dist/netcdf/netcdfjs/netcdf-reader.d.ts +68 -0
  49. package/dist/netcdf/netcdfjs/netcdf-reader.d.ts.map +1 -0
  50. package/dist/netcdf/netcdfjs/netcdf-reader.js +172 -0
  51. package/dist/netcdf/netcdfjs/netcdf-reader.js.map +1 -0
  52. package/dist/netcdf/netcdfjs/netcdf-types.d.ts +70 -0
  53. package/dist/netcdf/netcdfjs/netcdf-types.d.ts.map +1 -0
  54. package/dist/netcdf/netcdfjs/netcdf-types.js +3 -0
  55. package/dist/netcdf/netcdfjs/netcdf-types.js.map +1 -0
  56. package/dist/netcdf/netcdfjs/read-data.d.ts +19 -0
  57. package/dist/netcdf/netcdfjs/read-data.d.ts.map +1 -0
  58. package/dist/netcdf/netcdfjs/read-data.js +51 -0
  59. package/dist/netcdf/netcdfjs/read-data.js.map +1 -0
  60. package/dist/netcdf/netcdfjs/read-header.d.ts +16 -0
  61. package/dist/netcdf/netcdfjs/read-header.d.ts.map +1 -0
  62. package/dist/netcdf/netcdfjs/read-header.js +227 -0
  63. package/dist/netcdf/netcdfjs/read-header.js.map +1 -0
  64. package/dist/netcdf/netcdfjs/read-type.d.ts +36 -0
  65. package/dist/netcdf/netcdfjs/read-type.d.ts.map +1 -0
  66. package/dist/netcdf/netcdfjs/read-type.js +135 -0
  67. package/dist/netcdf/netcdfjs/read-type.js.map +1 -0
  68. package/dist/netcdf/unbundled.cjs +1394 -0
  69. package/dist/netcdf/unbundled.d.ts +2 -0
  70. package/dist/netcdf/unbundled.d.ts.map +1 -0
  71. package/dist/netcdf/unbundled.js +5 -0
  72. package/dist/netcdf/unbundled.js.map +1 -0
  73. package/dist/netcdf.dev.js +3153 -0
  74. package/dist/netcdf.min.js +12 -0
  75. package/dist/zarr/bundled.d.ts +2 -0
  76. package/dist/zarr/bundled.d.ts.map +1 -0
  77. package/dist/zarr/bundled.js +5 -0
  78. package/dist/zarr/bundled.js.map +1 -0
  79. package/dist/zarr/geo-zarr-source-loader.d.ts +121 -0
  80. package/dist/zarr/geo-zarr-source-loader.d.ts.map +1 -0
  81. package/dist/zarr/geo-zarr-source-loader.js +692 -0
  82. package/dist/zarr/geo-zarr-source-loader.js.map +1 -0
  83. package/dist/zarr/index.cjs +14747 -0
  84. package/dist/zarr/index.cjs.map +6 -0
  85. package/dist/zarr/index.d.ts +11 -0
  86. package/dist/zarr/index.d.ts.map +1 -0
  87. package/dist/zarr/index.js +10 -0
  88. package/dist/zarr/index.js.map +1 -0
  89. package/dist/zarr/lib/consolidated-zarr.d.ts +31 -0
  90. package/dist/zarr/lib/consolidated-zarr.d.ts.map +1 -0
  91. package/dist/zarr/lib/consolidated-zarr.js +113 -0
  92. package/dist/zarr/lib/consolidated-zarr.js.map +1 -0
  93. package/dist/zarr/lib/load-zarr.d.ts +11 -0
  94. package/dist/zarr/lib/load-zarr.d.ts.map +1 -0
  95. package/dist/zarr/lib/load-zarr.js +22 -0
  96. package/dist/zarr/lib/load-zarr.js.map +1 -0
  97. package/dist/zarr/lib/spatial-multiscales.d.ts +14 -0
  98. package/dist/zarr/lib/spatial-multiscales.d.ts.map +1 -0
  99. package/dist/zarr/lib/spatial-multiscales.js +34 -0
  100. package/dist/zarr/lib/spatial-multiscales.js.map +1 -0
  101. package/dist/zarr/lib/utils.d.ts +28 -0
  102. package/dist/zarr/lib/utils.d.ts.map +1 -0
  103. package/dist/zarr/lib/utils.js +137 -0
  104. package/dist/zarr/lib/utils.js.map +1 -0
  105. package/dist/zarr/lib/zarr-data-cache.d.ts +13 -0
  106. package/dist/zarr/lib/zarr-data-cache.d.ts.map +1 -0
  107. package/dist/zarr/lib/zarr-data-cache.js +70 -0
  108. package/dist/zarr/lib/zarr-data-cache.js.map +1 -0
  109. package/dist/zarr/lib/zarr-pixel-source.d.ts +41 -0
  110. package/dist/zarr/lib/zarr-pixel-source.d.ts.map +1 -0
  111. package/dist/zarr/lib/zarr-pixel-source.js +97 -0
  112. package/dist/zarr/lib/zarr-pixel-source.js.map +1 -0
  113. package/dist/zarr/lib/zarrita-pixel-source.d.ts +40 -0
  114. package/dist/zarr/lib/zarrita-pixel-source.d.ts.map +1 -0
  115. package/dist/zarr/lib/zarrita-pixel-source.js +96 -0
  116. package/dist/zarr/lib/zarrita-pixel-source.js.map +1 -0
  117. package/dist/zarr/ome-zarr-source-loader.d.ts +195 -0
  118. package/dist/zarr/ome-zarr-source-loader.d.ts.map +1 -0
  119. package/dist/zarr/ome-zarr-source-loader.js +523 -0
  120. package/dist/zarr/ome-zarr-source-loader.js.map +1 -0
  121. package/dist/zarr/spatial-data-source.d.ts +95 -0
  122. package/dist/zarr/spatial-data-source.d.ts.map +1 -0
  123. package/dist/zarr/spatial-data-source.js +242 -0
  124. package/dist/zarr/spatial-data-source.js.map +1 -0
  125. package/dist/zarr/types.d.ts +105 -0
  126. package/dist/zarr/types.d.ts.map +1 -0
  127. package/dist/zarr/types.js +5 -0
  128. package/dist/zarr/types.js.map +1 -0
  129. package/dist/zarr/unbundled.d.ts +2 -0
  130. package/dist/zarr/unbundled.d.ts.map +1 -0
  131. package/dist/zarr/unbundled.js +5 -0
  132. package/dist/zarr/unbundled.js.map +1 -0
  133. package/dist/zarr/zarr-array-source.d.ts +102 -0
  134. package/dist/zarr/zarr-array-source.d.ts.map +1 -0
  135. package/dist/zarr/zarr-array-source.js +132 -0
  136. package/dist/zarr/zarr-array-source.js.map +1 -0
  137. package/dist/zarr/zarr-loader-types.d.ts +236 -0
  138. package/dist/zarr/zarr-loader-types.d.ts.map +1 -0
  139. package/dist/zarr/zarr-loader-types.js +128 -0
  140. package/dist/zarr/zarr-loader-types.js.map +1 -0
  141. package/dist/zarr.dev.js +16574 -0
  142. package/dist/zarr.min.js +79 -0
  143. package/package.json +62 -4
  144. package/src/index.ts +52 -0
  145. package/src/netcdf/bundled.ts +5 -0
  146. package/src/netcdf/index.ts +14 -0
  147. package/src/netcdf/iobuffer/iobuffer.ts +510 -0
  148. package/src/netcdf/netcdf-format.ts +16 -0
  149. package/src/netcdf/netcdf-loader-with-parser.ts +54 -0
  150. package/src/netcdf/netcdf-loader.ts +62 -0
  151. package/src/netcdf/netcdf-source-loader-types.ts +45 -0
  152. package/src/netcdf/netcdf-source-loader.ts +526 -0
  153. package/src/netcdf/netcdfjs/LICENSE +24 -0
  154. package/src/netcdf/netcdfjs/netcdf-reader.ts +196 -0
  155. package/src/netcdf/netcdfjs/netcdf-types.ts +75 -0
  156. package/src/netcdf/netcdfjs/read-data.ts +71 -0
  157. package/src/netcdf/netcdfjs/read-header.ts +277 -0
  158. package/src/netcdf/netcdfjs/read-type.ts +147 -0
  159. package/src/netcdf/unbundled.ts +5 -0
  160. package/src/zarr/bundled.ts +5 -0
  161. package/src/zarr/geo-zarr-source-loader.ts +998 -0
  162. package/src/zarr/index.ts +60 -0
  163. package/src/zarr/lib/consolidated-zarr.ts +190 -0
  164. package/src/zarr/lib/load-zarr.ts +31 -0
  165. package/src/zarr/lib/spatial-multiscales.ts +47 -0
  166. package/src/zarr/lib/utils.ts +162 -0
  167. package/src/zarr/lib/zarr-data-cache.ts +91 -0
  168. package/src/zarr/lib/zarr-pixel-source.ts +134 -0
  169. package/src/zarr/lib/zarrita-pixel-source.ts +141 -0
  170. package/src/zarr/ome-zarr-source-loader.ts +837 -0
  171. package/src/zarr/spatial-data-source.ts +370 -0
  172. package/src/zarr/types.ts +129 -0
  173. package/src/zarr/unbundled.ts +5 -0
  174. package/src/zarr/zarr-array-source.ts +225 -0
  175. package/src/zarr/zarr-loader-types.ts +166 -0
@@ -0,0 +1,3153 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if (typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if (typeof define === 'function' && define.amd) define([], factory);
5
+ else if (typeof exports === 'object') exports['loaders'] = factory();
6
+ else root['loaders'] = factory();})(globalThis, function () {
7
+ "use strict";
8
+ var __exports__ = (() => {
9
+ var __create = Object.create;
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __getProtoOf = Object.getPrototypeOf;
14
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
15
+ var __esm = (fn, res, err) => function __init() {
16
+ if (err) throw err[0];
17
+ try {
18
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
19
+ } catch (e) {
20
+ throw err = [e], e;
21
+ }
22
+ };
23
+ var __commonJS = (cb, mod) => function __require() {
24
+ try {
25
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
26
+ } catch (e) {
27
+ throw mod = 0, e;
28
+ }
29
+ };
30
+ var __export = (target, all) => {
31
+ for (var name in all)
32
+ __defProp(target, name, { get: all[name], enumerable: true });
33
+ };
34
+ var __copyProps = (to, from, except, desc) => {
35
+ if (from && typeof from === "object" || typeof from === "function") {
36
+ for (let key of __getOwnPropNames(from))
37
+ if (!__hasOwnProp.call(to, key) && key !== except)
38
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
39
+ }
40
+ return to;
41
+ };
42
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
43
+ // If the importer is in node compatibility mode or this is not an ESM
44
+ // file that has been converted to a CommonJS file using a Babel-
45
+ // compatible transform (i.e. "__esModule" has not been set), then set
46
+ // "default" to the CommonJS "module.exports" for node compatibility.
47
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
48
+ mod
49
+ ));
50
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
51
+
52
+ // external-global-plugin:@loaders.gl/core
53
+ var require_core = __commonJS({
54
+ "external-global-plugin:@loaders.gl/core"(exports, module) {
55
+ module.exports = globalThis.loaders;
56
+ }
57
+ });
58
+
59
+ // src/netcdf/iobuffer/iobuffer.ts
60
+ var DEFAULT_BYTE_LENGTH, IOBuffer;
61
+ var init_iobuffer = __esm({
62
+ "src/netcdf/iobuffer/iobuffer.ts"() {
63
+ "use strict";
64
+ DEFAULT_BYTE_LENGTH = 1024 * 8;
65
+ IOBuffer = class _IOBuffer {
66
+ /**
67
+ * Reference to the internal ArrayBuffer object.
68
+ */
69
+ buffer;
70
+ /**
71
+ * Byte length of the internal ArrayBuffer.
72
+ */
73
+ byteLength;
74
+ /**
75
+ * Byte offset of the internal ArrayBuffer.
76
+ */
77
+ byteOffset;
78
+ /**
79
+ * Byte length of the internal ArrayBuffer.
80
+ */
81
+ length;
82
+ /**
83
+ * The current offset of the buffer's pointer.
84
+ */
85
+ offset;
86
+ lastWrittenByte;
87
+ littleEndian;
88
+ _data;
89
+ _mark;
90
+ _marks;
91
+ textDecoder = new TextDecoder();
92
+ textEncoder = new TextEncoder();
93
+ /**
94
+ * @param data - The data to construct the IOBuffer with.
95
+ * If data is a number, it will be the new buffer's length<br>
96
+ * If data is `undefined`, the buffer will be initialized with a default length of 8Kb<br>
97
+ * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,
98
+ * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.
99
+ * @param options
100
+ */
101
+ constructor(data = DEFAULT_BYTE_LENGTH, options = {}) {
102
+ let dataIsGiven = false;
103
+ if (typeof data === "number") {
104
+ data = new ArrayBuffer(data);
105
+ } else {
106
+ dataIsGiven = true;
107
+ this.lastWrittenByte = data.byteLength;
108
+ }
109
+ const offset = options.offset ? options.offset >>> 0 : 0;
110
+ const byteLength = data.byteLength - offset;
111
+ let dvOffset = offset;
112
+ if (ArrayBuffer.isView(data) || data instanceof _IOBuffer) {
113
+ if (data.byteLength !== data.buffer.byteLength) {
114
+ dvOffset = data.byteOffset + offset;
115
+ }
116
+ data = data.buffer;
117
+ }
118
+ if (dataIsGiven) {
119
+ this.lastWrittenByte = byteLength;
120
+ } else {
121
+ this.lastWrittenByte = 0;
122
+ }
123
+ this.buffer = data;
124
+ this.length = byteLength;
125
+ this.byteLength = byteLength;
126
+ this.byteOffset = dvOffset;
127
+ this.offset = 0;
128
+ this.littleEndian = true;
129
+ this._data = new DataView(this.buffer, dvOffset, byteLength);
130
+ this._mark = 0;
131
+ this._marks = [];
132
+ }
133
+ /**
134
+ * Checks if the memory allocated to the buffer is sufficient to store more
135
+ * bytes after the offset.
136
+ * @param byteLength - The needed memory in bytes.
137
+ * @returns `true` if there is sufficient space and `false` otherwise.
138
+ */
139
+ available(byteLength = 1) {
140
+ return this.offset + byteLength <= this.length;
141
+ }
142
+ /**
143
+ * Check if little-endian mode is used for reading and writing multi-byte
144
+ * values.
145
+ * @returns `true` if little-endian mode is used, `false` otherwise.
146
+ */
147
+ isLittleEndian() {
148
+ return this.littleEndian;
149
+ }
150
+ /**
151
+ * Set little-endian mode for reading and writing multi-byte values.
152
+ */
153
+ setLittleEndian() {
154
+ this.littleEndian = true;
155
+ return this;
156
+ }
157
+ /**
158
+ * Check if big-endian mode is used for reading and writing multi-byte values.
159
+ * @returns `true` if big-endian mode is used, `false` otherwise.
160
+ */
161
+ isBigEndian() {
162
+ return !this.littleEndian;
163
+ }
164
+ /**
165
+ * Switches to big-endian mode for reading and writing multi-byte values.
166
+ */
167
+ setBigEndian() {
168
+ this.littleEndian = false;
169
+ return this;
170
+ }
171
+ /**
172
+ * Move the pointer n bytes forward.
173
+ * @param n - Number of bytes to skip.
174
+ */
175
+ skip(n = 1) {
176
+ this.offset += n;
177
+ return this;
178
+ }
179
+ /**
180
+ * Move the pointer to the given offset.
181
+ * @param offset
182
+ */
183
+ seek(offset) {
184
+ this.offset = offset;
185
+ return this;
186
+ }
187
+ /**
188
+ * Store the current pointer offset.
189
+ * @see {@link IOBuffer#reset}
190
+ */
191
+ mark() {
192
+ this._mark = this.offset;
193
+ return this;
194
+ }
195
+ /**
196
+ * Move the pointer back to the last pointer offset set by mark.
197
+ * @see {@link IOBuffer#mark}
198
+ */
199
+ reset() {
200
+ this.offset = this._mark;
201
+ return this;
202
+ }
203
+ /**
204
+ * Push the current pointer offset to the mark stack.
205
+ * @see {@link IOBuffer#popMark}
206
+ */
207
+ pushMark() {
208
+ this._marks.push(this.offset);
209
+ return this;
210
+ }
211
+ /**
212
+ * Pop the last pointer offset from the mark stack, and set the current
213
+ * pointer offset to the popped value.
214
+ * @see {@link IOBuffer#pushMark}
215
+ */
216
+ popMark() {
217
+ const offset = this._marks.pop();
218
+ if (offset === void 0) {
219
+ throw new Error("Mark stack empty");
220
+ }
221
+ this.seek(offset);
222
+ return this;
223
+ }
224
+ /**
225
+ * Move the pointer offset back to 0.
226
+ */
227
+ rewind() {
228
+ this.offset = 0;
229
+ return this;
230
+ }
231
+ /**
232
+ * Make sure the buffer has sufficient memory to write a given byteLength at
233
+ * the current pointer offset.
234
+ * If the buffer's memory is insufficient, this method will create a new
235
+ * buffer (a copy) with a length that is twice (byteLength + current offset).
236
+ * @param byteLength
237
+ */
238
+ ensureAvailable(byteLength = 1) {
239
+ if (!this.available(byteLength)) {
240
+ const lengthNeeded = this.offset + byteLength;
241
+ const newLength = lengthNeeded * 2;
242
+ const newArray = new Uint8Array(newLength);
243
+ newArray.set(new Uint8Array(this.buffer));
244
+ this.buffer = newArray.buffer;
245
+ this.length = this.byteLength = newLength;
246
+ this._data = new DataView(this.buffer);
247
+ }
248
+ return this;
249
+ }
250
+ /**
251
+ * Read a byte and return false if the byte's value is 0, or true otherwise.
252
+ * Moves pointer forward by one byte.
253
+ */
254
+ readBoolean() {
255
+ return this.readUint8() !== 0;
256
+ }
257
+ /**
258
+ * Read a signed 8-bit integer and move pointer forward by 1 byte.
259
+ */
260
+ readInt8() {
261
+ return this._data.getInt8(this.offset++);
262
+ }
263
+ /**
264
+ * Read an unsigned 8-bit integer and move pointer forward by 1 byte.
265
+ */
266
+ readUint8() {
267
+ return this._data.getUint8(this.offset++);
268
+ }
269
+ /**
270
+ * Alias for {@link IOBuffer#readUint8}.
271
+ */
272
+ readByte() {
273
+ return this.readUint8();
274
+ }
275
+ /**
276
+ * Read `n` bytes and move pointer forward by `n` bytes.
277
+ */
278
+ readBytes(n = 1) {
279
+ const bytes = new Uint8Array(n);
280
+ for (let i = 0; i < n; i++) {
281
+ bytes[i] = this.readByte();
282
+ }
283
+ return bytes;
284
+ }
285
+ /**
286
+ * Read a 16-bit signed integer and move pointer forward by 2 bytes.
287
+ */
288
+ readInt16() {
289
+ const value = this._data.getInt16(this.offset, this.littleEndian);
290
+ this.offset += 2;
291
+ return value;
292
+ }
293
+ /**
294
+ * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.
295
+ */
296
+ readUint16() {
297
+ const value = this._data.getUint16(this.offset, this.littleEndian);
298
+ this.offset += 2;
299
+ return value;
300
+ }
301
+ /**
302
+ * Read a 32-bit signed integer and move pointer forward by 4 bytes.
303
+ */
304
+ readInt32() {
305
+ const value = this._data.getInt32(this.offset, this.littleEndian);
306
+ this.offset += 4;
307
+ return value;
308
+ }
309
+ /**
310
+ * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.
311
+ */
312
+ readUint32() {
313
+ const value = this._data.getUint32(this.offset, this.littleEndian);
314
+ this.offset += 4;
315
+ return value;
316
+ }
317
+ /**
318
+ * Read a 32-bit floating number and move pointer forward by 4 bytes.
319
+ */
320
+ readFloat32() {
321
+ const value = this._data.getFloat32(this.offset, this.littleEndian);
322
+ this.offset += 4;
323
+ return value;
324
+ }
325
+ /**
326
+ * Read a 64-bit floating number and move pointer forward by 8 bytes.
327
+ */
328
+ readFloat64() {
329
+ const value = this._data.getFloat64(this.offset, this.littleEndian);
330
+ this.offset += 8;
331
+ return value;
332
+ }
333
+ /**
334
+ * Read a 1-byte ASCII character and move pointer forward by 1 byte.
335
+ */
336
+ readChar() {
337
+ return String.fromCharCode(this.readInt8());
338
+ }
339
+ /**
340
+ * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.
341
+ */
342
+ readChars(n = 1) {
343
+ let result = "";
344
+ for (let i = 0; i < n; i++) {
345
+ result += this.readChar();
346
+ }
347
+ return result;
348
+ }
349
+ /**
350
+ * Read the next `n` bytes, return a UTF-8 decoded string and move pointer
351
+ * forward by `n` bytes.
352
+ */
353
+ readUtf8(n = 1) {
354
+ return this.textDecoder.decode(this.readBytes(n));
355
+ }
356
+ /**
357
+ * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer
358
+ * forward by 1 byte.
359
+ */
360
+ writeBoolean(value) {
361
+ this.writeUint8(value ? 255 : 0);
362
+ return this;
363
+ }
364
+ /**
365
+ * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.
366
+ */
367
+ writeInt8(value) {
368
+ this.ensureAvailable(1);
369
+ this._data.setInt8(this.offset++, value);
370
+ this._updateLastWrittenByte();
371
+ return this;
372
+ }
373
+ /**
374
+ * Write `value` as an 8-bit unsigned integer and move pointer forward by 1
375
+ * byte.
376
+ */
377
+ writeUint8(value) {
378
+ this.ensureAvailable(1);
379
+ this._data.setUint8(this.offset++, value);
380
+ this._updateLastWrittenByte();
381
+ return this;
382
+ }
383
+ /**
384
+ * An alias for {@link IOBuffer#writeUint8}.
385
+ */
386
+ writeByte(value) {
387
+ return this.writeUint8(value);
388
+ }
389
+ /**
390
+ * Write all elements of `bytes` as uint8 values and move pointer forward by
391
+ * `bytes.length` bytes.
392
+ */
393
+ writeBytes(bytes) {
394
+ this.ensureAvailable(bytes.length);
395
+ for (let i = 0; i < bytes.length; i++) {
396
+ this._data.setUint8(this.offset++, bytes[i]);
397
+ }
398
+ this._updateLastWrittenByte();
399
+ return this;
400
+ }
401
+ /**
402
+ * Write `value` as a 16-bit signed integer and move pointer forward by 2
403
+ * bytes.
404
+ */
405
+ writeInt16(value) {
406
+ this.ensureAvailable(2);
407
+ this._data.setInt16(this.offset, value, this.littleEndian);
408
+ this.offset += 2;
409
+ this._updateLastWrittenByte();
410
+ return this;
411
+ }
412
+ /**
413
+ * Write `value` as a 16-bit unsigned integer and move pointer forward by 2
414
+ * bytes.
415
+ */
416
+ writeUint16(value) {
417
+ this.ensureAvailable(2);
418
+ this._data.setUint16(this.offset, value, this.littleEndian);
419
+ this.offset += 2;
420
+ this._updateLastWrittenByte();
421
+ return this;
422
+ }
423
+ /**
424
+ * Write `value` as a 32-bit signed integer and move pointer forward by 4
425
+ * bytes.
426
+ */
427
+ writeInt32(value) {
428
+ this.ensureAvailable(4);
429
+ this._data.setInt32(this.offset, value, this.littleEndian);
430
+ this.offset += 4;
431
+ this._updateLastWrittenByte();
432
+ return this;
433
+ }
434
+ /**
435
+ * Write `value` as a 32-bit unsigned integer and move pointer forward by 4
436
+ * bytes.
437
+ */
438
+ writeUint32(value) {
439
+ this.ensureAvailable(4);
440
+ this._data.setUint32(this.offset, value, this.littleEndian);
441
+ this.offset += 4;
442
+ this._updateLastWrittenByte();
443
+ return this;
444
+ }
445
+ /**
446
+ * Write `value` as a 32-bit floating number and move pointer forward by 4
447
+ * bytes.
448
+ */
449
+ writeFloat32(value) {
450
+ this.ensureAvailable(4);
451
+ this._data.setFloat32(this.offset, value, this.littleEndian);
452
+ this.offset += 4;
453
+ this._updateLastWrittenByte();
454
+ return this;
455
+ }
456
+ /**
457
+ * Write `value` as a 64-bit floating number and move pointer forward by 8
458
+ * bytes.
459
+ */
460
+ writeFloat64(value) {
461
+ this.ensureAvailable(8);
462
+ this._data.setFloat64(this.offset, value, this.littleEndian);
463
+ this.offset += 8;
464
+ this._updateLastWrittenByte();
465
+ return this;
466
+ }
467
+ /**
468
+ * Write the charCode of `str`'s first character as an 8-bit unsigned integer
469
+ * and move pointer forward by 1 byte.
470
+ */
471
+ writeChar(str) {
472
+ return this.writeUint8(str.charCodeAt(0));
473
+ }
474
+ /**
475
+ * Write the charCodes of all `str`'s characters as 8-bit unsigned integers
476
+ * and move pointer forward by `str.length` bytes.
477
+ */
478
+ writeChars(str) {
479
+ for (let i = 0; i < str.length; i++) {
480
+ this.writeUint8(str.charCodeAt(i));
481
+ }
482
+ return this;
483
+ }
484
+ /**
485
+ * UTF-8 encode and write `str` to the current pointer offset and move pointer
486
+ * forward according to the encoded length.
487
+ */
488
+ writeUtf8(str) {
489
+ const bytes = this.textEncoder.encode(str);
490
+ return this.writeBytes(bytes);
491
+ }
492
+ /**
493
+ * Export a Uint8Array view of the internal buffer.
494
+ * The view starts at the byte offset and its length
495
+ * is calculated to stop at the last written byte or the original length.
496
+ */
497
+ toArray() {
498
+ return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);
499
+ }
500
+ /**
501
+ * Update the last written byte offset
502
+ * @private
503
+ */
504
+ _updateLastWrittenByte() {
505
+ if (this.offset > this.lastWrittenByte) {
506
+ this.lastWrittenByte = this.offset;
507
+ }
508
+ }
509
+ };
510
+ }
511
+ });
512
+
513
+ // src/netcdf/netcdfjs/read-type.ts
514
+ function readType(buffer, type, size) {
515
+ switch (type) {
516
+ case TYPES.BYTE:
517
+ return buffer.readBytes(size);
518
+ case TYPES.CHAR:
519
+ return trimNull(buffer.readChars(size));
520
+ case TYPES.SHORT:
521
+ return readNumber(size, buffer.readInt16.bind(buffer));
522
+ case TYPES.INT:
523
+ return readNumber(size, buffer.readInt32.bind(buffer));
524
+ case TYPES.FLOAT:
525
+ return readNumber(size, buffer.readFloat32.bind(buffer));
526
+ case TYPES.DOUBLE:
527
+ return readNumber(size, buffer.readFloat64.bind(buffer));
528
+ /* istanbul ignore next */
529
+ default:
530
+ throw new Error(`NetCDF: non valid type ${type}`);
531
+ }
532
+ }
533
+ function num2str(type) {
534
+ switch (Number(type)) {
535
+ case TYPES.BYTE:
536
+ return "byte";
537
+ case TYPES.CHAR:
538
+ return "char";
539
+ case TYPES.SHORT:
540
+ return "short";
541
+ case TYPES.INT:
542
+ return "int";
543
+ case TYPES.FLOAT:
544
+ return "float";
545
+ case TYPES.DOUBLE:
546
+ return "double";
547
+ /* istanbul ignore next */
548
+ default:
549
+ return "undefined";
550
+ }
551
+ }
552
+ function num2bytes(type) {
553
+ switch (Number(type)) {
554
+ case TYPES.BYTE:
555
+ return 1;
556
+ case TYPES.CHAR:
557
+ return 1;
558
+ case TYPES.SHORT:
559
+ return 2;
560
+ case TYPES.INT:
561
+ return 4;
562
+ case TYPES.FLOAT:
563
+ return 4;
564
+ case TYPES.DOUBLE:
565
+ return 8;
566
+ /* istanbul ignore next */
567
+ default:
568
+ return -1;
569
+ }
570
+ }
571
+ function str2num(type) {
572
+ switch (String(type)) {
573
+ case "byte":
574
+ return TYPES.BYTE;
575
+ case "char":
576
+ return TYPES.CHAR;
577
+ case "short":
578
+ return TYPES.SHORT;
579
+ case "int":
580
+ return TYPES.INT;
581
+ case "float":
582
+ return TYPES.FLOAT;
583
+ case "double":
584
+ return TYPES.DOUBLE;
585
+ /* istanbul ignore next */
586
+ default:
587
+ return -1;
588
+ }
589
+ }
590
+ function readNumber(size, bufferReader) {
591
+ if (size !== 1) {
592
+ const numbers = new Array(size);
593
+ for (let i = 0; i < size; i++) {
594
+ numbers[i] = bufferReader();
595
+ }
596
+ return numbers;
597
+ }
598
+ return bufferReader();
599
+ }
600
+ function trimNull(value) {
601
+ if (value.charCodeAt(value.length - 1) === 0) {
602
+ return value.substring(0, value.length - 1);
603
+ }
604
+ return value;
605
+ }
606
+ var TYPES;
607
+ var init_read_type = __esm({
608
+ "src/netcdf/netcdfjs/read-type.ts"() {
609
+ "use strict";
610
+ TYPES = {
611
+ BYTE: 1,
612
+ CHAR: 2,
613
+ SHORT: 3,
614
+ INT: 4,
615
+ FLOAT: 5,
616
+ DOUBLE: 6
617
+ };
618
+ }
619
+ });
620
+
621
+ // src/netcdf/netcdfjs/read-header.ts
622
+ function readNetCDFHeader(buffer, version2) {
623
+ const recordDimensionLength = buffer.readUint32();
624
+ const dimList = readDimensionsList(buffer);
625
+ const attributes = readAttributesList(buffer);
626
+ const variableList = readVariablesList(buffer, dimList.recordId, version2);
627
+ const header = {
628
+ version: version2,
629
+ recordDimension: {
630
+ length: recordDimensionLength,
631
+ id: dimList.recordId,
632
+ // id of the unlimited dimension
633
+ name: dimList.recordName,
634
+ // name of the unlimited dimension
635
+ recordStep: variableList.recordStep
636
+ },
637
+ dimensions: dimList.dimensions,
638
+ variables: variableList.variables,
639
+ attributes
640
+ };
641
+ return header;
642
+ }
643
+ function readDimensionsList(buffer) {
644
+ const dimList = buffer.readUint32();
645
+ if (dimList === ZERO) {
646
+ if (buffer.readUint32() !== ZERO) {
647
+ throw new Error("NetCDF: wrong empty tag for list of dimensions");
648
+ }
649
+ return {
650
+ recordId: 0,
651
+ recordName: "",
652
+ dimensions: []
653
+ };
654
+ }
655
+ if (dimList !== NC_DIMENSION) {
656
+ throw new Error("NetCDF: wrong tag for list of dimensions");
657
+ }
658
+ const dimensionSize = buffer.readUint32();
659
+ const dimensions = new Array(dimensionSize);
660
+ let recordId;
661
+ let recordName;
662
+ for (let dim = 0; dim < dimensionSize; dim++) {
663
+ const name = readName(buffer);
664
+ const size = buffer.readUint32();
665
+ if (size === NC_UNLIMITED) {
666
+ recordId = dim;
667
+ recordName = name;
668
+ }
669
+ dimensions[dim] = {
670
+ name,
671
+ size
672
+ };
673
+ }
674
+ return {
675
+ dimensions,
676
+ recordId,
677
+ recordName
678
+ };
679
+ }
680
+ function readAttributesList(buffer) {
681
+ const gAttList = buffer.readUint32();
682
+ if (gAttList === ZERO) {
683
+ if (buffer.readUint32() !== ZERO) {
684
+ throw new Error("NetCDF: wrong empty tag for list of attributes");
685
+ }
686
+ return [];
687
+ }
688
+ if (gAttList !== NC_ATTRIBUTE) {
689
+ throw new Error("NetCDF: wrong tag for list of attributes");
690
+ }
691
+ const attributeSize = buffer.readUint32();
692
+ const attributes = new Array(attributeSize);
693
+ for (let gAtt = 0; gAtt < attributeSize; gAtt++) {
694
+ const name = readName(buffer);
695
+ const type = buffer.readUint32();
696
+ if (type < 1 || type > 6) {
697
+ throw new Error(`NetCDF: non valid type ${type}`);
698
+ }
699
+ const size = buffer.readUint32();
700
+ const value = readType(buffer, type, size);
701
+ padding(buffer);
702
+ attributes[gAtt] = {
703
+ name,
704
+ type: num2str(type),
705
+ value
706
+ };
707
+ }
708
+ return attributes;
709
+ }
710
+ function readVariablesList(buffer, recordId, version2) {
711
+ const varList = buffer.readUint32();
712
+ let recordStep = 0;
713
+ if (varList === ZERO) {
714
+ if (buffer.readUint32() !== ZERO) {
715
+ throw new Error("NetCDF: wrong empty tag for list of variables");
716
+ }
717
+ return {
718
+ recordStep,
719
+ variables: []
720
+ };
721
+ }
722
+ if (varList !== NC_VARIABLE) {
723
+ throw new Error("NetCDF: wrong tag for list of variables");
724
+ }
725
+ const variableSize = buffer.readUint32();
726
+ const variables = new Array(variableSize);
727
+ for (let v = 0; v < variableSize; v++) {
728
+ const name = readName(buffer);
729
+ const dimensionality = buffer.readUint32();
730
+ const dimensionsIds = new Array(dimensionality);
731
+ for (let dim = 0; dim < dimensionality; dim++) {
732
+ dimensionsIds[dim] = buffer.readUint32();
733
+ }
734
+ const attributes = readAttributesList(buffer);
735
+ const type = buffer.readUint32();
736
+ if (type < 1 && type > 6) {
737
+ throw new Error(`NetCDF: non valid type ${type}`);
738
+ }
739
+ const varSize = buffer.readUint32();
740
+ let offset = buffer.readUint32();
741
+ if (version2 === 2) {
742
+ if (offset > 0) {
743
+ throw new Error("NetCDF: offsets larger than 4GB not supported");
744
+ }
745
+ offset = buffer.readUint32();
746
+ }
747
+ let record = false;
748
+ if (typeof recordId !== "undefined" && dimensionsIds[0] === recordId) {
749
+ recordStep += varSize;
750
+ record = true;
751
+ }
752
+ variables[v] = {
753
+ name,
754
+ dimensions: dimensionsIds,
755
+ attributes,
756
+ type: num2str(type),
757
+ size: varSize,
758
+ offset,
759
+ record
760
+ };
761
+ }
762
+ return {
763
+ variables,
764
+ recordStep
765
+ };
766
+ }
767
+ function readName(buffer) {
768
+ const nameLength = buffer.readUint32();
769
+ const name = buffer.readChars(nameLength);
770
+ padding(buffer);
771
+ return name;
772
+ }
773
+ function padding(buffer) {
774
+ if (buffer.offset % 4 !== 0) {
775
+ buffer.skip(4 - buffer.offset % 4);
776
+ }
777
+ }
778
+ var ZERO, NC_DIMENSION, NC_VARIABLE, NC_ATTRIBUTE, NC_UNLIMITED;
779
+ var init_read_header = __esm({
780
+ "src/netcdf/netcdfjs/read-header.ts"() {
781
+ "use strict";
782
+ init_read_type();
783
+ ZERO = 0;
784
+ NC_DIMENSION = 10;
785
+ NC_VARIABLE = 11;
786
+ NC_ATTRIBUTE = 12;
787
+ NC_UNLIMITED = 0;
788
+ }
789
+ });
790
+
791
+ // src/netcdf/netcdfjs/read-data.ts
792
+ function readNonRecord(buffer, variable) {
793
+ const type = str2num(variable.type);
794
+ const size = variable.size / num2bytes(type);
795
+ const data = new Array(size);
796
+ for (let i = 0; i < size; i++) {
797
+ data[i] = readType(buffer, type, 1);
798
+ }
799
+ return data;
800
+ }
801
+ function readRecord(buffer, variable, recordDimension, dimensions) {
802
+ const type = str2num(variable.type);
803
+ const width = variable.dimensions.filter((dimensionId) => dimensionId !== recordDimension.id).reduce((elementCount, dimensionId) => elementCount * dimensions[dimensionId].size, 1);
804
+ const size = recordDimension.length;
805
+ const data = new Array(size);
806
+ const step = recordDimension.recordStep;
807
+ for (let i = 0; i < size; i++) {
808
+ const currentOffset = buffer.offset;
809
+ data[i] = readType(buffer, type, width);
810
+ buffer.seek(currentOffset + step);
811
+ }
812
+ return data;
813
+ }
814
+ var init_read_data = __esm({
815
+ "src/netcdf/netcdfjs/read-data.ts"() {
816
+ "use strict";
817
+ init_read_type();
818
+ }
819
+ });
820
+
821
+ // src/netcdf/netcdfjs/netcdf-reader.ts
822
+ var NetCDFReader;
823
+ var init_netcdf_reader = __esm({
824
+ "src/netcdf/netcdfjs/netcdf-reader.ts"() {
825
+ "use strict";
826
+ init_iobuffer();
827
+ init_read_header();
828
+ init_read_data();
829
+ NetCDFReader = class {
830
+ header;
831
+ buffer;
832
+ constructor(data) {
833
+ const buffer = new IOBuffer(data);
834
+ buffer.setBigEndian();
835
+ const magic = buffer.readChars(3);
836
+ if (magic !== "CDF") {
837
+ throw new Error(`NetCDF: file should start with 'CDF', found ${magic}`);
838
+ }
839
+ const version2 = buffer.readByte();
840
+ if (version2 > 2) {
841
+ throw new Error(`NetCDF: unsupported version ${version2}`);
842
+ }
843
+ this.header = readNetCDFHeader(buffer, version2);
844
+ this.buffer = buffer;
845
+ }
846
+ /**
847
+ * @return {string} - Version for the NetCDF format
848
+ */
849
+ get version() {
850
+ if (this.header.version === 1) {
851
+ return "classic format";
852
+ }
853
+ return "64-bit offset format";
854
+ }
855
+ /**
856
+ * Get metadata for the record dimension
857
+ */
858
+ get recordDimension() {
859
+ return this.header.recordDimension;
860
+ }
861
+ /**
862
+ * Get list of dimensions (each with `name` and `size`)
863
+ */
864
+ get dimensions() {
865
+ return this.header.dimensions;
866
+ }
867
+ /**
868
+ * Get list of global attributes with:
869
+ * * `name`: String with the name of the attribute
870
+ * * `type`: String with the type of the attribute
871
+ * * `value`: A number or string with the value of the attribute
872
+ */
873
+ get attributes() {
874
+ return this.header.attributes;
875
+ }
876
+ /**
877
+ * Get list of variables
878
+ */
879
+ get variables() {
880
+ return this.header.variables;
881
+ }
882
+ /**
883
+ * Check if an attribute exists
884
+ * @param attributeName - Name of the attribute to find
885
+ * @return
886
+ */
887
+ attributeExists(attributeName) {
888
+ const attribute = this.attributes.find((val) => val.name === attributeName);
889
+ return attribute !== void 0;
890
+ }
891
+ /**
892
+ * Returns the value of an attribute
893
+ * @param attributeName
894
+ * @return Value of the attributeName or null
895
+ */
896
+ getAttribute(attributeName) {
897
+ const attribute = this.attributes.find((val) => val.name === attributeName);
898
+ if (attribute) return attribute.value;
899
+ return null;
900
+ }
901
+ /**
902
+ * Check if a dataVariable exists
903
+ * @param variableName - Name of the variable to find
904
+ * @return
905
+ */
906
+ dataVariableExists(variableName) {
907
+ const variable = this.header.variables.find(function(val) {
908
+ return val.name === variableName;
909
+ });
910
+ return variable !== void 0;
911
+ }
912
+ /**
913
+ * Returns the value of a variable as a string
914
+ * @param variableName
915
+ * @return Value of the variable as a string or null
916
+ */
917
+ getDataVariableAsString(variableName) {
918
+ const variable = this.getDataVariable(variableName);
919
+ if (variable) return variable.join("");
920
+ return null;
921
+ }
922
+ /**
923
+ * Retrieves the data for a given variable
924
+ * @param variableName - Name of the variable to search or variable object
925
+ * @return List with the variable values
926
+ */
927
+ getDataVariable(variableName) {
928
+ let variable;
929
+ if (typeof variableName === "string") {
930
+ variable = this.header.variables.find(function(val) {
931
+ return val.name === variableName;
932
+ });
933
+ } else {
934
+ variable = variableName;
935
+ }
936
+ if (variable === void 0) {
937
+ let errorOutput;
938
+ if (typeof variableName === "string") {
939
+ errorOutput = variableName;
940
+ } else if (typeof variableName === "object") {
941
+ errorOutput = JSON.stringify(variableName);
942
+ }
943
+ throw new Error(`NetCDF: variable not found: ${errorOutput}`);
944
+ }
945
+ this.buffer.seek(variable.offset);
946
+ if (variable.record) {
947
+ return readRecord(this.buffer, variable, this.header.recordDimension, this.header.dimensions);
948
+ }
949
+ return readNonRecord(this.buffer, variable);
950
+ }
951
+ toString() {
952
+ const result = [];
953
+ result.push("DIMENSIONS");
954
+ for (const dimension of this.dimensions) {
955
+ result.push(` ${dimension.name.padEnd(30)} = size: ${dimension.size}`);
956
+ }
957
+ result.push("");
958
+ result.push("GLOBAL ATTRIBUTES");
959
+ for (const attribute of this.attributes) {
960
+ result.push(` ${attribute.name.padEnd(30)} = ${attribute.value}`);
961
+ }
962
+ const variables = JSON.parse(JSON.stringify(this.variables));
963
+ result.push("");
964
+ result.push("VARIABLES:");
965
+ for (const variable of variables) {
966
+ variable.value = this.getDataVariable(variable);
967
+ let stringify = JSON.stringify(variable.value);
968
+ if (stringify.length > 50) stringify = stringify.substring(0, 50);
969
+ if (!Number.isNaN(variable.value.length)) {
970
+ stringify += ` (length: ${variable.value.length})`;
971
+ }
972
+ result.push(` ${variable.name.padEnd(30)} = ${stringify}`);
973
+ }
974
+ return result.join("\n");
975
+ }
976
+ };
977
+ }
978
+ });
979
+
980
+ // src/netcdf/netcdf-format.ts
981
+ var NetCDFFormat;
982
+ var init_netcdf_format = __esm({
983
+ "src/netcdf/netcdf-format.ts"() {
984
+ "use strict";
985
+ NetCDFFormat = {
986
+ name: "NetCDF",
987
+ id: "netcdf",
988
+ module: "netcdf",
989
+ encoding: "binary",
990
+ format: "netcdf",
991
+ extensions: ["cdf", "nc"],
992
+ mimeTypes: ["application/x-netcdf"],
993
+ binary: true
994
+ };
995
+ }
996
+ });
997
+
998
+ // netcdf-bundle.ts
999
+ var netcdf_bundle_exports = {};
1000
+ __export(netcdf_bundle_exports, {
1001
+ FetchError: () => import_core.FetchError,
1002
+ JSONLoader: () => JSONLoader,
1003
+ NetCDFFormat: () => NetCDFFormat,
1004
+ NetCDFReader: () => NetCDFReader,
1005
+ NetCDFSourceLoader: () => NetCDFSourceLoaderWithParser,
1006
+ NullLoader: () => import_core.NullLoader,
1007
+ NullWorkerLoader: () => import_core.NullWorkerLoader,
1008
+ RequestScheduler: () => RequestScheduler,
1009
+ _BrowserFileSystem: () => import_core._BrowserFileSystem,
1010
+ _fetchProgress: () => import_core._fetchProgress,
1011
+ _selectSource: () => import_core._selectSource,
1012
+ _unregisterLoaders: () => import_core._unregisterLoaders,
1013
+ assert: () => assert,
1014
+ concatenateArrayBuffersAsync: () => concatenateArrayBuffersAsync,
1015
+ coreApi: () => import_core.coreApi,
1016
+ createDataSource: () => import_core.createDataSource,
1017
+ document: () => document_,
1018
+ encode: () => import_core.encode,
1019
+ encodeInBatches: () => import_core.encodeInBatches,
1020
+ encodeSync: () => import_core.encodeSync,
1021
+ encodeTable: () => import_core.encodeTable,
1022
+ encodeTableAsText: () => import_core.encodeTableAsText,
1023
+ encodeTableInBatches: () => import_core.encodeTableInBatches,
1024
+ encodeText: () => import_core.encodeText,
1025
+ encodeTextSync: () => import_core.encodeTextSync,
1026
+ encodeURLtoURL: () => import_core.encodeURLtoURL,
1027
+ fetchFile: () => import_core.fetchFile,
1028
+ forEach: () => forEach,
1029
+ getLoaderOptions: () => import_core.getLoaderOptions,
1030
+ getPathPrefix: () => getPathPrefix,
1031
+ global: () => global_,
1032
+ isAsyncIterable: () => isAsyncIterable,
1033
+ isBrowser: () => isBrowser,
1034
+ isIterable: () => isIterable,
1035
+ isIterator: () => isIterator,
1036
+ isPromise: () => isPromise,
1037
+ isPureObject: () => isPureObject,
1038
+ isReadableStream: () => isReadableStream,
1039
+ isResponse: () => isResponse,
1040
+ isWorker: () => isWorker,
1041
+ isWritableStream: () => isWritableStream,
1042
+ load: () => import_core.load,
1043
+ loadInBatches: () => import_core.loadInBatches,
1044
+ makeIterator: () => import_core.makeIterator,
1045
+ makeLineIterator: () => makeLineIterator,
1046
+ makeNumberedLineIterator: () => makeNumberedLineIterator,
1047
+ makeStream: () => import_core.makeStream,
1048
+ makeTextDecoderIterator: () => makeTextDecoderIterator,
1049
+ makeTextEncoderIterator: () => makeTextEncoderIterator,
1050
+ parse: () => import_core.parse,
1051
+ parseFile: () => import_core.parseFile,
1052
+ parseInBatches: () => import_core.parseInBatches,
1053
+ parseSync: () => import_core.parseSync,
1054
+ preload: () => import_core.preload,
1055
+ preloadSync: () => import_core.preloadSync,
1056
+ readArrayBuffer: () => import_core.readArrayBuffer,
1057
+ registerLoaders: () => import_core.registerLoaders,
1058
+ resolvePath: () => resolvePath,
1059
+ selectLoader: () => import_core.selectLoader,
1060
+ selectLoaderSync: () => import_core.selectLoaderSync,
1061
+ self: () => self_,
1062
+ setLoaderOptions: () => import_core.setLoaderOptions,
1063
+ setPathPrefix: () => setPathPrefix,
1064
+ window: () => window_
1065
+ });
1066
+ var import_core = __toESM(require_core(), 1);
1067
+
1068
+ // ../core/src/loader-utils/lib/env-utils/assert.ts
1069
+ function assert(condition, message) {
1070
+ if (!condition) {
1071
+ throw new Error(message || "loader assertion failed.");
1072
+ }
1073
+ }
1074
+
1075
+ // ../core/src/loader-utils/lib/env-utils/globals.ts
1076
+ var globals = {
1077
+ self: typeof self !== "undefined" && self,
1078
+ window: typeof window !== "undefined" && window,
1079
+ global: typeof global !== "undefined" && global,
1080
+ document: typeof document !== "undefined" && document
1081
+ };
1082
+ var self_ = globals.self || globals.window || globals.global || {};
1083
+ var window_ = globals.window || globals.self || globals.global || {};
1084
+ var global_ = globals.global || globals.self || globals.window || {};
1085
+ var document_ = globals.document || {};
1086
+ var isBrowser = (
1087
+ // @ts-ignore process does not exist on browser
1088
+ Boolean(typeof process !== "object" || String(process) !== "[object process]" || process.browser)
1089
+ );
1090
+ var isWorker = typeof importScripts === "function";
1091
+ var matches = typeof process !== "undefined" && process.version && /v([0-9]*)/.exec(process.version);
1092
+ var nodeVersion = matches && parseFloat(matches[1]) || 0;
1093
+
1094
+ // ../../node_modules/probe.gl/dist/env/lib/globals.js
1095
+ var window_2 = globalThis;
1096
+ var document_2 = globalThis.document || {};
1097
+ var process_ = globalThis.process || {};
1098
+ var console_ = globalThis.console;
1099
+ var navigator_ = globalThis.navigator || {};
1100
+
1101
+ // ../../node_modules/probe.gl/dist/env/lib/is-electron.js
1102
+ function isElectron(mockUserAgent) {
1103
+ if (typeof window !== "undefined" && window.process?.type === "renderer") {
1104
+ return true;
1105
+ }
1106
+ if (typeof process !== "undefined" && Boolean(process.versions?.["electron"])) {
1107
+ return true;
1108
+ }
1109
+ const realUserAgent = typeof navigator !== "undefined" && navigator.userAgent;
1110
+ const userAgent = mockUserAgent || realUserAgent;
1111
+ return Boolean(userAgent && userAgent.indexOf("Electron") >= 0);
1112
+ }
1113
+
1114
+ // ../../node_modules/probe.gl/dist/env/lib/is-browser.js
1115
+ function isBrowser2() {
1116
+ const isNode = (
1117
+ // @ts-expect-error
1118
+ typeof process === "object" && String(process) === "[object process]" && !process?.browser
1119
+ );
1120
+ return !isNode || isElectron();
1121
+ }
1122
+
1123
+ // ../../node_modules/probe.gl/dist/env/index.js
1124
+ var VERSION = true ? "5.0.0" : "untranspiled source";
1125
+
1126
+ // ../../node_modules/probe.gl/dist/log/utils/assert.js
1127
+ function assert3(condition, message) {
1128
+ if (!condition) {
1129
+ throw new Error(message || "Assertion failed");
1130
+ }
1131
+ }
1132
+
1133
+ // ../../node_modules/probe.gl/dist/log/loggers/log-utils.js
1134
+ function normalizeLogLevel(logLevel) {
1135
+ if (!logLevel) {
1136
+ return 0;
1137
+ }
1138
+ let resolvedLevel;
1139
+ switch (typeof logLevel) {
1140
+ case "number":
1141
+ resolvedLevel = logLevel;
1142
+ break;
1143
+ case "object":
1144
+ resolvedLevel = logLevel.logLevel || logLevel.priority || 0;
1145
+ break;
1146
+ default:
1147
+ return 0;
1148
+ }
1149
+ assert3(Number.isFinite(resolvedLevel) && resolvedLevel >= 0);
1150
+ return resolvedLevel;
1151
+ }
1152
+ function normalizeArguments(opts) {
1153
+ const { logLevel, message } = opts;
1154
+ opts.logLevel = normalizeLogLevel(logLevel);
1155
+ const args = opts.args ? Array.from(opts.args) : [];
1156
+ while (args.length && args.shift() !== message) {
1157
+ }
1158
+ switch (typeof logLevel) {
1159
+ case "string":
1160
+ case "function":
1161
+ if (message !== void 0) {
1162
+ args.unshift(message);
1163
+ }
1164
+ opts.message = logLevel;
1165
+ break;
1166
+ case "object":
1167
+ Object.assign(opts, logLevel);
1168
+ break;
1169
+ default:
1170
+ }
1171
+ if (typeof opts.message === "function") {
1172
+ opts.message = opts.message();
1173
+ }
1174
+ const messageType = typeof opts.message;
1175
+ assert3(messageType === "string" || messageType === "object");
1176
+ return Object.assign(opts, { args }, opts.opts);
1177
+ }
1178
+
1179
+ // ../../node_modules/probe.gl/dist/log/loggers/base-log.js
1180
+ var noop = () => {
1181
+ };
1182
+ var BaseLog = class {
1183
+ constructor({ level = 0 } = {}) {
1184
+ this.userData = {};
1185
+ this._onceCache = /* @__PURE__ */ new Set();
1186
+ this._level = level;
1187
+ }
1188
+ set level(newLevel) {
1189
+ this.setLevel(newLevel);
1190
+ }
1191
+ get level() {
1192
+ return this.getLevel();
1193
+ }
1194
+ setLevel(level) {
1195
+ this._level = level;
1196
+ return this;
1197
+ }
1198
+ getLevel() {
1199
+ return this._level;
1200
+ }
1201
+ // Unconditional logging
1202
+ warn(message, ...args) {
1203
+ return this._log("warn", 0, message, args, { once: true });
1204
+ }
1205
+ error(message, ...args) {
1206
+ return this._log("error", 0, message, args);
1207
+ }
1208
+ // Conditional logging
1209
+ log(logLevel, message, ...args) {
1210
+ return this._log("log", logLevel, message, args);
1211
+ }
1212
+ info(logLevel, message, ...args) {
1213
+ return this._log("info", logLevel, message, args);
1214
+ }
1215
+ once(logLevel, message, ...args) {
1216
+ return this._log("once", logLevel, message, args, { once: true });
1217
+ }
1218
+ _log(type, logLevel, message, args, options = {}) {
1219
+ const normalized = normalizeArguments({
1220
+ logLevel,
1221
+ message,
1222
+ args: this._buildArgs(logLevel, message, args),
1223
+ opts: options
1224
+ });
1225
+ return this._createLogFunction(type, normalized, options);
1226
+ }
1227
+ _buildArgs(logLevel, message, args) {
1228
+ return [logLevel, message, ...args];
1229
+ }
1230
+ _createLogFunction(type, normalized, options) {
1231
+ if (!this._shouldLog(normalized.logLevel)) {
1232
+ return noop;
1233
+ }
1234
+ const tag = this._getOnceTag(options.tag ?? normalized.tag ?? normalized.message);
1235
+ if ((options.once || normalized.once) && tag !== void 0) {
1236
+ if (this._onceCache.has(tag)) {
1237
+ return noop;
1238
+ }
1239
+ this._onceCache.add(tag);
1240
+ }
1241
+ return this._emit(type, normalized);
1242
+ }
1243
+ _shouldLog(logLevel) {
1244
+ return this.getLevel() >= normalizeLogLevel(logLevel);
1245
+ }
1246
+ _getOnceTag(tag) {
1247
+ if (tag === void 0) {
1248
+ return void 0;
1249
+ }
1250
+ try {
1251
+ return typeof tag === "string" ? tag : String(tag);
1252
+ } catch {
1253
+ return void 0;
1254
+ }
1255
+ }
1256
+ };
1257
+
1258
+ // ../../node_modules/probe.gl/dist/log/utils/local-storage.js
1259
+ function getStorage(type) {
1260
+ try {
1261
+ const storage = window[type];
1262
+ const x = "__storage_test__";
1263
+ storage.setItem(x, x);
1264
+ storage.removeItem(x);
1265
+ return storage;
1266
+ } catch (e) {
1267
+ return null;
1268
+ }
1269
+ }
1270
+ var LocalStorage = class {
1271
+ constructor(id, defaultConfig, type = "sessionStorage") {
1272
+ this.storage = getStorage(type);
1273
+ this.id = id;
1274
+ this.config = defaultConfig;
1275
+ this._loadConfiguration();
1276
+ }
1277
+ getConfiguration() {
1278
+ return this.config;
1279
+ }
1280
+ setConfiguration(configuration) {
1281
+ Object.assign(this.config, configuration);
1282
+ if (this.storage) {
1283
+ const serialized = JSON.stringify(this.config);
1284
+ this.storage.setItem(this.id, serialized);
1285
+ }
1286
+ }
1287
+ // Get config from persistent store, if available
1288
+ _loadConfiguration() {
1289
+ let configuration = {};
1290
+ if (this.storage) {
1291
+ const serializedConfiguration = this.storage.getItem(this.id);
1292
+ configuration = serializedConfiguration ? JSON.parse(serializedConfiguration) : {};
1293
+ }
1294
+ Object.assign(this.config, configuration);
1295
+ return this;
1296
+ }
1297
+ };
1298
+
1299
+ // ../../node_modules/probe.gl/dist/log/utils/formatters.js
1300
+ function formatTime(ms) {
1301
+ let formatted;
1302
+ if (ms < 10) {
1303
+ formatted = `${ms.toFixed(2)}ms`;
1304
+ } else if (ms < 100) {
1305
+ formatted = `${ms.toFixed(1)}ms`;
1306
+ } else if (ms < 1e3) {
1307
+ formatted = `${ms.toFixed(0)}ms`;
1308
+ } else {
1309
+ formatted = `${(ms / 1e3).toFixed(2)}s`;
1310
+ }
1311
+ return formatted;
1312
+ }
1313
+ function leftPad(string, length = 8) {
1314
+ const padLength = Math.max(length - string.length, 0);
1315
+ return `${" ".repeat(padLength)}${string}`;
1316
+ }
1317
+
1318
+ // ../../node_modules/probe.gl/dist/log/utils/color.js
1319
+ var COLOR;
1320
+ (function(COLOR2) {
1321
+ COLOR2[COLOR2["BLACK"] = 30] = "BLACK";
1322
+ COLOR2[COLOR2["RED"] = 31] = "RED";
1323
+ COLOR2[COLOR2["GREEN"] = 32] = "GREEN";
1324
+ COLOR2[COLOR2["YELLOW"] = 33] = "YELLOW";
1325
+ COLOR2[COLOR2["BLUE"] = 34] = "BLUE";
1326
+ COLOR2[COLOR2["MAGENTA"] = 35] = "MAGENTA";
1327
+ COLOR2[COLOR2["CYAN"] = 36] = "CYAN";
1328
+ COLOR2[COLOR2["WHITE"] = 37] = "WHITE";
1329
+ COLOR2[COLOR2["BRIGHT_BLACK"] = 90] = "BRIGHT_BLACK";
1330
+ COLOR2[COLOR2["BRIGHT_RED"] = 91] = "BRIGHT_RED";
1331
+ COLOR2[COLOR2["BRIGHT_GREEN"] = 92] = "BRIGHT_GREEN";
1332
+ COLOR2[COLOR2["BRIGHT_YELLOW"] = 93] = "BRIGHT_YELLOW";
1333
+ COLOR2[COLOR2["BRIGHT_BLUE"] = 94] = "BRIGHT_BLUE";
1334
+ COLOR2[COLOR2["BRIGHT_MAGENTA"] = 95] = "BRIGHT_MAGENTA";
1335
+ COLOR2[COLOR2["BRIGHT_CYAN"] = 96] = "BRIGHT_CYAN";
1336
+ COLOR2[COLOR2["BRIGHT_WHITE"] = 97] = "BRIGHT_WHITE";
1337
+ })(COLOR || (COLOR = {}));
1338
+ var BACKGROUND_INCREMENT = 10;
1339
+ function getColor(color) {
1340
+ if (typeof color !== "string") {
1341
+ return color;
1342
+ }
1343
+ color = color.toUpperCase();
1344
+ return COLOR[color] || COLOR.WHITE;
1345
+ }
1346
+ function addColor(string, color, background) {
1347
+ if (!isBrowser2 && typeof string === "string") {
1348
+ if (color) {
1349
+ const colorCode = getColor(color);
1350
+ string = `\x1B[${colorCode}m${string}\x1B[39m`;
1351
+ }
1352
+ if (background) {
1353
+ const colorCode = getColor(background);
1354
+ string = `\x1B[${colorCode + BACKGROUND_INCREMENT}m${string}\x1B[49m`;
1355
+ }
1356
+ }
1357
+ return string;
1358
+ }
1359
+
1360
+ // ../../node_modules/probe.gl/dist/log/utils/autobind.js
1361
+ function autobind(obj, predefined = ["constructor"]) {
1362
+ const proto = Object.getPrototypeOf(obj);
1363
+ const propNames = Object.getOwnPropertyNames(proto);
1364
+ const object = obj;
1365
+ for (const key of propNames) {
1366
+ const value = object[key];
1367
+ if (typeof value === "function") {
1368
+ if (!predefined.find((name) => key === name)) {
1369
+ object[key] = value.bind(obj);
1370
+ }
1371
+ }
1372
+ }
1373
+ }
1374
+
1375
+ // ../../node_modules/probe.gl/dist/log/probe.js
1376
+ var Probe = class {
1377
+ getHighResolutionTimer() {
1378
+ let timestamp;
1379
+ if (isBrowser2() && window_2.performance) {
1380
+ timestamp = window_2?.performance?.now?.();
1381
+ } else if ("hrtime" in process_) {
1382
+ const timeParts = process_?.hrtime?.();
1383
+ timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6;
1384
+ } else {
1385
+ timestamp = Date.now();
1386
+ }
1387
+ return timestamp;
1388
+ }
1389
+ getMemoryUsageMB() {
1390
+ const performance = window_2?.performance;
1391
+ const usedJSHeapSize = performance?.memory?.usedJSHeapSize;
1392
+ if (usedJSHeapSize === void 0 || usedJSHeapSize === null) {
1393
+ return null;
1394
+ }
1395
+ return Math.trunc(usedJSHeapSize / 1024 / 1024);
1396
+ }
1397
+ };
1398
+ var probe = new Probe();
1399
+ globalThis.Probe = Probe;
1400
+ globalThis.probe = probe;
1401
+
1402
+ // ../../node_modules/probe.gl/dist/log/loggers/probe-log.js
1403
+ var originalConsole = {
1404
+ debug: isBrowser2() ? console.debug || console.log : console.log,
1405
+ log: console.log,
1406
+ info: console.info,
1407
+ warn: console.warn,
1408
+ error: console.error
1409
+ };
1410
+ var DEFAULT_LOG_CONFIGURATION = {
1411
+ enabled: true,
1412
+ level: 0
1413
+ };
1414
+ var ProbeLog = class extends BaseLog {
1415
+ constructor({ id } = { id: "" }) {
1416
+ super({ level: 0 });
1417
+ this.VERSION = VERSION;
1418
+ this._startTs = probe.getHighResolutionTimer();
1419
+ this._deltaTs = probe.getHighResolutionTimer();
1420
+ this.userData = {};
1421
+ this.LOG_THROTTLE_TIMEOUT = 0;
1422
+ this.id = id;
1423
+ this.userData = {};
1424
+ this._storage = new LocalStorage(`__probe-${this.id}__`, { [this.id]: DEFAULT_LOG_CONFIGURATION });
1425
+ this.timeStamp(`${this.id} started`);
1426
+ autobind(this);
1427
+ Object.seal(this);
1428
+ }
1429
+ isEnabled() {
1430
+ return this._getConfiguration().enabled;
1431
+ }
1432
+ getLevel() {
1433
+ return this._getConfiguration().level;
1434
+ }
1435
+ /** @return milliseconds, with fractions */
1436
+ getTotal() {
1437
+ return Number((probe.getHighResolutionTimer() - this._startTs).toPrecision(10));
1438
+ }
1439
+ /** @return milliseconds, with fractions */
1440
+ getDelta() {
1441
+ return Number((probe.getHighResolutionTimer() - this._deltaTs).toPrecision(10));
1442
+ }
1443
+ /** @deprecated use logLevel */
1444
+ set priority(newPriority) {
1445
+ this.level = newPriority;
1446
+ }
1447
+ /** @deprecated use logLevel */
1448
+ get priority() {
1449
+ return this.level;
1450
+ }
1451
+ /** @deprecated use logLevel */
1452
+ getPriority() {
1453
+ return this.level;
1454
+ }
1455
+ // Configure
1456
+ enable(enabled = true) {
1457
+ this._updateConfiguration({ enabled });
1458
+ return this;
1459
+ }
1460
+ setLevel(level) {
1461
+ this._updateConfiguration({ level });
1462
+ return this;
1463
+ }
1464
+ /** return the current status of the setting */
1465
+ get(setting) {
1466
+ return this._getConfiguration()[setting];
1467
+ }
1468
+ // update the status of the setting
1469
+ set(setting, value) {
1470
+ this._updateConfiguration({ [setting]: value });
1471
+ }
1472
+ /** Logs the current settings as a table */
1473
+ settings() {
1474
+ if (console.table) {
1475
+ console.table(this._storage.config);
1476
+ } else {
1477
+ console.log(this._storage.config);
1478
+ }
1479
+ }
1480
+ // Unconditional logging
1481
+ assert(condition, message) {
1482
+ if (!condition) {
1483
+ throw new Error(message || "Assertion failed");
1484
+ }
1485
+ }
1486
+ warn(message, ...args) {
1487
+ return this._log("warn", 0, message, args, {
1488
+ method: originalConsole.warn,
1489
+ once: true
1490
+ });
1491
+ }
1492
+ error(message, ...args) {
1493
+ return this._log("error", 0, message, args, {
1494
+ method: originalConsole.error
1495
+ });
1496
+ }
1497
+ /** Print a deprecation warning */
1498
+ deprecated(oldUsage, newUsage) {
1499
+ return this.warn(`\`${oldUsage}\` is deprecated and will be removed in a later version. Use \`${newUsage}\` instead`);
1500
+ }
1501
+ /** Print a removal warning */
1502
+ removed(oldUsage, newUsage) {
1503
+ return this.error(`\`${oldUsage}\` has been removed. Use \`${newUsage}\` instead`);
1504
+ }
1505
+ probe(logLevel, message, ...args) {
1506
+ const memoryUsageMB = probe.getMemoryUsageMB();
1507
+ if (memoryUsageMB !== null) {
1508
+ const memoryUsagePrefix = `${memoryUsageMB}MB `;
1509
+ if (typeof message === "function") {
1510
+ message = () => `${memoryUsagePrefix}${message()}`;
1511
+ } else if (typeof message === "string") {
1512
+ message = `${memoryUsagePrefix}${message}`;
1513
+ }
1514
+ }
1515
+ return this._log("log", logLevel, message, args, {
1516
+ method: originalConsole.log,
1517
+ time: true,
1518
+ once: true
1519
+ });
1520
+ }
1521
+ log(logLevel, message, ...args) {
1522
+ return this._log("log", logLevel, message, args, {
1523
+ method: originalConsole.debug
1524
+ });
1525
+ }
1526
+ info(logLevel, message, ...args) {
1527
+ return this._log("info", logLevel, message, args, { method: console.info });
1528
+ }
1529
+ once(logLevel, message, ...args) {
1530
+ return this._log("once", logLevel, message, args, {
1531
+ method: originalConsole.debug || originalConsole.info,
1532
+ once: true
1533
+ });
1534
+ }
1535
+ /** Logs an object as a table */
1536
+ table(logLevel, table, columns) {
1537
+ if (table) {
1538
+ return this._log("table", logLevel, table, columns && [columns] || [], {
1539
+ method: console.table || noop,
1540
+ tag: getTableHeader(table)
1541
+ });
1542
+ }
1543
+ return noop;
1544
+ }
1545
+ time(logLevel, message) {
1546
+ return this._log("time", logLevel, message, [], {
1547
+ method: console.time ? console.time : console.info
1548
+ });
1549
+ }
1550
+ timeEnd(logLevel, message) {
1551
+ return this._log("time", logLevel, message, [], {
1552
+ method: console.timeEnd ? console.timeEnd : console.info
1553
+ });
1554
+ }
1555
+ timeStamp(logLevel, message) {
1556
+ return this._log("time", logLevel, message, [], {
1557
+ method: console.timeStamp || noop
1558
+ });
1559
+ }
1560
+ group(logLevel, message, opts = { collapsed: false }) {
1561
+ const method = (opts.collapsed ? console.groupCollapsed : console.group) || console.info;
1562
+ return this._log("group", logLevel, message, [], { method });
1563
+ }
1564
+ groupCollapsed(logLevel, message, opts = {}) {
1565
+ return this.group(logLevel, message, Object.assign({}, opts, { collapsed: true }));
1566
+ }
1567
+ groupEnd(logLevel) {
1568
+ return this._log("groupEnd", logLevel, "", [], {
1569
+ method: console.groupEnd || noop
1570
+ });
1571
+ }
1572
+ // EXPERIMENTAL
1573
+ withGroup(logLevel, message, func) {
1574
+ this.group(logLevel, message)();
1575
+ try {
1576
+ func();
1577
+ } finally {
1578
+ this.groupEnd(logLevel)();
1579
+ }
1580
+ }
1581
+ trace() {
1582
+ if (console.trace) {
1583
+ console.trace();
1584
+ }
1585
+ }
1586
+ _shouldLog(logLevel) {
1587
+ return this.isEnabled() && super._shouldLog(logLevel);
1588
+ }
1589
+ _emit(_type, normalized) {
1590
+ const method = normalized.method;
1591
+ assert3(method);
1592
+ normalized.total = this.getTotal();
1593
+ normalized.delta = this.getDelta();
1594
+ this._deltaTs = probe.getHighResolutionTimer();
1595
+ const message = decorateMessage(this.id, normalized.message, normalized);
1596
+ return method.bind(console, message, ...normalized.args);
1597
+ }
1598
+ _getConfiguration() {
1599
+ if (!this._storage.config[this.id]) {
1600
+ this._updateConfiguration(DEFAULT_LOG_CONFIGURATION);
1601
+ }
1602
+ return this._storage.config[this.id];
1603
+ }
1604
+ _updateConfiguration(configuration) {
1605
+ const currentConfiguration = this._storage.config[this.id] || {
1606
+ ...DEFAULT_LOG_CONFIGURATION
1607
+ };
1608
+ this._storage.setConfiguration({
1609
+ [this.id]: { ...currentConfiguration, ...configuration }
1610
+ });
1611
+ }
1612
+ };
1613
+ ProbeLog.VERSION = VERSION;
1614
+ function decorateMessage(id, message, opts) {
1615
+ if (typeof message === "string") {
1616
+ const time = opts.time ? leftPad(formatTime(opts.total)) : "";
1617
+ message = opts.time ? `${id}: ${time} ${message}` : `${id}: ${message}`;
1618
+ message = addColor(message, opts.color, opts.background);
1619
+ }
1620
+ return message;
1621
+ }
1622
+ function getTableHeader(table) {
1623
+ for (const key in table) {
1624
+ for (const title in table[key]) {
1625
+ return title || "untitled";
1626
+ }
1627
+ }
1628
+ return "empty";
1629
+ }
1630
+
1631
+ // ../../node_modules/probe.gl/dist/log/init.js
1632
+ if (!globalThis.probe) {
1633
+ globalThis.probe = probe;
1634
+ }
1635
+
1636
+ // ../../node_modules/probe.gl/dist/log/index.js
1637
+ var log = new ProbeLog({ id: "@probe.gl/log" });
1638
+
1639
+ // ../core/src/loader-utils/lib/log-utils/log.ts
1640
+ var VERSION2 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
1641
+ var version = VERSION2[0] >= "0" && VERSION2[0] <= "9" ? `v${VERSION2}` : "";
1642
+ function createLog() {
1643
+ const log3 = new ProbeLog({ id: "loaders.gl" });
1644
+ globalThis.loaders ||= {};
1645
+ globalThis.loaders.log = log3;
1646
+ globalThis.loaders.version = version;
1647
+ globalThis.probe ||= {};
1648
+ globalThis.probe.loaders = log3;
1649
+ return log3;
1650
+ }
1651
+ var log2 = createLog();
1652
+
1653
+ // ../core/src/loader-utils/lib/javascript-utils/is-type.ts
1654
+ var isBoolean = (value) => typeof value === "boolean";
1655
+ var isFunction = (value) => typeof value === "function";
1656
+ var isObject = (value) => value !== null && typeof value === "object";
1657
+ var isPureObject = (value) => isObject(value) && value.constructor === {}.constructor;
1658
+ var isPromise = (value) => isObject(value) && "then" in value && isFunction(value.then);
1659
+ var isIterable = (value) => Boolean(value) && isFunction(value[Symbol.iterator]);
1660
+ var isAsyncIterable = (value) => Boolean(value) && isFunction(value[Symbol.asyncIterator]);
1661
+ var isIterator = (value) => Boolean(value) && isFunction(value.next);
1662
+ var isResponse = (value) => typeof Response !== "undefined" && value instanceof Response || isObject(value) && isFunction(value.arrayBuffer) && isFunction(value.text) && isFunction(value.json);
1663
+ var isWritableDOMStream = (value) => isObject(value) && isFunction(value.abort) && isFunction(value.getWriter);
1664
+ var isReadableDOMStream = (value) => typeof ReadableStream !== "undefined" && value instanceof ReadableStream || isObject(value) && isFunction(value.tee) && isFunction(value.cancel) && isFunction(value.getReader);
1665
+ var isWritableNodeStream = (value) => isObject(value) && isFunction(value.end) && isFunction(value.write) && isBoolean(value.writable);
1666
+ var isReadableNodeStream = (value) => isObject(value) && isFunction(value.read) && isFunction(value.pipe) && isBoolean(value.readable);
1667
+ var isReadableStream = (value) => isReadableDOMStream(value) || isReadableNodeStream(value);
1668
+ var isWritableStream = (value) => isWritableDOMStream(value) || isWritableNodeStream(value);
1669
+
1670
+ // ../core/src/loader-utils/lib/option-utils/merge-options.ts
1671
+ function mergeOptions(baseOptions, newOptions) {
1672
+ return mergeOptionsRecursively(baseOptions || {}, newOptions);
1673
+ }
1674
+ function mergeOptionsRecursively(baseOptions, newOptions, level = 0) {
1675
+ if (level > 3) {
1676
+ return newOptions;
1677
+ }
1678
+ const options = { ...baseOptions };
1679
+ for (const [key, newValue] of Object.entries(newOptions)) {
1680
+ if (isPureObject(newValue)) {
1681
+ options[key] = mergeOptionsRecursively(
1682
+ options[key] || {},
1683
+ newOptions[key],
1684
+ level + 1
1685
+ );
1686
+ } else {
1687
+ options[key] = newOptions[key];
1688
+ }
1689
+ }
1690
+ return options;
1691
+ }
1692
+
1693
+ // ../core/src/loader-utils/lib/binary-utils/array-buffer-utils.ts
1694
+ function concatenateArrayBuffers(...sources) {
1695
+ return concatenateArrayBuffersFromArray(sources);
1696
+ }
1697
+ function concatenateArrayBuffersFromArray(sources) {
1698
+ const sourceArrays = sources.map(
1699
+ (source2) => source2 instanceof ArrayBuffer ? new Uint8Array(source2) : source2
1700
+ );
1701
+ const byteLength = sourceArrays.reduce((length, typedArray) => length + typedArray.byteLength, 0);
1702
+ const result = new Uint8Array(byteLength);
1703
+ let offset = 0;
1704
+ for (const sourceArray of sourceArrays) {
1705
+ result.set(sourceArray, offset);
1706
+ offset += sourceArray.byteLength;
1707
+ }
1708
+ return result.buffer;
1709
+ }
1710
+
1711
+ // ../core/src/loader-utils/lib/iterators/text-iterators.ts
1712
+ async function* makeTextDecoderIterator(arrayBufferIterator, options = {}) {
1713
+ const textDecoder = new TextDecoder(void 0, options);
1714
+ for await (const arrayBuffer of arrayBufferIterator) {
1715
+ yield typeof arrayBuffer === "string" ? arrayBuffer : textDecoder.decode(arrayBuffer, { stream: true });
1716
+ }
1717
+ }
1718
+ async function* makeTextEncoderIterator(textIterator) {
1719
+ const textEncoder = new TextEncoder();
1720
+ for await (const text of textIterator) {
1721
+ yield typeof text === "string" ? textEncoder.encode(text).buffer : text;
1722
+ }
1723
+ }
1724
+ async function* makeLineIterator(textIterator) {
1725
+ let previous = "";
1726
+ for await (const textChunk of textIterator) {
1727
+ previous += textChunk;
1728
+ let eolIndex;
1729
+ eolIndex = previous.indexOf("\n");
1730
+ while (eolIndex >= 0) {
1731
+ const line = previous.slice(0, eolIndex + 1);
1732
+ previous = previous.slice(eolIndex + 1);
1733
+ yield line;
1734
+ eolIndex = previous.indexOf("\n");
1735
+ }
1736
+ }
1737
+ if (previous.length > 0) {
1738
+ yield previous;
1739
+ }
1740
+ }
1741
+ async function* makeNumberedLineIterator(lineIterator) {
1742
+ let counter = 1;
1743
+ for await (const line of lineIterator) {
1744
+ yield { counter, line };
1745
+ counter++;
1746
+ }
1747
+ }
1748
+
1749
+ // ../core/src/loader-utils/lib/iterators/async-iteration.ts
1750
+ async function forEach(iterable, visitor) {
1751
+ const iterator = toAsyncIterator(iterable);
1752
+ while (true) {
1753
+ const { done, value } = await iterator.next();
1754
+ if (done) {
1755
+ if (iterator.return) {
1756
+ iterator.return();
1757
+ }
1758
+ return;
1759
+ }
1760
+ const cancel = visitor(value);
1761
+ if (cancel) {
1762
+ return;
1763
+ }
1764
+ }
1765
+ }
1766
+ async function concatenateArrayBuffersAsync(asyncIterator) {
1767
+ const arrayBuffers = [];
1768
+ for await (const chunk of asyncIterator) {
1769
+ arrayBuffers.push(copyToArrayBuffer(chunk));
1770
+ }
1771
+ return concatenateArrayBuffers(...arrayBuffers);
1772
+ }
1773
+ function copyToArrayBuffer(chunk) {
1774
+ if (chunk instanceof ArrayBuffer) {
1775
+ return chunk;
1776
+ }
1777
+ if (ArrayBuffer.isView(chunk)) {
1778
+ const { buffer, byteOffset, byteLength } = chunk;
1779
+ return copyFromBuffer(buffer, byteOffset, byteLength);
1780
+ }
1781
+ return copyFromBuffer(chunk);
1782
+ }
1783
+ function copyFromBuffer(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
1784
+ const view = new Uint8Array(buffer, byteOffset, byteLength);
1785
+ const copy = new Uint8Array(view.length);
1786
+ copy.set(view);
1787
+ return copy.buffer;
1788
+ }
1789
+ function toAsyncIterator(iterable) {
1790
+ if (typeof iterable[Symbol.asyncIterator] === "function") {
1791
+ return iterable[Symbol.asyncIterator]();
1792
+ }
1793
+ if (typeof iterable[Symbol.iterator] === "function") {
1794
+ const iterator = iterable[Symbol.iterator]();
1795
+ return iteratorToAsyncIterator(iterator);
1796
+ }
1797
+ return iterable;
1798
+ }
1799
+ function iteratorToAsyncIterator(iterator) {
1800
+ return {
1801
+ next(value) {
1802
+ return Promise.resolve(iterator.next(value));
1803
+ },
1804
+ return(value) {
1805
+ if (typeof iterator.return === "function") {
1806
+ return Promise.resolve(iterator.return(value));
1807
+ }
1808
+ return Promise.resolve({ done: true, value });
1809
+ },
1810
+ throw(error) {
1811
+ if (typeof iterator.throw === "function") {
1812
+ return Promise.resolve(iterator.throw(error));
1813
+ }
1814
+ return Promise.reject(error);
1815
+ }
1816
+ };
1817
+ }
1818
+
1819
+ // ../../node_modules/probe.gl/dist/stats/utils/hi-res-timestamp.js
1820
+ function getHiResTimestamp2() {
1821
+ let timestamp;
1822
+ if (typeof window !== "undefined" && window.performance) {
1823
+ timestamp = window.performance.now();
1824
+ } else if (typeof process !== "undefined" && process.hrtime) {
1825
+ const timeParts = process.hrtime();
1826
+ timestamp = timeParts[0] * 1e3 + timeParts[1] / 1e6;
1827
+ } else {
1828
+ timestamp = Date.now();
1829
+ }
1830
+ return timestamp;
1831
+ }
1832
+
1833
+ // ../../node_modules/probe.gl/dist/stats/lib/stat.js
1834
+ var Stat = class {
1835
+ constructor(name, type) {
1836
+ this.sampleSize = 1;
1837
+ this.time = 0;
1838
+ this.count = 0;
1839
+ this.samples = 0;
1840
+ this.lastTiming = 0;
1841
+ this.lastSampleTime = 0;
1842
+ this.lastSampleCount = 0;
1843
+ this._count = 0;
1844
+ this._time = 0;
1845
+ this._samples = 0;
1846
+ this._startTime = 0;
1847
+ this._timerPending = false;
1848
+ this.name = name;
1849
+ this.type = type;
1850
+ this.reset();
1851
+ }
1852
+ reset() {
1853
+ this.time = 0;
1854
+ this.count = 0;
1855
+ this.samples = 0;
1856
+ this.lastTiming = 0;
1857
+ this.lastSampleTime = 0;
1858
+ this.lastSampleCount = 0;
1859
+ this._count = 0;
1860
+ this._time = 0;
1861
+ this._samples = 0;
1862
+ this._startTime = 0;
1863
+ this._timerPending = false;
1864
+ return this;
1865
+ }
1866
+ setSampleSize(samples) {
1867
+ this.sampleSize = samples;
1868
+ return this;
1869
+ }
1870
+ /** Call to increment count (+1) */
1871
+ incrementCount() {
1872
+ this.addCount(1);
1873
+ return this;
1874
+ }
1875
+ /** Call to decrement count (-1) */
1876
+ decrementCount() {
1877
+ this.subtractCount(1);
1878
+ return this;
1879
+ }
1880
+ /** Increase count */
1881
+ addCount(value) {
1882
+ this._count += value;
1883
+ this._samples++;
1884
+ this._checkSampling();
1885
+ return this;
1886
+ }
1887
+ /** Decrease count */
1888
+ subtractCount(value) {
1889
+ this._count -= value;
1890
+ this._samples++;
1891
+ this._checkSampling();
1892
+ return this;
1893
+ }
1894
+ /** Add an arbitrary timing and bump the count */
1895
+ addTime(time) {
1896
+ this._time += time;
1897
+ this.lastTiming = time;
1898
+ this._samples++;
1899
+ this._checkSampling();
1900
+ return this;
1901
+ }
1902
+ /** Start a timer */
1903
+ timeStart() {
1904
+ this._startTime = getHiResTimestamp2();
1905
+ this._timerPending = true;
1906
+ return this;
1907
+ }
1908
+ /** End a timer. Adds to time and bumps the timing count. */
1909
+ timeEnd() {
1910
+ if (!this._timerPending) {
1911
+ return this;
1912
+ }
1913
+ this.addTime(getHiResTimestamp2() - this._startTime);
1914
+ this._timerPending = false;
1915
+ this._checkSampling();
1916
+ return this;
1917
+ }
1918
+ getSampleAverageCount() {
1919
+ return this.sampleSize > 0 ? this.lastSampleCount / this.sampleSize : 0;
1920
+ }
1921
+ /** Calculate average time / count for the previous window */
1922
+ getSampleAverageTime() {
1923
+ return this.sampleSize > 0 ? this.lastSampleTime / this.sampleSize : 0;
1924
+ }
1925
+ /** Calculate counts per second for the previous window */
1926
+ getSampleHz() {
1927
+ return this.lastSampleTime > 0 ? this.sampleSize / (this.lastSampleTime / 1e3) : 0;
1928
+ }
1929
+ getAverageCount() {
1930
+ return this.samples > 0 ? this.count / this.samples : 0;
1931
+ }
1932
+ /** Calculate average time / count */
1933
+ getAverageTime() {
1934
+ return this.samples > 0 ? this.time / this.samples : 0;
1935
+ }
1936
+ /** Calculate counts per second */
1937
+ getHz() {
1938
+ return this.time > 0 ? this.samples / (this.time / 1e3) : 0;
1939
+ }
1940
+ _checkSampling() {
1941
+ if (this._samples === this.sampleSize) {
1942
+ this.lastSampleTime = this._time;
1943
+ this.lastSampleCount = this._count;
1944
+ this.count += this._count;
1945
+ this.time += this._time;
1946
+ this.samples += this._samples;
1947
+ this._time = 0;
1948
+ this._count = 0;
1949
+ this._samples = 0;
1950
+ }
1951
+ }
1952
+ };
1953
+
1954
+ // ../../node_modules/probe.gl/dist/stats/lib/stats.js
1955
+ var Stats = class {
1956
+ constructor(options) {
1957
+ this.stats = {};
1958
+ this.id = options.id;
1959
+ this.stats = {};
1960
+ this._initializeStats(options.stats);
1961
+ Object.seal(this);
1962
+ }
1963
+ /** Acquire a stat. Create if it doesn't exist. */
1964
+ get(name, type = "count") {
1965
+ return this._getOrCreate({ name, type });
1966
+ }
1967
+ get size() {
1968
+ return Object.keys(this.stats).length;
1969
+ }
1970
+ /** Reset all stats */
1971
+ reset() {
1972
+ for (const stat of Object.values(this.stats)) {
1973
+ stat.reset();
1974
+ }
1975
+ return this;
1976
+ }
1977
+ forEach(fn) {
1978
+ for (const stat of Object.values(this.stats)) {
1979
+ fn(stat);
1980
+ }
1981
+ }
1982
+ getTable() {
1983
+ const table = {};
1984
+ this.forEach((stat) => {
1985
+ table[stat.name] = {
1986
+ time: stat.time || 0,
1987
+ count: stat.count || 0,
1988
+ average: stat.getAverageTime() || 0,
1989
+ hz: stat.getHz() || 0
1990
+ };
1991
+ });
1992
+ return table;
1993
+ }
1994
+ _initializeStats(stats = []) {
1995
+ stats.forEach((stat) => this._getOrCreate(stat));
1996
+ }
1997
+ _getOrCreate(stat) {
1998
+ const { name, type } = stat;
1999
+ let result = this.stats[name];
2000
+ if (!result) {
2001
+ if (stat instanceof Stat) {
2002
+ result = stat;
2003
+ } else {
2004
+ result = new Stat(name, type);
2005
+ }
2006
+ this.stats[name] = result;
2007
+ }
2008
+ return result;
2009
+ }
2010
+ };
2011
+
2012
+ // ../core/src/loader-utils/lib/request-utils/request-scheduler.ts
2013
+ var STAT_QUEUED_REQUESTS = "Queued Requests";
2014
+ var STAT_ACTIVE_REQUESTS = "Active Requests";
2015
+ var STAT_CANCELLED_REQUESTS = "Cancelled Requests";
2016
+ var STAT_QUEUED_REQUESTS_EVER = "Queued Requests Ever";
2017
+ var STAT_ACTIVE_REQUESTS_EVER = "Active Requests Ever";
2018
+ var DEFAULT_PROPS = {
2019
+ id: "request-scheduler",
2020
+ /** Specifies if the request scheduler should throttle incoming requests, mainly for comparative testing. */
2021
+ throttleRequests: true,
2022
+ /** The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit. */
2023
+ maxRequests: 6,
2024
+ /**
2025
+ * Specifies a debounce time, in milliseconds. All requests are queued, until no new requests have
2026
+ * been added to the queue for this amount of time.
2027
+ */
2028
+ debounceTime: 0
2029
+ };
2030
+ var RequestScheduler = class {
2031
+ props;
2032
+ stats;
2033
+ activeRequestCount = 0;
2034
+ /** Tracks the number of active requests and prioritizes/cancels queued requests. */
2035
+ requestQueue = [];
2036
+ requestMap = /* @__PURE__ */ new Map();
2037
+ /** Pending arrival debounce or next-tick refill; only new arrivals replace this timer. */
2038
+ updateTimer = null;
2039
+ constructor(props = {}) {
2040
+ this.props = { ...DEFAULT_PROPS, ...props };
2041
+ this.stats = new Stats({ id: this.props.id });
2042
+ this.stats.get(STAT_QUEUED_REQUESTS);
2043
+ this.stats.get(STAT_ACTIVE_REQUESTS);
2044
+ this.stats.get(STAT_CANCELLED_REQUESTS);
2045
+ this.stats.get(STAT_QUEUED_REQUESTS_EVER);
2046
+ this.stats.get(STAT_ACTIVE_REQUESTS_EVER);
2047
+ }
2048
+ /**
2049
+ * Update scheduler props. Preserves active and queued requests.
2050
+ */
2051
+ setProps(props) {
2052
+ if (props.throttleRequests !== void 0) {
2053
+ this.props.throttleRequests = props.throttleRequests;
2054
+ }
2055
+ if (props.maxRequests !== void 0) {
2056
+ this.props.maxRequests = props.maxRequests;
2057
+ }
2058
+ if (props.debounceTime !== void 0) {
2059
+ this.props.debounceTime = props.debounceTime;
2060
+ }
2061
+ }
2062
+ /**
2063
+ * Called by an application that wants to issue a request, without having it deeply queued by the browser
2064
+ *
2065
+ * When the returned promise resolved, it is OK for the application to issue a request.
2066
+ * The promise resolves to an object that contains a `done` method.
2067
+ * When the application's request has completed (or failed), the application must call the `done` function
2068
+ *
2069
+ * @param handle
2070
+ * @param getPriority will be called when request "slots" open up,
2071
+ * allowing the caller to update priority or cancel the request
2072
+ * Highest priority executes first, priority < 0 cancels the request
2073
+ * @returns a promise
2074
+ * - resolves to a object (with a `done` field) when the request can be issued without queueing,
2075
+ * - resolves to `null` if the request has been cancelled (by the callback return < 0).
2076
+ * In this case the application should not issue the request
2077
+ */
2078
+ scheduleRequest(handle, getPriority = () => 0) {
2079
+ if (!this.props.throttleRequests) {
2080
+ return Promise.resolve({ done: () => {
2081
+ } });
2082
+ }
2083
+ if (this.requestMap.has(handle)) {
2084
+ return this.requestMap.get(handle);
2085
+ }
2086
+ const request = { handle, priority: 0, getPriority };
2087
+ const promise = new Promise((resolve) => {
2088
+ request.resolve = resolve;
2089
+ return request;
2090
+ });
2091
+ this.requestQueue.push(request);
2092
+ this.requestMap.set(handle, promise);
2093
+ this._issueNewRequests();
2094
+ return promise;
2095
+ }
2096
+ // PRIVATE
2097
+ _issueRequest(request) {
2098
+ const { handle, resolve } = request;
2099
+ let isDone = false;
2100
+ const done = () => {
2101
+ if (!isDone) {
2102
+ isDone = true;
2103
+ this.requestMap.delete(handle);
2104
+ this.activeRequestCount--;
2105
+ this.scheduleRefill();
2106
+ }
2107
+ };
2108
+ this.activeRequestCount++;
2109
+ return resolve ? resolve({ done }) : Promise.resolve({ done });
2110
+ }
2111
+ /** Refills freed slots on the next tick while preserving any pending arrival debounce. */
2112
+ scheduleRefill() {
2113
+ if (this.updateTimer !== null) {
2114
+ return;
2115
+ }
2116
+ this.updateTimer = setTimeout(() => this._issueNewRequestsAsync(), 0);
2117
+ }
2118
+ /** Restarts the quiet period when a new request enters the queue. */
2119
+ _issueNewRequests() {
2120
+ if (this.updateTimer !== null) {
2121
+ clearTimeout(this.updateTimer);
2122
+ }
2123
+ this.updateTimer = setTimeout(() => this._issueNewRequestsAsync(), this.props.debounceTime);
2124
+ }
2125
+ /** Clears timer ownership before updating priorities and dispatching queued requests. */
2126
+ _issueNewRequestsAsync() {
2127
+ if (this.updateTimer !== null) {
2128
+ clearTimeout(this.updateTimer);
2129
+ }
2130
+ this.updateTimer = null;
2131
+ const freeSlots = Math.max(this.props.maxRequests - this.activeRequestCount, 0);
2132
+ if (freeSlots === 0) {
2133
+ return;
2134
+ }
2135
+ this._updateAllRequests();
2136
+ for (let i = 0; i < freeSlots; ++i) {
2137
+ const request = this.requestQueue.shift();
2138
+ if (request) {
2139
+ this._issueRequest(request);
2140
+ }
2141
+ }
2142
+ }
2143
+ /** Ensure all requests have updated priorities, and that no longer valid requests are cancelled */
2144
+ _updateAllRequests() {
2145
+ const requestQueue = this.requestQueue;
2146
+ for (let i = 0; i < requestQueue.length; ++i) {
2147
+ const request = requestQueue[i];
2148
+ if (!this._updateRequest(request)) {
2149
+ requestQueue.splice(i, 1);
2150
+ this.requestMap.delete(request.handle);
2151
+ i--;
2152
+ }
2153
+ }
2154
+ requestQueue.sort((a, b) => a.priority - b.priority);
2155
+ }
2156
+ /** Update a single request by calling the callback */
2157
+ _updateRequest(request) {
2158
+ request.priority = request.getPriority(request.handle);
2159
+ if (request.priority < 0) {
2160
+ request.resolve(null);
2161
+ return false;
2162
+ }
2163
+ return true;
2164
+ }
2165
+ };
2166
+
2167
+ // ../core/src/loader-utils/lib/request-utils/authentication.ts
2168
+ function resolveCredentials(credentials, authentications = []) {
2169
+ if (credentials.every(isAuthentication)) return credentials;
2170
+ return credentials.map((credential, index) => {
2171
+ if (isAuthentication(credential)) return credential;
2172
+ const AuthenticationClass = authentications.find(
2173
+ (authentication2) => authentication2.type === credential?.type
2174
+ );
2175
+ if (!AuthenticationClass) {
2176
+ throw new Error(`No authentication class registered for credential at index ${index}.`);
2177
+ }
2178
+ let authentication;
2179
+ try {
2180
+ authentication = new AuthenticationClass(credential);
2181
+ } catch {
2182
+ throw new Error(`Invalid authentication configuration at index ${index}.`);
2183
+ }
2184
+ if (!isAuthentication(authentication)) {
2185
+ throw new Error(`Authentication class returned an invalid credential at index ${index}.`);
2186
+ }
2187
+ return authentication;
2188
+ });
2189
+ }
2190
+ function resolveAuthenticationOptions(options) {
2191
+ if (!options.core?.credentials?.length) return options;
2192
+ const credentials = resolveCredentials(options.core.credentials, options.core.authentications);
2193
+ if (credentials === options.core.credentials) return options;
2194
+ return { ...options, core: { ...options.core, credentials } };
2195
+ }
2196
+ function isAuthentication(credential) {
2197
+ if (!credential || typeof credential !== "object") return false;
2198
+ if (typeof credential.id !== "string" || !Array.isArray(credential.origins)) return false;
2199
+ if (credential.type === "request") return typeof credential.authenticate === "function";
2200
+ return (credential.type === "header" || credential.type === "query-parameter") && typeof credential.name === "string" && (typeof credential.token === "string" || typeof credential.token === "function") && Array.isArray(credential.refreshStatusCodes);
2201
+ }
2202
+
2203
+ // ../core/src/loader-utils/lib/request-utils/request-credentials.ts
2204
+ var AUTHENTICATED_FETCH = /* @__PURE__ */ Symbol("loaders.gl.authenticated-fetch");
2205
+ var refreshPromises = /* @__PURE__ */ new WeakMap();
2206
+ function createAuthenticatedFetch(options) {
2207
+ const suppliedFetch = options.fetch || ((url, requestOptions) => fetch(url, requestOptions));
2208
+ const existingMetadata = suppliedFetch[AUTHENTICATED_FETCH];
2209
+ const credentialResolutions = new Map(existingMetadata?.credentialResolutions);
2210
+ const resolvedCredentials = resolveCredentials(
2211
+ options.credentials.map((credential) => credentialResolutions.get(credential) || credential),
2212
+ options.authentications
2213
+ );
2214
+ options.credentials.forEach((credential, index) => {
2215
+ credentialResolutions.set(credential, resolvedCredentials[index]);
2216
+ });
2217
+ if (!options.fetchOptions && (!resolvedCredentials.length || existingMetadata?.credentials.length === resolvedCredentials.length && resolvedCredentials.every(
2218
+ (credential, index) => credential === existingMetadata.credentials[index]
2219
+ )))
2220
+ return suppliedFetch;
2221
+ const baseFetch = existingMetadata?.fetch || suppliedFetch;
2222
+ const credentials = existingMetadata ? [.../* @__PURE__ */ new Set([...resolvedCredentials, ...existingMetadata.credentials])] : resolvedCredentials;
2223
+ const fetchOptions = mergeFetchOptions(
2224
+ existingMetadata?.fetchOptions || {},
2225
+ options.fetchOptions
2226
+ );
2227
+ const tokenCredentials = credentials.filter(
2228
+ (credential) => credential.type !== "request"
2229
+ );
2230
+ const requestCredentials = credentials.filter(
2231
+ (credential) => credential.type === "request"
2232
+ );
2233
+ for (const credential of requestCredentials) normalizeRequestOrigins(credential.origins);
2234
+ const authenticatedFetch = async (url, requestOptions = {}) => {
2235
+ requestOptions = mergeFetchOptions(fetchOptions, requestOptions);
2236
+ if (requestOptions.signal?.aborted) throw createAbortError();
2237
+ if (!credentials.length) return baseFetch(url, requestOptions);
2238
+ const resolvedURL = parseHTTPURL(url);
2239
+ const authorization = resolvedURL ? await authorizeRequest(resolvedURL, requestOptions, tokenCredentials) : { url, options: requestOptions, credentials: [] };
2240
+ const signedRequest = await authenticateRequest(authorization, requestCredentials, "request");
2241
+ const response = await baseFetch(signedRequest.url, signedRequest.options);
2242
+ const refreshableCredentials = [];
2243
+ for (const resolvedCredential of authorization.credentials) {
2244
+ const { credential } = resolvedCredential;
2245
+ if (typeof credential.token === "function" && (isReplayableRequest(requestOptions) || credential.canReplayRequest?.(url, requestOptions)) && (isReplayableRequest(signedRequest.options) || credential.canReplayRequest?.(signedRequest.url, signedRequest.options)) && (credential.refreshStatusCodes.includes(response.status) || await credential.shouldRefresh?.(response)))
2246
+ refreshableCredentials.push(resolvedCredential);
2247
+ }
2248
+ const shouldRetrySignature = isReplayableRequest(requestOptions) && isReplayableRequest(signedRequest.options) && signedRequest.credentials.some(
2249
+ (credential) => credential.refreshStatusCodes?.includes(response.status)
2250
+ );
2251
+ if (!refreshableCredentials.length && !shouldRetrySignature) return response;
2252
+ if (requestOptions.signal?.aborted) throw createAbortError();
2253
+ const refreshedTokens = /* @__PURE__ */ new Map();
2254
+ await Promise.all(
2255
+ refreshableCredentials.map(async ({ credential }) => {
2256
+ const token = await refreshCredential(credential, url, response);
2257
+ if (token) refreshedTokens.set(credential, token);
2258
+ })
2259
+ );
2260
+ if (!refreshedTokens.size && !shouldRetrySignature) return response;
2261
+ await response.body?.cancel().catch(() => {
2262
+ });
2263
+ if (requestOptions.signal?.aborted) throw createAbortError();
2264
+ const replayAuthorization = resolvedURL ? await authorizeRequest(
2265
+ resolvedURL,
2266
+ requestOptions,
2267
+ tokenCredentials,
2268
+ refreshedTokens,
2269
+ authorization.credentials
2270
+ ) : { url, options: requestOptions };
2271
+ const replayRequest = await authenticateRequest(
2272
+ replayAuthorization,
2273
+ requestCredentials,
2274
+ "retry",
2275
+ response
2276
+ );
2277
+ return baseFetch(replayRequest.url, replayRequest.options);
2278
+ };
2279
+ Object.defineProperty(authenticatedFetch, AUTHENTICATED_FETCH, {
2280
+ value: {
2281
+ fetch: baseFetch,
2282
+ credentials,
2283
+ credentialResolutions,
2284
+ fetchOptions
2285
+ }
2286
+ });
2287
+ return authenticatedFetch;
2288
+ }
2289
+ function getAuthenticatedFetch(options = {}) {
2290
+ const fetchOption = options.fetch ?? options.core?.fetch;
2291
+ let fetchFunction;
2292
+ if (typeof fetchOption === "function") {
2293
+ fetchFunction = fetchOption;
2294
+ } else {
2295
+ fetchFunction = (url, requestOptions) => fetch(url, requestOptions);
2296
+ }
2297
+ return createAuthenticatedFetch({
2298
+ fetch: fetchFunction,
2299
+ fetchOptions: typeof fetchOption === "object" && fetchOption ? fetchOption : void 0,
2300
+ credentials: options.core?.credentials || [],
2301
+ authentications: options.core?.authentications
2302
+ });
2303
+ }
2304
+ function mergeFetchOptions(defaultOptions, requestOptions) {
2305
+ const mergedOptions = { ...defaultOptions, ...requestOptions };
2306
+ if (defaultOptions.headers || requestOptions?.headers) {
2307
+ const headers = new Headers(defaultOptions.headers);
2308
+ new Headers(requestOptions?.headers).forEach((value, key) => headers.set(key, value));
2309
+ mergedOptions.headers = headers;
2310
+ }
2311
+ return mergedOptions;
2312
+ }
2313
+ async function authenticateRequest(request, credentials, reason, response) {
2314
+ const appliedCredentials = [];
2315
+ const signal = request.options.signal;
2316
+ for (const credential of credentials) {
2317
+ const origin = getRequestOrigin(request.url);
2318
+ if (!origin || !normalizeRequestOrigins(credential.origins).includes(origin)) continue;
2319
+ if (signal?.aborted) throw createAbortError();
2320
+ const authenticatedRequest = await credential.authenticate({
2321
+ url: request.url,
2322
+ options: { ...request.options, headers: new Headers(request.options.headers) },
2323
+ reason,
2324
+ response: response ? { status: response.status, headers: new Headers(response.headers) } : void 0
2325
+ });
2326
+ if (!authenticatedRequest || typeof authenticatedRequest.url !== "string" || !authenticatedRequest.options || typeof authenticatedRequest.options !== "object") {
2327
+ throw new Error("Authentication callback returned an invalid request.");
2328
+ }
2329
+ request = {
2330
+ url: authenticatedRequest.url,
2331
+ options: { ...authenticatedRequest.options, ...signal ? { signal } : {} }
2332
+ };
2333
+ appliedCredentials.push(credential);
2334
+ }
2335
+ if (signal?.aborted) throw createAbortError();
2336
+ return { ...request, credentials: appliedCredentials };
2337
+ }
2338
+ function getRequestOrigin(url) {
2339
+ try {
2340
+ const parsedURL = new URL(url);
2341
+ if (!parsedURL.host || parsedURL.username || parsedURL.password) return null;
2342
+ return parsedURL.origin !== "null" ? parsedURL.origin : `${parsedURL.protocol}//${parsedURL.host}`;
2343
+ } catch {
2344
+ return null;
2345
+ }
2346
+ }
2347
+ function normalizeRequestOrigins(origins) {
2348
+ if (!origins.length)
2349
+ throw new Error("Request authentication requires at least one exact origin.");
2350
+ return origins.map((origin) => {
2351
+ const resolvedOrigin = getRequestOrigin(origin);
2352
+ let url;
2353
+ try {
2354
+ url = new URL(origin);
2355
+ } catch {
2356
+ throw new Error("Invalid request authentication origin.");
2357
+ }
2358
+ if (!resolvedOrigin || url.pathname && url.pathname !== "/" || url.search || url.hash) {
2359
+ throw new Error("Invalid request authentication origin.");
2360
+ }
2361
+ return resolvedOrigin;
2362
+ });
2363
+ }
2364
+ async function authorizeRequest(sourceURL, requestOptions, credentials, tokenOverrides = /* @__PURE__ */ new Map(), previousCredentials = []) {
2365
+ const url = new URL(sourceURL);
2366
+ const headers = new Headers(requestOptions.headers);
2367
+ const resolvedCredentials = [];
2368
+ const previousTokens = new Map(
2369
+ previousCredentials.map(({ credential, token }) => [credential, token])
2370
+ );
2371
+ for (const credential of credentials) {
2372
+ if (!credential.origins.includes(url.origin)) continue;
2373
+ const overrideToken = tokenOverrides.get(credential);
2374
+ const previousToken = previousTokens.get(credential);
2375
+ const ownsQueryParameter = credential.type === "query-parameter" && previousToken !== void 0;
2376
+ const ownsHeader = credential.type === "header" && previousToken !== void 0;
2377
+ if (credential.type === "query-parameter" && url.searchParams.has(credential.name) && !ownsQueryParameter || credential.type === "header" && headers.has(credential.name) && !ownsHeader) {
2378
+ continue;
2379
+ }
2380
+ const token = overrideToken ?? previousToken ?? await resolveToken(credential.token, { url: sourceURL.toString(), reason: "request" });
2381
+ if (!token) continue;
2382
+ if (credential.type === "query-parameter") {
2383
+ url.searchParams.set(credential.name, token);
2384
+ } else {
2385
+ headers.set(credential.name, `${credential.prefix || ""}${token}`);
2386
+ }
2387
+ resolvedCredentials.push({ credential, token });
2388
+ }
2389
+ return {
2390
+ url: url.toString(),
2391
+ options: { ...requestOptions, headers },
2392
+ credentials: resolvedCredentials
2393
+ };
2394
+ }
2395
+ async function refreshCredential(credential, url, response) {
2396
+ const existingPromise = refreshPromises.get(credential);
2397
+ if (existingPromise) return existingPromise;
2398
+ const tokenProvider = credential.token;
2399
+ const promise = Promise.resolve(
2400
+ tokenProvider({
2401
+ url,
2402
+ reason: "refresh",
2403
+ response: { status: response.status, headers: response.headers }
2404
+ })
2405
+ ).finally(() => refreshPromises.delete(credential));
2406
+ refreshPromises.set(credential, promise);
2407
+ return promise;
2408
+ }
2409
+ async function resolveToken(token, context) {
2410
+ return typeof token === "function" ? token(context) : token;
2411
+ }
2412
+ function parseHTTPURL(url) {
2413
+ try {
2414
+ const parsedURL = new URL(url);
2415
+ return ["http:", "https:"].includes(parsedURL.protocol) ? parsedURL : null;
2416
+ } catch {
2417
+ return null;
2418
+ }
2419
+ }
2420
+ function isReplayableRequest(options) {
2421
+ const method = (options.method || "GET").toUpperCase();
2422
+ if (!["GET", "HEAD", "OPTIONS", "PUT", "DELETE"].includes(method)) return false;
2423
+ return !(options.body && typeof ReadableStream !== "undefined" && options.body instanceof ReadableStream);
2424
+ }
2425
+ function createAbortError() {
2426
+ return new DOMException("The operation was aborted.", "AbortError");
2427
+ }
2428
+
2429
+ // ../core/src/loader-utils/lib/path-utils/file-aliases.ts
2430
+ var pathPrefix = "";
2431
+ var fileAliases = {};
2432
+ function setPathPrefix(prefix) {
2433
+ pathPrefix = prefix;
2434
+ }
2435
+ function getPathPrefix() {
2436
+ return pathPrefix;
2437
+ }
2438
+ function resolvePath(filename) {
2439
+ for (const alias in fileAliases) {
2440
+ if (filename.startsWith(alias)) {
2441
+ const replacement = fileAliases[alias];
2442
+ filename = filename.replace(alias, replacement);
2443
+ }
2444
+ }
2445
+ if (!filename.startsWith("http://") && !filename.startsWith("https://")) {
2446
+ filename = `${pathPrefix}${filename}`;
2447
+ }
2448
+ return filename;
2449
+ }
2450
+
2451
+ // ../core/src/loader-utils/json-loader.ts
2452
+ var VERSION3 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
2453
+ var JSONLoader = {
2454
+ dataType: null,
2455
+ batchType: null,
2456
+ name: "JSON",
2457
+ id: "json",
2458
+ module: "json",
2459
+ version: VERSION3,
2460
+ encoding: "json",
2461
+ format: "json",
2462
+ extensions: ["json", "geojson"],
2463
+ mimeTypes: ["application/json"],
2464
+ category: "json",
2465
+ text: true,
2466
+ parseTextSync,
2467
+ parse: async (arrayBuffer) => parseTextSync(new TextDecoder().decode(arrayBuffer)),
2468
+ options: {}
2469
+ };
2470
+ function parseTextSync(text) {
2471
+ return JSON.parse(text);
2472
+ }
2473
+
2474
+ // ../core/src/loader-utils/lib/sources/data-source.ts
2475
+ var UNAVAILABLE_CORE_API = {
2476
+ fetchFile: unavailableCoreApiMethod("fetchFile"),
2477
+ parse: unavailableCoreApiMethod("parse"),
2478
+ parseFile: unavailableCoreApiMethod("parseFile"),
2479
+ parseSync: unavailableCoreApiMethod("parseSync"),
2480
+ parseInBatches: unavailableCoreApiMethod("parseInBatches"),
2481
+ load: unavailableCoreApiMethod("load"),
2482
+ loadInBatches: unavailableCoreApiMethod("loadInBatches")
2483
+ };
2484
+ var DataSource = class _DataSource {
2485
+ static defaultOptions = {
2486
+ core: {
2487
+ type: "auto",
2488
+ attributions: [],
2489
+ loaders: [],
2490
+ onError: void 0
2491
+ }
2492
+ };
2493
+ optionsType;
2494
+ options;
2495
+ data;
2496
+ url;
2497
+ /** Shared parser options derived from the source options, excluding source-only core controls. */
2498
+ loadOptions;
2499
+ /** A resolved fetch function extracted from the shared core options. */
2500
+ fetch;
2501
+ /** Shared source-level runtime hooks, when supplied by the source factory. */
2502
+ coreApi;
2503
+ /** Whether a real CoreAPI instance was injected by the integration layer. */
2504
+ hasCoreApi;
2505
+ _needsRefresh = true;
2506
+ constructor(data, options, defaultOptions, coreApi2) {
2507
+ this.options = mergeOptions(
2508
+ mergeOptions(_DataSource.defaultOptions, defaultOptions || {}),
2509
+ options
2510
+ );
2511
+ this.data = data;
2512
+ this.url = typeof data === "string" ? resolvePath(data) : "";
2513
+ const loadOptions = resolveAuthenticationOptions(getSourceLoaderOptions(this.options));
2514
+ this.loadOptions = loadOptions;
2515
+ const fetch2 = getFetchFunction(loadOptions);
2516
+ this.coreApi = coreApi2 || UNAVAILABLE_CORE_API;
2517
+ this.hasCoreApi = Boolean(coreApi2);
2518
+ this.fetch = fetch2;
2519
+ }
2520
+ setProps(options) {
2521
+ const mergedOptions = mergeOptions(this.options, options);
2522
+ const loadOptions = resolveAuthenticationOptions(getSourceLoaderOptions(mergedOptions));
2523
+ this.options = mergedOptions;
2524
+ this.loadOptions = loadOptions;
2525
+ this.fetch = getFetchFunction(loadOptions);
2526
+ this.setNeedsRefresh();
2527
+ }
2528
+ /** Mark this data source as needing a refresh (redraw) */
2529
+ setNeedsRefresh() {
2530
+ this._needsRefresh = true;
2531
+ }
2532
+ /**
2533
+ * Does this data source need refreshing?
2534
+ * @note The specifics of the refresh mechanism depends on type of data source
2535
+ */
2536
+ getNeedsRefresh(clear = true) {
2537
+ const needsRefresh = this._needsRefresh;
2538
+ if (clear) {
2539
+ this._needsRefresh = false;
2540
+ }
2541
+ return needsRefresh;
2542
+ }
2543
+ /** Reports a source-level failure through the configured callback or the shared logger. */
2544
+ reportError(error, message) {
2545
+ const normalizedError = normalizeError(error, message);
2546
+ const callback = this.options.core?.onError;
2547
+ if (callback) {
2548
+ callback(normalizedError, this);
2549
+ } else {
2550
+ log2.warn(`${this.constructor.name}: ${normalizedError.message}`)();
2551
+ }
2552
+ return normalizedError;
2553
+ }
2554
+ };
2555
+ function getFetchFunction(options) {
2556
+ return getAuthenticatedFetch(options);
2557
+ }
2558
+ function getSourceLoaderOptions(options) {
2559
+ if (options.loadOptions !== void 0 || options.core?.loadOptions !== void 0) {
2560
+ throw new Error(
2561
+ "Source loadOptions and core.loadOptions were removed. Use core and root loader namespaces directly."
2562
+ );
2563
+ }
2564
+ const loadOptions = { ...options };
2565
+ if (options?.core) {
2566
+ loadOptions.core = { ...options.core };
2567
+ const parserCore = loadOptions.core;
2568
+ for (const key of ["type", "attributions", "loaders", "onError", "loadOptions"]) {
2569
+ delete parserCore[key];
2570
+ }
2571
+ if (Object.keys(parserCore).length === 0) {
2572
+ delete loadOptions.core;
2573
+ }
2574
+ }
2575
+ const topLevelBaseUri = typeof loadOptions.baseUri === "string" ? loadOptions.baseUri : void 0;
2576
+ const topLevelBaseUrl = typeof loadOptions.baseUrl === "string" ? loadOptions.baseUrl : void 0;
2577
+ if (topLevelBaseUri !== void 0 || topLevelBaseUrl !== void 0) {
2578
+ loadOptions.core ||= {};
2579
+ if (loadOptions.core.baseUrl === void 0) {
2580
+ loadOptions.core.baseUrl = topLevelBaseUrl ?? topLevelBaseUri;
2581
+ }
2582
+ delete loadOptions.baseUri;
2583
+ delete loadOptions.baseUrl;
2584
+ }
2585
+ return loadOptions;
2586
+ }
2587
+ function normalizeError(error, message) {
2588
+ if (error instanceof Error) {
2589
+ return error;
2590
+ }
2591
+ if (typeof error === "string") {
2592
+ return new Error(error);
2593
+ }
2594
+ return new Error(message);
2595
+ }
2596
+ function unavailableCoreApiMethod(methodName) {
2597
+ return () => {
2598
+ throw new Error(
2599
+ `CoreAPI.${methodName} is unavailable. Use @loaders.gl/core.createDataSource().`
2600
+ );
2601
+ };
2602
+ }
2603
+
2604
+ // ../../node_modules/@math.gl/geospatial/dist/crs/spatial-reference.js
2605
+ function createSpatialReference(options = {}) {
2606
+ if (options.coordinateEpoch !== void 0 && !Number.isFinite(options.coordinateEpoch)) {
2607
+ throw new Error("Spatial reference coordinate epoch must be a finite decimal year");
2608
+ }
2609
+ return Object.freeze({
2610
+ crs: freezeCRSReference(options.crs || { state: "absent", provenance: "unknown" }),
2611
+ vertical: options.vertical ? freezeCRSReference(options.vertical) : void 0,
2612
+ coordinateEpoch: options.coordinateEpoch,
2613
+ coordinateFrame: options.coordinateFrame || "unknown",
2614
+ coordinateOrder: Object.freeze([...options.coordinateOrder || []]),
2615
+ units: options.units ? Object.freeze([...options.units]) : void 0
2616
+ });
2617
+ }
2618
+ function freezeCRSReference(reference) {
2619
+ if (reference.state === "explicit" || reference.state === "default") {
2620
+ return Object.freeze({
2621
+ ...reference,
2622
+ definition: cloneAndFreezeDefinition(reference.definition),
2623
+ alternatives: reference.alternatives ? Object.freeze(reference.alternatives.map((alternative) => Object.freeze({
2624
+ ...alternative,
2625
+ definition: cloneAndFreezeDefinition(alternative.definition)
2626
+ }))) : void 0
2627
+ });
2628
+ }
2629
+ return Object.freeze({ ...reference });
2630
+ }
2631
+ function cloneAndFreezeDefinition(definition) {
2632
+ return typeof definition === "string" ? definition : cloneAndFreezeJsonValue(definition);
2633
+ }
2634
+ function cloneAndFreezeJsonValue(value) {
2635
+ if (Array.isArray(value)) {
2636
+ return Object.freeze(value.map((item) => cloneAndFreezeJsonValue(item)));
2637
+ }
2638
+ if (value && typeof value === "object") {
2639
+ return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, cloneAndFreezeJsonValue(item)])));
2640
+ }
2641
+ return value;
2642
+ }
2643
+
2644
+ // ../core/src/loader-utils/lib/scan-utils/scan-query-metadata.ts
2645
+ function createScanQueryMetadata(options) {
2646
+ validateScanExecutionSupport(options.queryType, options.execution);
2647
+ const schema = Object.freeze({
2648
+ fields: Object.freeze(
2649
+ options.schema.fields.map(
2650
+ (field) => Object.freeze({ ...field, metadata: Object.freeze({ ...field.metadata }) })
2651
+ )
2652
+ ),
2653
+ metadata: Object.freeze({ ...options.schema.metadata })
2654
+ });
2655
+ const columns = schema.fields.map(
2656
+ (field) => Object.freeze({
2657
+ name: field.name,
2658
+ type: field.type,
2659
+ nullable: field.nullable !== false,
2660
+ role: options.columnRoles?.[field.name] || "attribute",
2661
+ title: getNonEmptyMetadataValue(field.metadata, "title"),
2662
+ description: getNonEmptyMetadataValue(field.metadata, "description"),
2663
+ metadata: field.metadata || Object.freeze({})
2664
+ })
2665
+ );
2666
+ return Object.freeze({
2667
+ sourceType: options.sourceType,
2668
+ queryType: options.queryType,
2669
+ execution: Object.freeze({ ...options.execution }),
2670
+ name: options.name,
2671
+ description: options.description,
2672
+ schema,
2673
+ columns: Object.freeze(columns),
2674
+ capabilities: Object.freeze({ ...options.capabilities }),
2675
+ spatial: options.spatial ? Object.freeze({
2676
+ ...options.spatial,
2677
+ bounds: options.spatial.bounds ? Object.freeze({
2678
+ minimum: Object.freeze([...options.spatial.bounds.minimum]),
2679
+ maximum: Object.freeze([...options.spatial.bounds.maximum])
2680
+ }) : void 0,
2681
+ coordinateReferenceSystems: options.spatial.coordinateReferenceSystems ? Object.freeze([...options.spatial.coordinateReferenceSystems]) : void 0,
2682
+ spatialReference: options.spatial.spatialReference ? createSpatialReference(options.spatial.spatialReference) : void 0
2683
+ }) : void 0,
2684
+ statistics: options.statistics ? Object.freeze({ ...options.statistics }) : void 0,
2685
+ levels: options.levels ? Object.freeze(
2686
+ options.levels.map(
2687
+ (level) => Object.freeze({
2688
+ ...level,
2689
+ scale: level.scale ? Object.freeze([...level.scale]) : void 0
2690
+ })
2691
+ )
2692
+ ) : void 0
2693
+ });
2694
+ }
2695
+ function validateScanExecutionSupport(queryType, execution) {
2696
+ if (execution.status === "metadata-only") {
2697
+ if (!execution.reason.trim()) {
2698
+ throw new Error("Metadata-only scan support requires a concrete reason");
2699
+ }
2700
+ return;
2701
+ }
2702
+ const validMethods = {
2703
+ table: ["read", "query"],
2704
+ raster: ["getRaster"],
2705
+ "point-cloud": ["scan"]
2706
+ };
2707
+ if (!validMethods[queryType].includes(execution.method)) {
2708
+ throw new Error(
2709
+ `Scan execution method "${execution.method}" is not valid for ${queryType} queries`
2710
+ );
2711
+ }
2712
+ }
2713
+ function getNonEmptyMetadataValue(metadata, key) {
2714
+ const value = metadata?.[key];
2715
+ return value || void 0;
2716
+ }
2717
+
2718
+ // ../core/src/loader-utils/lib/scan-utils/raster-query.ts
2719
+ function validateRasterQueryOptions(options) {
2720
+ if (options.width !== void 0) validatePositiveInteger(options.width, "width");
2721
+ if (options.height !== void 0) validatePositiveInteger(options.height, "height");
2722
+ if (options.level !== void 0) validateNonNegativeInteger(options.level, "level");
2723
+ if (options.bounds) {
2724
+ for (let axis = 0; axis < 2; axis++) {
2725
+ const minimum = options.bounds[0][axis];
2726
+ const maximum = options.bounds[1][axis];
2727
+ if (!Number.isFinite(minimum) || !Number.isFinite(maximum) || minimum > maximum) {
2728
+ throw new Error("Raster query bounds must contain finite, ordered coordinates.");
2729
+ }
2730
+ }
2731
+ }
2732
+ for (const channel of options.channels || []) {
2733
+ validateNonNegativeInteger(channel, "channel");
2734
+ }
2735
+ for (const [name, slice] of Object.entries(options.slices || {})) {
2736
+ if (!name) throw new Error("Raster query slice names must be non-empty.");
2737
+ if (Array.isArray(slice)) {
2738
+ if (slice.length !== 2 || !slice.every(Number.isFinite) || slice[0] > slice[1]) {
2739
+ throw new Error(`Raster query slice ${name} must be an ordered finite range.`);
2740
+ }
2741
+ } else if (!Number.isFinite(slice)) {
2742
+ throw new Error(`Raster query slice ${name} must be finite.`);
2743
+ }
2744
+ }
2745
+ }
2746
+ function validatePositiveInteger(value, name) {
2747
+ if (!Number.isSafeInteger(value) || value < 1) {
2748
+ throw new Error(`Raster query ${name} must be a positive safe integer.`);
2749
+ }
2750
+ }
2751
+ function validateNonNegativeInteger(value, name) {
2752
+ if (!Number.isSafeInteger(value) || value < 0) {
2753
+ throw new Error(`Raster query ${name} must be a non-negative safe integer.`);
2754
+ }
2755
+ }
2756
+
2757
+ // src/netcdf/index.ts
2758
+ init_netcdf_reader();
2759
+ init_netcdf_format();
2760
+
2761
+ // src/netcdf/netcdf-source-loader.ts
2762
+ init_netcdf_format();
2763
+ init_netcdf_reader();
2764
+ var VERSION4 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
2765
+ var NetCDFSource = class _NetCDFSource extends DataSource {
2766
+ static HEADER_RANGE_SIZE = 64 * 1024;
2767
+ static MAX_HEADER_RANGE_SIZE = 4 * 1024 * 1024;
2768
+ headerPromise = null;
2769
+ /** Capabilities of the NetCDF variable and dimension-slice executor. */
2770
+ rasterQueryCapabilities = Object.freeze({
2771
+ bounds: "unsupported",
2772
+ level: "unsupported",
2773
+ variables: "pushdown",
2774
+ slices: "residual",
2775
+ streaming: false,
2776
+ cancellation: true
2777
+ });
2778
+ /** Creates a source over a NetCDF URL or Blob. */
2779
+ constructor(data, options = {}) {
2780
+ super(data, options);
2781
+ }
2782
+ /** Discovers variables and dimensions without decoding data arrays. */
2783
+ async getQueryMetadata(options = {}) {
2784
+ throwIfAborted(options.signal);
2785
+ const { header, byteLength } = await this.getHeader(options.signal);
2786
+ throwIfAborted(options.signal);
2787
+ const fields = header.variables.map((variable) => createVariableField(variable, header));
2788
+ const schema = { fields, metadata: createDimensionMetadata(header) };
2789
+ return createScanQueryMetadata({
2790
+ sourceType: "netcdf",
2791
+ queryType: "raster",
2792
+ execution: { status: "supported", method: "getRaster" },
2793
+ name: typeof this.data === "string" ? this.data.split("/").pop() : void 0,
2794
+ schema,
2795
+ capabilities: {
2796
+ bounds: "unsupported",
2797
+ levelOfDetail: "unsupported",
2798
+ raster: this.rasterQueryCapabilities
2799
+ },
2800
+ statistics: {
2801
+ byteLength,
2802
+ rowCount: header.recordDimension.length || void 0
2803
+ }
2804
+ });
2805
+ }
2806
+ /**
2807
+ * Reads selected numeric variables and applies named dimension slices.
2808
+ *
2809
+ * Multiple variables must retain the same shape and numeric type so they can be returned as
2810
+ * ordinary raster bands. Leading dimensions are folded into height and the final dimension is
2811
+ * exposed as width; the original dimension names and shape remain in result metadata.
2812
+ */
2813
+ async getRaster(options = {}) {
2814
+ validateRasterQueryOptions(options);
2815
+ validateNetCDFUnsupportedRasterOptions(options);
2816
+ throwIfAborted(options.signal);
2817
+ const reader = await this.loadReader(options.signal);
2818
+ throwIfAborted(options.signal);
2819
+ validateNetCDFSliceNames(reader.header, options.slices);
2820
+ const variables = selectNetCDFVariables(reader.header, options.variables);
2821
+ const results = variables.map((variable) => {
2822
+ throwIfAborted(options.signal);
2823
+ const dimensionNames = variable.dimensions.map(
2824
+ (dimensionId) => reader.header.dimensions[dimensionId]?.name || `dimension_${dimensionId}`
2825
+ );
2826
+ const dimensionSizes = variable.dimensions.map(
2827
+ (dimensionId) => getDimensionSize(reader.header, dimensionId)
2828
+ );
2829
+ const values = flattenNetCDFValues(reader.getDataVariable(variable));
2830
+ const selection = selectNetCDFValues(
2831
+ values,
2832
+ dimensionNames,
2833
+ dimensionSizes,
2834
+ options.slices || {},
2835
+ options.signal
2836
+ );
2837
+ const dtype = getNetCDFRasterDataType(variable.type);
2838
+ return {
2839
+ variable,
2840
+ dimensionNames: selection.dimensionNames,
2841
+ shape: selection.shape,
2842
+ data: createNetCDFTypedArray(selection.values, dtype),
2843
+ dtype
2844
+ };
2845
+ });
2846
+ const reference = results[0];
2847
+ for (const result of results.slice(1)) {
2848
+ if (result.dtype !== reference.dtype || !arraysEqual(result.shape, reference.shape)) {
2849
+ throw new Error(
2850
+ "NetCDF raster variables must retain the same shape and numeric type after slicing."
2851
+ );
2852
+ }
2853
+ }
2854
+ const width = reference.shape.at(-1) ?? 1;
2855
+ const height = reference.shape.length < 2 ? 1 : reference.shape.slice(0, -1).reduce((product, size) => product * size, 1);
2856
+ const noData = getNetCDFNoDataValue(reference.variable);
2857
+ return {
2858
+ data: results.length === 1 ? reference.data : results.map((result) => result.data),
2859
+ width,
2860
+ height,
2861
+ bandCount: results.length,
2862
+ dtype: reference.dtype,
2863
+ interleaved: false,
2864
+ noData,
2865
+ metadata: {
2866
+ variables: results.map((result) => result.variable.name),
2867
+ dimensions: reference.dimensionNames,
2868
+ shape: reference.shape,
2869
+ slices: { ...options.slices }
2870
+ }
2871
+ };
2872
+ }
2873
+ /** Loads a complete NetCDF reader for selected-variable execution. */
2874
+ async loadReader(signal) {
2875
+ let arrayBuffer;
2876
+ if (typeof this.data === "string") {
2877
+ const response = await this.fetch(this.url, { signal });
2878
+ if (!response.ok) throw new Error(`NetCDF request failed with status ${response.status}.`);
2879
+ arrayBuffer = await response.arrayBuffer();
2880
+ } else {
2881
+ arrayBuffer = await this.data.arrayBuffer();
2882
+ }
2883
+ throwIfAborted(signal);
2884
+ return new NetCDFReader(arrayBuffer);
2885
+ }
2886
+ /** Reads and caches the NetCDF header, preserving abort behavior for each caller. */
2887
+ async getHeader(signal) {
2888
+ throwIfAborted(signal);
2889
+ if (!this.headerPromise) {
2890
+ this.headerPromise = this.loadHeader().catch((error) => {
2891
+ this.headerPromise = null;
2892
+ throw error;
2893
+ });
2894
+ }
2895
+ const result = await this.headerPromise;
2896
+ throwIfAborted(signal);
2897
+ return result;
2898
+ }
2899
+ /** Loads enough leading bytes to parse a remote header, growing ranges when required. */
2900
+ async loadHeader() {
2901
+ if (typeof this.data !== "string") {
2902
+ const arrayBuffer2 = await this.data.arrayBuffer();
2903
+ return { header: new NetCDFReader(arrayBuffer2).header, byteLength: arrayBuffer2.byteLength };
2904
+ }
2905
+ let rangeSize = _NetCDFSource.HEADER_RANGE_SIZE;
2906
+ let response = null;
2907
+ let arrayBuffer = null;
2908
+ let lastError;
2909
+ while (rangeSize <= _NetCDFSource.MAX_HEADER_RANGE_SIZE) {
2910
+ response = await this.fetch(this.url, {
2911
+ headers: { Range: `bytes=0-${rangeSize - 1}` }
2912
+ });
2913
+ if (!response.ok) throw new Error(`NetCDF request failed with status ${response.status}.`);
2914
+ arrayBuffer = await response.arrayBuffer();
2915
+ const byteLength = getResponseByteLength(response, arrayBuffer.byteLength);
2916
+ try {
2917
+ return { header: new NetCDFReader(arrayBuffer).header, byteLength };
2918
+ } catch (error) {
2919
+ lastError = error;
2920
+ if (response.status !== 206 || arrayBuffer.byteLength < rangeSize) throw error;
2921
+ rangeSize *= 2;
2922
+ }
2923
+ }
2924
+ throw lastError || new Error("NetCDF header exceeds the maximum metadata range.");
2925
+ }
2926
+ };
2927
+ var NetCDFSourceLoaderWithParser = {
2928
+ dataType: null,
2929
+ batchType: null,
2930
+ ...NetCDFFormat,
2931
+ module: "scientific",
2932
+ name: "NetCDFSourceLoader",
2933
+ version: VERSION4,
2934
+ type: "netcdf-source",
2935
+ fromUrl: true,
2936
+ fromBlob: true,
2937
+ options: {},
2938
+ defaultOptions: {},
2939
+ testURL: (url) => /\.(?:cdf|nc)(?:$|[?#])/i.test(url),
2940
+ createDataSource: (data, options) => new NetCDFSource(data, options)
2941
+ };
2942
+ function getNetCDFDataType(type) {
2943
+ switch (type.toLowerCase()) {
2944
+ case "byte":
2945
+ return "int8";
2946
+ case "ubyte":
2947
+ return "uint8";
2948
+ case "short":
2949
+ return "int16";
2950
+ case "ushort":
2951
+ return "uint16";
2952
+ case "int":
2953
+ return "int32";
2954
+ case "uint":
2955
+ return "uint32";
2956
+ case "int64":
2957
+ return "int64";
2958
+ case "uint64":
2959
+ return "uint64";
2960
+ case "float":
2961
+ return "float32";
2962
+ case "double":
2963
+ return "float64";
2964
+ case "char":
2965
+ case "string":
2966
+ return "utf8";
2967
+ default:
2968
+ return "binary";
2969
+ }
2970
+ }
2971
+ function validateNetCDFUnsupportedRasterOptions(options) {
2972
+ if (options.bounds) throw new Error("NetCDF raster bounds are not supported.");
2973
+ if (options.level !== void 0) throw new Error("NetCDF raster levels are not supported.");
2974
+ if (options.width !== void 0 || options.height !== void 0) {
2975
+ throw new Error("NetCDF raster resampling is not supported.");
2976
+ }
2977
+ if (options.channels?.length) {
2978
+ throw new Error("NetCDF uses named variables instead of numeric channels.");
2979
+ }
2980
+ }
2981
+ function selectNetCDFVariables(header, requestedVariableNames) {
2982
+ const defaultVariable = header.variables.find(
2983
+ (variable) => variable.dimensions.length > 0 && isNetCDFRasterDataType(variable.type)
2984
+ );
2985
+ const variableNames = requestedVariableNames?.length ? [...requestedVariableNames] : defaultVariable ? [defaultVariable.name] : [];
2986
+ if (variableNames.length === 0) {
2987
+ throw new Error("NetCDF contains no numeric variables that can be read as raster data.");
2988
+ }
2989
+ if (new Set(variableNames).size !== variableNames.length) {
2990
+ throw new Error("NetCDF raster variables must not contain duplicates.");
2991
+ }
2992
+ return variableNames.map((variableName) => {
2993
+ const variable = header.variables.find((candidate) => candidate.name === variableName);
2994
+ if (!variable) throw new Error(`NetCDF variable not found: ${variableName}`);
2995
+ getNetCDFRasterDataType(variable.type);
2996
+ return variable;
2997
+ });
2998
+ }
2999
+ function validateNetCDFSliceNames(header, slices) {
3000
+ const dimensionNames = new Set(header.dimensions.map((dimension) => dimension.name));
3001
+ for (const dimensionName of Object.keys(slices || {})) {
3002
+ if (!dimensionNames.has(dimensionName)) {
3003
+ throw new Error(`NetCDF dimension not found: ${dimensionName}`);
3004
+ }
3005
+ }
3006
+ }
3007
+ function selectNetCDFValues(values, dimensionNames, dimensionSizes, slices, signal) {
3008
+ const selectors = dimensionNames.map((dimensionName, dimensionIndex) => {
3009
+ const size = dimensionSizes[dimensionIndex];
3010
+ const slice = slices[dimensionName];
3011
+ if (slice === void 0) return { start: 0, stop: size, remove: false };
3012
+ if (typeof slice !== "number") {
3013
+ const [start, stop] = slice;
3014
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(stop) || start < 0 || stop < start || stop > size) {
3015
+ throw new Error(
3016
+ `NetCDF slice ${dimensionName} must be a valid half-open range within 0..${size}.`
3017
+ );
3018
+ }
3019
+ return { start, stop, remove: false };
3020
+ }
3021
+ if (!Number.isSafeInteger(slice) || slice < 0 || slice >= size) {
3022
+ throw new Error(`NetCDF slice ${dimensionName} must be an index within 0..${size - 1}.`);
3023
+ }
3024
+ return { start: slice, stop: slice + 1, remove: true };
3025
+ });
3026
+ const strides = dimensionSizes.map(
3027
+ (_, dimensionIndex) => dimensionSizes.slice(dimensionIndex + 1).reduce((product, dimensionSize) => product * dimensionSize, 1)
3028
+ );
3029
+ const selectedValues = [];
3030
+ const visitDimension = (dimensionIndex, flatOffset) => {
3031
+ throwIfAborted(signal);
3032
+ if (dimensionIndex === selectors.length) {
3033
+ const value = values[flatOffset];
3034
+ if (typeof value !== "number") {
3035
+ throw new Error("NetCDF raster variables must contain numeric values.");
3036
+ }
3037
+ selectedValues.push(value);
3038
+ return;
3039
+ }
3040
+ const selector = selectors[dimensionIndex];
3041
+ for (let index = selector.start; index < selector.stop; index++) {
3042
+ visitDimension(dimensionIndex + 1, flatOffset + index * strides[dimensionIndex]);
3043
+ }
3044
+ };
3045
+ visitDimension(0, 0);
3046
+ return {
3047
+ values: selectedValues,
3048
+ dimensionNames: dimensionNames.filter((_, index) => !selectors[index].remove),
3049
+ shape: selectors.map((selector) => selector.stop - selector.start).filter((_, index) => !selectors[index].remove)
3050
+ };
3051
+ }
3052
+ function flattenNetCDFValues(values) {
3053
+ if (Array.isArray(values)) return values.flatMap(flattenNetCDFValues);
3054
+ if (ArrayBuffer.isView(values)) {
3055
+ return Array.from(values);
3056
+ }
3057
+ return [values];
3058
+ }
3059
+ function isNetCDFRasterDataType(type) {
3060
+ try {
3061
+ getNetCDFRasterDataType(type);
3062
+ return true;
3063
+ } catch {
3064
+ return false;
3065
+ }
3066
+ }
3067
+ function getNetCDFRasterDataType(type) {
3068
+ switch (type.toLowerCase()) {
3069
+ case "byte":
3070
+ return "int8";
3071
+ case "ubyte":
3072
+ return "uint8";
3073
+ case "short":
3074
+ return "int16";
3075
+ case "ushort":
3076
+ return "uint16";
3077
+ case "int":
3078
+ return "int32";
3079
+ case "uint":
3080
+ return "uint32";
3081
+ case "float":
3082
+ return "float32";
3083
+ case "double":
3084
+ return "float64";
3085
+ default:
3086
+ throw new Error(`NetCDF variable type is not supported as raster data: ${type}`);
3087
+ }
3088
+ }
3089
+ function createNetCDFTypedArray(values, dtype) {
3090
+ switch (dtype) {
3091
+ case "int8":
3092
+ return Int8Array.from(values);
3093
+ case "uint8":
3094
+ return Uint8Array.from(values);
3095
+ case "int16":
3096
+ return Int16Array.from(values);
3097
+ case "uint16":
3098
+ return Uint16Array.from(values);
3099
+ case "int32":
3100
+ return Int32Array.from(values);
3101
+ case "uint32":
3102
+ return Uint32Array.from(values);
3103
+ case "float32":
3104
+ return Float32Array.from(values);
3105
+ case "float64":
3106
+ return Float64Array.from(values);
3107
+ }
3108
+ }
3109
+ function getNetCDFNoDataValue(variable) {
3110
+ const attribute = variable.attributes.find(
3111
+ (candidate) => candidate.name === "_FillValue" || candidate.name === "missing_value"
3112
+ );
3113
+ const value = Number(attribute?.value);
3114
+ return attribute && Number.isFinite(value) ? value : null;
3115
+ }
3116
+ function arraysEqual(left, right) {
3117
+ return left.length === right.length && left.every((value, index) => value === right[index]);
3118
+ }
3119
+ function createVariableField(variable, header) {
3120
+ const dimensions = variable.dimensions.map((dimensionId) => header.dimensions[dimensionId]).filter(Boolean).map(
3121
+ (dimension, index) => `${dimension.name}[${getDimensionSize(header, variable.dimensions[index])}]`
3122
+ ).join(",");
3123
+ const metadata = { dimensions };
3124
+ for (const attribute of variable.attributes) {
3125
+ metadata[attribute.name] = String(attribute.value);
3126
+ }
3127
+ return { name: variable.name, type: getNetCDFDataType(variable.type), nullable: true, metadata };
3128
+ }
3129
+ function createDimensionMetadata(header) {
3130
+ const metadata = {};
3131
+ for (const [dimensionId, dimension] of header.dimensions.entries()) {
3132
+ metadata[`dimension:${dimension.name}`] = String(getDimensionSize(header, dimensionId));
3133
+ }
3134
+ return metadata;
3135
+ }
3136
+ function getDimensionSize(header, dimensionId) {
3137
+ const dimension = header.dimensions[dimensionId];
3138
+ return dimensionId === header.recordDimension.id ? header.recordDimension.length : dimension?.size || 0;
3139
+ }
3140
+ function getResponseByteLength(response, fallback) {
3141
+ const contentRange = response.headers.get("content-range");
3142
+ const total = contentRange?.match(/\/([0-9]+)$/)?.[1];
3143
+ return Number(total || response.headers.get("content-length") || fallback);
3144
+ }
3145
+ function throwIfAborted(signal) {
3146
+ if (signal?.aborted) {
3147
+ throw new DOMException("The operation was aborted", "AbortError");
3148
+ }
3149
+ }
3150
+ return __toCommonJS(netcdf_bundle_exports);
3151
+ })();
3152
+ return __exports__;
3153
+ });