@loaders.gl/scene 5.0.0-beta.4 → 5.0.0-beta.6

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 (177) hide show
  1. package/DRACO-README.md +1 -1
  2. package/GLTF-README.md +1 -1
  3. package/OBJ-README.md +1 -1
  4. package/README.md +6 -1
  5. package/THIRD-PARTY-NOTICES.md +6 -0
  6. package/dist/dist.dev.js +2959 -750
  7. package/dist/dist.min.js +18 -18
  8. package/dist/draco/draco-javascript-loader-with-parser.d.ts +2 -2
  9. package/dist/draco/draco-loader-types.cjs +3 -3
  10. package/dist/draco/draco-loader-types.cjs.map +2 -2
  11. package/dist/draco/draco-loader-types.d.ts +1 -1
  12. package/dist/draco/draco-loader-types.d.ts.map +1 -1
  13. package/dist/draco/draco-loader-types.js +1 -1
  14. package/dist/draco/draco-loader-types.js.map +1 -1
  15. package/dist/draco/draco-loader.d.ts +2 -2
  16. package/dist/draco/draco-wasm-loader-with-parser.d.ts +2 -2
  17. package/dist/draco/draco3d-loader-with-parser.d.ts +2 -2
  18. package/dist/draco/lib/utils/version.cjs +1 -1
  19. package/dist/draco/lib/utils/version.js +1 -1
  20. package/dist/draco-worker-node.js +401 -113
  21. package/dist/draco-worker-node.js.map +4 -4
  22. package/dist/draco-worker.js +395 -113
  23. package/dist/draco-worker.js.map +4 -4
  24. package/dist/draco-writer-worker-node.cjs +655 -85
  25. package/dist/draco-writer-worker-node.cjs.map +4 -4
  26. package/dist/draco-writer-worker.js +625 -69
  27. package/dist/draco-writer-worker.js.map +4 -4
  28. package/dist/gltf/lib/extensions/KHR_gaussian_splatting.cjs +11 -4
  29. package/dist/gltf/lib/extensions/KHR_gaussian_splatting.cjs.map +2 -2
  30. package/dist/gltf/lib/extensions/KHR_gaussian_splatting.d.ts.map +1 -1
  31. package/dist/gltf/lib/extensions/KHR_gaussian_splatting.js +12 -2
  32. package/dist/gltf/lib/extensions/KHR_gaussian_splatting.js.map +1 -1
  33. package/dist/gltf/lib/parsers/parse-gltf.cjs.map +2 -2
  34. package/dist/gltf/lib/parsers/parse-gltf.d.ts +2 -0
  35. package/dist/gltf/lib/parsers/parse-gltf.d.ts.map +1 -1
  36. package/dist/gltf/lib/parsers/parse-gltf.js.map +1 -1
  37. package/dist/gltf/lib/types/gltf-additional-extension-schemas.cjs +22 -0
  38. package/dist/gltf/lib/types/gltf-additional-extension-schemas.cjs.map +2 -2
  39. package/dist/gltf/lib/types/gltf-additional-extension-schemas.d.ts +23 -0
  40. package/dist/gltf/lib/types/gltf-additional-extension-schemas.d.ts.map +1 -1
  41. package/dist/gltf/lib/types/gltf-additional-extension-schemas.js +22 -0
  42. package/dist/gltf/lib/types/gltf-additional-extension-schemas.js.map +1 -1
  43. package/dist/gltf/lib/types/gltf-extension-schemas.cjs +8 -0
  44. package/dist/gltf/lib/types/gltf-extension-schemas.cjs.map +2 -2
  45. package/dist/gltf/lib/types/gltf-extension-schemas.d.ts +27 -0
  46. package/dist/gltf/lib/types/gltf-extension-schemas.d.ts.map +1 -1
  47. package/dist/gltf/lib/types/gltf-extension-schemas.js +8 -1
  48. package/dist/gltf/lib/types/gltf-extension-schemas.js.map +1 -1
  49. package/dist/gltf/lib/types/gltf-json-schema.cjs.map +1 -1
  50. package/dist/gltf/lib/types/gltf-json-schema.d.ts +2 -2
  51. package/dist/gltf/lib/types/gltf-json-schema.d.ts.map +1 -1
  52. package/dist/gltf/lib/types/gltf-version-zod-schemas.d.ts +34 -0
  53. package/dist/gltf/lib/types/gltf-version-zod-schemas.d.ts.map +1 -1
  54. package/dist/gltf/lib/types/gltf-zod-schema.cjs +1 -1
  55. package/dist/gltf/lib/types/gltf-zod-schema.cjs.map +2 -2
  56. package/dist/gltf/lib/types/gltf-zod-schema.d.ts +51 -0
  57. package/dist/gltf/lib/types/gltf-zod-schema.d.ts.map +1 -1
  58. package/dist/gltf/lib/types/gltf-zod-schema.js +2 -2
  59. package/dist/gltf/lib/types/gltf-zod-schema.js.map +1 -1
  60. package/dist/gltf/lib/utils/version.cjs +1 -1
  61. package/dist/gltf/lib/utils/version.js +1 -1
  62. package/dist/index.cjs +4 -1
  63. package/dist/index.cjs.map +2 -2
  64. package/dist/index.d.ts +1 -0
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +2 -1
  67. package/dist/index.js.map +1 -1
  68. package/dist/mtl-loader-types.cjs +1 -1
  69. package/dist/obj/mtl-loader-types.cjs +1 -1
  70. package/dist/obj/mtl-loader-types.js +1 -1
  71. package/dist/obj/obj-loader-types.cjs +3 -3
  72. package/dist/obj/obj-loader-types.cjs.map +2 -2
  73. package/dist/obj/obj-loader-types.d.ts +1 -1
  74. package/dist/obj/obj-loader-types.d.ts.map +1 -1
  75. package/dist/obj/obj-loader-types.js +2 -2
  76. package/dist/obj/obj-loader-types.js.map +1 -1
  77. package/dist/obj/obj-loader.cjs +5 -5
  78. package/dist/obj/obj-loader.cjs.map +2 -2
  79. package/dist/obj/obj-loader.d.ts +1 -1
  80. package/dist/obj/obj-loader.d.ts.map +1 -1
  81. package/dist/obj/obj-loader.js +1 -1
  82. package/dist/obj/obj-loader.js.map +1 -1
  83. package/dist/obj/obj-writer.cjs +1 -1
  84. package/dist/obj/obj-writer.js +1 -1
  85. package/dist/obj-loader-types.cjs +3 -3
  86. package/dist/obj-loader-types.cjs.map +2 -2
  87. package/dist/obj-loader.cjs +5 -5
  88. package/dist/obj-loader.cjs.map +2 -2
  89. package/dist/obj-worker.js +568 -287
  90. package/dist/obj-writer.cjs +1 -1
  91. package/dist/stl/parse-stl.cjs +100 -0
  92. package/dist/stl/parse-stl.cjs.map +7 -0
  93. package/dist/stl/parse-stl.d.ts +4 -0
  94. package/dist/stl/parse-stl.d.ts.map +1 -0
  95. package/dist/stl/parse-stl.js +84 -0
  96. package/dist/stl/parse-stl.js.map +1 -0
  97. package/dist/stl-loader-types.cjs +58 -0
  98. package/dist/stl-loader-types.cjs.map +7 -0
  99. package/dist/stl-loader-types.d.ts +32 -0
  100. package/dist/stl-loader-types.d.ts.map +1 -0
  101. package/dist/stl-loader-types.js +25 -0
  102. package/dist/stl-loader-types.js.map +1 -0
  103. package/dist/stl-loader.cjs +38 -0
  104. package/dist/stl-loader.cjs.map +7 -0
  105. package/dist/stl-loader.d.ts +17 -0
  106. package/dist/stl-loader.d.ts.map +1 -0
  107. package/dist/stl-loader.js +13 -0
  108. package/dist/stl-loader.js.map +1 -0
  109. package/dist/usd/index.cjs.map +1 -1
  110. package/dist/usd/index.d.ts +1 -1
  111. package/dist/usd/index.d.ts.map +1 -1
  112. package/dist/usd/lib/parse-usd.cjs +42 -5
  113. package/dist/usd/lib/parse-usd.cjs.map +2 -2
  114. package/dist/usd/lib/parse-usd.d.ts.map +1 -1
  115. package/dist/usd/lib/parse-usd.js +53 -6
  116. package/dist/usd/lib/parse-usd.js.map +1 -1
  117. package/dist/usd/lib/parse-usdc.cjs +187 -0
  118. package/dist/usd/lib/parse-usdc.cjs.map +7 -0
  119. package/dist/usd/lib/parse-usdc.d.ts +4 -0
  120. package/dist/usd/lib/parse-usdc.d.ts.map +1 -0
  121. package/dist/usd/lib/parse-usdc.js +176 -0
  122. package/dist/usd/lib/parse-usdc.js.map +1 -0
  123. package/dist/usd/lib/parse-usdz.cjs +22 -0
  124. package/dist/usd/lib/parse-usdz.cjs.map +2 -2
  125. package/dist/usd/lib/parse-usdz.d.ts.map +1 -1
  126. package/dist/usd/lib/parse-usdz.js +26 -0
  127. package/dist/usd/lib/parse-usdz.js.map +1 -1
  128. package/dist/usd/lib/usd-types.cjs.map +1 -1
  129. package/dist/usd/lib/usd-types.d.ts +14 -1
  130. package/dist/usd/lib/usd-types.d.ts.map +1 -1
  131. package/dist/usd/lib/usd-types.js +1 -1
  132. package/dist/usd/lib/usd-types.js.map +1 -1
  133. package/dist/usd/libs/README.md +27 -0
  134. package/dist/usd/libs/THREE-LICENSE +21 -0
  135. package/dist/usd/libs/usdc-parser.d.ts +78 -0
  136. package/dist/usd/libs/usdc-parser.d.ts.map +1 -0
  137. package/dist/usd/libs/usdc-parser.js +1669 -0
  138. package/dist/usd/libs/usdc-parser.js.map +1 -0
  139. package/dist/usd/usd-loader-types.cjs +4 -4
  140. package/dist/usd/usd-loader-types.cjs.map +2 -2
  141. package/dist/usd/usd-loader-types.d.ts +7 -7
  142. package/dist/usd/usd-loader-types.d.ts.map +1 -1
  143. package/dist/usd/usd-loader-types.js +6 -6
  144. package/dist/usd/usd-loader-types.js.map +1 -1
  145. package/dist/usd/usd-loader.cjs.map +1 -1
  146. package/dist/usd/usd-loader.d.ts +4 -4
  147. package/dist/usd/usd-loader.d.ts.map +1 -1
  148. package/dist/usd/usd-loader.js +2 -2
  149. package/dist/usd/usd-loader.js.map +1 -1
  150. package/dist/usd-loader-types.cjs +4 -4
  151. package/dist/usd-loader-types.cjs.map +2 -2
  152. package/dist/usd-loader.cjs.map +1 -1
  153. package/package.json +14 -8
  154. package/src/draco/draco-loader-types.ts +1 -1
  155. package/src/gltf/lib/extensions/KHR_gaussian_splatting.ts +14 -4
  156. package/src/gltf/lib/parsers/parse-gltf.ts +2 -0
  157. package/src/gltf/lib/types/gltf-additional-extension-schemas.ts +32 -0
  158. package/src/gltf/lib/types/gltf-extension-schemas.ts +12 -0
  159. package/src/gltf/lib/types/gltf-json-schema.ts +2 -1
  160. package/src/gltf/lib/types/gltf-zod-schema.ts +2 -1
  161. package/src/index.ts +3 -1
  162. package/src/obj/obj-loader-types.ts +1 -1
  163. package/src/obj/obj-loader.ts +1 -1
  164. package/src/stl/parse-stl.ts +90 -0
  165. package/src/stl-loader-types.ts +28 -0
  166. package/src/stl-loader.ts +12 -0
  167. package/src/usd/index.ts +1 -0
  168. package/src/usd/lib/parse-usd.ts +68 -7
  169. package/src/usd/lib/parse-usdc.ts +188 -0
  170. package/src/usd/lib/parse-usdz.ts +28 -0
  171. package/src/usd/lib/usd-types.ts +16 -2
  172. package/src/usd/libs/README.md +27 -0
  173. package/src/usd/libs/THREE-LICENSE +21 -0
  174. package/src/usd/libs/usdc-parser.d.ts +18 -0
  175. package/src/usd/libs/usdc-parser.js +1669 -0
  176. package/src/usd/usd-loader-types.ts +5 -5
  177. package/src/usd/usd-loader.ts +2 -2
package/dist/dist.dev.js CHANGED
@@ -56,6 +56,1417 @@ var __exports__ = (() => {
56
56
  }
57
57
  });
58
58
 
59
+ // src/usd/libs/usdc-parser.js
60
+ function checkedLength(length4, bytesPerElement = 8) {
61
+ const byteLength = length4 * bytesPerElement;
62
+ if (!Number.isSafeInteger(length4) || length4 < 0 || !Number.isSafeInteger(byteLength) || byteLength > 256 * 1024 * 1024 - allocationBytes)
63
+ throw new Error("USDC: decoded allocation limit exceeded");
64
+ allocationBytes += byteLength;
65
+ return length4;
66
+ }
67
+ function checkedCount(count) {
68
+ if (!Number.isSafeInteger(count) || count < 0 || count > 4e6)
69
+ throw new Error("USDC: decoded allocation limit exceeded");
70
+ return checkedLength(count);
71
+ }
72
+ function lz4DecompressBlock(input, inputOffset, inputEnd, output, outputOffset, outputEnd) {
73
+ while (inputOffset < inputEnd) {
74
+ const token = input[inputOffset++];
75
+ if (inputOffset > inputEnd) throw new Error("USDC: truncated LZ4 token");
76
+ let literalLength = token >> 4;
77
+ if (literalLength === 15) {
78
+ let b;
79
+ do {
80
+ if (inputOffset >= inputEnd) throw new Error("USDC: truncated LZ4 length");
81
+ b = input[inputOffset++];
82
+ literalLength += b;
83
+ } while (b === 255);
84
+ }
85
+ if (literalLength > 0) {
86
+ if (inputOffset + literalLength > inputEnd) {
87
+ throw new Error("USDC: truncated LZ4 literal");
88
+ }
89
+ for (let i = 0; i < literalLength; i++) {
90
+ if (outputOffset >= outputEnd) throw new Error("USDC: LZ4 output overflow");
91
+ output[outputOffset++] = input[inputOffset++];
92
+ }
93
+ }
94
+ if (inputOffset >= inputEnd) break;
95
+ if (inputOffset + 2 > inputEnd) throw new Error("USDC: truncated LZ4 offset");
96
+ const matchOffset = input[inputOffset++] | input[inputOffset++] << 8;
97
+ if (matchOffset === 0) {
98
+ throw new Error("USDC: invalid LZ4 match offset");
99
+ }
100
+ let matchLength = (token & 15) + 4;
101
+ if (matchLength === 19) {
102
+ let b;
103
+ do {
104
+ if (inputOffset >= inputEnd) throw new Error("USDC: truncated LZ4 length");
105
+ b = input[inputOffset++];
106
+ matchLength += b;
107
+ } while (b === 255);
108
+ }
109
+ const matchPos = outputOffset - matchOffset;
110
+ if (matchPos < 0) {
111
+ throw new Error("USDC: invalid LZ4 match position");
112
+ }
113
+ for (let i = 0; i < matchLength; i++) {
114
+ if (outputOffset >= outputEnd) throw new Error("USDC: LZ4 output overflow");
115
+ output[outputOffset++] = output[matchPos + i];
116
+ }
117
+ }
118
+ return outputOffset;
119
+ }
120
+ function decompressLZ4(input, uncompressedSize, allowShortOutput = false) {
121
+ const output = new Uint8Array(checkedLength(uncompressedSize, 1));
122
+ if (!input.length) throw new Error("USDC: missing LZ4 chunk header");
123
+ const numChunks = input[0];
124
+ if (numChunks === 0) {
125
+ const written = lz4DecompressBlock(input, 1, input.length, output, 0, uncompressedSize);
126
+ if (!allowShortOutput && written !== uncompressedSize)
127
+ throw new Error("USDC: incomplete LZ4 output");
128
+ return output.subarray(0, written);
129
+ } else {
130
+ const CHUNK_SIZE = 65536;
131
+ if (1 + numChunks * 4 > input.length) throw new Error("USDC: truncated LZ4 chunk sizes");
132
+ let headerOffset = 1;
133
+ const compressedSizes = [];
134
+ for (let i = 0; i < numChunks; i++) {
135
+ const size = (input[headerOffset] | input[headerOffset + 1] << 8 | input[headerOffset + 2] << 16 | input[headerOffset + 3] << 24) >>> 0;
136
+ compressedSizes.push(size);
137
+ headerOffset += 4;
138
+ }
139
+ let inputOffset = headerOffset;
140
+ let outputOffset = 0;
141
+ for (let i = 0; i < numChunks; i++) {
142
+ const chunkCompressedSize = compressedSizes[i];
143
+ const chunkOutputSize = Math.min(CHUNK_SIZE, uncompressedSize - outputOffset);
144
+ if (chunkCompressedSize > input.length - inputOffset)
145
+ throw new Error("USDC: truncated LZ4 chunk");
146
+ const written = lz4DecompressBlock(
147
+ input,
148
+ inputOffset,
149
+ inputOffset + chunkCompressedSize,
150
+ output,
151
+ outputOffset,
152
+ outputOffset + chunkOutputSize
153
+ );
154
+ inputOffset += chunkCompressedSize;
155
+ if (i < numChunks - 1 && written !== outputOffset + chunkOutputSize)
156
+ throw new Error("USDC: incomplete LZ4 chunk");
157
+ outputOffset = written;
158
+ }
159
+ if (inputOffset !== input.length || !allowShortOutput && outputOffset !== uncompressedSize)
160
+ throw new Error("USDC: incomplete LZ4 output");
161
+ return output.subarray(0, outputOffset);
162
+ }
163
+ }
164
+ function decompressIntegers32(compressedData, numInts) {
165
+ const encodedSize = numInts * 4 + (numInts * 2 + 7 >> 3) + 4;
166
+ const encoded = decompressLZ4(new Uint8Array(compressedData), encodedSize, true);
167
+ return decodeIntegers32(encoded, numInts);
168
+ }
169
+ function decodeIntegers32(data, numInts) {
170
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
171
+ let offset = 0;
172
+ const commonValue = view.getInt32(offset, true);
173
+ offset += 4;
174
+ const numCodesBytes = numInts * 2 + 7 >> 3;
175
+ if (data.length < offset + numCodesBytes) throw new Error("USDC: truncated integer codes");
176
+ const codesStart = offset;
177
+ const vintsStart = offset + numCodesBytes;
178
+ const result = new Int32Array(checkedLength(numInts));
179
+ let prevVal = 0;
180
+ let codesOffset = codesStart;
181
+ let vintsOffset = vintsStart;
182
+ for (let i = 0; i < numInts; ) {
183
+ const codeByte = data[codesOffset++];
184
+ for (let j = 0; j < 4 && i < numInts; j++, i++) {
185
+ const code = codeByte >> j * 2 & 3;
186
+ let delta = 0;
187
+ switch (code) {
188
+ case 0:
189
+ delta = commonValue;
190
+ break;
191
+ case 1:
192
+ delta = view.getInt8(vintsOffset);
193
+ vintsOffset += 1;
194
+ break;
195
+ case 2:
196
+ delta = view.getInt16(vintsOffset, true);
197
+ vintsOffset += 2;
198
+ break;
199
+ case 3:
200
+ delta = view.getInt32(vintsOffset, true);
201
+ vintsOffset += 4;
202
+ break;
203
+ }
204
+ prevVal += delta;
205
+ result[i] = prevVal;
206
+ }
207
+ }
208
+ return result;
209
+ }
210
+ var allocationBytes, textDecoder, HALF_EXPONENT_TABLE, HALF_DENORM_SCALE, TypeEnum, DICTIONARY_ARRAY_TYPES, FIELD_SET_TERMINATOR, FLOAT_COMPRESSION_INT, FLOAT_COMPRESSION_LUT, BinaryReader, ValueRep, USDCParser;
211
+ var init_usdc_parser = __esm({
212
+ "src/usd/libs/usdc-parser.js"() {
213
+ "use strict";
214
+ allocationBytes = 0;
215
+ textDecoder = new TextDecoder();
216
+ HALF_EXPONENT_TABLE = new Float32Array(32);
217
+ for (let i = 0; i < 32; i++) {
218
+ HALF_EXPONENT_TABLE[i] = Math.pow(2, i - 15);
219
+ }
220
+ HALF_DENORM_SCALE = Math.pow(2, -14);
221
+ TypeEnum = {
222
+ Invalid: 0,
223
+ Bool: 1,
224
+ UChar: 2,
225
+ Int: 3,
226
+ UInt: 4,
227
+ Int64: 5,
228
+ UInt64: 6,
229
+ Half: 7,
230
+ Float: 8,
231
+ Double: 9,
232
+ String: 10,
233
+ Token: 11,
234
+ AssetPath: 12,
235
+ Matrix2d: 13,
236
+ Matrix3d: 14,
237
+ Matrix4d: 15,
238
+ Quatd: 16,
239
+ Quatf: 17,
240
+ Quath: 18,
241
+ Vec2d: 19,
242
+ Vec2f: 20,
243
+ Vec2h: 21,
244
+ Vec2i: 22,
245
+ Vec3d: 23,
246
+ Vec3f: 24,
247
+ Vec3h: 25,
248
+ Vec3i: 26,
249
+ Vec4d: 27,
250
+ Vec4f: 28,
251
+ Vec4h: 29,
252
+ Vec4i: 30,
253
+ Dictionary: 31,
254
+ TokenListOp: 32,
255
+ StringListOp: 33,
256
+ PathListOp: 34,
257
+ ReferenceListOp: 35,
258
+ IntListOp: 36,
259
+ Int64ListOp: 37,
260
+ UIntListOp: 38,
261
+ UInt64ListOp: 39,
262
+ PathVector: 40,
263
+ TokenVector: 41,
264
+ Specifier: 42,
265
+ Permission: 43,
266
+ Variability: 44,
267
+ VariantSelectionMap: 45,
268
+ TimeSamples: 46,
269
+ Payload: 47,
270
+ DoubleVector: 48,
271
+ LayerOffsetVector: 49,
272
+ StringVector: 50,
273
+ ValueBlock: 51,
274
+ Value: 52,
275
+ UnregisteredValue: 53,
276
+ UnregisteredValueListOp: 54,
277
+ PayloadListOp: 55,
278
+ TimeCode: 56,
279
+ PathExpression: 57,
280
+ Relocates: 58,
281
+ Spline: 59,
282
+ AnimationBlock: 60
283
+ };
284
+ DICTIONARY_ARRAY_TYPES = /* @__PURE__ */ new Set([
285
+ TypeEnum.Int,
286
+ TypeEnum.UInt,
287
+ TypeEnum.Float,
288
+ TypeEnum.Double,
289
+ TypeEnum.Half,
290
+ TypeEnum.String,
291
+ TypeEnum.Token
292
+ ]);
293
+ FIELD_SET_TERMINATOR = 4294967295;
294
+ FLOAT_COMPRESSION_INT = 105;
295
+ FLOAT_COMPRESSION_LUT = 116;
296
+ BinaryReader = class {
297
+ constructor(buffer) {
298
+ this.buffer = buffer;
299
+ this.view = new DataView(buffer);
300
+ this.offset = 0;
301
+ }
302
+ seek(offset) {
303
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > this.buffer.byteLength)
304
+ throw new Error("USDC: invalid seek");
305
+ this.offset = offset;
306
+ }
307
+ tell() {
308
+ return this.offset;
309
+ }
310
+ readUint8() {
311
+ const value = this.view.getUint8(this.offset);
312
+ this.offset += 1;
313
+ return value;
314
+ }
315
+ readInt8() {
316
+ const value = this.view.getInt8(this.offset);
317
+ this.offset += 1;
318
+ return value;
319
+ }
320
+ readUint16() {
321
+ const value = this.view.getUint16(this.offset, true);
322
+ this.offset += 2;
323
+ return value;
324
+ }
325
+ readInt16() {
326
+ const value = this.view.getInt16(this.offset, true);
327
+ this.offset += 2;
328
+ return value;
329
+ }
330
+ readUint32() {
331
+ const value = this.view.getUint32(this.offset, true);
332
+ this.offset += 4;
333
+ return value;
334
+ }
335
+ readInt32() {
336
+ const value = this.view.getInt32(this.offset, true);
337
+ this.offset += 4;
338
+ return value;
339
+ }
340
+ readUint64() {
341
+ const lo = this.view.getUint32(this.offset, true);
342
+ const hi = this.view.getUint32(this.offset + 4, true);
343
+ this.offset += 8;
344
+ const result = hi * 4294967296 + lo;
345
+ if (!Number.isSafeInteger(result)) throw new Error("USDC: integer exceeds safe precision");
346
+ return result;
347
+ }
348
+ readInt64() {
349
+ const lo = this.view.getUint32(this.offset, true);
350
+ const hi = this.view.getInt32(this.offset + 4, true);
351
+ this.offset += 8;
352
+ const result = hi * 4294967296 + lo;
353
+ if (!Number.isSafeInteger(result)) throw new Error("USDC: integer exceeds safe precision");
354
+ return result;
355
+ }
356
+ readFloat32() {
357
+ const value = this.view.getFloat32(this.offset, true);
358
+ this.offset += 4;
359
+ return value;
360
+ }
361
+ readFloat64() {
362
+ const value = this.view.getFloat64(this.offset, true);
363
+ this.offset += 8;
364
+ return value;
365
+ }
366
+ readBytes(length4) {
367
+ const bytes = new Uint8Array(this.buffer, this.offset, length4);
368
+ this.offset += length4;
369
+ return bytes;
370
+ }
371
+ readString(length4) {
372
+ const bytes = this.readBytes(length4);
373
+ let end = 0;
374
+ while (end < length4 && bytes[end] !== 0) end++;
375
+ return textDecoder.decode(bytes.subarray(0, end));
376
+ }
377
+ };
378
+ ValueRep = class {
379
+ constructor(lo, hi) {
380
+ this.lo = lo;
381
+ this.hi = hi;
382
+ }
383
+ get isArray() {
384
+ return (this.hi & 2147483648) !== 0;
385
+ }
386
+ get isInlined() {
387
+ return (this.hi & 1073741824) !== 0;
388
+ }
389
+ get isCompressed() {
390
+ return (this.hi & 536870912) !== 0;
391
+ }
392
+ get typeEnum() {
393
+ return this.hi >> 16 & 255;
394
+ }
395
+ get payload() {
396
+ return this.lo + (this.hi & 65535) * 4294967296;
397
+ }
398
+ getInlinedValue() {
399
+ return this.lo;
400
+ }
401
+ };
402
+ USDCParser = class {
403
+ /**
404
+ * Parse USDC file and return raw spec data without building Three.js scene.
405
+ * Used by USDComposer for unified scene composition.
406
+ */
407
+ parseData(buffer) {
408
+ allocationBytes = 0;
409
+ this._valueReadCount = 0;
410
+ this._activeDictionaries = /* @__PURE__ */ new Set();
411
+ this.buffer = buffer instanceof ArrayBuffer ? buffer : buffer.buffer;
412
+ this.reader = new BinaryReader(this.buffer);
413
+ this.version = { major: 0, minor: 0, patch: 0 };
414
+ this._conversionBuffer = new ArrayBuffer(4);
415
+ this._conversionView = new DataView(this._conversionBuffer);
416
+ this._readBootstrap();
417
+ this._readTOC();
418
+ this._readTokens();
419
+ this._readStrings();
420
+ this._readFields();
421
+ this._readFieldSets();
422
+ this._readPaths();
423
+ this._readSpecs();
424
+ this.specsByPath = /* @__PURE__ */ Object.create(null);
425
+ for (const spec of this.specs) {
426
+ const path2 = this.paths[spec.pathIndex];
427
+ if (!path2) continue;
428
+ const fields = this._getFieldsForSpec(spec);
429
+ this.specsByPath[path2] = { specType: spec.specType, fields };
430
+ }
431
+ return { specsByPath: this.specsByPath };
432
+ }
433
+ _readBootstrap() {
434
+ const reader = this.reader;
435
+ reader.seek(0);
436
+ const magic = reader.readString(8);
437
+ if (magic !== "PXR-USDC") {
438
+ throw new Error("THREE.USDCParser: Not a valid USDC file.");
439
+ }
440
+ this.version.major = reader.readUint8();
441
+ this.version.minor = reader.readUint8();
442
+ this.version.patch = reader.readUint8();
443
+ reader.readBytes(5);
444
+ this.tocOffset = reader.readUint64();
445
+ }
446
+ _readTOC() {
447
+ const reader = this.reader;
448
+ reader.seek(this.tocOffset);
449
+ const numSections = reader.readUint64();
450
+ if (numSections > 16) throw new Error("USDC: invalid section count");
451
+ this.sections = /* @__PURE__ */ Object.create(null);
452
+ for (let i = 0; i < numSections; i++) {
453
+ const name22 = reader.readString(16);
454
+ const start = reader.readUint64();
455
+ const size = reader.readUint64();
456
+ this.sections[name22] = { start, size };
457
+ }
458
+ }
459
+ _readTokens() {
460
+ const section = this.sections["TOKENS"];
461
+ if (!section) return;
462
+ const reader = this.reader;
463
+ reader.seek(section.start);
464
+ const numTokens = checkedCount(reader.readUint64());
465
+ this.tokens = [];
466
+ if (this.version.major === 0 && this.version.minor < 4) {
467
+ const tokensNumBytes = reader.readUint64();
468
+ const tokensData = reader.readBytes(tokensNumBytes);
469
+ let strStart = 0;
470
+ for (let i = 0; i < numTokens; i++) {
471
+ let strEnd = strStart;
472
+ while (strEnd < tokensData.length && tokensData[strEnd] !== 0) strEnd++;
473
+ if (strEnd >= tokensData.length) throw new Error("USDC: unterminated token data");
474
+ this.tokens.push(textDecoder.decode(tokensData.subarray(strStart, strEnd)));
475
+ strStart = strEnd + 1;
476
+ }
477
+ } else {
478
+ const uncompressedSize = reader.readUint64();
479
+ const compressedSize = reader.readUint64();
480
+ const compressedData = reader.readBytes(compressedSize);
481
+ const tokensData = decompressLZ4(compressedData, uncompressedSize);
482
+ checkedLength(tokensData.length, 2);
483
+ let strStart = 0;
484
+ for (let i = 0; i < numTokens; i++) {
485
+ let strEnd = strStart;
486
+ while (strEnd < tokensData.length && tokensData[strEnd] !== 0) strEnd++;
487
+ if (strEnd >= tokensData.length) throw new Error("USDC: unterminated token data");
488
+ this.tokens.push(textDecoder.decode(tokensData.subarray(strStart, strEnd)));
489
+ strStart = strEnd + 1;
490
+ }
491
+ }
492
+ }
493
+ _readStrings() {
494
+ const section = this.sections["STRINGS"];
495
+ if (!section) {
496
+ this.strings = [];
497
+ return;
498
+ }
499
+ const reader = this.reader;
500
+ reader.seek(section.start);
501
+ const numStrings = checkedCount(reader.readUint64());
502
+ this.strings = [];
503
+ for (let i = 0; i < numStrings; i++) {
504
+ this.strings.push(reader.readUint32());
505
+ }
506
+ }
507
+ _readFields() {
508
+ const section = this.sections["FIELDS"];
509
+ if (!section) return;
510
+ const reader = this.reader;
511
+ reader.seek(section.start);
512
+ this.fields = [];
513
+ if (this.version.major === 0 && this.version.minor < 4) {
514
+ const numFields = Math.floor(section.size / 12);
515
+ for (let i = 0; i < numFields; i++) {
516
+ const tokenIndex = reader.readUint32();
517
+ const repLo = reader.readUint32();
518
+ const repHi = reader.readUint32();
519
+ this.fields.push({
520
+ tokenIndex,
521
+ valueRep: new ValueRep(repLo, repHi)
522
+ });
523
+ }
524
+ } else {
525
+ const numFields = checkedCount(reader.readUint64());
526
+ const tokenIndicesCompressedSize = reader.readUint64();
527
+ const tokenIndicesCompressed = reader.readBytes(tokenIndicesCompressedSize);
528
+ const tokenIndices = decompressIntegers32(
529
+ tokenIndicesCompressed.buffer.slice(
530
+ tokenIndicesCompressed.byteOffset,
531
+ tokenIndicesCompressed.byteOffset + tokenIndicesCompressedSize
532
+ ),
533
+ numFields
534
+ );
535
+ const repsCompressedSize = reader.readUint64();
536
+ const repsCompressed = reader.readBytes(repsCompressedSize);
537
+ const repsData = decompressLZ4(repsCompressed, numFields * 8);
538
+ const repsView = new DataView(repsData.buffer, repsData.byteOffset, repsData.byteLength);
539
+ for (let i = 0; i < numFields; i++) {
540
+ const repLo = repsView.getUint32(i * 8, true);
541
+ const repHi = repsView.getUint32(i * 8 + 4, true);
542
+ this.fields.push({
543
+ tokenIndex: tokenIndices[i],
544
+ valueRep: new ValueRep(repLo, repHi)
545
+ });
546
+ }
547
+ }
548
+ }
549
+ _readFieldSets() {
550
+ const section = this.sections["FIELDSETS"];
551
+ if (!section) return;
552
+ const reader = this.reader;
553
+ reader.seek(section.start);
554
+ this.fieldSets = [];
555
+ if (this.version.major === 0 && this.version.minor < 4) {
556
+ const numFieldSets = Math.floor(section.size / 4);
557
+ for (let i = 0; i < numFieldSets; i++) {
558
+ this.fieldSets.push(reader.readUint32());
559
+ }
560
+ } else {
561
+ const numFieldSets = checkedCount(reader.readUint64());
562
+ const compressedSize = reader.readUint64();
563
+ const compressed = reader.readBytes(compressedSize);
564
+ const indices = decompressIntegers32(
565
+ compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressedSize),
566
+ numFieldSets
567
+ );
568
+ for (let i = 0; i < numFieldSets; i++) {
569
+ this.fieldSets.push(indices[i]);
570
+ }
571
+ }
572
+ }
573
+ _readPaths() {
574
+ const section = this.sections["PATHS"];
575
+ if (!section) return;
576
+ const reader = this.reader;
577
+ reader.seek(section.start);
578
+ const numPaths = checkedCount(reader.readUint64());
579
+ this.paths = new Array(checkedLength(numPaths)).fill("");
580
+ if (this.version.major === 0 && this.version.minor < 4) {
581
+ this._readPathsRecursive("");
582
+ } else {
583
+ reader.readUint64();
584
+ const compressedSize1 = reader.readUint64();
585
+ const pathIndicesCompressed = reader.readBytes(compressedSize1);
586
+ const pathIndices = decompressIntegers32(
587
+ pathIndicesCompressed.buffer.slice(
588
+ pathIndicesCompressed.byteOffset,
589
+ pathIndicesCompressed.byteOffset + compressedSize1
590
+ ),
591
+ numPaths
592
+ );
593
+ const compressedSize2 = reader.readUint64();
594
+ const elementTokenIndicesCompressed = reader.readBytes(compressedSize2);
595
+ const elementTokenIndices = decompressIntegers32(
596
+ elementTokenIndicesCompressed.buffer.slice(
597
+ elementTokenIndicesCompressed.byteOffset,
598
+ elementTokenIndicesCompressed.byteOffset + compressedSize2
599
+ ),
600
+ numPaths
601
+ );
602
+ const compressedSize3 = reader.readUint64();
603
+ const jumpsCompressed = reader.readBytes(compressedSize3);
604
+ const jumps = decompressIntegers32(
605
+ jumpsCompressed.buffer.slice(
606
+ jumpsCompressed.byteOffset,
607
+ jumpsCompressed.byteOffset + compressedSize3
608
+ ),
609
+ numPaths
610
+ );
611
+ this._buildPathsFromCompressed(pathIndices, elementTokenIndices, jumps);
612
+ }
613
+ }
614
+ _readPathsRecursive(parentPath, depth = 0) {
615
+ const reader = this.reader;
616
+ if (depth > 1e3) return;
617
+ const index = reader.readUint32();
618
+ const elementTokenIndex = reader.readUint32();
619
+ const bits = reader.readUint8();
620
+ const hasChild = (bits & 1) !== 0;
621
+ const hasSibling = (bits & 2) !== 0;
622
+ const isPrimProperty = (bits & 4) !== 0;
623
+ let path2;
624
+ if (parentPath === "") {
625
+ path2 = "/";
626
+ } else {
627
+ const elemToken = this.tokens[elementTokenIndex] || "";
628
+ if (isPrimProperty) {
629
+ path2 = parentPath + "." + elemToken;
630
+ } else {
631
+ path2 = parentPath === "/" ? "/" + elemToken : parentPath + "/" + elemToken;
632
+ }
633
+ }
634
+ checkedLength(path2.length, 2);
635
+ this.paths[index] = path2;
636
+ if (hasChild && hasSibling) {
637
+ const siblingOffset = reader.readUint64();
638
+ this._readPathsRecursive(path2, depth + 1);
639
+ reader.seek(siblingOffset);
640
+ this._readPathsRecursive(parentPath, depth + 1);
641
+ } else if (hasChild) {
642
+ this._readPathsRecursive(path2, depth + 1);
643
+ } else if (hasSibling) {
644
+ this._readPathsRecursive(parentPath, depth + 1);
645
+ }
646
+ }
647
+ /** Rebuilds compressed paths with an explicit stack instead of sibling recursion. */
648
+ _buildPathsFromCompressed(pathIndices, elementTokenIndices, jumps) {
649
+ let traversalCount = 0;
650
+ const pendingPaths = [{ startIndex: 0, parentPath: "" }];
651
+ while (pendingPaths.length) {
652
+ const pendingPath = pendingPaths.pop();
653
+ let currentIndex = pendingPath.startIndex;
654
+ let parentPath = pendingPath.parentPath;
655
+ while (currentIndex < pathIndices.length) {
656
+ if (++traversalCount > pathIndices.length * 2)
657
+ throw new Error("USDC: path traversal limit exceeded");
658
+ const nodeIndex = currentIndex++;
659
+ const pathIndex = pathIndices[nodeIndex];
660
+ const elementTokenIndex = elementTokenIndices[nodeIndex];
661
+ const jump = jumps[nodeIndex];
662
+ if (pathIndex < 0 || pathIndex >= this.paths.length || Math.abs(elementTokenIndex) >= this.tokens.length || jump < -2)
663
+ throw new Error("USDC: invalid compressed path index");
664
+ let path2;
665
+ if (parentPath === "") {
666
+ path2 = "/";
667
+ parentPath = path2;
668
+ } else {
669
+ const elementToken = this.tokens[Math.abs(elementTokenIndex)];
670
+ path2 = elementTokenIndex < 0 ? parentPath + "." + elementToken : parentPath === "/" ? "/" + elementToken : parentPath + "/" + elementToken;
671
+ }
672
+ checkedLength(path2.length, 2);
673
+ this.paths[pathIndex] = path2;
674
+ const hasChild = jump > 0 || jump === -1;
675
+ const hasSibling = jump >= 0;
676
+ if ((hasChild || hasSibling) && currentIndex >= pathIndices.length)
677
+ throw new Error("USDC: missing compressed path entry");
678
+ if (hasChild && hasSibling) {
679
+ const siblingIndex = nodeIndex + jump;
680
+ if (siblingIndex <= currentIndex || siblingIndex >= pathIndices.length)
681
+ throw new Error("USDC: invalid compressed path jump");
682
+ pendingPaths.push({ startIndex: siblingIndex, parentPath });
683
+ }
684
+ if (hasChild) parentPath = path2;
685
+ else if (!hasSibling) break;
686
+ }
687
+ }
688
+ }
689
+ _readSpecs() {
690
+ const section = this.sections["SPECS"];
691
+ if (!section) return;
692
+ const reader = this.reader;
693
+ reader.seek(section.start);
694
+ this.specs = [];
695
+ if (this.version.major === 0 && this.version.minor < 4) {
696
+ const specSize = this.version.minor === 0 && this.version.patch === 1 ? 16 : 12;
697
+ const numSpecs = Math.floor(section.size / specSize);
698
+ for (let i = 0; i < numSpecs; i++) {
699
+ const pathIndex = reader.readUint32();
700
+ const fieldSetIndex = reader.readUint32();
701
+ const specType = reader.readUint32();
702
+ if (specSize === 16) reader.readUint32();
703
+ this.specs.push({ pathIndex, fieldSetIndex, specType });
704
+ }
705
+ } else {
706
+ const numSpecs = checkedCount(reader.readUint64());
707
+ const compressedSize1 = reader.readUint64();
708
+ const pathIndicesCompressed = reader.readBytes(compressedSize1);
709
+ const pathIndices = decompressIntegers32(
710
+ pathIndicesCompressed.buffer.slice(
711
+ pathIndicesCompressed.byteOffset,
712
+ pathIndicesCompressed.byteOffset + compressedSize1
713
+ ),
714
+ numSpecs
715
+ );
716
+ const compressedSize2 = reader.readUint64();
717
+ const fieldSetIndicesCompressed = reader.readBytes(compressedSize2);
718
+ const fieldSetIndices = decompressIntegers32(
719
+ fieldSetIndicesCompressed.buffer.slice(
720
+ fieldSetIndicesCompressed.byteOffset,
721
+ fieldSetIndicesCompressed.byteOffset + compressedSize2
722
+ ),
723
+ numSpecs
724
+ );
725
+ const compressedSize3 = reader.readUint64();
726
+ const specTypesCompressed = reader.readBytes(compressedSize3);
727
+ const specTypes = decompressIntegers32(
728
+ specTypesCompressed.buffer.slice(
729
+ specTypesCompressed.byteOffset,
730
+ specTypesCompressed.byteOffset + compressedSize3
731
+ ),
732
+ numSpecs
733
+ );
734
+ for (let i = 0; i < numSpecs; i++) {
735
+ this.specs.push({
736
+ pathIndex: pathIndices[i],
737
+ fieldSetIndex: fieldSetIndices[i],
738
+ specType: specTypes[i]
739
+ });
740
+ }
741
+ }
742
+ }
743
+ // ========================================================================
744
+ // Value Reading
745
+ // ========================================================================
746
+ _readValue(valueRep) {
747
+ this._valueReadCount = (this._valueReadCount || 0) + 1;
748
+ if (this._valueReadCount > 1e6) throw new Error("USDC: value traversal limit exceeded");
749
+ const type = valueRep.typeEnum;
750
+ const isArray2 = valueRep.isArray;
751
+ const isInlined = valueRep.isInlined;
752
+ if (type === TypeEnum.TimeSamples) {
753
+ return this._readTimeSamples(valueRep);
754
+ }
755
+ if (isInlined) {
756
+ return this._readInlinedValue(valueRep);
757
+ }
758
+ const offset = valueRep.payload;
759
+ if (offset === 0 && isArray2) {
760
+ return [];
761
+ }
762
+ if (offset < 0 || offset >= this.buffer.byteLength) {
763
+ throw new RangeError(
764
+ "USDCParser: Invalid payload offset " + offset + " for type " + type + "."
765
+ );
766
+ }
767
+ const savedOffset = this.reader.tell();
768
+ this.reader.seek(offset);
769
+ let value;
770
+ if (isArray2) {
771
+ value = this._readArrayValue(valueRep);
772
+ } else {
773
+ value = this._readScalarValue(type);
774
+ }
775
+ this.reader.seek(savedOffset);
776
+ return value;
777
+ }
778
+ _readInlinedValue(valueRep) {
779
+ const type = valueRep.typeEnum;
780
+ const payload = valueRep.getInlinedValue();
781
+ const view = this._conversionView;
782
+ switch (type) {
783
+ case TypeEnum.Dictionary:
784
+ if (payload !== 0) throw new Error("USDC: invalid inline dictionary");
785
+ return /* @__PURE__ */ Object.create(null);
786
+ case TypeEnum.Bool:
787
+ return payload !== 0;
788
+ case TypeEnum.UChar:
789
+ return payload & 255;
790
+ case TypeEnum.Int:
791
+ case TypeEnum.Int64:
792
+ return payload | 0;
793
+ case TypeEnum.UInt:
794
+ case TypeEnum.UInt64:
795
+ return payload >>> 0;
796
+ case TypeEnum.Half:
797
+ return this._halfToFloat(payload & 65535);
798
+ case TypeEnum.Float: {
799
+ view.setUint32(0, payload, true);
800
+ return view.getFloat32(0, true);
801
+ }
802
+ case TypeEnum.Double: {
803
+ view.setUint32(0, payload, true);
804
+ return view.getFloat32(0, true);
805
+ }
806
+ case TypeEnum.Token:
807
+ return this.tokens[payload] || "";
808
+ case TypeEnum.String:
809
+ return this.tokens[this.strings[payload]] || "";
810
+ case TypeEnum.AssetPath:
811
+ return this.tokens[payload] || "";
812
+ case TypeEnum.Specifier:
813
+ return payload;
814
+ // 0=def, 1=over, 2=class
815
+ case TypeEnum.Permission:
816
+ case TypeEnum.Variability:
817
+ return payload;
818
+ // Vec2h: Two half-floats fit in 4 bytes, stored directly
819
+ case TypeEnum.Vec2h: {
820
+ view.setUint32(0, payload, true);
821
+ return [
822
+ this._halfToFloat(view.getUint16(0, true)),
823
+ this._halfToFloat(view.getUint16(2, true))
824
+ ];
825
+ }
826
+ // Inlined vectors that don't fit in 4 bytes are encoded as signed 8-bit integers
827
+ // Vec2f = 8 bytes (2x float32), Vec3f = 12 bytes, Vec4f = 16 bytes, etc.
828
+ case TypeEnum.Vec2f:
829
+ case TypeEnum.Vec2i: {
830
+ view.setUint32(0, payload, true);
831
+ return [view.getInt8(0), view.getInt8(1)];
832
+ }
833
+ case TypeEnum.Vec3f:
834
+ case TypeEnum.Vec3i: {
835
+ view.setUint32(0, payload, true);
836
+ return [view.getInt8(0), view.getInt8(1), view.getInt8(2)];
837
+ }
838
+ case TypeEnum.Vec4f:
839
+ case TypeEnum.Vec4i: {
840
+ view.setUint32(0, payload, true);
841
+ return [view.getInt8(0), view.getInt8(1), view.getInt8(2), view.getInt8(3)];
842
+ }
843
+ case TypeEnum.Matrix2d: {
844
+ view.setUint32(0, payload, true);
845
+ const d0 = view.getInt8(0), d1 = view.getInt8(1);
846
+ return [d0, 0, 0, d1];
847
+ }
848
+ case TypeEnum.Matrix3d: {
849
+ view.setUint32(0, payload, true);
850
+ const d0 = view.getInt8(0), d1 = view.getInt8(1), d2 = view.getInt8(2);
851
+ return [d0, 0, 0, 0, d1, 0, 0, 0, d2];
852
+ }
853
+ case TypeEnum.Matrix4d: {
854
+ view.setUint32(0, payload, true);
855
+ const d0 = view.getInt8(0), d1 = view.getInt8(1), d2 = view.getInt8(2), d3 = view.getInt8(3);
856
+ return [d0, 0, 0, 0, 0, d1, 0, 0, 0, 0, d2, 0, 0, 0, 0, d3];
857
+ }
858
+ default:
859
+ throw new Error("USDC: unsupported inline value type " + type);
860
+ }
861
+ }
862
+ _readTimeSamples(valueRep) {
863
+ const reader = this.reader;
864
+ const offset = valueRep.payload;
865
+ const savedOffset = reader.tell();
866
+ reader.seek(offset);
867
+ const timesStart = reader.tell();
868
+ const timesRelOffset = reader.readInt64();
869
+ reader.seek(timesStart + timesRelOffset);
870
+ const timesRepLo = reader.readUint32();
871
+ const timesRepHi = reader.readUint32();
872
+ const timesRep = new ValueRep(timesRepLo, timesRepHi);
873
+ const times = this._readValue(timesRep);
874
+ const afterTimesRep = timesStart + timesRelOffset + 8;
875
+ reader.seek(afterTimesRep);
876
+ const valuesStart = reader.tell();
877
+ const valuesRelOffset = reader.readInt64();
878
+ reader.seek(valuesStart + valuesRelOffset);
879
+ const numValues = checkedCount(reader.readUint64());
880
+ const valueReps = [];
881
+ for (let i = 0; i < numValues; i++) {
882
+ const repLo = reader.readUint32();
883
+ const repHi = reader.readUint32();
884
+ valueReps.push(new ValueRep(repLo, repHi));
885
+ }
886
+ const values = [];
887
+ for (let i = 0; i < numValues; i++) {
888
+ values.push(this._readValue(valueReps[i]));
889
+ }
890
+ reader.seek(savedOffset);
891
+ const timesArray = times instanceof Float64Array ? Array.from(times) : Array.isArray(times) ? times : [times];
892
+ return { times: timesArray, values };
893
+ }
894
+ _readScalarValue(type) {
895
+ const reader = this.reader;
896
+ switch (type) {
897
+ case TypeEnum.Invalid:
898
+ return null;
899
+ case TypeEnum.Bool:
900
+ return reader.readUint8() !== 0;
901
+ case TypeEnum.UChar:
902
+ return reader.readUint8();
903
+ case TypeEnum.Int:
904
+ return reader.readInt32();
905
+ case TypeEnum.UInt:
906
+ return reader.readUint32();
907
+ case TypeEnum.Int64:
908
+ return reader.readInt64();
909
+ case TypeEnum.UInt64:
910
+ return reader.readUint64();
911
+ case TypeEnum.Half:
912
+ return this._readHalf();
913
+ case TypeEnum.Float:
914
+ return reader.readFloat32();
915
+ case TypeEnum.Double:
916
+ return reader.readFloat64();
917
+ case TypeEnum.String:
918
+ case TypeEnum.Token: {
919
+ const index = reader.readUint32();
920
+ return this.tokens[index] || "";
921
+ }
922
+ case TypeEnum.AssetPath: {
923
+ const index = reader.readUint32();
924
+ return this.tokens[index] || "";
925
+ }
926
+ case TypeEnum.Vec2f:
927
+ return [reader.readFloat32(), reader.readFloat32()];
928
+ case TypeEnum.Vec2d:
929
+ return [reader.readFloat64(), reader.readFloat64()];
930
+ case TypeEnum.Vec2i:
931
+ return [reader.readInt32(), reader.readInt32()];
932
+ case TypeEnum.Vec3f:
933
+ return [reader.readFloat32(), reader.readFloat32(), reader.readFloat32()];
934
+ case TypeEnum.Vec3d:
935
+ return [reader.readFloat64(), reader.readFloat64(), reader.readFloat64()];
936
+ case TypeEnum.Vec3i:
937
+ return [reader.readInt32(), reader.readInt32(), reader.readInt32()];
938
+ case TypeEnum.Vec4f:
939
+ return [
940
+ reader.readFloat32(),
941
+ reader.readFloat32(),
942
+ reader.readFloat32(),
943
+ reader.readFloat32()
944
+ ];
945
+ case TypeEnum.Vec4d:
946
+ return [
947
+ reader.readFloat64(),
948
+ reader.readFloat64(),
949
+ reader.readFloat64(),
950
+ reader.readFloat64()
951
+ ];
952
+ case TypeEnum.Quatf:
953
+ return [
954
+ reader.readFloat32(),
955
+ reader.readFloat32(),
956
+ reader.readFloat32(),
957
+ reader.readFloat32()
958
+ ];
959
+ case TypeEnum.Quatd:
960
+ return [
961
+ reader.readFloat64(),
962
+ reader.readFloat64(),
963
+ reader.readFloat64(),
964
+ reader.readFloat64()
965
+ ];
966
+ case TypeEnum.Matrix4d: {
967
+ const m = [];
968
+ for (let i = 0; i < 16; i++) m.push(reader.readFloat64());
969
+ return m;
970
+ }
971
+ case TypeEnum.TokenVector: {
972
+ const count = checkedCount(reader.readUint64());
973
+ const tokens = [];
974
+ for (let i = 0; i < count; i++) {
975
+ const index = reader.readUint32();
976
+ tokens.push(this.tokens[index] || "");
977
+ }
978
+ return tokens;
979
+ }
980
+ case TypeEnum.PathVector: {
981
+ const count = checkedCount(reader.readUint64());
982
+ const paths = [];
983
+ for (let i = 0; i < count; i++) {
984
+ const index = reader.readUint32();
985
+ paths.push(this.paths[index] || "");
986
+ }
987
+ return paths;
988
+ }
989
+ case TypeEnum.DoubleVector: {
990
+ const count = checkedCount(reader.readUint64());
991
+ const arr = new Float64Array(checkedLength(count));
992
+ for (let i = 0; i < count; i++) arr[i] = reader.readFloat64();
993
+ return arr;
994
+ }
995
+ case TypeEnum.Dictionary:
996
+ return this._readDictionary();
997
+ case TypeEnum.TokenListOp:
998
+ case TypeEnum.StringListOp:
999
+ case TypeEnum.IntListOp:
1000
+ case TypeEnum.Int64ListOp:
1001
+ case TypeEnum.UIntListOp:
1002
+ case TypeEnum.UInt64ListOp:
1003
+ throw new Error("USDC: value list operations are unsupported");
1004
+ case TypeEnum.PathListOp: {
1005
+ const flags = reader.readUint8();
1006
+ if (flags & 24 || (flags & 102).toString(2).replaceAll("0", "").length > 1)
1007
+ throw new Error("USDC: compound path list operations are unsupported");
1008
+ const hasExplicitItems = (flags & 2) !== 0;
1009
+ const hasAddItems = (flags & 4) !== 0;
1010
+ const hasDeleteItems = (flags & 8) !== 0;
1011
+ const hasReorderItems = (flags & 16) !== 0;
1012
+ const hasPrependItems = (flags & 32) !== 0;
1013
+ const hasAppendItems = (flags & 64) !== 0;
1014
+ const readPathList = () => {
1015
+ const itemCount = checkedCount(reader.readUint64());
1016
+ const paths = [];
1017
+ for (let i = 0; i < itemCount; i++) {
1018
+ const pathIdx = reader.readUint32();
1019
+ paths.push(this.paths[pathIdx]);
1020
+ }
1021
+ return paths;
1022
+ };
1023
+ let explicitPaths = null;
1024
+ let addPaths = null;
1025
+ let prependPaths = null;
1026
+ let appendPaths = null;
1027
+ if (hasExplicitItems) explicitPaths = readPathList();
1028
+ if (hasAddItems) addPaths = readPathList();
1029
+ if (hasPrependItems) prependPaths = readPathList();
1030
+ if (hasAppendItems) appendPaths = readPathList();
1031
+ if (hasDeleteItems) readPathList();
1032
+ if (hasReorderItems) readPathList();
1033
+ if (prependPaths && prependPaths.length > 0) return prependPaths;
1034
+ if (explicitPaths && explicitPaths.length > 0) return explicitPaths;
1035
+ if (appendPaths && appendPaths.length > 0) return appendPaths;
1036
+ if (addPaths && addPaths.length > 0) return addPaths;
1037
+ return null;
1038
+ }
1039
+ case TypeEnum.VariantSelectionMap: {
1040
+ const elementCount = checkedCount(reader.readUint64());
1041
+ const map = /* @__PURE__ */ Object.create(null);
1042
+ for (let i = 0; i < elementCount; i++) {
1043
+ const keyIdx = reader.readUint32();
1044
+ const valueIdx = reader.readUint32();
1045
+ const key = this.tokens[this.strings[keyIdx]];
1046
+ const value = this.tokens[this.strings[valueIdx]];
1047
+ if (key && value) map[key] = value;
1048
+ }
1049
+ return map;
1050
+ }
1051
+ default:
1052
+ throw new Error(
1053
+ "USDC: unsupported encoding: " + ["USDCParser: Unsupported scalar type", type].join(" ")
1054
+ );
1055
+ }
1056
+ }
1057
+ /** Reads bounded string-keyed dictionary entries and their recursive value representations. */
1058
+ _readDictionary() {
1059
+ const reader = this.reader;
1060
+ const dictionaryOffset = reader.tell();
1061
+ this._activeDictionaries ||= /* @__PURE__ */ new Set();
1062
+ if (this._activeDictionaries.has(dictionaryOffset))
1063
+ throw new Error("USDC: cyclic dictionary value");
1064
+ if (this._activeDictionaries.size >= 64)
1065
+ throw new Error("USDC: dictionary depth limit exceeded");
1066
+ this._activeDictionaries.add(dictionaryOffset);
1067
+ try {
1068
+ const count = checkedCount(reader.readUint64());
1069
+ if (count > Math.floor((this.buffer.byteLength - reader.tell()) / 20))
1070
+ throw new Error("USDC: truncated dictionary entries");
1071
+ const dictionary = /* @__PURE__ */ Object.create(null);
1072
+ for (let index = 0; index < count; index++) {
1073
+ const stringIndex = reader.readUint32();
1074
+ const key = this.tokens[this.strings[stringIndex]];
1075
+ if (typeof key !== "string" || Object.hasOwn(dictionary, key))
1076
+ throw new Error("USDC: invalid dictionary key");
1077
+ const offsetLocation = reader.tell();
1078
+ const relativeOffset = reader.readInt64();
1079
+ if (relativeOffset < 8) throw new Error("USDC: invalid dictionary value offset");
1080
+ reader.seek(offsetLocation + relativeOffset);
1081
+ const representation = new ValueRep(reader.readUint32(), reader.readUint32());
1082
+ if (representation.typeEnum < TypeEnum.Bool || representation.typeEnum > TypeEnum.AssetPath && representation.typeEnum !== TypeEnum.Dictionary || representation.isArray && !DICTIONARY_ARRAY_TYPES.has(representation.typeEnum))
1083
+ throw new Error("USDC: unsupported dictionary value type");
1084
+ const nextEntry = reader.tell();
1085
+ const value = this._readValue(representation);
1086
+ dictionary[key] = representation.typeEnum === TypeEnum.AssetPath ? { assetPath: value } : value;
1087
+ reader.seek(nextEntry);
1088
+ }
1089
+ return dictionary;
1090
+ } finally {
1091
+ this._activeDictionaries.delete(dictionaryOffset);
1092
+ }
1093
+ }
1094
+ _readArrayValue(valueRep) {
1095
+ const reader = this.reader;
1096
+ const type = valueRep.typeEnum;
1097
+ const isCompressed = valueRep.isCompressed;
1098
+ let size;
1099
+ if (this.version.major === 0 && this.version.minor < 7) {
1100
+ size = reader.readUint32();
1101
+ } else {
1102
+ size = reader.readUint64();
1103
+ }
1104
+ if (!Number.isSafeInteger(size) || size < 0) {
1105
+ throw new RangeError("USDCParser: Invalid array size " + size + " for type " + type + ".");
1106
+ }
1107
+ if (size > 2147483647) {
1108
+ throw new RangeError("USDCParser: Array size " + size + " exceeds implementation limits.");
1109
+ }
1110
+ size = checkedCount(size);
1111
+ if (size === 0) return [];
1112
+ if (isCompressed) {
1113
+ return this._readCompressedArray(type, size);
1114
+ }
1115
+ switch (type) {
1116
+ case TypeEnum.Int: {
1117
+ const arr = new Int32Array(checkedLength(size));
1118
+ for (let i = 0; i < size; i++) arr[i] = reader.readInt32();
1119
+ return arr;
1120
+ }
1121
+ case TypeEnum.UInt: {
1122
+ const arr = new Uint32Array(checkedLength(size));
1123
+ for (let i = 0; i < size; i++) arr[i] = reader.readUint32();
1124
+ return arr;
1125
+ }
1126
+ case TypeEnum.Float: {
1127
+ const arr = new Float32Array(checkedLength(size));
1128
+ for (let i = 0; i < size; i++) arr[i] = reader.readFloat32();
1129
+ return arr;
1130
+ }
1131
+ case TypeEnum.Double: {
1132
+ const arr = new Float64Array(checkedLength(size));
1133
+ for (let i = 0; i < size; i++) arr[i] = reader.readFloat64();
1134
+ return arr;
1135
+ }
1136
+ case TypeEnum.Vec2f: {
1137
+ const arr = new Float32Array(checkedLength(size * 2));
1138
+ for (let i = 0; i < size * 2; i++) arr[i] = reader.readFloat32();
1139
+ return arr;
1140
+ }
1141
+ case TypeEnum.Vec3f: {
1142
+ const arr = new Float32Array(checkedLength(size * 3));
1143
+ for (let i = 0; i < size * 3; i++) arr[i] = reader.readFloat32();
1144
+ return arr;
1145
+ }
1146
+ case TypeEnum.Vec4f: {
1147
+ const arr = new Float32Array(checkedLength(size * 4));
1148
+ for (let i = 0; i < size * 4; i++) arr[i] = reader.readFloat32();
1149
+ return arr;
1150
+ }
1151
+ case TypeEnum.Vec3h: {
1152
+ const arr = new Float32Array(checkedLength(size * 3));
1153
+ for (let i = 0; i < size * 3; i++) arr[i] = this._readHalf();
1154
+ return arr;
1155
+ }
1156
+ case TypeEnum.Quatf: {
1157
+ const arr = new Float32Array(checkedLength(size * 4));
1158
+ for (let i = 0; i < size * 4; i++) arr[i] = reader.readFloat32();
1159
+ return arr;
1160
+ }
1161
+ case TypeEnum.Quath: {
1162
+ const arr = new Float32Array(checkedLength(size * 4));
1163
+ for (let i = 0; i < size * 4; i++) arr[i] = this._readHalf();
1164
+ return arr;
1165
+ }
1166
+ case TypeEnum.Matrix4d: {
1167
+ const arr = new Float64Array(checkedLength(size * 16));
1168
+ for (let i = 0; i < size * 16; i++) arr[i] = reader.readFloat64();
1169
+ return arr;
1170
+ }
1171
+ case TypeEnum.String:
1172
+ case TypeEnum.Token: {
1173
+ const arr = [];
1174
+ for (let i = 0; i < size; i++) {
1175
+ const index = reader.readUint32();
1176
+ const tokenIndex = type === TypeEnum.String ? this.strings[index] : index;
1177
+ const value = this.tokens[tokenIndex];
1178
+ if (typeof value !== "string") throw new Error("USDC: invalid string array index");
1179
+ arr.push(value);
1180
+ }
1181
+ return arr;
1182
+ }
1183
+ case TypeEnum.Half: {
1184
+ const arr = new Float32Array(checkedLength(size));
1185
+ for (let i = 0; i < size; i++) arr[i] = this._readHalf();
1186
+ return arr;
1187
+ }
1188
+ default:
1189
+ throw new Error(
1190
+ "USDC: unsupported encoding: " + ["USDCParser: Unsupported array type", type].join(" ")
1191
+ );
1192
+ }
1193
+ }
1194
+ _readCompressedArray(type, size) {
1195
+ const reader = this.reader;
1196
+ switch (type) {
1197
+ case TypeEnum.Int:
1198
+ case TypeEnum.UInt: {
1199
+ const compressedSize = reader.readUint64();
1200
+ const compressed = reader.readBytes(compressedSize);
1201
+ const values = decompressIntegers32(
1202
+ compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressedSize),
1203
+ size
1204
+ );
1205
+ return type === TypeEnum.UInt ? new Uint32Array(values.buffer, values.byteOffset, values.length) : values;
1206
+ }
1207
+ case TypeEnum.Half:
1208
+ case TypeEnum.Double:
1209
+ case TypeEnum.Float: {
1210
+ const code = reader.readInt8();
1211
+ if (code === FLOAT_COMPRESSION_INT) {
1212
+ const compressedSize = reader.readUint64();
1213
+ const compressed = reader.readBytes(compressedSize);
1214
+ const ints = decompressIntegers32(
1215
+ compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressedSize),
1216
+ size
1217
+ );
1218
+ const floats = type === TypeEnum.Double ? new Float64Array(checkedLength(size)) : new Float32Array(checkedLength(size));
1219
+ for (let i = 0; i < size; i++)
1220
+ floats[i] = type === TypeEnum.Half ? this._convertHalfInteger(ints[i]) : ints[i];
1221
+ return floats;
1222
+ } else if (code === FLOAT_COMPRESSION_LUT) {
1223
+ const lutSize = checkedCount(reader.readUint32());
1224
+ if (lutSize === 0) throw new Error("USDC: invalid float lookup table");
1225
+ const lut = type === TypeEnum.Double ? new Float64Array(checkedLength(lutSize)) : new Float32Array(checkedLength(lutSize));
1226
+ for (let i = 0; i < lutSize; i++)
1227
+ lut[i] = type === TypeEnum.Half ? this._readHalf() : type === TypeEnum.Double ? reader.readFloat64() : reader.readFloat32();
1228
+ const compressedSize = reader.readUint64();
1229
+ const compressed = reader.readBytes(compressedSize);
1230
+ const indices = decompressIntegers32(
1231
+ compressed.buffer.slice(compressed.byteOffset, compressed.byteOffset + compressedSize),
1232
+ size
1233
+ );
1234
+ const floats = type === TypeEnum.Double ? new Float64Array(checkedLength(size)) : new Float32Array(checkedLength(size));
1235
+ for (let i = 0; i < size; i++) {
1236
+ if (indices[i] < 0 || indices[i] >= lutSize)
1237
+ throw new Error("USDC: invalid float lookup index");
1238
+ floats[i] = lut[indices[i]];
1239
+ }
1240
+ return floats;
1241
+ }
1242
+ throw new Error(
1243
+ "USDC: unsupported encoding: " + ["USDCParser: Unknown float compression code", code].join(" ")
1244
+ );
1245
+ }
1246
+ default:
1247
+ throw new Error(
1248
+ "USDC: unsupported encoding: " + ["USDCParser: Unsupported compressed array type", type].join(" ")
1249
+ );
1250
+ }
1251
+ }
1252
+ /** Rounds integer-compressed half samples using IEEE ties-to-even semantics. */
1253
+ _convertHalfInteger(value) {
1254
+ const absoluteValue = Math.abs(value);
1255
+ if (absoluteValue <= 2048) return value;
1256
+ if (absoluteValue >= 65520) return Math.sign(value) * Infinity;
1257
+ const spacing = 2 ** (Math.floor(Math.log2(absoluteValue)) - 10);
1258
+ const scaledValue = absoluteValue / spacing;
1259
+ const lowerValue = Math.floor(scaledValue);
1260
+ const fractionValue = scaledValue - lowerValue;
1261
+ const roundedValue = fractionValue > 0.5 || fractionValue === 0.5 && lowerValue % 2 !== 0 ? lowerValue + 1 : lowerValue;
1262
+ return Math.sign(value) * roundedValue * spacing;
1263
+ }
1264
+ _readHalf() {
1265
+ return this._halfToFloat(this.reader.readUint16());
1266
+ }
1267
+ _halfToFloat(h) {
1268
+ const sign = (h & 32768) >> 15;
1269
+ const exp = (h & 31744) >> 10;
1270
+ const frac = h & 1023;
1271
+ if (exp === 0) {
1272
+ if (frac === 0) {
1273
+ return sign ? -0 : 0;
1274
+ }
1275
+ return (sign ? -1 : 1) * HALF_DENORM_SCALE * (frac / 1024);
1276
+ } else if (exp === 31) {
1277
+ return frac ? NaN : sign ? -Infinity : Infinity;
1278
+ }
1279
+ return (sign ? -1 : 1) * HALF_EXPONENT_TABLE[exp] * (1 + frac / 1024);
1280
+ }
1281
+ _getFieldsForSpec(spec) {
1282
+ const fields = /* @__PURE__ */ Object.create(null);
1283
+ let fieldSetIndex = spec.fieldSetIndex;
1284
+ const maxIterations = 1e4;
1285
+ let iterations = 0;
1286
+ while (fieldSetIndex < this.fieldSets.length && iterations < maxIterations) {
1287
+ const fieldIndex = this.fieldSets[fieldSetIndex];
1288
+ if (fieldIndex === FIELD_SET_TERMINATOR || fieldIndex === -1) break;
1289
+ const field = this.fields[fieldIndex];
1290
+ if (!field) throw new Error("USDC: invalid field index");
1291
+ if (field) {
1292
+ const name22 = this.tokens[field.tokenIndex];
1293
+ const value = this._readValue(field.valueRep);
1294
+ fields[name22] = value;
1295
+ }
1296
+ fieldSetIndex++;
1297
+ iterations++;
1298
+ }
1299
+ if (iterations >= maxIterations) throw new Error("USDC: field traversal limit exceeded");
1300
+ return fields;
1301
+ }
1302
+ };
1303
+ }
1304
+ });
1305
+
1306
+ // src/usd/lib/parse-usdc.ts
1307
+ function parseUSDC(data, url) {
1308
+ if (data.byteLength < 88 || data.byteLength > 64 * 1024 * 1024)
1309
+ throw new Error("USDC: invalid input size");
1310
+ const bytes = new Uint8Array(data);
1311
+ if (bytes[8] !== 0 || bytes[9] !== 8 || bytes[10] !== 0)
1312
+ throw new Error("USDC: initial decoder requires crate version 0.8.0");
1313
+ const reader = new DataView(data);
1314
+ const table = reader.getBigUint64(16, true);
1315
+ if (table > BigInt(data.byteLength - 8)) throw new Error("USDC: invalid section table");
1316
+ const offset = Number(table), count = reader.getBigUint64(offset, true);
1317
+ if (count > 16n || offset + 8 + Number(count) * 32 > data.byteLength)
1318
+ throw new Error("USDC: invalid section table length");
1319
+ const sectionNames = /* @__PURE__ */ new Set();
1320
+ for (let index = 0; index < Number(count); index++) {
1321
+ const entry = offset + 8 + index * 32;
1322
+ const nameBytes = bytes.subarray(entry, entry + 16);
1323
+ const terminator = nameBytes.indexOf(0);
1324
+ const name22 = new TextDecoder().decode(
1325
+ nameBytes.subarray(0, terminator < 0 ? nameBytes.length : terminator)
1326
+ );
1327
+ if (sectionNames.has(name22)) throw new Error("USDC: duplicate section");
1328
+ sectionNames.add(name22);
1329
+ const start = reader.getBigUint64(entry + 16, true), size = reader.getBigUint64(entry + 24, true);
1330
+ if (start < 88n || start + size > BigInt(data.byteLength))
1331
+ throw new Error("USDC: section out of bounds");
1332
+ }
1333
+ for (const name22 of ["TOKENS", "STRINGS", "FIELDS", "FIELDSETS", "PATHS", "SPECS"])
1334
+ if (!sectionNames.has(name22)) throw new Error("USDC: missing required section");
1335
+ const { specsByPath } = new USDCParser().parseData(data);
1336
+ const prims = /* @__PURE__ */ new Map();
1337
+ for (const [path2, specification] of Object.entries(specsByPath)) {
1338
+ if (specification.specType === 7 && path2 === "/") continue;
1339
+ if (specification.specType === 1 || specification.specType === 8) continue;
1340
+ if (specification.specType !== 6 || !/^\/(?:[A-Za-z_][\w:]*\/)*[A-Za-z_][\w:]*$/.test(path2))
1341
+ throw new Error("USDC: unsupported prim specification");
1342
+ const fields = specification.fields;
1343
+ const specifier = fields.specifier ?? 0;
1344
+ if (specifier !== 0 && specifier !== 1 && specifier !== 2)
1345
+ throw new Error("USDC: invalid prim specifier");
1346
+ const metadata3 = convertFields(
1347
+ fields,
1348
+ /* @__PURE__ */ new Set(["specifier", "typeName", "primChildren", "properties"])
1349
+ );
1350
+ prims.set(path2, {
1351
+ name: path2.slice(path2.lastIndexOf("/") + 1),
1352
+ path: path2,
1353
+ sourceUrl: url,
1354
+ type: String(fields.typeName || ""),
1355
+ specifier: ["def", "over", "class"][specifier],
1356
+ attributes: /* @__PURE__ */ Object.create(null),
1357
+ metadata: metadata3,
1358
+ variants: /* @__PURE__ */ Object.create(null),
1359
+ children: []
1360
+ });
1361
+ }
1362
+ const roots = [];
1363
+ for (const prim of prims.values()) {
1364
+ const parentPath = prim.path.slice(0, prim.path.lastIndexOf("/"));
1365
+ if (!parentPath) roots.push(prim);
1366
+ else {
1367
+ const parent = prims.get(parentPath);
1368
+ if (!parent) throw new Error("USDC: missing parent prim");
1369
+ parent.children.push(prim);
1370
+ }
1371
+ }
1372
+ orderPrims(roots, specsByPath["/"]?.fields.primChildren);
1373
+ for (const prim of prims.values())
1374
+ orderPrims(prim.children, specsByPath[prim.path]?.fields.primChildren);
1375
+ for (const [path2, specification] of Object.entries(specsByPath)) {
1376
+ if (specification.specType !== 1 && specification.specType !== 8) continue;
1377
+ const separator = path2.indexOf(".");
1378
+ const prim = prims.get(path2.slice(0, separator));
1379
+ if (separator < 0 || !prim) throw new Error("USDC: property has no owning prim");
1380
+ const name22 = path2.slice(separator + 1), fields = specification.fields;
1381
+ const type = specification.specType === 8 ? "rel" : String(fields.typeName || "");
1382
+ const value = convertAttributeValue(
1383
+ specification.specType === 8 ? fields.targetPaths : fields.default,
1384
+ type
1385
+ );
1386
+ const metadata3 = convertFields(
1387
+ fields,
1388
+ /* @__PURE__ */ new Set(["typeName", "default", "targetPaths", "timeSamples"])
1389
+ );
1390
+ if (fields.timeSamples !== void 0)
1391
+ metadata3.timeSamples = convertTimeSamples(fields.timeSamples, type);
1392
+ prim.attributes[name22] = {
1393
+ name: name22,
1394
+ type,
1395
+ value,
1396
+ metadata: metadata3
1397
+ };
1398
+ }
1399
+ return {
1400
+ format: "usdc",
1401
+ url,
1402
+ metadata: convertFields(specsByPath["/"]?.fields || {}, /* @__PURE__ */ new Set(["primChildren"])),
1403
+ rootPrims: roots,
1404
+ layers: []
1405
+ };
1406
+ }
1407
+ function convertFields(fields, excluded) {
1408
+ const result = /* @__PURE__ */ Object.create(null);
1409
+ for (const [name22, value] of Object.entries(fields))
1410
+ if (!excluded.has(name22)) result[name22] = convertValue(value);
1411
+ return result;
1412
+ }
1413
+ function convertValue(value) {
1414
+ if (value === void 0 || value === null) return null;
1415
+ if (typeof value === "number" || typeof value === "string" || typeof value === "boolean")
1416
+ return value;
1417
+ if (Array.isArray(value)) return value.map(convertValue);
1418
+ if (ArrayBuffer.isView(value) && !(value instanceof DataView))
1419
+ return Array.from(value);
1420
+ if (typeof value === "object") return convertFields(value, /* @__PURE__ */ new Set());
1421
+ throw new Error("USDC: unsupported decoded value");
1422
+ }
1423
+ function convertAttributeValue(raw, type) {
1424
+ const value = convertValue(raw);
1425
+ if (type === "asset" && typeof value === "string") return { assetPath: value };
1426
+ if (type === "rel" && Array.isArray(value))
1427
+ return value.map((path2) => typeof path2 === "string" ? { path: path2 } : path2);
1428
+ const tuple = /^(?:(?:point|normal|vector|color|texCoord)([234])[fdh]|(?:float|double|half|int)([234]))\[\]$/.exec(
1429
+ type
1430
+ );
1431
+ if (tuple && Array.isArray(value)) {
1432
+ const components = Number(tuple[1] || tuple[2]);
1433
+ if (value.length % components) throw new Error("USDC: incomplete vector tuple");
1434
+ const tuples = [];
1435
+ for (let offset = 0; offset < value.length; offset += components)
1436
+ tuples.push(value.slice(offset, offset + components));
1437
+ return tuples;
1438
+ }
1439
+ return value;
1440
+ }
1441
+ function orderPrims(prims, names) {
1442
+ if (names === void 0) return;
1443
+ if (!Array.isArray(names)) throw new Error("USDC: invalid primChildren order");
1444
+ const remaining = new Map(prims.map((prim) => [prim.name, prim]));
1445
+ const ordered = [];
1446
+ for (const name22 of names) {
1447
+ const prim = typeof name22 === "string" ? remaining.get(name22) : void 0;
1448
+ if (!prim) throw new Error("USDC: invalid primChildren reference");
1449
+ ordered.push(prim);
1450
+ remaining.delete(name22);
1451
+ }
1452
+ for (const prim of remaining.values()) ordered.push(prim);
1453
+ for (let index = 0; index < ordered.length; index++) prims[index] = ordered[index];
1454
+ }
1455
+ function convertTimeSamples(raw, type) {
1456
+ if (!raw || typeof raw !== "object") throw new Error("USDC: invalid time samples");
1457
+ const samples = raw;
1458
+ const times = convertValue(samples.times);
1459
+ if (!Array.isArray(times) || !Array.isArray(samples.values) || times.length !== samples.values.length)
1460
+ throw new Error("USDC: invalid time samples");
1461
+ return { times, values: samples.values.map((value) => convertAttributeValue(value, type)) };
1462
+ }
1463
+ var init_parse_usdc = __esm({
1464
+ "src/usd/lib/parse-usdc.ts"() {
1465
+ "use strict";
1466
+ init_usdc_parser();
1467
+ }
1468
+ });
1469
+
59
1470
  // src/usd/lib/parse-usda.ts
60
1471
  function parseUSDA(source, url) {
61
1472
  if (!source.trimStart().startsWith("#usda")) {
@@ -90,7 +1501,7 @@ var __exports__ = (() => {
90
1501
  }
91
1502
  /** Parses the complete USDA layer. */
92
1503
  parse() {
93
- const metadata2 = this.tokenizer.match("(") ? this.parseMetadata(")") : {};
1504
+ const metadata3 = this.tokenizer.match("(") ? this.parseMetadata(")") : {};
94
1505
  const rootPrims = [];
95
1506
  while (!this.tokenizer.isAtEnd()) {
96
1507
  if (this.isPrimDeclaration()) {
@@ -102,7 +1513,7 @@ var __exports__ = (() => {
102
1513
  return {
103
1514
  format: "usda",
104
1515
  url: this.url,
105
- metadata: metadata2,
1516
+ metadata: metadata3,
106
1517
  rootPrims,
107
1518
  layers: this.url ? [this.url] : []
108
1519
  };
@@ -116,7 +1527,7 @@ var __exports__ = (() => {
116
1527
  const type = hasExplicitType ? firstToken.value : "";
117
1528
  const name22 = hasExplicitType ? this.tokenizer.read().value : firstToken.value;
118
1529
  const path2 = `${parentPath}/${name22}`;
119
- const metadata2 = this.tokenizer.match("(") ? this.parseMetadata(")") : {};
1530
+ const metadata3 = this.tokenizer.match("(") ? this.parseMetadata(")") : {};
120
1531
  this.tokenizer.expect("{");
121
1532
  const contents = this.parsePrimContents(path2);
122
1533
  return {
@@ -126,7 +1537,7 @@ var __exports__ = (() => {
126
1537
  type,
127
1538
  specifier,
128
1539
  attributes: contents.attributes,
129
- metadata: { ...metadata2, ...contents.metadata },
1540
+ metadata: { ...metadata3, ...contents.metadata },
130
1541
  variants: contents.variants,
131
1542
  children: contents.children
132
1543
  };
@@ -134,7 +1545,7 @@ var __exports__ = (() => {
134
1545
  /** Parses the attributes, variants, and child prims inside a prim body. */
135
1546
  parsePrimContents(parentPath) {
136
1547
  const attributes = {};
137
- const metadata2 = {};
1548
+ const metadata3 = {};
138
1549
  const children = [];
139
1550
  const variants = {};
140
1551
  while (!this.tokenizer.isAtEnd() && !this.tokenizer.match("}")) {
@@ -149,7 +1560,7 @@ var __exports__ = (() => {
149
1560
  }
150
1561
  }
151
1562
  }
152
- return { attributes, metadata: metadata2, children, variants };
1563
+ return { attributes, metadata: metadata3, children, variants };
153
1564
  }
154
1565
  /** Parses one named variant set. */
155
1566
  parseVariantSet(parentPath, variants) {
@@ -199,12 +1610,12 @@ var __exports__ = (() => {
199
1610
  const name22 = significantTokens[significantTokens.length - 1].value;
200
1611
  const type = significantTokens.slice(0, -1).map((token) => token.value).join("");
201
1612
  const value = this.parseValue();
202
- const metadata2 = this.tokenizer.match("(") ? this.parseMetadata(")") : {};
203
- return { name: name22, type, value, metadata: metadata2 };
1613
+ const metadata3 = this.tokenizer.match("(") ? this.parseMetadata(")") : {};
1614
+ return { name: name22, type, value, metadata: metadata3 };
204
1615
  }
205
1616
  /** Parses a metadata dictionary through the requested terminator. */
206
1617
  parseMetadata(terminator) {
207
- const metadata2 = {};
1618
+ const metadata3 = {};
208
1619
  while (!this.tokenizer.isAtEnd() && !this.tokenizer.match(terminator)) {
209
1620
  this.tokenizer.match(",");
210
1621
  if (this.tokenizer.peek().value === terminator) {
@@ -227,10 +1638,10 @@ var __exports__ = (() => {
227
1638
  continue;
228
1639
  }
229
1640
  const name22 = declarationTokens[declarationTokens.length - 1].value;
230
- metadata2[name22] = this.parseValue();
1641
+ metadata3[name22] = this.parseValue();
231
1642
  this.tokenizer.match(",");
232
1643
  }
233
- return metadata2;
1644
+ return metadata3;
234
1645
  }
235
1646
  /** Parses one scalar, list, tuple, dictionary, asset path, or scene path value. */
236
1647
  parseValue() {
@@ -446,30 +1857,52 @@ var __exports__ = (() => {
446
1857
  const directoryOffset = findCentralDirectory(view);
447
1858
  const entryCount = view.getUint16(directoryOffset + 10, true);
448
1859
  let entryOffset = view.getUint32(directoryOffset + 16, true);
1860
+ const dataLimit = entryOffset;
449
1861
  const files = /* @__PURE__ */ new Map();
450
- const textDecoder = new TextDecoder();
1862
+ const textDecoder2 = new TextDecoder();
1863
+ let extractedByteLength = 0;
451
1864
  for (let entryIndex = 0; entryIndex < entryCount; entryIndex++) {
1865
+ if (entryOffset + 46 > directoryOffset) {
1866
+ throw new Error("USDZ archive contains a truncated ZIP central-directory entry.");
1867
+ }
452
1868
  if (view.getUint32(entryOffset, true) !== CENTRAL_DIRECTORY_ENTRY) {
453
1869
  throw new Error("USDZ archive contains an invalid ZIP central-directory entry.");
454
1870
  }
455
1871
  const compression = view.getUint16(entryOffset + 10, true);
456
1872
  const compressedLength = view.getUint32(entryOffset + 20, true);
1873
+ const uncompressedLength = view.getUint32(entryOffset + 24, true);
457
1874
  const filenameLength = view.getUint16(entryOffset + 28, true);
458
1875
  const extraLength = view.getUint16(entryOffset + 30, true);
459
1876
  const commentLength = view.getUint16(entryOffset + 32, true);
460
1877
  const localOffset = view.getUint32(entryOffset + 42, true);
461
- const filename = textDecoder.decode(
1878
+ if (entryOffset + 46 + filenameLength + extraLength + commentLength > directoryOffset) {
1879
+ throw new Error("USDZ archive contains a truncated ZIP filename or extra field.");
1880
+ }
1881
+ const filename = textDecoder2.decode(
462
1882
  new Uint8Array(arrayBuffer, entryOffset + 46, filenameLength)
463
1883
  );
464
1884
  if (compression !== 0) {
465
1885
  throw new Error(`USDZ entry "${filename}" is compressed; USDZ requires stored ZIP entries.`);
466
1886
  }
1887
+ if (localOffset + 30 > dataLimit || compressedLength !== uncompressedLength) {
1888
+ throw new Error(`USDZ entry "${filename}" has invalid stored ZIP bounds.`);
1889
+ }
467
1890
  if (view.getUint32(localOffset, true) !== LOCAL_FILE_HEADER) {
468
1891
  throw new Error(`USDZ entry "${filename}" has an invalid local ZIP header.`);
469
1892
  }
470
1893
  const localNameLength = view.getUint16(localOffset + 26, true);
471
1894
  const localExtraLength = view.getUint16(localOffset + 28, true);
472
1895
  const contentOffset = localOffset + 30 + localNameLength + localExtraLength;
1896
+ if ((view.getUint16(entryOffset + 8, true) | view.getUint16(localOffset + 6, true)) & 1) {
1897
+ throw new Error(`USDZ entry "${filename}" is encrypted.`);
1898
+ }
1899
+ if (contentOffset + compressedLength > dataLimit || view.getUint16(localOffset + 8, true) !== 0 || textDecoder2.decode(new Uint8Array(arrayBuffer, localOffset + 30, localNameLength)) !== filename || files.has(filename)) {
1900
+ throw new Error(`USDZ entry "${filename}" has invalid or duplicate stored ZIP data.`);
1901
+ }
1902
+ extractedByteLength += compressedLength;
1903
+ if (extractedByteLength > arrayBuffer.byteLength) {
1904
+ throw new Error("USDZ archive exceeds its stored data budget.");
1905
+ }
473
1906
  files.set(filename, arrayBuffer.slice(contentOffset, contentOffset + compressedLength));
474
1907
  entryOffset += 46 + filenameLength + extraLength + commentLength;
475
1908
  }
@@ -519,21 +1952,32 @@ var __exports__ = (() => {
519
1952
  let stage;
520
1953
  if (isZIPArchive(data)) {
521
1954
  const archive = parseUSDZArchive(data);
522
- const rootFilename = Array.from(archive.keys()).find((filename) => /\.usda?$/i.test(filename));
523
- if (!rootFilename) {
524
- throw new Error("USDZ archives with binary USDC root layers are not implemented yet.");
1955
+ const rootFilename = archive.keys().next().value;
1956
+ if (!rootFilename || !/\.(?:usd[ac]?)$/i.test(rootFilename)) {
1957
+ throw new Error("USDZ archive has no supported USD root layer.");
525
1958
  }
526
1959
  const archiveBase = "https://usd.archive/";
1960
+ const assets = /* @__PURE__ */ Object.create(null);
527
1961
  for (const [filename, content] of archive) {
528
- environment.archiveFiles.set(new URL(filename, archiveBase).href, content);
1962
+ const assetUrl = new URL(filename, archiveBase);
1963
+ if (filename.startsWith("/") || /^[a-z][a-z\d+.-]*:/i.test(filename) || filename.includes("\\") || /[\u0000-\u001f\u007f]/.test(filename) || filename.trim() !== filename || filename.split("/").some((segment) => {
1964
+ const normalizedSegment = segment.replace(/%2e/gi, ".");
1965
+ return normalizedSegment === "." || normalizedSegment === "..";
1966
+ }) || assetUrl.origin !== new URL(archiveBase).origin || assetUrl.search || assetUrl.hash || assets[assetUrl.href]) {
1967
+ throw new Error(`USDZ entry "${filename}" has an ambiguous package URL.`);
1968
+ }
1969
+ environment.archiveFiles.set(assetUrl.href, content);
1970
+ assets[assetUrl.href] = createEmbeddedAsset(filename, content);
529
1971
  }
530
1972
  const rootUrl = new URL(rootFilename, archiveBase).href;
531
1973
  stage = parseUSDLayer(archive.get(rootFilename), rootUrl);
532
1974
  stage.format = "usdz";
1975
+ stage.assets = assets;
533
1976
  } else {
534
1977
  stage = parseUSDLayer(data, url);
535
1978
  }
536
1979
  if (stage.url) {
1980
+ setAttributeSourceUrls(stage, stage.url);
537
1981
  environment.layers.add(stage.url);
538
1982
  }
539
1983
  if (environment.options.usd?.compose !== false) {
@@ -545,6 +1989,11 @@ var __exports__ = (() => {
545
1989
  }
546
1990
  return stage;
547
1991
  }
1992
+ function createEmbeddedAsset(path2, data) {
1993
+ const extension = path2.slice(path2.lastIndexOf(".") + 1).toLowerCase();
1994
+ const mimeType = extension === "png" ? "image/png" : /^(?:jpe?g)$/.test(extension) ? "image/jpeg" : void 0;
1995
+ return mimeType ? { path: path2, data, mimeType } : { path: path2, data };
1996
+ }
548
1997
  function getSourceLocation(configuredLocation, contextLocation) {
549
1998
  const configuredUrl = getAbsoluteUrl(configuredLocation);
550
1999
  if (configuredUrl) {
@@ -571,10 +2020,29 @@ var __exports__ = (() => {
571
2020
  function parseUSDLayer(data, url) {
572
2021
  const signature = TEXT_DECODER.decode(data.slice(0, 8));
573
2022
  if (signature === CRATE_SIGNATURE) {
574
- throw new Error("Binary USDC crate layers are not implemented yet; use ASCII USDA layers.");
2023
+ return parseUSDC(data, url);
575
2024
  }
576
2025
  return parseUSDA(TEXT_DECODER.decode(data), url);
577
2026
  }
2027
+ function setAttributeSourceUrls(stage, sourceUrl) {
2028
+ const pendingContents = [...stage.rootPrims];
2029
+ while (pendingContents.length) {
2030
+ const contents = pendingContents.pop();
2031
+ for (const attribute of Object.values(contents.attributes)) {
2032
+ attribute.sourceUrl = sourceUrl;
2033
+ }
2034
+ for (const child of contents.children) {
2035
+ pendingContents.push(child);
2036
+ }
2037
+ if ("variants" in contents) {
2038
+ for (const variants of Object.values(contents.variants)) {
2039
+ for (const variant of Object.values(variants)) {
2040
+ pendingContents.push(variant);
2041
+ }
2042
+ }
2043
+ }
2044
+ }
2045
+ }
578
2046
  async function composePrims(prims, sourceUrl, inheritedVariants, environment, depth) {
579
2047
  if (depth > (environment.options.usd?.maxReferenceDepth ?? 12)) {
580
2048
  throw new Error("OpenUSD reference composition exceeded the configured depth limit.");
@@ -653,6 +2121,7 @@ var __exports__ = (() => {
653
2121
  content = response.arrayBuffer();
654
2122
  }
655
2123
  const stage = parseUSDLayer(await content, url);
2124
+ setAttributeSourceUrls(stage, url);
656
2125
  environment.layers.add(url);
657
2126
  return stage;
658
2127
  })();
@@ -752,6 +2221,7 @@ var __exports__ = (() => {
752
2221
  var init_parse_usd = __esm({
753
2222
  "src/usd/lib/parse-usd.ts"() {
754
2223
  "use strict";
2224
+ init_parse_usdc();
755
2225
  init_parse_usda();
756
2226
  init_parse_usdz();
757
2227
  TEXT_DECODER = new TextDecoder();
@@ -814,11 +2284,11 @@ var __exports__ = (() => {
814
2284
  id: "usd",
815
2285
  module: "scene",
816
2286
  version: VERSION,
817
- extensions: ["usd", "usda", "usdz"],
818
- mimeTypes: ["model/vnd.usd", "model/vnd.usda", "model/vnd.usdz+zip"],
2287
+ extensions: ["usd", "usda", "usdc", "usdz"],
2288
+ mimeTypes: ["model/vnd.usd", "model/vnd.usda", "model/vnd.usdc", "model/vnd.usdz+zip"],
819
2289
  text: true,
820
2290
  binary: true,
821
- tests: ["#usda", "PK"],
2291
+ tests: ["#usda", "PXR-USDC", "PK"],
822
2292
  options: {
823
2293
  usd: {
824
2294
  compose: true,
@@ -8733,9 +10203,9 @@ return true;`);
8733
10203
  static isSchema(x) {
8734
10204
  return (x === null || x === void 0 ? void 0 : x[kSchemaSymbol]) === true;
8735
10205
  }
8736
- constructor(fields = [], metadata2, dictionaries, metadataVersion = MetadataVersion.V5) {
10206
+ constructor(fields = [], metadata3, dictionaries, metadataVersion = MetadataVersion.V5) {
8737
10207
  this.fields = fields || [];
8738
- this.metadata = metadata2 || /* @__PURE__ */ new Map();
10208
+ this.metadata = metadata3 || /* @__PURE__ */ new Map();
8739
10209
  if (!dictionaries) {
8740
10210
  dictionaries = generateDictionaryMap(this.fields);
8741
10211
  }
@@ -8775,7 +10245,7 @@ return true;`);
8775
10245
  assign(...args) {
8776
10246
  const other = args[0] instanceof _Schema ? args[0] : Array.isArray(args[0]) ? new _Schema(args[0]) : new _Schema(args);
8777
10247
  const curFields = [...this.fields];
8778
- const metadata2 = mergeMaps(mergeMaps(/* @__PURE__ */ new Map(), this.metadata), other.metadata);
10248
+ const metadata3 = mergeMaps(mergeMaps(/* @__PURE__ */ new Map(), this.metadata), other.metadata);
8779
10249
  const newFields = other.fields.filter((f2) => {
8780
10250
  const i = curFields.findIndex((f) => f.name === f2.name);
8781
10251
  return ~i ? (curFields[i] = f2.clone({
@@ -8783,7 +10253,7 @@ return true;`);
8783
10253
  })) && false : true;
8784
10254
  });
8785
10255
  const newDictionaries = generateDictionaryMap(newFields, /* @__PURE__ */ new Map());
8786
- return new _Schema([...curFields, ...newFields], metadata2, new Map([...this.dictionaries, ...newDictionaries]));
10256
+ return new _Schema([...curFields, ...newFields], metadata3, new Map([...this.dictionaries, ...newDictionaries]));
8787
10257
  }
8788
10258
  };
8789
10259
  Schema2.prototype.fields = null;
@@ -8806,20 +10276,20 @@ return true;`);
8806
10276
  }
8807
10277
  /** @nocollapse */
8808
10278
  static new(...args) {
8809
- let [name22, type, nullable, metadata2] = args;
10279
+ let [name22, type, nullable, metadata3] = args;
8810
10280
  if (args[0] && typeof args[0] === "object") {
8811
10281
  ({ name: name22 } = args[0]);
8812
10282
  type === void 0 && (type = args[0].type);
8813
10283
  nullable === void 0 && (nullable = args[0].nullable);
8814
- metadata2 === void 0 && (metadata2 = args[0].metadata);
10284
+ metadata3 === void 0 && (metadata3 = args[0].metadata);
8815
10285
  }
8816
- return new _Field(`${name22}`, type, nullable, metadata2);
10286
+ return new _Field(`${name22}`, type, nullable, metadata3);
8817
10287
  }
8818
- constructor(name22, type, nullable = false, metadata2) {
10288
+ constructor(name22, type, nullable = false, metadata3) {
8819
10289
  this.name = name22;
8820
10290
  this.type = type;
8821
10291
  this.nullable = nullable;
8822
- this.metadata = metadata2 || /* @__PURE__ */ new Map();
10292
+ this.metadata = metadata3 || /* @__PURE__ */ new Map();
8823
10293
  }
8824
10294
  get typeId() {
8825
10295
  return this.type.typeId;
@@ -8831,9 +10301,9 @@ return true;`);
8831
10301
  return `${this.name}: ${this.type}`;
8832
10302
  }
8833
10303
  clone(...args) {
8834
- let [name22, type, nullable, metadata2] = args;
8835
- !args[0] || typeof args[0] !== "object" ? [name22 = this.name, type = this.type, nullable = this.nullable, metadata2 = this.metadata] = args : { name: name22 = this.name, type = this.type, nullable = this.nullable, metadata: metadata2 = this.metadata } = args[0];
8836
- return _Field.new(name22, type, nullable, metadata2);
10304
+ let [name22, type, nullable, metadata3] = args;
10305
+ !args[0] || typeof args[0] !== "object" ? [name22 = this.name, type = this.type, nullable = this.nullable, metadata3 = this.metadata] = args : { name: name22 = this.name, type = this.type, nullable = this.nullable, metadata: metadata3 = this.metadata } = args[0];
10306
+ return _Field.new(name22, type, nullable, metadata3);
8837
10307
  }
8838
10308
  };
8839
10309
  Field2.prototype.type = null;
@@ -9311,8 +10781,8 @@ return true;`);
9311
10781
  }
9312
10782
  return field || null;
9313
10783
  }
9314
- function customMetadataFromJSON(metadata2 = []) {
9315
- return new Map(metadata2.map(({ key, value }) => [key, value]));
10784
+ function customMetadataFromJSON(metadata3 = []) {
10785
+ return new Map(metadata3.map(({ key, value }) => [key, value]));
9316
10786
  }
9317
10787
  function indexTypeFromJSON(_type) {
9318
10788
  return new Int_(_type["isSigned"], _type["bitWidth"]);
@@ -9794,8 +11264,8 @@ return true;`);
9794
11264
  const bodyLength = _message.bodyLength();
9795
11265
  const version = _message.version();
9796
11266
  const headerType = _message.headerType();
9797
- const metadata2 = decodeMessageCustomMetadata(_message);
9798
- const message = new _Message(bodyLength, version, headerType, void 0, metadata2);
11267
+ const metadata3 = decodeMessageCustomMetadata(_message);
11268
+ const message = new _Message(bodyLength, version, headerType, void 0, metadata3);
9799
11269
  message._createHeader = decodeMessageHeader(_message, headerType);
9800
11270
  return message;
9801
11271
  }
@@ -9872,14 +11342,14 @@ return true;`);
9872
11342
  isDictionaryBatch() {
9873
11343
  return this.headerType === MessageHeader.DictionaryBatch;
9874
11344
  }
9875
- constructor(bodyLength, version, headerType, header, metadata2) {
11345
+ constructor(bodyLength, version, headerType, header, metadata3) {
9876
11346
  this._version = version;
9877
11347
  this._headerType = headerType;
9878
11348
  this.body = new Uint8Array(0);
9879
11349
  this._compression = header === null || header === void 0 ? void 0 : header.compression;
9880
11350
  header && (this._createHeader = () => header);
9881
11351
  this._bodyLength = bigIntToNumber(bodyLength);
9882
- this._metadata = metadata2 || /* @__PURE__ */ new Map();
11352
+ this._metadata = metadata3 || /* @__PURE__ */ new Map();
9883
11353
  }
9884
11354
  };
9885
11355
  RecordBatch2 = class {
@@ -9901,13 +11371,13 @@ return true;`);
9901
11371
  get metadata() {
9902
11372
  return this._metadata;
9903
11373
  }
9904
- constructor(length4, nodes, buffers, compression, variadicBufferCounts = [], metadata2) {
11374
+ constructor(length4, nodes, buffers, compression, variadicBufferCounts = [], metadata3) {
9905
11375
  this._nodes = nodes;
9906
11376
  this._buffers = buffers;
9907
11377
  this._length = bigIntToNumber(length4);
9908
11378
  this._compression = compression;
9909
11379
  this._variadicBufferCounts = variadicBufferCounts;
9910
- this._metadata = metadata2 || /* @__PURE__ */ new Map();
11380
+ this._metadata = metadata3 || /* @__PURE__ */ new Map();
9911
11381
  }
9912
11382
  };
9913
11383
  DictionaryBatch2 = class {
@@ -13145,10 +14615,10 @@ return true;`);
13145
14615
  }
13146
14616
  });
13147
14617
  _InternalEmptyPlaceholderRecordBatch = class extends RecordBatch3 {
13148
- constructor(schema, metadata2) {
14618
+ constructor(schema, metadata3) {
13149
14619
  const children = schema.fields.map((f) => makeData({ type: f.type }));
13150
14620
  const data = makeData({ type: new Struct(schema.fields), length: 0, nullCount: 0, children });
13151
- super(schema, data, metadata2 || /* @__PURE__ */ new Map());
14621
+ super(schema, data, metadata3 || /* @__PURE__ */ new Map());
13152
14622
  }
13153
14623
  };
13154
14624
  }
@@ -15749,442 +17219,29 @@ return true;`);
15749
17219
  }
15750
17220
  });
15751
17221
 
15752
- // ../core/src/schema-utils/lib/schema/convert-arrow-schema.ts
15753
- function serializeArrowSchema(arrowSchema) {
15754
- return {
15755
- fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
15756
- metadata: serializeArrowMetadata(arrowSchema.metadata)
15757
- };
17222
+ // ../../node_modules/@math.gl/arrow/dist/arrow/arrow-data.js
17223
+ function getArrowVariadicBuffers(data) {
17224
+ return data.variadicBuffers ?? [];
15758
17225
  }
15759
- function deserializeArrowSchema(schema, options) {
15760
- return new Schema2(
15761
- schema.fields.map((field) => deserializeArrowField(field, options)),
15762
- deserializeArrowMetadata(schema.metadata)
15763
- );
15764
- }
15765
- function serializeArrowMetadata(arrowMetadata) {
15766
- return Object.fromEntries(arrowMetadata);
15767
- }
15768
- function deserializeArrowMetadata(metadata2) {
15769
- return metadata2 ? new Map(Object.entries(metadata2)) : /* @__PURE__ */ new Map();
15770
- }
15771
- function serializeArrowField(field) {
15772
- return {
15773
- name: field.name,
15774
- type: serializeArrowType(field.type),
15775
- nullable: field.nullable,
15776
- metadata: serializeArrowMetadata(field.metadata)
15777
- };
15778
- }
15779
- function deserializeArrowField(field, options) {
15780
- return new Field2(
15781
- field.name,
15782
- deserializeArrowType(field.type, options),
15783
- field.nullable,
15784
- deserializeArrowMetadata(field.metadata)
15785
- );
15786
- }
15787
- function serializeArrowType(arrowType) {
15788
- if (isArrowViewType(arrowType, "BinaryView")) {
15789
- return "binary-view";
15790
- }
15791
- if (isArrowViewType(arrowType, "Utf8View")) {
15792
- return "utf8-view";
15793
- }
15794
- if (isOptionalArrowType(arrowType, "LargeList")) {
15795
- const largeListType = arrowType;
15796
- return {
15797
- type: "large-list",
15798
- children: [serializeArrowField(largeListType.valueField)]
15799
- };
15800
- }
15801
- switch (arrowType.constructor) {
15802
- case Null2:
15803
- return "null";
15804
- case Binary2:
15805
- return "binary";
15806
- case FixedSizeBinary2:
15807
- return {
15808
- type: "fixed-size-binary",
15809
- byteWidth: arrowType.byteWidth
15810
- };
15811
- case Bool2:
15812
- return "bool";
15813
- case Int_:
15814
- const intType = arrowType;
15815
- return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
15816
- case Int8:
15817
- return "int8";
15818
- case Int16:
15819
- return "int16";
15820
- case Int32:
15821
- return "int32";
15822
- case Int64:
15823
- return "int64";
15824
- case Uint8:
15825
- return "uint8";
15826
- case Uint16:
15827
- return "uint16";
15828
- case Uint32:
15829
- return "uint32";
15830
- case Uint64:
15831
- return "uint64";
15832
- case Float:
15833
- const precision = arrowType.precision;
15834
- switch (precision) {
15835
- case Precision.HALF:
15836
- return "float16";
15837
- case Precision.SINGLE:
15838
- return "float32";
15839
- case Precision.DOUBLE:
15840
- return "float64";
15841
- default:
15842
- return "float16";
15843
- }
15844
- case Float16:
15845
- return "float16";
15846
- case Float32:
15847
- return "float32";
15848
- case Float64:
15849
- return "float64";
15850
- case Utf82:
15851
- return "utf8";
15852
- case Decimal2:
15853
- const decimal = arrowType;
15854
- return {
15855
- type: "decimal",
15856
- bitWidth: decimal.bitWidth,
15857
- precision: decimal.precision,
15858
- scale: decimal.scale
15859
- };
15860
- case Date_:
15861
- const dateUnit = arrowType.unit;
15862
- return dateUnit === DateUnit.DAY ? "date-day" : "date-millisecond";
15863
- case DateDay:
15864
- return "date-day";
15865
- case DateMillisecond:
15866
- return "date-millisecond";
15867
- case Time_:
15868
- const timeUnit = arrowType.unit;
15869
- switch (timeUnit) {
15870
- case TimeUnit.SECOND:
15871
- return "time-second";
15872
- case TimeUnit.MILLISECOND:
15873
- return "time-millisecond";
15874
- case TimeUnit.MICROSECOND:
15875
- return "time-microsecond";
15876
- case TimeUnit.NANOSECOND:
15877
- return "time-nanosecond";
15878
- default:
15879
- return "time-second";
15880
- }
15881
- case TimeMillisecond:
15882
- return "time-millisecond";
15883
- case TimeSecond:
15884
- return "time-second";
15885
- case TimeMicrosecond:
15886
- return "time-microsecond";
15887
- case TimeNanosecond:
15888
- return "time-nanosecond";
15889
- case Timestamp_:
15890
- const timeStampUnit = arrowType.unit;
15891
- switch (timeStampUnit) {
15892
- case TimeUnit.SECOND:
15893
- return "timestamp-second";
15894
- case TimeUnit.MILLISECOND:
15895
- return "timestamp-millisecond";
15896
- case TimeUnit.MICROSECOND:
15897
- return "timestamp-microsecond";
15898
- case TimeUnit.NANOSECOND:
15899
- return "timestamp-nanosecond";
15900
- default:
15901
- return "timestamp-second";
15902
- }
15903
- case TimestampSecond:
15904
- return "timestamp-second";
15905
- case TimestampMillisecond:
15906
- return "timestamp-millisecond";
15907
- case TimestampMicrosecond:
15908
- return "timestamp-microsecond";
15909
- case TimestampNanosecond:
15910
- return "timestamp-nanosecond";
15911
- case Interval_:
15912
- const intervalUnit = arrowType.unit;
15913
- switch (intervalUnit) {
15914
- case IntervalUnit.DAY_TIME:
15915
- return "interval-daytime";
15916
- case IntervalUnit.YEAR_MONTH:
15917
- return "interval-yearmonth";
15918
- default:
15919
- return "interval-daytime";
15920
- }
15921
- case IntervalDayTime:
15922
- return "interval-daytime";
15923
- case IntervalYearMonth:
15924
- return "interval-yearmonth";
15925
- case Map_:
15926
- const mapType = arrowType;
15927
- return {
15928
- type: "map",
15929
- keysSorted: mapType.keysSorted,
15930
- children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
15931
- };
15932
- case List2:
15933
- const listType = arrowType;
15934
- const listField = listType.valueField;
15935
- return {
15936
- type: "list",
15937
- children: [serializeArrowField(listField)]
15938
- };
15939
- case FixedSizeList2:
15940
- const fixedSizeList = arrowType;
15941
- return {
15942
- type: "fixed-size-list",
15943
- listSize: fixedSizeList.listSize,
15944
- children: [serializeArrowField(fixedSizeList.children[0])]
15945
- };
15946
- case Struct:
15947
- const structType = arrowType;
15948
- return {
15949
- type: "struct",
15950
- children: structType.children.map((arrowField) => serializeArrowField(arrowField))
15951
- };
15952
- case SparseUnion:
15953
- case DenseUnion:
15954
- const unionType = arrowType;
15955
- return {
15956
- type: unionType instanceof DenseUnion ? "dense-union" : "sparse-union",
15957
- typeIds: unionType.typeIds,
15958
- children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
15959
- typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
15960
- };
15961
- case Dictionary:
15962
- const dictionaryType = arrowType;
15963
- return {
15964
- type: "dictionary",
15965
- id: dictionaryType.id,
15966
- indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
15967
- dictionary: serializeArrowType(dictionaryType.dictionary),
15968
- isOrdered: dictionaryType.isOrdered
15969
- };
15970
- default:
15971
- throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
15972
- }
15973
- }
15974
- function deserializeArrowType(dataType, options) {
15975
- if (typeof dataType === "object") {
15976
- switch (dataType.type) {
15977
- case "decimal":
15978
- return new Decimal2(dataType.scale, dataType.precision, dataType.bitWidth);
15979
- case "map": {
15980
- const children = dataType.children.map(
15981
- (arrowField) => deserializeArrowField(arrowField, options)
15982
- );
15983
- return new Map_(children[0], dataType.keysSorted);
15984
- }
15985
- case "list": {
15986
- const field = deserializeArrowField(dataType.children[0], options);
15987
- return new List2(field);
15988
- }
15989
- case "large-list": {
15990
- const field = deserializeArrowField(dataType.children[0], options);
15991
- const LargeList3 = getOptionalArrowConstructor("LargeList");
15992
- if (!LargeList3) {
15993
- throw new Error(
15994
- "LargeList requires an Apache Arrow runtime that exports the LargeList constructor"
15995
- );
15996
- }
15997
- return new LargeList3(field);
15998
- }
15999
- case "fixed-size-list": {
16000
- const child = deserializeArrowField(dataType.children[0], options);
16001
- return new FixedSizeList2(dataType.listSize, child);
16002
- }
16003
- case "fixed-size-binary":
16004
- return new FixedSizeBinary2(dataType.byteWidth);
16005
- case "struct": {
16006
- const children = dataType.children.map(
16007
- (arrowField) => deserializeArrowField(arrowField, options)
16008
- );
16009
- return new Struct(children);
16010
- }
16011
- case "sparse-union":
16012
- case "dense-union": {
16013
- const children = dataType.children.map(
16014
- (arrowField) => deserializeArrowField(arrowField, options)
16015
- );
16016
- return dataType.type === "dense-union" ? new DenseUnion(dataType.typeIds, children) : new SparseUnion(dataType.typeIds, children);
16017
- }
16018
- case "dictionary": {
16019
- return new Dictionary(
16020
- deserializeArrowType(dataType.dictionary, options),
16021
- deserializeArrowDictionaryKeyType(dataType.indices),
16022
- dataType.id,
16023
- dataType.isOrdered
16024
- );
16025
- }
16026
- default:
16027
- throw new Error("array type not supported");
16028
- }
16029
- }
16030
- switch (dataType) {
16031
- case "null":
16032
- return new Null2();
16033
- case "binary":
16034
- return makeVariableWidthArrowType("BinaryView", new Binary2(), options);
16035
- case "binary-view":
16036
- return makeRequiredArrowViewType("BinaryView");
16037
- case "bool":
16038
- return new Bool2();
16039
- case "int8":
16040
- return new Int8();
16041
- case "int16":
16042
- return new Int16();
16043
- case "int32":
16044
- return new Int32();
16045
- case "int64":
16046
- return new Int64();
16047
- case "uint8":
16048
- return new Uint8();
16049
- case "uint16":
16050
- return new Uint16();
16051
- case "uint32":
16052
- return new Uint32();
16053
- case "uint64":
16054
- return new Uint64();
16055
- case "float16":
16056
- return new Float16();
16057
- case "float32":
16058
- return new Float32();
16059
- case "float64":
16060
- return new Float64();
16061
- case "utf8":
16062
- return makeVariableWidthArrowType("Utf8View", new Utf82(), options);
16063
- case "utf8-view":
16064
- return makeRequiredArrowViewType("Utf8View");
16065
- case "date-day":
16066
- return new DateDay();
16067
- case "date-millisecond":
16068
- return new DateMillisecond();
16069
- case "time-second":
16070
- return new TimeSecond();
16071
- case "time-millisecond":
16072
- return new TimeMillisecond();
16073
- case "time-microsecond":
16074
- return new TimeMicrosecond();
16075
- case "time-nanosecond":
16076
- return new TimeNanosecond();
16077
- case "timestamp-second":
16078
- return new TimestampSecond();
16079
- case "timestamp-millisecond":
16080
- return new TimestampMillisecond();
16081
- case "timestamp-microsecond":
16082
- return new TimestampMicrosecond();
16083
- case "timestamp-nanosecond":
16084
- return new TimestampNanosecond();
16085
- case "interval-daytime":
16086
- return new IntervalDayTime();
16087
- case "interval-yearmonth":
16088
- return new IntervalYearMonth();
16089
- default:
16090
- throw new Error("array type not supported");
16091
- }
16092
- }
16093
- function getOptionalArrowConstructor(typeName) {
16094
- return Arrow_dom_exports[typeName];
16095
- }
16096
- function isArrowViewType(arrowType, viewTypeName) {
16097
- const constructor = getOptionalArrowConstructor(viewTypeName);
16098
- if (constructor && arrowType instanceof constructor) {
16099
- return true;
16100
- }
16101
- const guards = DataType;
16102
- const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
16103
- return Boolean(guard?.(arrowType));
16104
- }
16105
- function isOptionalArrowType(arrowType, typeName) {
16106
- const constructor = getOptionalArrowConstructor(typeName);
16107
- return Boolean(constructor && arrowType instanceof constructor);
16108
- }
16109
- function makeVariableWidthArrowType(viewTypeName, fallbackType, options) {
16110
- const viewTypeMode = options?.viewTypes || "never";
16111
- if (viewTypeMode === "never") {
16112
- return fallbackType;
16113
- }
16114
- const constructor = getOptionalArrowConstructor(viewTypeName);
16115
- if (constructor) {
16116
- return new constructor();
16117
- }
16118
- if (viewTypeMode === "require") {
16119
- throw new Error(
16120
- `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
16121
- );
16122
- }
16123
- return fallbackType;
16124
- }
16125
- function makeRequiredArrowViewType(viewTypeName) {
16126
- const constructor = getOptionalArrowConstructor(viewTypeName);
16127
- if (!constructor) {
16128
- throw new Error(
16129
- `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
16130
- );
16131
- }
16132
- return new constructor();
16133
- }
16134
- function serializeArrowDictionaryKeyType(arrowType) {
16135
- if (arrowType instanceof Int_) {
16136
- const prefix = arrowType.isSigned ? "int" : "uint";
16137
- const keyType = `${prefix}${arrowType.bitWidth}`;
16138
- if (isSchemaDictionaryKeyType(keyType)) {
16139
- return keyType;
16140
- }
16141
- }
16142
- switch (arrowType.constructor) {
16143
- case Int8:
16144
- return "int8";
16145
- case Int16:
16146
- return "int16";
16147
- case Int32:
16148
- return "int32";
16149
- case Uint8:
16150
- return "uint8";
16151
- case Uint16:
16152
- return "uint16";
16153
- case Uint32:
16154
- return "uint32";
16155
- default:
16156
- throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
16157
- }
16158
- }
16159
- function isSchemaDictionaryKeyType(keyType) {
16160
- return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
16161
- }
16162
- function deserializeArrowDictionaryKeyType(keyType) {
16163
- switch (keyType) {
16164
- case "int8":
16165
- return new Int8();
16166
- case "int16":
16167
- return new Int16();
16168
- case "int32":
16169
- return new Int32();
16170
- case "uint8":
16171
- return new Uint8();
16172
- case "uint16":
16173
- return new Uint16();
16174
- case "uint32":
16175
- return new Uint32();
16176
- default:
16177
- throw new Error(`schema dictionary index type not supported: ${keyType}`);
16178
- }
17226
+ function createArrowData(type, offset, length4, nullCount, buffers, children, dictionary, variadicBuffers) {
17227
+ return Reflect.construct(Data, [
17228
+ type,
17229
+ offset,
17230
+ length4,
17231
+ nullCount,
17232
+ buffers,
17233
+ children,
17234
+ dictionary,
17235
+ variadicBuffers
17236
+ ]);
16179
17237
  }
16180
- var init_convert_arrow_schema = __esm({
16181
- "../core/src/schema-utils/lib/schema/convert-arrow-schema.ts"() {
16182
- "use strict";
17238
+ var init_arrow_data = __esm({
17239
+ "../../node_modules/@math.gl/arrow/dist/arrow/arrow-data.js"() {
16183
17240
  init_Arrow_dom();
16184
17241
  }
16185
17242
  });
16186
17243
 
16187
- // ../core/src/schema-utils/lib/arrow/split-arrow-buffers.ts
17244
+ // ../../node_modules/@math.gl/arrow/dist/arrow/split-arrow-buffers.js
16188
17245
  function splitArrowBuffers(input, options = {}) {
16189
17246
  const context = { ...options, copies: /* @__PURE__ */ new WeakMap() };
16190
17247
  if (isArrowTable2(input)) {
@@ -16207,17 +17264,12 @@ return true;`);
16207
17264
  function isArrowVector2(input) {
16208
17265
  return "data" in input && Array.isArray(input.data);
16209
17266
  }
16210
- function splitArrowTableBuffersInternal(table, options) {
16211
- const recordBatches = table.batches.map(
16212
- (recordBatch) => splitArrowRecordBatchBuffers(recordBatch, options)
16213
- );
16214
- return new Table(table.schema, recordBatches);
17267
+ function splitArrowTableBuffersInternal(arrowTable, options) {
17268
+ const recordBatches = arrowTable.batches.map((recordBatch) => splitArrowRecordBatchBuffers(recordBatch, options));
17269
+ return new Table(arrowTable.schema, recordBatches);
16215
17270
  }
16216
17271
  function splitArrowRecordBatchBuffers(recordBatch, options) {
16217
- return new RecordBatch3(
16218
- recordBatch.schema,
16219
- splitArrowDataBuffers(recordBatch.data, options)
16220
- );
17272
+ return new RecordBatch3(recordBatch.schema, splitArrowDataBuffers(recordBatch.data, options));
16221
17273
  }
16222
17274
  function splitArrowDataBuffers(data, options) {
16223
17275
  const children = data.children.map((childData) => splitArrowDataBuffers(childData, options));
@@ -16228,7 +17280,7 @@ return true;`);
16228
17280
  [BufferType.VALIDITY]: splitArrowBuffer(data.buffers[BufferType.VALIDITY], options),
16229
17281
  [BufferType.TYPE]: splitArrowBuffer(data.buffers[BufferType.TYPE], options)
16230
17282
  };
16231
- return new Data(
17283
+ return createArrowData(
16232
17284
  data.type,
16233
17285
  data.offset,
16234
17286
  data.length,
@@ -16236,7 +17288,8 @@ return true;`);
16236
17288
  data._nullCount,
16237
17289
  buffers,
16238
17290
  children,
16239
- dictionary
17291
+ dictionary,
17292
+ getArrowVariadicBuffers(data).map((buffer) => splitArrowBuffer(buffer, options))
16240
17293
  );
16241
17294
  }
16242
17295
  function splitArrowVectorBuffers(vector, options) {
@@ -16254,7 +17307,7 @@ return true;`);
16254
17307
  }
16255
17308
  let copy2 = options.copies.get(array);
16256
17309
  if (!copy2) {
16257
- copy2 = array.slice();
17310
+ copy2 = array instanceof Uint8Array ? new Uint8Array(array) : array.slice();
16258
17311
  options.copies.set(array, copy2);
16259
17312
  }
16260
17313
  return copy2;
@@ -16263,36 +17316,113 @@ return true;`);
16263
17316
  return ArrayBuffer.isView(value) && !(value instanceof DataView);
16264
17317
  }
16265
17318
  var init_split_arrow_buffers = __esm({
16266
- "../core/src/schema-utils/lib/arrow/split-arrow-buffers.ts"() {
16267
- "use strict";
17319
+ "../../node_modules/@math.gl/arrow/dist/arrow/split-arrow-buffers.js"() {
16268
17320
  init_Arrow_dom();
17321
+ init_arrow_data();
16269
17322
  }
16270
17323
  });
16271
17324
 
16272
- // ../core/src/schema-utils/lib/arrow/arrow-table-transport.ts
16273
- function dehydrateArrowTable(table, options) {
16274
- const splitTable = splitArrowBuffers(table, options);
17325
+ // ../../node_modules/@math.gl/arrow/dist/arrow/indexed-arrow-vector.js
17326
+ var init_indexed_arrow_vector = __esm({
17327
+ "../../node_modules/@math.gl/arrow/dist/arrow/indexed-arrow-vector.js"() {
17328
+ }
17329
+ });
17330
+
17331
+ // ../../node_modules/@math.gl/arrow/dist/arrow/indexed-arrow-table.js
17332
+ var init_indexed_arrow_table = __esm({
17333
+ "../../node_modules/@math.gl/arrow/dist/arrow/indexed-arrow-table.js"() {
17334
+ }
17335
+ });
17336
+
17337
+ // ../../node_modules/@math.gl/arrow/dist/arrow/mapped-arrow-table.js
17338
+ var init_mapped_arrow_table = __esm({
17339
+ "../../node_modules/@math.gl/arrow/dist/arrow/mapped-arrow-table.js"() {
17340
+ }
17341
+ });
17342
+
17343
+ // ../../node_modules/@math.gl/arrow/dist/arrow/rename-arrow-columns.js
17344
+ var init_rename_arrow_columns = __esm({
17345
+ "../../node_modules/@math.gl/arrow/dist/arrow/rename-arrow-columns.js"() {
17346
+ }
17347
+ });
17348
+
17349
+ // ../../node_modules/@math.gl/arrow/dist/arrow/arrow-table-transport.js
17350
+ function dehydrateArrowTable(arrowTable, options) {
17351
+ const splitTable = splitArrowBuffers(arrowTable, options);
16275
17352
  return {
16276
- shape: "arrow-table",
16277
17353
  transport: "arrow-js",
16278
- schema: serializeArrowSchema(splitTable.schema),
16279
- batches: splitTable.batches.map((recordBatch) => dehydrateArrowRecordBatch(recordBatch))
17354
+ version: 1,
17355
+ schema: tableToIPC(new Table(splitTable.schema, [])),
17356
+ metadataVersion: splitTable.schema.metadataVersion,
17357
+ batches: splitTable.batches.map((batch) => dehydrateArrowData(batch.data))
16280
17358
  };
16281
17359
  }
16282
17360
  function hydrateArrowTable(table) {
16283
- const schema = deserializeArrowSchema(table.schema);
16284
- const recordBatches = table.batches.map(
16285
- (recordBatch) => new RecordBatch3(schema, hydrateArrowData(recordBatch.data))
16286
- );
16287
- return new Table(schema, recordBatches);
17361
+ if (table.transport !== "arrow-js" || table.version !== 1) {
17362
+ throw new Error("Unsupported Arrow column-buffer transport protocol.");
17363
+ }
17364
+ const decodedSchema = tableFromIPC(table.schema).schema;
17365
+ const schema = new Schema2(decodedSchema.fields, decodedSchema.metadata, decodedSchema.dictionaries, table.metadataVersion);
17366
+ const type = new Struct(schema.fields);
17367
+ const batches = table.batches.map((data) => new RecordBatch3(schema, hydrateArrowData(data, type)));
17368
+ return new Table(schema, batches);
17369
+ }
17370
+ function dehydrateArrowData(data) {
17371
+ return {
17372
+ offset: data.offset,
17373
+ length: data.length,
17374
+ nullCount: data.nullCount,
17375
+ buffers: {
17376
+ [BufferType.OFFSET]: data.buffers[BufferType.OFFSET],
17377
+ [BufferType.DATA]: data.buffers[BufferType.DATA],
17378
+ [BufferType.VALIDITY]: data.buffers[BufferType.VALIDITY],
17379
+ [BufferType.TYPE]: data.buffers[BufferType.TYPE]
17380
+ },
17381
+ children: data.children.map((child) => dehydrateArrowData(child)),
17382
+ variadicBuffers: getArrowVariadicBuffers(data),
17383
+ dictionary: data.dictionary?.data.map((chunk) => dehydrateArrowData(chunk))
17384
+ };
16288
17385
  }
17386
+ function hydrateArrowData(data, type) {
17387
+ const children = data.children.map((child, index) => hydrateArrowData(child, type.children[index].type));
17388
+ const dictionary = data.dictionary && DataType.isDictionary(type) ? new Vector(data.dictionary.map((chunk) => hydrateArrowData(chunk, type.dictionary))) : void 0;
17389
+ return createArrowData(type, data.offset, data.length, data.nullCount, data.buffers, children, dictionary, data.variadicBuffers);
17390
+ }
17391
+ var init_arrow_table_transport = __esm({
17392
+ "../../node_modules/@math.gl/arrow/dist/arrow/arrow-table-transport.js"() {
17393
+ init_Arrow_dom();
17394
+ init_arrow_data();
17395
+ init_split_arrow_buffers();
17396
+ }
17397
+ });
17398
+
17399
+ // ../../node_modules/@math.gl/arrow/dist/arrow/index.js
17400
+ var init_arrow = __esm({
17401
+ "../../node_modules/@math.gl/arrow/dist/arrow/index.js"() {
17402
+ init_indexed_arrow_table();
17403
+ init_indexed_arrow_vector();
17404
+ init_mapped_arrow_table();
17405
+ init_rename_arrow_columns();
17406
+ init_split_arrow_buffers();
17407
+ init_arrow_table_transport();
17408
+ }
17409
+ });
17410
+
17411
+ // ../../node_modules/@math.gl/arrow/dist/index.js
17412
+ var init_dist = __esm({
17413
+ "../../node_modules/@math.gl/arrow/dist/index.js"() {
17414
+ init_arrow();
17415
+ }
17416
+ });
17417
+
17418
+ // ../core/src/arrow-worker-transport.ts
16289
17419
  function serializeArrowWorkerTable(result) {
16290
17420
  if (!isArrowTableWrapper(result)) {
16291
17421
  throw new Error("Workers require Arrow table output");
16292
17422
  }
16293
- const { data, ...metadata2 } = result;
17423
+ const { data, ...metadata3 } = result;
16294
17424
  return {
16295
- ...structuredClone(metadata2),
17425
+ ...structuredClone(metadata3),
16296
17426
  data: dehydrateArrowTable(data, { copy: "all" })
16297
17427
  };
16298
17428
  }
@@ -16331,60 +17461,10 @@ return true;`);
16331
17461
  table && table.shape === "arrow-table" && table.data && table.data.transport === "arrow-js" && Array.isArray(table.data.batches)
16332
17462
  );
16333
17463
  }
16334
- function dehydrateArrowRecordBatch(recordBatch) {
16335
- return { data: dehydrateArrowData(recordBatch.data) };
16336
- }
16337
- function dehydrateArrowData(data) {
16338
- return {
16339
- type: serializeArrowType(data.type),
16340
- offset: data.offset,
16341
- length: data.length,
16342
- // @ts-expect-error _nullCount is protected. Preserve the Arrow lazy null-count state.
16343
- nullCount: data._nullCount,
16344
- buffers: {
16345
- [BufferType.OFFSET]: data.buffers[BufferType.OFFSET],
16346
- [BufferType.DATA]: data.buffers[BufferType.DATA],
16347
- [BufferType.VALIDITY]: data.buffers[BufferType.VALIDITY],
16348
- [BufferType.TYPE]: data.buffers[BufferType.TYPE]
16349
- },
16350
- children: data.children.map((childData) => dehydrateArrowData(childData)),
16351
- dictionary: data.dictionary ? dehydrateArrowVector(data.dictionary) : void 0
16352
- };
16353
- }
16354
- function dehydrateArrowVector(vector) {
16355
- return { data: vector.data.map((data) => dehydrateArrowData(data)) };
16356
- }
16357
- function hydrateArrowData(data) {
16358
- const children = data.children.map((childData) => hydrateArrowData(childData));
16359
- const dictionary = data.dictionary ? hydrateArrowVector(data.dictionary) : void 0;
16360
- return new Data(
16361
- deserializeArrowType(data.type),
16362
- data.offset,
16363
- data.length,
16364
- data.nullCount,
16365
- data.buffers,
16366
- children,
16367
- dictionary
16368
- );
16369
- }
16370
- function hydrateArrowVector(vector) {
16371
- return new Vector(vector.data.map((data) => hydrateArrowData(data)));
16372
- }
16373
- var init_arrow_table_transport = __esm({
16374
- "../core/src/schema-utils/lib/arrow/arrow-table-transport.ts"() {
17464
+ var init_arrow_worker_transport = __esm({
17465
+ "../core/src/arrow-worker-transport.ts"() {
16375
17466
  "use strict";
16376
- init_Arrow_dom();
16377
- init_convert_arrow_schema();
16378
- init_split_arrow_buffers();
16379
- }
16380
- });
16381
-
16382
- // ../core/src/schema-utils/arrow-transport.ts
16383
- var init_arrow_transport = __esm({
16384
- "../core/src/schema-utils/arrow-transport.ts"() {
16385
- "use strict";
16386
- init_arrow_table_transport();
16387
- init_split_arrow_buffers();
17467
+ init_dist();
16388
17468
  }
16389
17469
  });
16390
17470
 
@@ -16564,41 +17644,41 @@ return true;`);
16564
17644
  }
16565
17645
  });
16566
17646
 
16567
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/npm-tag.js
17647
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/npm-tag.js
16568
17648
  var NPM_TAG2;
16569
17649
  var init_npm_tag2 = __esm({
16570
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/npm-tag.js"() {
17650
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/npm-tag.js"() {
16571
17651
  NPM_TAG2 = "latest";
16572
17652
  }
16573
17653
  });
16574
17654
 
16575
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/env-utils/version.js
17655
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/env-utils/version.js
16576
17656
  function getVersion2() {
16577
17657
  return typeof __VERSION__ === "undefined" ? NPM_TAG2 : __VERSION__;
16578
17658
  }
16579
17659
  var VERSION3;
16580
17660
  var init_version2 = __esm({
16581
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/env-utils/version.js"() {
17661
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/env-utils/version.js"() {
16582
17662
  init_npm_tag2();
16583
17663
  VERSION3 = getVersion2();
16584
17664
  }
16585
17665
  });
16586
17666
 
16587
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/env-utils/assert.js
17667
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/env-utils/assert.js
16588
17668
  function assert3(condition, message) {
16589
17669
  if (!condition) {
16590
17670
  throw new Error(message || "loaders.gl assertion failed.");
16591
17671
  }
16592
17672
  }
16593
17673
  var init_assert3 = __esm({
16594
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/env-utils/assert.js"() {
17674
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/env-utils/assert.js"() {
16595
17675
  }
16596
17676
  });
16597
17677
 
16598
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/env-utils/globals.js
17678
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/env-utils/globals.js
16599
17679
  var globals3, self_3, window_3, global_3, document_3, isBrowser3, isMobile2, matches3, nodeVersion3;
16600
17680
  var init_globals3 = __esm({
16601
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/env-utils/globals.js"() {
17681
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/env-utils/globals.js"() {
16602
17682
  globals3 = {
16603
17683
  self: typeof self !== "undefined" && self,
16604
17684
  window: typeof window !== "undefined" && window,
@@ -16617,7 +17697,7 @@ return true;`);
16617
17697
  }
16618
17698
  });
16619
17699
 
16620
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-job.js
17700
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-job.js
16621
17701
  function createAbortError(message) {
16622
17702
  const error = new Error(message);
16623
17703
  error.name = "AbortError";
@@ -16625,7 +17705,7 @@ return true;`);
16625
17705
  }
16626
17706
  var WorkerJob;
16627
17707
  var init_worker_job = __esm({
16628
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-job.js"() {
17708
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-job.js"() {
16629
17709
  WorkerJob = class {
16630
17710
  constructor(jobName, workerThread) {
16631
17711
  this.isRunning = true;
@@ -16739,10 +17819,10 @@ return true;`);
16739
17819
  }
16740
17820
  });
16741
17821
 
16742
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/node/worker_threads-browser.js
17822
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/node/worker_threads-browser.js
16743
17823
  var NodeWorker, parentPort;
16744
17824
  var init_worker_threads_browser = __esm({
16745
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/node/worker_threads-browser.js"() {
17825
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/node/worker_threads-browser.js"() {
16746
17826
  NodeWorker = class {
16747
17827
  /** Restores the native worker constructor when this browser shim is embedded in a Node bundle. */
16748
17828
  constructor(...arguments_) {
@@ -16760,7 +17840,7 @@ return true;`);
16760
17840
  }
16761
17841
  });
16762
17842
 
16763
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.js
17843
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.js
16764
17844
  function getLoadableWorkerURL(props) {
16765
17845
  assert3(props.source && !props.url || !props.source && props.url);
16766
17846
  if (props.url && props.workerType === "module") {
@@ -16809,13 +17889,13 @@ return true;`);
16809
17889
  }
16810
17890
  var workerURLCache;
16811
17891
  var init_get_loadable_worker_url = __esm({
16812
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.js"() {
17892
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-loadable-worker-url.js"() {
16813
17893
  init_assert3();
16814
17894
  workerURLCache = /* @__PURE__ */ new Map();
16815
17895
  }
16816
17896
  });
16817
17897
 
16818
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-utils/get-transfer-list.js
17898
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-transfer-list.js
16819
17899
  function getTransferList(object, recursive = true, transfers) {
16820
17900
  const transfersSet = transfers || /* @__PURE__ */ new Set();
16821
17901
  const seen = /* @__PURE__ */ new Set();
@@ -16899,14 +17979,14 @@ return true;`);
16899
17979
  return object === null ? {} : clone2(object);
16900
17980
  }
16901
17981
  var init_get_transfer_list = __esm({
16902
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-utils/get-transfer-list.js"() {
17982
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-transfer-list.js"() {
16903
17983
  }
16904
17984
  });
16905
17985
 
16906
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-thread.js
17986
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-thread.js
16907
17987
  var NOOP, WorkerThread;
16908
17988
  var init_worker_thread = __esm({
16909
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-thread.js"() {
17989
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-thread.js"() {
16910
17990
  init_worker_threads_browser();
16911
17991
  init_globals3();
16912
17992
  init_assert3();
@@ -17094,10 +18174,10 @@ return true;`);
17094
18174
  }
17095
18175
  });
17096
18176
 
17097
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-pool.js
18177
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-pool.js
17098
18178
  var WorkerPool;
17099
18179
  var init_worker_pool = __esm({
17100
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-pool.js"() {
18180
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-pool.js"() {
17101
18181
  init_globals3();
17102
18182
  init_worker_thread();
17103
18183
  init_worker_job();
@@ -17628,7 +18708,7 @@ return true;`);
17628
18708
  }
17629
18709
  });
17630
18710
 
17631
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-farm.js
18711
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-farm.js
17632
18712
  function getWorkerPoolKey(options) {
17633
18713
  const { name: name22, source, url, urlKey, loadWorker, workerType } = options;
17634
18714
  const sourceKey = source ? `source:${source}` : "";
@@ -17646,7 +18726,7 @@ return true;`);
17646
18726
  }
17647
18727
  var DEFAULT_PROPS, loadWorkerIds, nextLoadWorkerId, WorkerFarm;
17648
18728
  var init_worker_farm = __esm({
17649
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-farm/worker-farm.js"() {
18729
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-farm/worker-farm.js"() {
17650
18730
  init_worker_pool();
17651
18731
  init_worker_thread();
17652
18732
  DEFAULT_PROPS = {
@@ -17756,10 +18836,10 @@ return true;`);
17756
18836
  }
17757
18837
  });
17758
18838
 
17759
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/async-queue/async-queue.js
18839
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/async-queue/async-queue.js
17760
18840
  var AsyncQueue2;
17761
18841
  var init_async_queue = __esm({
17762
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/async-queue/async-queue.js"() {
18842
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/async-queue/async-queue.js"() {
17763
18843
  AsyncQueue2 = class {
17764
18844
  constructor() {
17765
18845
  this._values = [];
@@ -17828,7 +18908,7 @@ return true;`);
17828
18908
  }
17829
18909
  });
17830
18910
 
17831
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/get-worker-url.js
18911
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/get-worker-url.js
17832
18912
  function getWorkerName(worker) {
17833
18913
  const warning = worker.version !== VERSION3 ? ` (worker-utils@${VERSION3})` : "";
17834
18914
  return `${worker.name}@${worker.version}${warning}`;
@@ -17841,7 +18921,7 @@ return true;`);
17841
18921
  if (isBrowser3) {
17842
18922
  url = `modules/${worker.module}/dist/${workerFile}`;
17843
18923
  } else {
17844
- const workerSourceDirectory = worker.module === "core" && worker.workerNode?.startsWith("worker-utils/") ? "worker-utils/workers" : "workers";
18924
+ const workerSourceDirectory = worker.module === "tasks" && worker.workerNode?.startsWith("worker-utils/") ? "worker-utils/workers" : "workers";
17845
18925
  const workerSourceNode = worker.workerSourceNode || `${workerSourceDirectory}/${worker.id}-worker-node.ts`;
17846
18926
  url = `modules/${worker.module}/src/${workerSourceNode}`;
17847
18927
  }
@@ -17886,7 +18966,7 @@ return true;`);
17886
18966
  }
17887
18967
  var warnedWorkerVersionFallbacks;
17888
18968
  var init_get_worker_url = __esm({
17889
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/get-worker-url.js"() {
18969
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/get-worker-url.js"() {
17890
18970
  init_assert3();
17891
18971
  init_globals3();
17892
18972
  init_version2();
@@ -17895,7 +18975,7 @@ return true;`);
17895
18975
  }
17896
18976
  });
17897
18977
 
17898
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/shared-state.js
18978
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/shared-state.js
17899
18979
  function getWorkerCapabilities() {
17900
18980
  const isolated = typeof globalThis.crossOriginIsolated === "boolean" ? globalThis.crossOriginIsolated : void 0;
17901
18981
  const capabilities = {
@@ -17942,7 +19022,7 @@ return true;`);
17942
19022
  }
17943
19023
  var SharedWorkerState;
17944
19024
  var init_shared_state = __esm({
17945
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/shared-state.js"() {
19025
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/shared-state.js"() {
17946
19026
  init_worker_thread();
17947
19027
  init_globals3();
17948
19028
  SharedWorkerState = class {
@@ -17985,7 +19065,7 @@ return true;`);
17985
19065
  }
17986
19066
  });
17987
19067
 
17988
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-utils/get-input-byte-length.js
19068
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-input-byte-length.js
17989
19069
  function getInputByteLength(input) {
17990
19070
  const seen = /* @__PURE__ */ new Set();
17991
19071
  let bytes = 0;
@@ -18014,22 +19094,22 @@ return true;`);
18014
19094
  return bytes;
18015
19095
  }
18016
19096
  var init_get_input_byte_length = __esm({
18017
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-utils/get-input-byte-length.js"() {
19097
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-utils/get-input-byte-length.js"() {
18018
19098
  }
18019
19099
  });
18020
19100
 
18021
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/validate-output-ownership.js
19101
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/validate-output-ownership.js
18022
19102
  function validateOutputOwnership(ownership) {
18023
19103
  if (ownership !== void 0 && ownership !== "copy" && ownership !== "transfer") {
18024
19104
  throw new Error("Invalid worker output ownership");
18025
19105
  }
18026
19106
  }
18027
19107
  var init_validate_output_ownership = __esm({
18028
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/validate-output-ownership.js"() {
19108
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/validate-output-ownership.js"() {
18029
19109
  }
18030
19110
  });
18031
19111
 
18032
- // ../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/process-on-worker.js
19112
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/process-on-worker.js
18033
19113
  async function processOnWorker(worker, data, options = {}, context = {}, jobContext = {}) {
18034
19114
  validateOutputOwnership(options.outputOwnership);
18035
19115
  if (options.inputOwnership !== void 0 && !["copy", "transfer", "share"].includes(options.inputOwnership))
@@ -18323,7 +19403,7 @@ return true;`);
18323
19403
  return inputOptions;
18324
19404
  }
18325
19405
  var init_process_on_worker = __esm({
18326
- "../../node_modules/@math.gl/core/dist/worker-utils/lib/worker-api/process-on-worker.js"() {
19406
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/lib/worker-api/process-on-worker.js"() {
18327
19407
  init_async_queue();
18328
19408
  init_worker_farm();
18329
19409
  init_get_worker_url();
@@ -18335,10 +19415,10 @@ return true;`);
18335
19415
  }
18336
19416
  });
18337
19417
 
18338
- // ../../node_modules/@math.gl/core/dist/worker-utils/index.js
19418
+ // ../../node_modules/@math.gl/tasks/dist/worker-utils/index.js
18339
19419
  var import_meta, path, moduleUrl;
18340
19420
  var init_worker_utils = __esm({
18341
- "../../node_modules/@math.gl/core/dist/worker-utils/index.js"() {
19421
+ "../../node_modules/@math.gl/tasks/dist/worker-utils/index.js"() {
18342
19422
  init_worker_pool();
18343
19423
  init_process_on_worker();
18344
19424
  init_get_transfer_list();
@@ -18348,7 +19428,7 @@ return true;`);
18348
19428
  }
18349
19429
  });
18350
19430
 
18351
- // ../../node_modules/@math.gl/core/dist/tasks/task-preload.js
19431
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-preload.js
18352
19432
  function preloadTaskCode(task, signal) {
18353
19433
  if (!task.preload)
18354
19434
  return Promise.resolve();
@@ -18387,13 +19467,162 @@ return true;`);
18387
19467
  }
18388
19468
  var pending, loaded;
18389
19469
  var init_task_preload = __esm({
18390
- "../../node_modules/@math.gl/core/dist/tasks/task-preload.js"() {
19470
+ "../../node_modules/@math.gl/tasks/dist/tasks/task-preload.js"() {
18391
19471
  pending = /* @__PURE__ */ new WeakMap();
18392
19472
  loaded = /* @__PURE__ */ new WeakSet();
18393
19473
  }
18394
19474
  });
18395
19475
 
18396
- // ../../node_modules/@math.gl/core/dist/tasks/task-runtime.js
19476
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-channel.js
19477
+ var TaskRequestError, TaskChannel;
19478
+ var init_task_channel = __esm({
19479
+ "../../node_modules/@math.gl/tasks/dist/tasks/task-channel.js"() {
19480
+ TaskRequestError = class extends Error {
19481
+ };
19482
+ TaskChannel = class {
19483
+ constructor(options) {
19484
+ this.options = options;
19485
+ this.nextId = 1;
19486
+ this.pending = /* @__PURE__ */ new Map();
19487
+ this.incoming = /* @__PURE__ */ new Map();
19488
+ }
19489
+ /** Send a request without serializing other in-flight requests. */
19490
+ request(operation, value, signal, transfer = []) {
19491
+ if (this.failure)
19492
+ return Promise.reject(this.failure.reason);
19493
+ if (signal?.aborted)
19494
+ return Promise.reject(signal.reason);
19495
+ const id = this.nextId++;
19496
+ return new Promise((resolve, reject) => {
19497
+ const abort = () => {
19498
+ const pending2 = this.pending.get(id);
19499
+ if (!pending2)
19500
+ return;
19501
+ this.pending.delete(id);
19502
+ pending2.cleanup();
19503
+ reject(signal?.reason);
19504
+ this.send({ source: "math.gl/tasks", kind: "cancel", id });
19505
+ };
19506
+ this.pending.set(id, {
19507
+ resolve,
19508
+ reject,
19509
+ cleanup: () => signal?.removeEventListener("abort", abort)
19510
+ });
19511
+ signal?.addEventListener("abort", abort, { once: true });
19512
+ this.send({ source: "math.gl/tasks", kind: "request", id, operation, value }, transfer);
19513
+ });
19514
+ }
19515
+ /** Send a one-way notification. */
19516
+ emit(operation, value, transfer = []) {
19517
+ if (this.failure)
19518
+ throw this.failure.reason;
19519
+ this.send({ source: "math.gl/tasks", kind: "event", id: 0, operation, value }, transfer);
19520
+ }
19521
+ /** Dispatch a transport message; unrelated protocols are ignored. */
19522
+ receive(message) {
19523
+ if (this.failure || message?.source !== "math.gl/tasks")
19524
+ return;
19525
+ if (message.kind === "failure") {
19526
+ const reason = new Error(message.error?.message ?? "Task channel failed");
19527
+ this.close(reason);
19528
+ this.options.onFailure?.(reason);
19529
+ } else if (message.kind === "result" || message.kind === "error") {
19530
+ const pending2 = this.pending.get(message.id);
19531
+ if (!pending2)
19532
+ return;
19533
+ this.pending.delete(message.id);
19534
+ pending2.cleanup();
19535
+ if (message.kind === "result")
19536
+ pending2.resolve(message.value);
19537
+ else {
19538
+ const error = new TaskRequestError(message.error?.message ?? "Task request failed");
19539
+ error.name = message.error?.name ?? "Error";
19540
+ pending2.reject(error);
19541
+ }
19542
+ } else if (message.kind === "cancel") {
19543
+ this.incoming.get(message.id)?.abort(new DOMException("Task request cancelled", "AbortError"));
19544
+ } else if (message.kind === "event") {
19545
+ try {
19546
+ this.options.handleEvent?.(message.operation, message.value);
19547
+ } catch (error) {
19548
+ this.fail(error);
19549
+ }
19550
+ } else if (message.kind === "request") {
19551
+ if (this.incoming.has(message.id)) {
19552
+ this.fail(new Error("Duplicate task request identifier"));
19553
+ return;
19554
+ }
19555
+ const controller = new AbortController();
19556
+ this.incoming.set(message.id, controller);
19557
+ void Promise.resolve().then(() => {
19558
+ controller.signal.throwIfAborted();
19559
+ return this.options.handleRequest(message.operation, message.value, controller.signal);
19560
+ }).then((value) => {
19561
+ if (!controller.signal.aborted && !this.failure) {
19562
+ this.send({ source: "math.gl/tasks", kind: "result", id: message.id, value }, this.options.getResultTransferList?.(value, message.value));
19563
+ }
19564
+ }).catch((reason) => {
19565
+ if (!controller.signal.aborted && !this.failure) {
19566
+ this.send({
19567
+ source: "math.gl/tasks",
19568
+ kind: "error",
19569
+ id: message.id,
19570
+ error: {
19571
+ name: reason instanceof Error ? reason.name : "Error",
19572
+ message: reason instanceof Error ? reason.message : String(reason)
19573
+ }
19574
+ });
19575
+ }
19576
+ }).finally(() => this.incoming.delete(message.id));
19577
+ }
19578
+ }
19579
+ /** Reject all outstanding calls with a common cause and abort incoming callbacks. */
19580
+ close(reason = new Error("Task channel closed")) {
19581
+ if (this.failure)
19582
+ return;
19583
+ this.failure = { reason };
19584
+ for (const pending2 of this.pending.values()) {
19585
+ pending2.cleanup();
19586
+ pending2.reject(reason);
19587
+ }
19588
+ this.pending.clear();
19589
+ for (const controller of this.incoming.values())
19590
+ controller.abort(reason);
19591
+ this.incoming.clear();
19592
+ }
19593
+ send(message, transfer = []) {
19594
+ if (this.failure)
19595
+ return;
19596
+ try {
19597
+ this.options.send(message, transfer);
19598
+ } catch (error) {
19599
+ this.fail(error);
19600
+ }
19601
+ }
19602
+ /** Invalidate the channel and notify the peer when the transport still works. */
19603
+ fail(reason) {
19604
+ if (this.failure)
19605
+ return;
19606
+ this.close(reason);
19607
+ try {
19608
+ this.options.send({
19609
+ source: "math.gl/tasks",
19610
+ kind: "failure",
19611
+ id: 0,
19612
+ error: {
19613
+ name: reason instanceof Error ? reason.name : "Error",
19614
+ message: reason instanceof Error ? reason.message : String(reason)
19615
+ }
19616
+ }, []);
19617
+ } catch {
19618
+ }
19619
+ this.options.onFailure?.(reason);
19620
+ }
19621
+ };
19622
+ }
19623
+ });
19624
+
19625
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-runtime.js
18397
19626
  function assertPayload(value) {
18398
19627
  if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype) {
18399
19628
  throw new TypeError("Task payloads must be plain objects with named fields");
@@ -18415,6 +19644,16 @@ return true;`);
18415
19644
  return {
18416
19645
  state,
18417
19646
  signal,
19647
+ requestHost: async (operation, payload, controls) => {
19648
+ signal.throwIfAborted();
19649
+ if (!context.requestHost)
19650
+ throw new Error("No host request handler configured");
19651
+ return context.requestHost(operation, payload, controls);
19652
+ },
19653
+ emitHost: (operation, payload) => {
19654
+ signal.throwIfAborted();
19655
+ context.emitHost?.(operation, payload);
19656
+ },
18418
19657
  throwIfAborted: () => {
18419
19658
  signal.throwIfAborted();
18420
19659
  context.throwIfAborted?.();
@@ -18434,7 +19673,7 @@ return true;`);
18434
19673
  }
18435
19674
  var TaskRuntime;
18436
19675
  var init_task_runtime = __esm({
18437
- "../../node_modules/@math.gl/core/dist/tasks/task-runtime.js"() {
19676
+ "../../node_modules/@math.gl/tasks/dist/tasks/task-runtime.js"() {
18438
19677
  init_worker_utils();
18439
19678
  init_task_preload();
18440
19679
  TaskRuntime = class {
@@ -18486,7 +19725,7 @@ return true;`);
18486
19725
  }
18487
19726
  });
18488
19727
 
18489
- // ../../node_modules/@math.gl/core/dist/tasks/task-sync.js
19728
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-sync.js
18490
19729
  function runTaskSync(task, input, request = {}) {
18491
19730
  if (!isTaskCodeLoaded(task))
18492
19731
  throw new Error("Preload task on the main thread before runTaskSync");
@@ -18504,8 +19743,8 @@ return true;`);
18504
19743
  context.throwIfAborted();
18505
19744
  const options = request.options ?? {};
18506
19745
  if (request.inputOwnership === "transfer") {
18507
- const metadata2 = new Set(getTransferList(options));
18508
- if (getTransferList(input).some((buffer) => metadata2.has(buffer)))
19746
+ const metadata3 = new Set(getTransferList(options));
19747
+ if (getTransferList(input).some((buffer) => metadata3.has(buffer)))
18509
19748
  throw new Error("Transferred input aliases reusable options; use inputOwnership: copy");
18510
19749
  }
18511
19750
  const copiedOptions = clonePayload(options);
@@ -18566,14 +19805,151 @@ return true;`);
18566
19805
  return Boolean(value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function");
18567
19806
  }
18568
19807
  var init_task_sync = __esm({
18569
- "../../node_modules/@math.gl/core/dist/tasks/task-sync.js"() {
19808
+ "../../node_modules/@math.gl/tasks/dist/tasks/task-sync.js"() {
18570
19809
  init_task_preload();
18571
19810
  init_worker_utils();
18572
19811
  init_task_runtime();
18573
19812
  }
18574
19813
  });
18575
19814
 
18576
- // ../../node_modules/@math.gl/core/dist/tasks/task-runner.js
19815
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-operation-queue.js
19816
+ var TaskOperationQueue;
19817
+ var init_task_operation_queue = __esm({
19818
+ "../../node_modules/@math.gl/tasks/dist/tasks/task-operation-queue.js"() {
19819
+ TaskOperationQueue = class {
19820
+ constructor(maxConcurrency) {
19821
+ this.maxConcurrency = maxConcurrency;
19822
+ this.pending = [];
19823
+ this.active = 0;
19824
+ this.exclusive = false;
19825
+ this.closed = false;
19826
+ this.idleWaiters = /* @__PURE__ */ new Set();
19827
+ if (!Number.isSafeInteger(maxConcurrency) || maxConcurrency < 1) {
19828
+ throw new RangeError("maxConcurrency must be a positive safe integer");
19829
+ }
19830
+ }
19831
+ /** Queue an operation; aborting before it starts removes it without running it. */
19832
+ run(mode, operation, signal) {
19833
+ if (this.closed)
19834
+ return Promise.reject(new Error("Task operation queue is closed"));
19835
+ if (mode !== "parallel" && mode !== "exclusive")
19836
+ return Promise.reject(new TypeError("Invalid operation mode"));
19837
+ if (signal?.aborted)
19838
+ return Promise.reject(signal.reason);
19839
+ return new Promise((resolve, reject) => {
19840
+ const onAbort = () => {
19841
+ const index = this.pending.indexOf(entry);
19842
+ if (index >= 0) {
19843
+ this.pending.splice(index, 1);
19844
+ entry.cancel(signal?.reason);
19845
+ this.pump();
19846
+ }
19847
+ };
19848
+ const entry = {
19849
+ mode,
19850
+ cancel: (reason) => {
19851
+ signal?.removeEventListener("abort", onAbort);
19852
+ reject(reason);
19853
+ },
19854
+ start: () => {
19855
+ signal?.removeEventListener("abort", onAbort);
19856
+ this.active++;
19857
+ if (mode === "exclusive")
19858
+ this.exclusive = true;
19859
+ void Promise.resolve().then(() => {
19860
+ signal?.throwIfAborted();
19861
+ return operation();
19862
+ }).then(resolve, reject).finally(() => {
19863
+ this.active--;
19864
+ if (mode === "exclusive")
19865
+ this.exclusive = false;
19866
+ this.pump();
19867
+ });
19868
+ }
19869
+ };
19870
+ this.pending.push(entry);
19871
+ signal?.addEventListener("abort", onAbort, { once: true });
19872
+ if (signal?.aborted)
19873
+ onAbort();
19874
+ else
19875
+ this.pump();
19876
+ });
19877
+ }
19878
+ /** Reject queued calls with one cause while allowing active operations to settle. */
19879
+ cancelPending(reason) {
19880
+ this.closed = true;
19881
+ for (const entry of this.pending.splice(0))
19882
+ entry.cancel(reason);
19883
+ this.pump();
19884
+ }
19885
+ /** Stop accepting new work; accepted operations continue to completion. */
19886
+ close() {
19887
+ this.closed = true;
19888
+ return this.whenIdle();
19889
+ }
19890
+ /** Wait until the queue has no running or waiting operations. */
19891
+ whenIdle() {
19892
+ if (!this.active && !this.pending.length)
19893
+ return Promise.resolve();
19894
+ return new Promise((resolve) => this.idleWaiters.add(resolve));
19895
+ }
19896
+ pump() {
19897
+ while (!this.exclusive && this.pending.length && this.active < this.maxConcurrency) {
19898
+ const entry = this.pending[0];
19899
+ if (entry.mode === "exclusive" && this.active)
19900
+ break;
19901
+ this.pending.shift();
19902
+ entry.start();
19903
+ if (entry.mode === "exclusive")
19904
+ break;
19905
+ }
19906
+ if (!this.active && !this.pending.length) {
19907
+ for (const resolve of this.idleWaiters)
19908
+ resolve();
19909
+ this.idleWaiters.clear();
19910
+ }
19911
+ }
19912
+ };
19913
+ }
19914
+ });
19915
+
19916
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-worker-channel.js
19917
+ var TaskWorkerChannel;
19918
+ var init_task_worker_channel = __esm({
19919
+ "../../node_modules/@math.gl/tasks/dist/tasks/task-worker-channel.js"() {
19920
+ init_worker_thread();
19921
+ init_task_channel();
19922
+ TaskWorkerChannel = class {
19923
+ constructor(name22, target, options) {
19924
+ this.thread = new WorkerThread({
19925
+ name: name22,
19926
+ url: target.url?.toString(),
19927
+ loadWorker: target.create,
19928
+ workerType: "module"
19929
+ });
19930
+ this.channel = new TaskChannel({
19931
+ ...options,
19932
+ send: (message, transfer) => this.thread.postMessage({ source: "loaders.gl/tasks", type: "task-channel", payload: message }, transfer)
19933
+ });
19934
+ this.thread.onMessage = (message) => {
19935
+ if (message?.type === "task-channel")
19936
+ this.channel.receive(message.payload);
19937
+ };
19938
+ this.thread.onError = (reason) => {
19939
+ this.channel.close(reason);
19940
+ options.onFailure?.(reason);
19941
+ };
19942
+ }
19943
+ /** Settle pending calls and terminate the worker without replacing its state. */
19944
+ async destroy(reason) {
19945
+ this.channel.close(reason);
19946
+ await this.thread.destroy();
19947
+ }
19948
+ };
19949
+ }
19950
+ });
19951
+
19952
+ // ../../node_modules/@math.gl/tasks/dist/tasks/task-runner.js
18577
19953
  async function finish(handle, operation) {
18578
19954
  let result;
18579
19955
  try {
@@ -18645,29 +20021,44 @@ return true;`);
18645
20021
  }
18646
20022
  function assertNoTransferAlias(input, options, ownership) {
18647
20023
  if (ownership === "transfer") {
18648
- const metadata2 = new Set(getTransferList(options));
18649
- if (getTransferList(input).some((buffer) => metadata2.has(buffer))) {
20024
+ const metadata3 = new Set(getTransferList(options));
20025
+ if (getTransferList(input).some((buffer) => metadata3.has(buffer))) {
18650
20026
  throw new Error("Transferred input aliases reusable options; use inputOwnership: copy");
18651
20027
  }
18652
20028
  }
18653
20029
  }
18654
20030
  var InitializedTask, TaskRunner;
18655
20031
  var init_task_runner = __esm({
18656
- "../../node_modules/@math.gl/core/dist/tasks/task-runner.js"() {
20032
+ "../../node_modules/@math.gl/tasks/dist/tasks/task-runner.js"() {
18657
20033
  init_worker_utils();
18658
20034
  init_task_runtime();
18659
20035
  init_task_sync();
20036
+ init_task_operation_queue();
20037
+ init_task_worker_channel();
20038
+ init_task_channel();
18660
20039
  InitializedTask = class {
18661
20040
  /** @internal Use TaskRunner.initializeTask. */
18662
- constructor(task, release, controls) {
20041
+ constructor(task, release, initializationControls) {
18663
20042
  this.task = task;
18664
20043
  this.release = release;
18665
- this.tail = Promise.resolve();
20044
+ this.initializationControls = initializationControls;
20045
+ this.nextProgressId = 1;
20046
+ this.progressCallbacks = /* @__PURE__ */ new Map();
20047
+ this.callbackFailures = /* @__PURE__ */ new Map();
18666
20048
  this.closed = false;
20049
+ this.finalized = false;
18667
20050
  this.streams = /* @__PURE__ */ new Set();
18668
20051
  this.invalid = false;
18669
20052
  this.controller = new AbortController();
20053
+ const controls = initializationControls;
18670
20054
  this.runtime = new TaskRuntime(task);
20055
+ const concurrency = controls.operationConcurrency ?? 1;
20056
+ const maximum = task.concurrency?.maxConcurrency ?? 1;
20057
+ if (!Number.isSafeInteger(maximum) || maximum < 1 || !Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > maximum) {
20058
+ throw new RangeError("Task concurrency must be between 1 and the task maximum");
20059
+ }
20060
+ this.operationQueue = new TaskOperationQueue(concurrency);
20061
+ this.concurrent = concurrency > 1;
18671
20062
  const execution = controls.execution ?? "auto";
18672
20063
  if (!["auto", "main-thread", "worker"].includes(execution))
18673
20064
  throw new TypeError("Invalid execution mode");
@@ -18677,6 +20068,47 @@ return true;`);
18677
20068
  const target = task.worker;
18678
20069
  if (Boolean(target.url) === Boolean(target.create))
18679
20070
  throw new Error("Supply exactly one worker URL or factory");
20071
+ if (this.concurrent || controls.onRequest || controls.onEvent) {
20072
+ this.workerChannel = new TaskWorkerChannel(task.id, target, {
20073
+ handleRequest: async (operation, payload, signal) => {
20074
+ if (operation === "task:next-input") {
20075
+ if (!this.channelInputs)
20076
+ throw new Error("No active task stream");
20077
+ return this.channelInputs.next();
20078
+ }
20079
+ if (!controls.onRequest)
20080
+ throw new Error("No host request handler configured");
20081
+ const request = payload;
20082
+ if (operation !== "task:host-request")
20083
+ throw new Error("Unknown host request");
20084
+ return controls.onRequest(request.operation, request.payload, signal);
20085
+ },
20086
+ getResultTransferList: (value, request) => request.outputOwnership === "transfer" ? getTransferList(value) : [],
20087
+ handleEvent: (operation, payload) => {
20088
+ const { id } = payload;
20089
+ try {
20090
+ if (operation === "task:progress") {
20091
+ const event = payload;
20092
+ (this.progressCallbacks.get(event.id) ?? this.streamProgress)?.(event.progress);
20093
+ } else if (operation === "task:host-event") {
20094
+ const event = payload;
20095
+ controls.onEvent?.(event.operation, event.payload);
20096
+ }
20097
+ } catch (reason) {
20098
+ if (this.progressCallbacks.has(id) || this.streamProgressId === id) {
20099
+ if (!this.callbackFailures.has(id))
20100
+ this.callbackFailures.set(id, { reason });
20101
+ }
20102
+ }
20103
+ },
20104
+ onFailure: (reason) => {
20105
+ this.invalid = true;
20106
+ this.operationQueue.cancelPending(reason);
20107
+ this.controller.abort(reason);
20108
+ }
20109
+ });
20110
+ return;
20111
+ }
18680
20112
  this.pool = new WorkerPool({
18681
20113
  name: task.id,
18682
20114
  url: target.url?.toString(),
@@ -18688,7 +20120,7 @@ return true;`);
18688
20120
  this.descriptor = {
18689
20121
  id: task.id,
18690
20122
  name: task.id,
18691
- module: "core",
20123
+ module: "tasks",
18692
20124
  version: "prototype",
18693
20125
  options: {},
18694
20126
  worker: target.url?.toString() ?? true,
@@ -18708,23 +20140,48 @@ return true;`);
18708
20140
  }
18709
20141
  }
18710
20142
  runTask(input, ...args) {
18711
- return this.enqueue(async () => {
20143
+ if (this.invalid)
20144
+ return Promise.reject(new Error("Initialized task is invalid; initialize a new instance"));
20145
+ if (this.closed)
20146
+ return Promise.reject(new Error("Initialized task is closed"));
20147
+ const timeout = args[0]?.timeout;
20148
+ if (timeout !== void 0 && (!Number.isSafeInteger(timeout) || timeout < 0 || timeout > 4294967295)) {
20149
+ return Promise.reject(new RangeError("Invalid task timeout"));
20150
+ }
20151
+ const deadline = timeout === void 0 ? void 0 : AbortSignal.timeout(timeout);
20152
+ const signal = deadline && args[0]?.signal ? AbortSignal.any([deadline, args[0].signal]) : deadline ?? args[0]?.signal;
20153
+ const controls = { ...args[0], signal };
20154
+ const mode = this.task.concurrency?.getSchedulingMode?.(input) ?? "exclusive";
20155
+ return this.operationQueue.run(mode, async () => {
20156
+ signal?.throwIfAborted();
18712
20157
  this.checkCapability("atomic");
18713
- return this.invoke("process", input, args[0]?.options ?? {}, args[0]);
18714
- });
20158
+ const invalidate = () => {
20159
+ if (this.concurrent) {
20160
+ this.invalid = true;
20161
+ this.operationQueue.cancelPending(signal?.reason);
20162
+ this.controller.abort(signal?.reason);
20163
+ }
20164
+ };
20165
+ signal?.addEventListener("abort", invalidate, { once: true });
20166
+ try {
20167
+ return await this.invoke("process", input, args[0]?.options ?? {}, controls);
20168
+ } finally {
20169
+ signal?.removeEventListener("abort", invalidate);
20170
+ }
20171
+ }, signal);
18715
20172
  }
18716
20173
  /** Independent calls sharing this instance, always serial and in input order. */
18717
- async *runTasks(inputs, ...args) {
18718
- yield* this.serialStream(async function* (self3) {
20174
+ runTasks(inputs, ...args) {
20175
+ return this.serialStream(async function* (self3) {
18719
20176
  self3.checkCapability("atomic");
18720
20177
  for await (const input of asAsync(inputs, self3.controls(args[0]).signal)) {
18721
20178
  yield await self3.invoke("process", input, args[0]?.options ?? {}, args[0]);
18722
20179
  }
18723
- });
20180
+ }, args[0]?.signal);
18724
20181
  }
18725
20182
  /** One processor invocation for the entire input iterable. */
18726
- async *runTaskInBatches(inputs, ...args) {
18727
- yield* this.serialStream(async function* (self3) {
20183
+ runTaskInBatches(inputs, ...args) {
20184
+ return this.serialStream(async function* (self3) {
18728
20185
  self3.checkCapability("streaming");
18729
20186
  const controls = self3.controls(args[0]);
18730
20187
  const options = clonePayload(args[0]?.options ?? {});
@@ -18737,7 +20194,31 @@ return true;`);
18737
20194
  }
18738
20195
  let completed = false;
18739
20196
  try {
18740
- if (self3.pool) {
20197
+ if (self3.workerChannel) {
20198
+ self3.channelInputs = prepared()[Symbol.asyncIterator]();
20199
+ self3.streamProgress = controls.onProgress;
20200
+ try {
20201
+ await self3.invoke("stream-open", {}, options, controls);
20202
+ while (true) {
20203
+ const result = await self3.invoke("stream-next", {}, {}, controls);
20204
+ if (result.done)
20205
+ break;
20206
+ yield result.value;
20207
+ }
20208
+ } finally {
20209
+ try {
20210
+ if (!self3.invalid)
20211
+ await self3.invoke("stream-close", {}, {}, controls);
20212
+ } finally {
20213
+ await self3.channelInputs.return?.();
20214
+ self3.channelInputs = void 0;
20215
+ self3.streamProgress = void 0;
20216
+ if (self3.streamProgressId !== void 0)
20217
+ self3.callbackFailures.delete(self3.streamProgressId);
20218
+ self3.streamProgressId = void 0;
20219
+ }
20220
+ }
20221
+ } else if (self3.pool) {
18741
20222
  await self3.invoke("stream-options", {}, options, controls);
18742
20223
  yield* processOnWorkerInBatches(self3.descriptor, prepared(), {
18743
20224
  ...self3.workerOptions(controls),
@@ -18745,13 +20226,19 @@ return true;`);
18745
20226
  workerInBatches: true
18746
20227
  });
18747
20228
  } else {
18748
- for await (const output of self3.runtime.stream(prepared(), options, localContext(controls))) {
20229
+ for await (const output of self3.runtime.stream(prepared(), options, self3.runtimeContext(controls))) {
18749
20230
  controls.signal?.throwIfAborted();
18750
20231
  yield clonePayload(output, controls.outputOwnership ?? "transfer");
18751
20232
  }
18752
20233
  }
18753
20234
  completed = true;
18754
20235
  } catch (error) {
20236
+ if (self3.workerChannel) {
20237
+ self3.invalid = true;
20238
+ self3.operationQueue.cancelPending(error);
20239
+ self3.controller.abort(error);
20240
+ await self3.workerChannel.destroy(error);
20241
+ }
18755
20242
  if (self3.pool) {
18756
20243
  self3.invalid = true;
18757
20244
  await self3.pool.destroy(error);
@@ -18760,8 +20247,23 @@ return true;`);
18760
20247
  } finally {
18761
20248
  if (self3.pool && !completed)
18762
20249
  self3.invalid = true;
20250
+ if (self3.workerChannel && !completed && !self3.invalid) {
20251
+ const reason = new Error("Worker stream ended before completion");
20252
+ self3.invalid = true;
20253
+ self3.operationQueue.cancelPending(reason);
20254
+ self3.controller.abort(reason);
20255
+ await self3.workerChannel.destroy(reason);
20256
+ }
18763
20257
  }
18764
- });
20258
+ }, args[0]?.signal);
20259
+ }
20260
+ /** Lifecycle status of this initialized task. */
20261
+ get state() {
20262
+ if (this.invalid)
20263
+ return "invalid";
20264
+ if (this.finalized)
20265
+ return "closed";
20266
+ return this.closed ? "closing" : "ready";
18765
20267
  }
18766
20268
  /** Drain accepted work, invoke destroy, and release execution capacity. */
18767
20269
  close() {
@@ -18769,13 +20271,17 @@ return true;`);
18769
20271
  this.closed = true;
18770
20272
  this.closing = (async () => {
18771
20273
  try {
18772
- await this.tail;
20274
+ await this.operationQueue.close();
18773
20275
  if (!this.invalid)
18774
20276
  await this.invoke("destroy", {}, {});
20277
+ else if (!this.pool && !this.workerChannel)
20278
+ await this.runtime.destroy();
18775
20279
  } finally {
18776
20280
  try {
18777
20281
  await this.pool?.destroy();
20282
+ await this.workerChannel?.destroy();
18778
20283
  } finally {
20284
+ this.finalized = true;
18779
20285
  this.release();
18780
20286
  }
18781
20287
  }
@@ -18785,7 +20291,12 @@ return true;`);
18785
20291
  }
18786
20292
  /** Abort work. Local JavaScript must settle before its state can be destroyed. */
18787
20293
  async terminate(reason = new Error("Task terminated")) {
20294
+ this.operationQueue.cancelPending(reason);
18788
20295
  this.controller.abort(reason);
20296
+ if (this.workerChannel) {
20297
+ this.invalid = true;
20298
+ await this.workerChannel.destroy(reason);
20299
+ }
18789
20300
  if (this.pool) {
18790
20301
  this.invalid = true;
18791
20302
  await this.pool.destroy(reason);
@@ -18794,7 +20305,7 @@ return true;`);
18794
20305
  await this.close();
18795
20306
  }
18796
20307
  checkCapability(kind) {
18797
- if (this.pool ? !this.task.worker?.capabilities[kind] : !(kind === "atomic" ? this.task.process : this.task.processInBatches)) {
20308
+ if (this.pool || this.workerChannel ? !this.task.worker?.capabilities[kind] : !(kind === "atomic" ? this.task.process : this.task.processInBatches)) {
18798
20309
  throw new Error(`Task has no ${kind} processor for this execution route`);
18799
20310
  }
18800
20311
  }
@@ -18825,6 +20336,38 @@ return true;`);
18825
20336
  assertPayload(input);
18826
20337
  assertNoTransferAlias(input, options, prepared.inputOwnership);
18827
20338
  const copiedOptions = clonePayload(options);
20339
+ if (this.workerChannel) {
20340
+ const progressId = this.nextProgressId++;
20341
+ const request = {
20342
+ input: clonePayload(input, prepared.inputOwnership),
20343
+ options: copiedOptions,
20344
+ outputOwnership: prepared.outputOwnership ?? "transfer",
20345
+ progressId
20346
+ };
20347
+ if (operation === "stream-open")
20348
+ this.streamProgressId = progressId;
20349
+ this.progressCallbacks.set(progressId, prepared.onProgress);
20350
+ let callbackFailure;
20351
+ try {
20352
+ const result2 = await this.workerChannel.channel.request(operation, request, prepared.signal, getTransferList(request));
20353
+ callbackFailure = this.callbackFailures.get(progressId) ?? (operation.startsWith("stream-") && this.streamProgressId !== void 0 ? this.callbackFailures.get(this.streamProgressId) : void 0);
20354
+ if (callbackFailure)
20355
+ throw callbackFailure.reason;
20356
+ return result2;
20357
+ } catch (reason) {
20358
+ if (operation === "process" && !prepared.signal?.aborted && (reason instanceof TaskRequestError || callbackFailure))
20359
+ throw reason;
20360
+ this.invalid = true;
20361
+ this.operationQueue.cancelPending(reason);
20362
+ this.controller.abort(reason);
20363
+ await this.workerChannel.destroy(reason);
20364
+ throw reason;
20365
+ } finally {
20366
+ this.progressCallbacks.delete(progressId);
20367
+ if (this.streamProgressId !== progressId)
20368
+ this.callbackFailures.delete(progressId);
20369
+ }
20370
+ }
18828
20371
  if (this.pool) {
18829
20372
  try {
18830
20373
  return await processOnWorker(this.descriptor, { operation, input: clonePayload(input, prepared.inputOwnership), options: copiedOptions }, this.workerOptions({ ...prepared, inputOwnership: "transfer" }));
@@ -18837,7 +20380,7 @@ return true;`);
18837
20380
  if (operation === "destroy")
18838
20381
  return this.runtime.destroy();
18839
20382
  const copied = clonePayload(input, prepared.inputOwnership);
18840
- const context = localContext(prepared);
20383
+ const context = this.runtimeContext(prepared);
18841
20384
  if (operation === "initialize") {
18842
20385
  const result2 = await this.runtime.initialize(copied, context);
18843
20386
  prepared.signal?.throwIfAborted();
@@ -18847,27 +20390,76 @@ return true;`);
18847
20390
  prepared.signal?.throwIfAborted();
18848
20391
  return clonePayload(result, prepared.outputOwnership ?? "transfer");
18849
20392
  }
20393
+ runtimeContext(prepared) {
20394
+ return {
20395
+ ...localContext(prepared),
20396
+ requestHost: async (operation, payload, controls = {}) => {
20397
+ const signal = prepared.signal ?? this.controller.signal;
20398
+ signal.throwIfAborted();
20399
+ const handler = this.initializationControls.onRequest;
20400
+ if (!handler)
20401
+ throw new Error("No host request handler configured");
20402
+ const result = await handler(operation, clonePayload(payload, controls.inputOwnership), signal);
20403
+ signal.throwIfAborted();
20404
+ return structuredClone(result, {
20405
+ transfer: controls.outputOwnership === "transfer" ? getTransferList(result) : []
20406
+ });
20407
+ },
20408
+ emitHost: (operation, payload) => this.initializationControls.onEvent?.(operation, structuredClone(payload))
20409
+ };
20410
+ }
18850
20411
  enqueue(operation) {
18851
20412
  if (this.closed)
18852
20413
  return Promise.reject(new Error("Initialized task is closed"));
18853
- const result = this.tail.then(operation);
18854
- this.tail = result.catch(() => {
20414
+ return this.operationQueue.run("exclusive", operation);
20415
+ }
20416
+ serialStream(operation, signal) {
20417
+ const waiting = new AbortController();
20418
+ const queueSignal = AbortSignal.any([waiting.signal, this.controller.signal, signal].filter((value) => Boolean(value)));
20419
+ let started = false;
20420
+ const iterator = this.acquireStream(operation, queueSignal, () => {
20421
+ started = true;
18855
20422
  });
18856
- return result;
20423
+ const cancelWaiting = () => {
20424
+ if (!started)
20425
+ waiting.abort(new Error("Stream returned before execution"));
20426
+ };
20427
+ return {
20428
+ [Symbol.asyncIterator]() {
20429
+ return this;
20430
+ },
20431
+ next: () => iterator.next(),
20432
+ return: async () => {
20433
+ cancelWaiting();
20434
+ return iterator.return(void 0);
20435
+ },
20436
+ throw: async (reason) => {
20437
+ cancelWaiting();
20438
+ return iterator.throw(reason);
20439
+ }
20440
+ };
18857
20441
  }
18858
- async *serialStream(operation) {
20442
+ async *acquireStream(operation, signal, onStart) {
18859
20443
  if (this.closed)
18860
20444
  throw new Error("Initialized task is closed");
18861
- const before = this.tail;
20445
+ let acquire;
20446
+ const acquired = new Promise((resolve) => {
20447
+ acquire = resolve;
20448
+ });
18862
20449
  let release;
18863
- this.tail = new Promise((resolve) => {
20450
+ const held = new Promise((resolve) => {
18864
20451
  release = resolve;
18865
20452
  });
18866
- await before;
18867
- if (this.controller.signal.aborted) {
20453
+ const lease = this.operationQueue.run("exclusive", async () => {
20454
+ acquire();
20455
+ await held;
20456
+ }, signal);
20457
+ await Promise.race([acquired, lease]);
20458
+ if (signal.aborted) {
18868
20459
  release();
18869
- throw this.controller.signal.reason;
20460
+ throw signal.reason;
18870
20461
  }
20462
+ onStart();
18871
20463
  const iterator = operation(this)[Symbol.asyncIterator]();
18872
20464
  let stopping;
18873
20465
  const stop = () => {
@@ -19108,20 +20700,17 @@ return true;`);
19108
20700
  }
19109
20701
  });
19110
20702
 
19111
- // ../../node_modules/@math.gl/core/dist/tasks/index.js
20703
+ // ../../node_modules/@math.gl/tasks/dist/tasks/index.js
19112
20704
  var init_tasks = __esm({
19113
- "../../node_modules/@math.gl/core/dist/tasks/index.js"() {
20705
+ "../../node_modules/@math.gl/tasks/dist/tasks/index.js"() {
19114
20706
  init_task_runner();
19115
20707
  }
19116
20708
  });
19117
20709
 
19118
- // ../core/src/worker-utils/lib/worker-api/task-runtime.ts
19119
- function normalizeTaskProgress(progress) {
19120
- return { ...progress, phase: progress.phase ?? "process", unit: progress.unit ?? "items" };
19121
- }
19122
- var init_task_runtime2 = __esm({
19123
- "../core/src/worker-utils/lib/worker-api/task-runtime.ts"() {
19124
- "use strict";
20710
+ // ../../node_modules/@math.gl/tasks/dist/index.js
20711
+ var init_dist2 = __esm({
20712
+ "../../node_modules/@math.gl/tasks/dist/index.js"() {
20713
+ init_tasks();
19125
20714
  }
19126
20715
  });
19127
20716
 
@@ -19189,6 +20778,16 @@ return true;`);
19189
20778
  }
19190
20779
  });
19191
20780
 
20781
+ // ../core/src/worker-utils/lib/worker-api/task-runtime.ts
20782
+ function normalizeTaskProgress(progress) {
20783
+ return { ...progress, phase: progress.phase ?? "process", unit: progress.unit ?? "items" };
20784
+ }
20785
+ var init_task_runtime2 = __esm({
20786
+ "../core/src/worker-utils/lib/worker-api/task-runtime.ts"() {
20787
+ "use strict";
20788
+ }
20789
+ });
20790
+
19192
20791
  // ../core/src/worker-utils/lib/worker-utils/get-transfer-list.ts
19193
20792
  function getTransferList2(object, recursive = true, transfers) {
19194
20793
  const transfersSet = transfers || /* @__PURE__ */ new Set();
@@ -19433,7 +21032,7 @@ return true;`);
19433
21032
  var init_process_on_worker2 = __esm({
19434
21033
  "../core/src/worker-utils/lib/worker-api/process-on-worker.ts"() {
19435
21034
  "use strict";
19436
- init_tasks();
21035
+ init_dist2();
19437
21036
  init_get_worker_url2();
19438
21037
  init_task_runtime2();
19439
21038
  init_get_transfer_list2();
@@ -19546,6 +21145,7 @@ return true;`);
19546
21145
  } catch {
19547
21146
  const moduleUrl2 = new URL(moduleLibraryUrl, globalThis.location.href).href;
19548
21147
  const library = await import(
21148
+ /* webpackIgnore: true */
19549
21149
  /* @vite-ignore */
19550
21150
  moduleUrl2
19551
21151
  );
@@ -19784,9 +21384,9 @@ return true;`);
19784
21384
 
19785
21385
  // ../core/src/loader-utils/lib/iterators/text-iterators.ts
19786
21386
  async function* makeTextDecoderIterator(arrayBufferIterator, options = {}) {
19787
- const textDecoder = new TextDecoder(void 0, options);
21387
+ const textDecoder2 = new TextDecoder(void 0, options);
19788
21388
  for await (const arrayBuffer of arrayBufferIterator) {
19789
- yield typeof arrayBuffer === "string" ? arrayBuffer : textDecoder.decode(arrayBuffer, { stream: true });
21389
+ yield typeof arrayBuffer === "string" ? arrayBuffer : textDecoder2.decode(arrayBuffer, { stream: true });
19790
21390
  }
19791
21391
  }
19792
21392
  async function* makeLineIterator(textIterator) {
@@ -21731,6 +23331,35 @@ return true;`);
21731
23331
  out[15] = 1;
21732
23332
  return out;
21733
23333
  }
23334
+ function affineComponents(matrix) {
23335
+ if (matrix.length !== 16 || Array.from(matrix).some((x) => !Number.isFinite(x)) || matrix[3] !== 0 || matrix[7] !== 0 || matrix[11] !== 0 || matrix[15] !== 1) {
23336
+ throw new RangeError("Expected a finite affine matrix");
23337
+ }
23338
+ const scale5 = [
23339
+ Math.hypot(matrix[0], matrix[1], matrix[2]),
23340
+ Math.hypot(matrix[4], matrix[5], matrix[6]),
23341
+ Math.hypot(matrix[8], matrix[9], matrix[10])
23342
+ ];
23343
+ if (scale5.some((x) => x === 0 || !Number.isFinite(x)))
23344
+ throw new RangeError("Singular transform");
23345
+ const rotation = Array.from({ length: 9 }, (_, i) => matrix[Math.floor(i / 3) * 4 + i % 3] / scale5[Math.floor(i / 3)]);
23346
+ for (const [a, b] of [
23347
+ [0, 3],
23348
+ [0, 6],
23349
+ [3, 6]
23350
+ ]) {
23351
+ if (Math.abs(rotation[a] * rotation[b] + rotation[a + 1] * rotation[b + 1] + rotation[a + 2] * rotation[b + 2]) > 1e-7) {
23352
+ throw new RangeError("Sheared transforms do not have a TRS decomposition");
23353
+ }
23354
+ }
23355
+ const determinant3 = rotation[0] * (rotation[4] * rotation[8] - rotation[5] * rotation[7]) - rotation[3] * (rotation[1] * rotation[8] - rotation[2] * rotation[7]) + rotation[6] * (rotation[1] * rotation[5] - rotation[2] * rotation[4]);
23356
+ if (determinant3 < 0) {
23357
+ scale5[0] = -scale5[0];
23358
+ for (let i = 0; i < 3; i++)
23359
+ rotation[i] = -rotation[i];
23360
+ }
23361
+ return { rotation, scale: scale5, translation: [matrix[12], matrix[13], matrix[14]] };
23362
+ }
21734
23363
  var perspective, ortho;
21735
23364
  var init_mat4 = __esm({
21736
23365
  "../../node_modules/@math.gl/core/dist/gl-matrix/mat4.js"() {
@@ -21864,6 +23493,7 @@ return true;`);
21864
23493
  var init_matrix4 = __esm({
21865
23494
  "../../node_modules/@math.gl/core/dist/classes/matrix4.js"() {
21866
23495
  init_matrix();
23496
+ init_mat4();
21867
23497
  init_validators2();
21868
23498
  init_gl_matrix_extras();
21869
23499
  init_mat4();
@@ -22148,27 +23778,15 @@ return true;`);
22148
23778
  * @returns self
22149
23779
  */
22150
23780
  getRotation(result, scaleResult) {
22151
- result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0, -0];
22152
- scaleResult = scaleResult || [-0, -0, -0];
22153
- const scale5 = this.getScale(scaleResult);
22154
- const inverseScale0 = 1 / scale5[0];
22155
- const inverseScale1 = 1 / scale5[1];
22156
- const inverseScale2 = 1 / scale5[2];
22157
- result[0] = this[0] * inverseScale0;
22158
- result[1] = this[1] * inverseScale1;
22159
- result[2] = this[2] * inverseScale2;
22160
- result[3] = 0;
22161
- result[4] = this[4] * inverseScale0;
22162
- result[5] = this[5] * inverseScale1;
22163
- result[6] = this[6] * inverseScale2;
22164
- result[7] = 0;
22165
- result[8] = this[8] * inverseScale0;
22166
- result[9] = this[9] * inverseScale1;
22167
- result[10] = this[10] * inverseScale2;
22168
- result[11] = 0;
22169
- result[12] = 0;
22170
- result[13] = 0;
22171
- result[14] = 0;
23781
+ const { rotation, scale: scale5 } = affineComponents(this);
23782
+ result = result || new Array(16);
23783
+ if (scaleResult)
23784
+ for (let i = 0; i < 3; i++)
23785
+ scaleResult[i] = scale5[i];
23786
+ for (let i = 0; i < 16; i++)
23787
+ result[i] = 0;
23788
+ for (let i = 0; i < 9; i++)
23789
+ result[Math.floor(i / 3) * 4 + i % 3] = rotation[i];
22172
23790
  result[15] = 1;
22173
23791
  return result;
22174
23792
  }
@@ -22179,21 +23797,13 @@ return true;`);
22179
23797
  * @returns self
22180
23798
  */
22181
23799
  getRotationMatrix3(result, scaleResult) {
22182
- result = result || [-0, -0, -0, -0, -0, -0, -0, -0, -0];
22183
- scaleResult = scaleResult || [-0, -0, -0];
22184
- const scale5 = this.getScale(scaleResult);
22185
- const inverseScale0 = 1 / scale5[0];
22186
- const inverseScale1 = 1 / scale5[1];
22187
- const inverseScale2 = 1 / scale5[2];
22188
- result[0] = this[0] * inverseScale0;
22189
- result[1] = this[1] * inverseScale1;
22190
- result[2] = this[2] * inverseScale2;
22191
- result[3] = this[4] * inverseScale0;
22192
- result[4] = this[5] * inverseScale1;
22193
- result[5] = this[6] * inverseScale2;
22194
- result[6] = this[8] * inverseScale0;
22195
- result[7] = this[9] * inverseScale1;
22196
- result[8] = this[10] * inverseScale2;
23800
+ const { rotation, scale: scale5 } = affineComponents(this);
23801
+ result = result || new Array(9);
23802
+ if (scaleResult)
23803
+ for (let i = 0; i < 3; i++)
23804
+ scaleResult[i] = scale5[i];
23805
+ for (let i = 0; i < 9; i++)
23806
+ result[i] = rotation[i];
22197
23807
  return result;
22198
23808
  }
22199
23809
  // Modifiers
@@ -22506,6 +24116,28 @@ return true;`);
22506
24116
  }
22507
24117
  return out;
22508
24118
  }
24119
+ function rotateTowards(out, a, b, step) {
24120
+ if (a.length !== 4 || b.length !== 4 || [...Array.from(a), ...Array.from(b), step].some((x) => !Number.isFinite(x))) {
24121
+ throw new RangeError("Expected finite quaternions and step");
24122
+ }
24123
+ if (a.length !== 4 || step < 0)
24124
+ throw new RangeError("Expected quaternions and a nonnegative step");
24125
+ const aScale = Math.max(...Array.from(a, Math.abs)), bScale = Math.max(...Array.from(b, Math.abs));
24126
+ if (!aScale || !bScale)
24127
+ throw new RangeError("Zero quaternion");
24128
+ const an = Array.from(a, (x) => x / aScale), bn = Array.from(b, (x) => x / bScale);
24129
+ const al = Math.hypot(...an), bl = Math.hypot(...bn);
24130
+ for (let i = 0; i < 4; i++) {
24131
+ an[i] /= al;
24132
+ bn[i] /= bl;
24133
+ }
24134
+ const dot4 = an.reduce((sum, x, i) => sum + x * bn[i], 0);
24135
+ const angle2 = 2 * Math.acos(Math.min(1, Math.abs(dot4)));
24136
+ if (out.length < 4)
24137
+ throw new RangeError("Result buffer is too short");
24138
+ slerp(out, an, bn, angle2 === 0 ? 0 : Math.min(1, step / angle2));
24139
+ return out;
24140
+ }
22509
24141
  var add2, scale4, dot3, lerp2, length3, squaredLength2, normalize3, rotationTo;
22510
24142
  var init_quat = __esm({
22511
24143
  "../../node_modules/@math.gl/core/dist/gl-matrix/quat.js"() {
@@ -22554,6 +24186,7 @@ return true;`);
22554
24186
  var Quaternion;
22555
24187
  var init_quaternion = __esm({
22556
24188
  "../../node_modules/@math.gl/core/dist/classes/quaternion.js"() {
24189
+ init_quat();
22557
24190
  init_math_array();
22558
24191
  init_validators2();
22559
24192
  init_quat();
@@ -22627,6 +24260,9 @@ return true;`);
22627
24260
  return this.check();
22628
24261
  }
22629
24262
  /** Set a quat to the identity quaternion */
24263
+ rotateTowards(target, step) {
24264
+ return rotateTowards(this, this, target, step);
24265
+ }
22630
24266
  identity() {
22631
24267
  identity2(this);
22632
24268
  return this.check();
@@ -22887,7 +24523,7 @@ return true;`);
22887
24523
  });
22888
24524
 
22889
24525
  // ../../node_modules/@math.gl/core/dist/index.js
22890
- var init_dist = __esm({
24526
+ var init_dist3 = __esm({
22891
24527
  "../../node_modules/@math.gl/core/dist/index.js"() {
22892
24528
  init_vector32();
22893
24529
  init_matrix3();
@@ -22993,6 +24629,435 @@ return true;`);
22993
24629
  }
22994
24630
  });
22995
24631
 
24632
+ // ../core/src/schema-utils/lib/schema/convert-arrow-schema.ts
24633
+ function serializeArrowSchema(arrowSchema) {
24634
+ return {
24635
+ fields: arrowSchema.fields.map((arrowField) => serializeArrowField(arrowField)),
24636
+ metadata: serializeArrowMetadata(arrowSchema.metadata)
24637
+ };
24638
+ }
24639
+ function serializeArrowMetadata(arrowMetadata) {
24640
+ return Object.fromEntries(arrowMetadata);
24641
+ }
24642
+ function deserializeArrowMetadata(metadata3) {
24643
+ return metadata3 ? new Map(Object.entries(metadata3)) : /* @__PURE__ */ new Map();
24644
+ }
24645
+ function serializeArrowField(field) {
24646
+ return {
24647
+ name: field.name,
24648
+ type: serializeArrowType(field.type),
24649
+ nullable: field.nullable,
24650
+ metadata: serializeArrowMetadata(field.metadata)
24651
+ };
24652
+ }
24653
+ function deserializeArrowField(field, options) {
24654
+ return new Field2(
24655
+ field.name,
24656
+ deserializeArrowType(field.type, options),
24657
+ field.nullable,
24658
+ deserializeArrowMetadata(field.metadata)
24659
+ );
24660
+ }
24661
+ function serializeArrowType(arrowType) {
24662
+ if (isArrowViewType(arrowType, "BinaryView")) {
24663
+ return "binary-view";
24664
+ }
24665
+ if (isArrowViewType(arrowType, "Utf8View")) {
24666
+ return "utf8-view";
24667
+ }
24668
+ if (isOptionalArrowType(arrowType, "LargeList")) {
24669
+ const largeListType = arrowType;
24670
+ return {
24671
+ type: "large-list",
24672
+ children: [serializeArrowField(largeListType.valueField)]
24673
+ };
24674
+ }
24675
+ switch (arrowType.constructor) {
24676
+ case Null2:
24677
+ return "null";
24678
+ case Binary2:
24679
+ return "binary";
24680
+ case FixedSizeBinary2:
24681
+ return {
24682
+ type: "fixed-size-binary",
24683
+ byteWidth: arrowType.byteWidth
24684
+ };
24685
+ case Bool2:
24686
+ return "bool";
24687
+ case Int_:
24688
+ const intType = arrowType;
24689
+ return `${intType.isSigned ? "" : "u"}int${intType.bitWidth}`;
24690
+ case Int8:
24691
+ return "int8";
24692
+ case Int16:
24693
+ return "int16";
24694
+ case Int32:
24695
+ return "int32";
24696
+ case Int64:
24697
+ return "int64";
24698
+ case Uint8:
24699
+ return "uint8";
24700
+ case Uint16:
24701
+ return "uint16";
24702
+ case Uint32:
24703
+ return "uint32";
24704
+ case Uint64:
24705
+ return "uint64";
24706
+ case Float:
24707
+ const precision = arrowType.precision;
24708
+ switch (precision) {
24709
+ case Precision.HALF:
24710
+ return "float16";
24711
+ case Precision.SINGLE:
24712
+ return "float32";
24713
+ case Precision.DOUBLE:
24714
+ return "float64";
24715
+ default:
24716
+ return "float16";
24717
+ }
24718
+ case Float16:
24719
+ return "float16";
24720
+ case Float32:
24721
+ return "float32";
24722
+ case Float64:
24723
+ return "float64";
24724
+ case Utf82:
24725
+ return "utf8";
24726
+ case Decimal2:
24727
+ const decimal = arrowType;
24728
+ return {
24729
+ type: "decimal",
24730
+ bitWidth: decimal.bitWidth,
24731
+ precision: decimal.precision,
24732
+ scale: decimal.scale
24733
+ };
24734
+ case Date_:
24735
+ const dateUnit = arrowType.unit;
24736
+ return dateUnit === DateUnit.DAY ? "date-day" : "date-millisecond";
24737
+ case DateDay:
24738
+ return "date-day";
24739
+ case DateMillisecond:
24740
+ return "date-millisecond";
24741
+ case Time_:
24742
+ const timeUnit = arrowType.unit;
24743
+ switch (timeUnit) {
24744
+ case TimeUnit.SECOND:
24745
+ return "time-second";
24746
+ case TimeUnit.MILLISECOND:
24747
+ return "time-millisecond";
24748
+ case TimeUnit.MICROSECOND:
24749
+ return "time-microsecond";
24750
+ case TimeUnit.NANOSECOND:
24751
+ return "time-nanosecond";
24752
+ default:
24753
+ return "time-second";
24754
+ }
24755
+ case TimeMillisecond:
24756
+ return "time-millisecond";
24757
+ case TimeSecond:
24758
+ return "time-second";
24759
+ case TimeMicrosecond:
24760
+ return "time-microsecond";
24761
+ case TimeNanosecond:
24762
+ return "time-nanosecond";
24763
+ case Timestamp_:
24764
+ const timeStampUnit = arrowType.unit;
24765
+ switch (timeStampUnit) {
24766
+ case TimeUnit.SECOND:
24767
+ return "timestamp-second";
24768
+ case TimeUnit.MILLISECOND:
24769
+ return "timestamp-millisecond";
24770
+ case TimeUnit.MICROSECOND:
24771
+ return "timestamp-microsecond";
24772
+ case TimeUnit.NANOSECOND:
24773
+ return "timestamp-nanosecond";
24774
+ default:
24775
+ return "timestamp-second";
24776
+ }
24777
+ case TimestampSecond:
24778
+ return "timestamp-second";
24779
+ case TimestampMillisecond:
24780
+ return "timestamp-millisecond";
24781
+ case TimestampMicrosecond:
24782
+ return "timestamp-microsecond";
24783
+ case TimestampNanosecond:
24784
+ return "timestamp-nanosecond";
24785
+ case Interval_:
24786
+ const intervalUnit = arrowType.unit;
24787
+ switch (intervalUnit) {
24788
+ case IntervalUnit.DAY_TIME:
24789
+ return "interval-daytime";
24790
+ case IntervalUnit.YEAR_MONTH:
24791
+ return "interval-yearmonth";
24792
+ default:
24793
+ return "interval-daytime";
24794
+ }
24795
+ case IntervalDayTime:
24796
+ return "interval-daytime";
24797
+ case IntervalYearMonth:
24798
+ return "interval-yearmonth";
24799
+ case Map_:
24800
+ const mapType = arrowType;
24801
+ return {
24802
+ type: "map",
24803
+ keysSorted: mapType.keysSorted,
24804
+ children: mapType.children.map((arrowField) => serializeArrowField(arrowField))
24805
+ };
24806
+ case List2:
24807
+ const listType = arrowType;
24808
+ const listField = listType.valueField;
24809
+ return {
24810
+ type: "list",
24811
+ children: [serializeArrowField(listField)]
24812
+ };
24813
+ case FixedSizeList2:
24814
+ const fixedSizeList = arrowType;
24815
+ return {
24816
+ type: "fixed-size-list",
24817
+ listSize: fixedSizeList.listSize,
24818
+ children: [serializeArrowField(fixedSizeList.children[0])]
24819
+ };
24820
+ case Struct:
24821
+ const structType = arrowType;
24822
+ return {
24823
+ type: "struct",
24824
+ children: structType.children.map((arrowField) => serializeArrowField(arrowField))
24825
+ };
24826
+ case SparseUnion:
24827
+ case DenseUnion:
24828
+ const unionType = arrowType;
24829
+ return {
24830
+ type: unionType instanceof DenseUnion ? "dense-union" : "sparse-union",
24831
+ typeIds: unionType.typeIds,
24832
+ children: unionType.children.map((arrowField) => serializeArrowField(arrowField)),
24833
+ typeIdToChildIndex: { ...unionType.typeIdToChildIndex }
24834
+ };
24835
+ case Dictionary:
24836
+ const dictionaryType = arrowType;
24837
+ return {
24838
+ type: "dictionary",
24839
+ id: dictionaryType.id,
24840
+ indices: serializeArrowDictionaryKeyType(dictionaryType.indices),
24841
+ dictionary: serializeArrowType(dictionaryType.dictionary),
24842
+ isOrdered: dictionaryType.isOrdered
24843
+ };
24844
+ default:
24845
+ throw new Error(`arrow type not supported: ${arrowType.constructor.name}`);
24846
+ }
24847
+ }
24848
+ function deserializeArrowType(dataType, options) {
24849
+ if (typeof dataType === "object") {
24850
+ switch (dataType.type) {
24851
+ case "decimal":
24852
+ return new Decimal2(dataType.scale, dataType.precision, dataType.bitWidth);
24853
+ case "map": {
24854
+ const children = dataType.children.map(
24855
+ (arrowField) => deserializeArrowField(arrowField, options)
24856
+ );
24857
+ return new Map_(children[0], dataType.keysSorted);
24858
+ }
24859
+ case "list": {
24860
+ const field = deserializeArrowField(dataType.children[0], options);
24861
+ return new List2(field);
24862
+ }
24863
+ case "large-list": {
24864
+ const field = deserializeArrowField(dataType.children[0], options);
24865
+ const LargeList3 = getOptionalArrowConstructor("LargeList");
24866
+ if (!LargeList3) {
24867
+ throw new Error(
24868
+ "LargeList requires an Apache Arrow runtime that exports the LargeList constructor"
24869
+ );
24870
+ }
24871
+ return new LargeList3(field);
24872
+ }
24873
+ case "fixed-size-list": {
24874
+ const child = deserializeArrowField(dataType.children[0], options);
24875
+ return new FixedSizeList2(dataType.listSize, child);
24876
+ }
24877
+ case "fixed-size-binary":
24878
+ return new FixedSizeBinary2(dataType.byteWidth);
24879
+ case "struct": {
24880
+ const children = dataType.children.map(
24881
+ (arrowField) => deserializeArrowField(arrowField, options)
24882
+ );
24883
+ return new Struct(children);
24884
+ }
24885
+ case "sparse-union":
24886
+ case "dense-union": {
24887
+ const children = dataType.children.map(
24888
+ (arrowField) => deserializeArrowField(arrowField, options)
24889
+ );
24890
+ return dataType.type === "dense-union" ? new DenseUnion(dataType.typeIds, children) : new SparseUnion(dataType.typeIds, children);
24891
+ }
24892
+ case "dictionary": {
24893
+ return new Dictionary(
24894
+ deserializeArrowType(dataType.dictionary, options),
24895
+ deserializeArrowDictionaryKeyType(dataType.indices),
24896
+ dataType.id,
24897
+ dataType.isOrdered
24898
+ );
24899
+ }
24900
+ default:
24901
+ throw new Error("array type not supported");
24902
+ }
24903
+ }
24904
+ switch (dataType) {
24905
+ case "null":
24906
+ return new Null2();
24907
+ case "binary":
24908
+ return makeVariableWidthArrowType("BinaryView", new Binary2(), options);
24909
+ case "binary-view":
24910
+ return makeRequiredArrowViewType("BinaryView");
24911
+ case "bool":
24912
+ return new Bool2();
24913
+ case "int8":
24914
+ return new Int8();
24915
+ case "int16":
24916
+ return new Int16();
24917
+ case "int32":
24918
+ return new Int32();
24919
+ case "int64":
24920
+ return new Int64();
24921
+ case "uint8":
24922
+ return new Uint8();
24923
+ case "uint16":
24924
+ return new Uint16();
24925
+ case "uint32":
24926
+ return new Uint32();
24927
+ case "uint64":
24928
+ return new Uint64();
24929
+ case "float16":
24930
+ return new Float16();
24931
+ case "float32":
24932
+ return new Float32();
24933
+ case "float64":
24934
+ return new Float64();
24935
+ case "utf8":
24936
+ return makeVariableWidthArrowType("Utf8View", new Utf82(), options);
24937
+ case "utf8-view":
24938
+ return makeRequiredArrowViewType("Utf8View");
24939
+ case "date-day":
24940
+ return new DateDay();
24941
+ case "date-millisecond":
24942
+ return new DateMillisecond();
24943
+ case "time-second":
24944
+ return new TimeSecond();
24945
+ case "time-millisecond":
24946
+ return new TimeMillisecond();
24947
+ case "time-microsecond":
24948
+ return new TimeMicrosecond();
24949
+ case "time-nanosecond":
24950
+ return new TimeNanosecond();
24951
+ case "timestamp-second":
24952
+ return new TimestampSecond();
24953
+ case "timestamp-millisecond":
24954
+ return new TimestampMillisecond();
24955
+ case "timestamp-microsecond":
24956
+ return new TimestampMicrosecond();
24957
+ case "timestamp-nanosecond":
24958
+ return new TimestampNanosecond();
24959
+ case "interval-daytime":
24960
+ return new IntervalDayTime();
24961
+ case "interval-yearmonth":
24962
+ return new IntervalYearMonth();
24963
+ default:
24964
+ throw new Error("array type not supported");
24965
+ }
24966
+ }
24967
+ function getOptionalArrowConstructor(typeName) {
24968
+ return Arrow_dom_exports[typeName];
24969
+ }
24970
+ function isArrowViewType(arrowType, viewTypeName) {
24971
+ const constructor = getOptionalArrowConstructor(viewTypeName);
24972
+ if (constructor && arrowType instanceof constructor) {
24973
+ return true;
24974
+ }
24975
+ const guards = DataType;
24976
+ const guard = viewTypeName === "BinaryView" ? guards.isBinaryView : guards.isUtf8View;
24977
+ return Boolean(guard?.(arrowType));
24978
+ }
24979
+ function isOptionalArrowType(arrowType, typeName) {
24980
+ const constructor = getOptionalArrowConstructor(typeName);
24981
+ return Boolean(constructor && arrowType instanceof constructor);
24982
+ }
24983
+ function makeVariableWidthArrowType(viewTypeName, fallbackType, options) {
24984
+ const viewTypeMode = options?.viewTypes || "never";
24985
+ if (viewTypeMode === "never") {
24986
+ return fallbackType;
24987
+ }
24988
+ const constructor = getOptionalArrowConstructor(viewTypeName);
24989
+ if (constructor) {
24990
+ return new constructor();
24991
+ }
24992
+ if (viewTypeMode === "require") {
24993
+ throw new Error(
24994
+ `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
24995
+ );
24996
+ }
24997
+ return fallbackType;
24998
+ }
24999
+ function makeRequiredArrowViewType(viewTypeName) {
25000
+ const constructor = getOptionalArrowConstructor(viewTypeName);
25001
+ if (!constructor) {
25002
+ throw new Error(
25003
+ `${viewTypeName} requires apache-arrow 21.2.0 or later; the installed runtime does not support it`
25004
+ );
25005
+ }
25006
+ return new constructor();
25007
+ }
25008
+ function serializeArrowDictionaryKeyType(arrowType) {
25009
+ if (arrowType instanceof Int_) {
25010
+ const prefix = arrowType.isSigned ? "int" : "uint";
25011
+ const keyType = `${prefix}${arrowType.bitWidth}`;
25012
+ if (isSchemaDictionaryKeyType(keyType)) {
25013
+ return keyType;
25014
+ }
25015
+ }
25016
+ switch (arrowType.constructor) {
25017
+ case Int8:
25018
+ return "int8";
25019
+ case Int16:
25020
+ return "int16";
25021
+ case Int32:
25022
+ return "int32";
25023
+ case Uint8:
25024
+ return "uint8";
25025
+ case Uint16:
25026
+ return "uint16";
25027
+ case Uint32:
25028
+ return "uint32";
25029
+ default:
25030
+ throw new Error(`arrow dictionary index type not supported: ${arrowType.constructor.name}`);
25031
+ }
25032
+ }
25033
+ function isSchemaDictionaryKeyType(keyType) {
25034
+ return ["int8", "int16", "int32", "uint8", "uint16", "uint32"].includes(keyType);
25035
+ }
25036
+ function deserializeArrowDictionaryKeyType(keyType) {
25037
+ switch (keyType) {
25038
+ case "int8":
25039
+ return new Int8();
25040
+ case "int16":
25041
+ return new Int16();
25042
+ case "int32":
25043
+ return new Int32();
25044
+ case "uint8":
25045
+ return new Uint8();
25046
+ case "uint16":
25047
+ return new Uint16();
25048
+ case "uint32":
25049
+ return new Uint32();
25050
+ default:
25051
+ throw new Error(`schema dictionary index type not supported: ${keyType}`);
25052
+ }
25053
+ }
25054
+ var init_convert_arrow_schema = __esm({
25055
+ "../core/src/schema-utils/lib/schema/convert-arrow-schema.ts"() {
25056
+ "use strict";
25057
+ init_Arrow_dom();
25058
+ }
25059
+ });
25060
+
22996
25061
  // ../core/src/schema-utils/lib/mesh/mesh-utils.ts
22997
25062
  function getMeshBoundingBox(attributes) {
22998
25063
  const positionAttribute = attributes?.POSITION;
@@ -23094,7 +25159,7 @@ return true;`);
23094
25159
  var init_float162 = __esm({
23095
25160
  "../core/src/schema/float16.ts"() {
23096
25161
  "use strict";
23097
- init_dist();
25162
+ init_dist3();
23098
25163
  }
23099
25164
  });
23100
25165
 
@@ -23273,22 +25338,22 @@ return true;`);
23273
25338
  if (!suppliedField?.metadata) {
23274
25339
  return canonicalField;
23275
25340
  }
23276
- const metadata2 = new Map(canonicalField.metadata);
25341
+ const metadata3 = new Map(canonicalField.metadata);
23277
25342
  for (const [key, value] of Object.entries(suppliedField.metadata)) {
23278
- metadata2.set(key, value);
25343
+ metadata3.set(key, value);
23279
25344
  }
23280
25345
  return new Field2(
23281
25346
  canonicalField.name,
23282
25347
  canonicalField.type,
23283
25348
  canonicalField.nullable,
23284
- metadata2
25349
+ metadata3
23285
25350
  );
23286
25351
  }
23287
25352
  const field = schema?.fields.find((schemaField) => schemaField.name === attributeName);
23288
25353
  if (componentType === "float16") {
23289
- const metadata2 = new Map(Object.entries(field?.metadata || {}));
23290
- metadata2.set("componentType", "float16");
23291
- return new Field2(attributeName, column.type, false, metadata2);
25354
+ const metadata3 = new Map(Object.entries(field?.metadata || {}));
25355
+ metadata3.set("componentType", "float16");
25356
+ return new Field2(attributeName, column.type, false, metadata3);
23292
25357
  }
23293
25358
  if (field && field.type.toString() !== column.type.toString()) {
23294
25359
  const deserializedField = deserializeArrowField(field);
@@ -23336,17 +25401,17 @@ return true;`);
23336
25401
  return new Vector([indicesData]);
23337
25402
  }
23338
25403
  function getMeshArrowMetadata(options) {
23339
- const metadata2 = { ...options.schema?.metadata };
25404
+ const metadata3 = { ...options.schema?.metadata };
23340
25405
  if (options.topology) {
23341
- metadata2.topology ||= options.topology;
25406
+ metadata3.topology ||= options.topology;
23342
25407
  }
23343
25408
  if (Number.isFinite(options.mode)) {
23344
- metadata2.mode ||= String(options.mode);
25409
+ metadata3.mode ||= String(options.mode);
23345
25410
  }
23346
25411
  if (options.boundingBox) {
23347
- metadata2.boundingBox ||= JSON.stringify(options.boundingBox);
25412
+ metadata3.boundingBox ||= JSON.stringify(options.boundingBox);
23348
25413
  }
23349
- return deserializeArrowMetadata(metadata2);
25414
+ return deserializeArrowMetadata(metadata3);
23350
25415
  }
23351
25416
  var MESH_ARROW_ATTRIBUTE_ORDER;
23352
25417
  var init_convert_mesh_to_table = __esm({
@@ -23386,15 +25451,15 @@ return true;`);
23386
25451
  const attributeData = arrowTable.getChild(name22);
23387
25452
  const size = getFixedSizeListSize(attributeData);
23388
25453
  const typedArray = getAttributeTypedArray(attributeData, size);
23389
- const metadata2 = getMeshAttributeMetadata(field.metadata);
23390
- const value = metadata2.componentType === "float16" ? restoreFloat16Array(typedArray) : typedArray;
25454
+ const metadata3 = getMeshAttributeMetadata(field.metadata);
25455
+ const value = metadata3.componentType === "float16" ? restoreFloat16Array(typedArray) : typedArray;
23391
25456
  const shared = columns.find(
23392
25457
  (column) => column.data.length === attributeData.data.length && attributes[column.name].value.constructor === value.constructor && column.data.every((chunk, index) => shareArrowStorage(chunk, attributeData.data[index]))
23393
25458
  );
23394
25459
  attributes[name22] = {
23395
25460
  value: shared ? attributes[shared.name].value : value,
23396
25461
  size,
23397
- ...metadata2
25462
+ ...metadata3
23398
25463
  };
23399
25464
  if (!shared) columns.push({ name: name22, data: attributeData.data });
23400
25465
  }
@@ -23431,23 +25496,23 @@ return true;`);
23431
25496
  }
23432
25497
  return null;
23433
25498
  }
23434
- function getMeshAttributeMetadata(metadata2 = {}) {
25499
+ function getMeshAttributeMetadata(metadata3 = {}) {
23435
25500
  const result = {};
23436
- if (metadata2.byteOffset !== void 0) {
23437
- result.byteOffset = Number(metadata2.byteOffset);
25501
+ if (metadata3.byteOffset !== void 0) {
25502
+ result.byteOffset = Number(metadata3.byteOffset);
23438
25503
  }
23439
- if (metadata2.byteStride !== void 0) {
23440
- result.byteStride = Number(metadata2.byteStride);
25504
+ if (metadata3.byteStride !== void 0) {
25505
+ result.byteStride = Number(metadata3.byteStride);
23441
25506
  }
23442
- if (metadata2.normalized !== void 0) {
23443
- result.normalized = metadata2.normalized === "true";
25507
+ if (metadata3.normalized !== void 0) {
25508
+ result.normalized = metadata3.normalized === "true";
23444
25509
  }
23445
- if (metadata2.componentType === "float16") {
25510
+ if (metadata3.componentType === "float16") {
23446
25511
  result.componentType = "float16";
23447
25512
  }
23448
- if (metadata2["loaders.gl.transform"]) {
25513
+ if (metadata3["loaders.gl.transform"]) {
23449
25514
  try {
23450
- const transform = JSON.parse(metadata2["loaders.gl.transform"]);
25515
+ const transform = JSON.parse(metadata3["loaders.gl.transform"]);
23451
25516
  if (isMeshAttributeTransform(transform)) {
23452
25517
  result.transform = transform;
23453
25518
  }
@@ -23534,17 +25599,29 @@ return true;`);
23534
25599
  });
23535
25600
 
23536
25601
  // ../core/src/schema-utils/lib/mesh/deduce-mesh-schema.ts
25602
+ function deduceMeshSchema(attributes, metadata3 = {}) {
25603
+ const fields = deduceMeshFields(attributes);
25604
+ return { fields, metadata: metadata3 };
25605
+ }
23537
25606
  function deduceMeshField(name22, attribute, optionalMetadata) {
23538
25607
  const type = attribute.componentType || getDataTypeFromTypedArray(attribute.value);
23539
- const metadata2 = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
25608
+ const metadata3 = optionalMetadata ? optionalMetadata : makeMeshAttributeMetadata(attribute);
23540
25609
  const dataType = attribute.size === 1 ? type : { type: "fixed-size-list", listSize: attribute.size, children: [{ name: "value", type }] };
23541
25610
  return {
23542
25611
  name: name22,
23543
25612
  type: dataType,
23544
25613
  nullable: false,
23545
- metadata: metadata2
25614
+ metadata: metadata3
23546
25615
  };
23547
25616
  }
25617
+ function deduceMeshFields(attributes) {
25618
+ const fields = [];
25619
+ for (const attributeName in attributes) {
25620
+ const attribute = attributes[attributeName];
25621
+ fields.push(deduceMeshField(attributeName, attribute));
25622
+ }
25623
+ return fields;
25624
+ }
23548
25625
  function makeMeshAttributeMetadata(attribute) {
23549
25626
  const result = {};
23550
25627
  if ("byteOffset" in attribute) {
@@ -23584,11 +25661,11 @@ return true;`);
23584
25661
  });
23585
25662
 
23586
25663
  // src/obj/lib/get-obj-schema.ts
23587
- function getOBJSchema(attributes, metadata2 = {}) {
25664
+ function getOBJSchema(attributes, metadata3 = {}) {
23588
25665
  const stringMetadata = {};
23589
- for (const key in metadata2) {
25666
+ for (const key in metadata3) {
23590
25667
  if (key !== "value") {
23591
- stringMetadata[key] = JSON.stringify(metadata2[key]);
25668
+ stringMetadata[key] = JSON.stringify(metadata3[key]);
23592
25669
  }
23593
25670
  }
23594
25671
  const fields = [];
@@ -23600,10 +25677,10 @@ return true;`);
23600
25677
  return { fields, metadata: stringMetadata };
23601
25678
  }
23602
25679
  function getFieldFromAttribute(name22, attribute) {
23603
- const metadata2 = {};
25680
+ const metadata3 = {};
23604
25681
  for (const key in attribute) {
23605
25682
  if (key !== "value") {
23606
- metadata2[key] = JSON.stringify(attribute[key]);
25683
+ metadata3[key] = JSON.stringify(attribute[key]);
23607
25684
  }
23608
25685
  }
23609
25686
  let { type } = getDataTypeFromArray(attribute.value);
@@ -23611,7 +25688,7 @@ return true;`);
23611
25688
  if (!isSingleValue) {
23612
25689
  type = { type: "fixed-size-list", listSize: attribute.size, children: [{ name: "values", type }] };
23613
25690
  }
23614
- return { name: name22, type, nullable: false, metadata: metadata2 };
25691
+ return { name: name22, type, nullable: false, metadata: metadata3 };
23615
25692
  }
23616
25693
  var init_get_obj_schema = __esm({
23617
25694
  "src/obj/lib/get-obj-schema.ts"() {
@@ -24165,7 +26242,7 @@ return true;`);
24165
26242
  "src/obj/obj-loader.ts"() {
24166
26243
  "use strict";
24167
26244
  init_loader_utils();
24168
- init_arrow_transport();
26245
+ init_arrow_worker_transport();
24169
26246
  init_schema_utils();
24170
26247
  init_get_obj_schema();
24171
26248
  init_parse_obj();
@@ -24224,7 +26301,7 @@ return true;`);
24224
26301
  "src/obj/obj-loader-types.ts"() {
24225
26302
  "use strict";
24226
26303
  init_obj_format();
24227
- init_arrow_transport();
26304
+ init_arrow_worker_transport();
24228
26305
  VERSION4 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
24229
26306
  OBJLoader = {
24230
26307
  ...OBJFormat,
@@ -24666,8 +26743,8 @@ return true;`);
24666
26743
  }
24667
26744
  function getBlobOrSVGDataUrl(arrayBuffer, url) {
24668
26745
  if (isSVG(url)) {
24669
- const textDecoder = new TextDecoder();
24670
- let xmlText = textDecoder.decode(arrayBuffer);
26746
+ const textDecoder2 = new TextDecoder();
26747
+ let xmlText = textDecoder2.decode(arrayBuffer);
24671
26748
  try {
24672
26749
  if (typeof unescape === "function" && typeof encodeURIComponent === "function") {
24673
26750
  xmlText = unescape(encodeURIComponent(xmlText));
@@ -26127,8 +28204,8 @@ return true;`);
26127
28204
  }
26128
28205
  function parseJSONChunk(glb, dataView, byteOffset, chunkLength2, chunkIndex) {
26129
28206
  const jsonChunk = new Uint8Array(dataView.buffer, byteOffset, chunkLength2);
26130
- const textDecoder = new TextDecoder("utf8");
26131
- const jsonText = textDecoder.decode(jsonChunk);
28207
+ const textDecoder2 = new TextDecoder("utf8");
28208
+ const jsonText = textDecoder2.decode(jsonChunk);
26132
28209
  glb.json = JSON.parse(jsonText);
26133
28210
  glb.jsonChunkIndex = chunkIndex;
26134
28211
  return padToFourBytes(chunkLength2);
@@ -26913,8 +28990,8 @@ return true;`);
26913
28990
  * @param mimeType
26914
28991
  */
26915
28992
  addImage(imageData, mimeTypeOpt) {
26916
- const metadata2 = getBinaryImageMetadata(imageData);
26917
- const mimeType = mimeTypeOpt || metadata2?.mimeType;
28993
+ const metadata3 = getBinaryImageMetadata(imageData);
28994
+ const mimeType = mimeTypeOpt || metadata3?.mimeType;
26918
28995
  const bufferViewIndex = this.addBufferView(imageData);
26919
28996
  const glTFImage = {
26920
28997
  bufferView: bufferViewIndex,
@@ -27773,8 +29850,8 @@ return true;`);
27773
29850
  }
27774
29851
  /** Return the loaded buffer companion for a raw buffer definition. */
27775
29852
  getLoadedBuffer(buffer) {
27776
- const metadata2 = this.getMetadata(buffer);
27777
- return this.gltf.buffers[metadata2.index];
29853
+ const metadata3 = this.getMetadata(buffer);
29854
+ return this.gltf.buffers[metadata3.index];
27778
29855
  }
27779
29856
  /** Return the loaded byte range for a raw buffer-view definition. */
27780
29857
  getLoadedBufferView(bufferView) {
@@ -28321,7 +30398,7 @@ return true;`);
28321
30398
  return attributeValueArray;
28322
30399
  }
28323
30400
  function getPropertyDataString(numberOfElements, valuesDataBytes, arrayOffsets, stringOffsets, fixedArrayCount) {
28324
- const textDecoder = new TextDecoder("utf8");
30401
+ const textDecoder2 = new TextDecoder("utf8");
28325
30402
  if (arrayOffsets) {
28326
30403
  if (!stringOffsets) {
28327
30404
  throw new Error("stringOffsets is required for variable-length string arrays");
@@ -28335,7 +30412,7 @@ return true;`);
28335
30412
  const startByte = stringOffsets[stringIndex];
28336
30413
  const endByte = stringOffsets[stringIndex + 1];
28337
30414
  const stringData = valuesDataBytes.subarray(startByte, endByte);
28338
- strings.push(textDecoder.decode(stringData));
30415
+ strings.push(textDecoder2.decode(stringData));
28339
30416
  }
28340
30417
  result.push(strings);
28341
30418
  }
@@ -28348,7 +30425,7 @@ return true;`);
28348
30425
  const startByte = Number(stringOffsets[index]);
28349
30426
  const endByte = Number(stringOffsets[index + 1]);
28350
30427
  if (startByte >= 0 && endByte >= startByte && endByte <= valuesDataBytes.length) {
28351
- stringsArray.push(textDecoder.decode(valuesDataBytes.subarray(startByte, endByte)));
30428
+ stringsArray.push(textDecoder2.decode(valuesDataBytes.subarray(startByte, endByte)));
28352
30429
  }
28353
30430
  }
28354
30431
  return fixedArrayCount ? Array.from(
@@ -29238,19 +31315,26 @@ return true;`);
29238
31315
  for (const [primitiveIndex, primitive] of mesh.primitives.entries()) {
29239
31316
  const extension = primitive.extensions?.[name4];
29240
31317
  if (!extension) continue;
31318
+ const descriptor = descriptors.find(
31319
+ (item) => item.meshIndex === meshIndex && item.primitiveIndex === primitiveIndex
31320
+ );
31321
+ const legacyColorSpace = options?.gltf?.legacyGaussianSplatColorSpace;
31322
+ const normalizedExtension = legacyColorSpace && extension.extensions?.[SPZ_COMPRESSION_EXTENSION_NAME] ? {
31323
+ ...extension,
31324
+ kernel: extension.kernel ?? "ellipse",
31325
+ colorSpace: extension.colorSpace ?? legacyColorSpace
31326
+ } : extension;
31327
+ if (descriptor) descriptor.extension = normalizedExtension;
29241
31328
  validateGaussianSplatPrimitive(
29242
31329
  gltfData.json,
29243
31330
  primitive,
29244
- extension,
31331
+ normalizedExtension,
29245
31332
  meshIndex,
29246
31333
  primitiveIndex,
29247
31334
  iterator
29248
31335
  );
29249
31336
  const compression = extension.extensions?.[SPZ_COMPRESSION_EXTENSION_NAME];
29250
31337
  if (compression) {
29251
- const descriptor = descriptors.find(
29252
- (item) => item.meshIndex === meshIndex && item.primitiveIndex === primitiveIndex
29253
- );
29254
31338
  if (descriptor) {
29255
31339
  const decoder2 = options?.gltf?.splatDecoder;
29256
31340
  const bufferView = gltfData.json.bufferViews?.[compression.bufferView];
@@ -30807,7 +32891,7 @@ return true;`);
30807
32891
 
30808
32892
  // src/draco/lib/utils/get-draco-schema.ts
30809
32893
  function getDracoSchema(attributes, loaderData, indices) {
30810
- const metadata2 = makeMetadata(loaderData.metadata);
32894
+ const metadata3 = makeMetadata(loaderData.metadata);
30811
32895
  const fields = [];
30812
32896
  const namedLoaderDataAttributes = transformAttributesLoaderData(loaderData.attributes);
30813
32897
  for (const attributeName in attributes) {
@@ -30823,7 +32907,7 @@ return true;`);
30823
32907
  const indicesField = getArrowFieldFromAttribute("indices", indices);
30824
32908
  fields.push(indicesField);
30825
32909
  }
30826
- return { fields, metadata: metadata2 };
32910
+ return { fields, metadata: metadata3 };
30827
32911
  }
30828
32912
  function transformAttributesLoaderData(loaderData) {
30829
32913
  const result = {};
@@ -30841,11 +32925,11 @@ return true;`);
30841
32925
  const field = deduceMeshField(attributeName, attribute, metadataMap);
30842
32926
  return field;
30843
32927
  }
30844
- function makeMetadata(metadata2) {
30845
- Object.entries(metadata2);
32928
+ function makeMetadata(metadata3) {
32929
+ Object.entries(metadata3);
30846
32930
  const serializedMetadata = {};
30847
- for (const key in metadata2) {
30848
- serializedMetadata[`${key}.string`] = JSON.stringify(metadata2[key]);
32931
+ for (const key in metadata3) {
32932
+ serializedMetadata[`${key}.string`] = JSON.stringify(metadata3[key]);
30849
32933
  }
30850
32934
  return serializedMetadata;
30851
32935
  }
@@ -31062,14 +33146,14 @@ return true;`);
31062
33146
  * @returns
31063
33147
  */
31064
33148
  _getDracoLoaderData(dracoGeometry, geometry_type, options) {
31065
- const metadata2 = this._getTopLevelMetadata(dracoGeometry);
33149
+ const metadata3 = this._getTopLevelMetadata(dracoGeometry);
31066
33150
  const attributes = this._getDracoAttributes(dracoGeometry, options);
31067
33151
  return {
31068
33152
  geometry_type,
31069
33153
  num_attributes: dracoGeometry.num_attributes(),
31070
33154
  num_points: dracoGeometry.num_points(),
31071
33155
  num_faces: dracoGeometry instanceof this.draco.Mesh ? dracoGeometry.num_faces() : 0,
31072
- metadata: metadata2,
33156
+ metadata: metadata3,
31073
33157
  attributes
31074
33158
  };
31075
33159
  }
@@ -31083,7 +33167,7 @@ return true;`);
31083
33167
  const dracoAttributes = {};
31084
33168
  for (let attributeId = 0; attributeId < dracoGeometry.num_attributes(); attributeId++) {
31085
33169
  const dracoAttribute = this.decoder.GetAttribute(dracoGeometry, attributeId);
31086
- const metadata2 = this._getAttributeMetadata(dracoGeometry, attributeId);
33170
+ const metadata3 = this._getAttributeMetadata(dracoGeometry, attributeId);
31087
33171
  dracoAttributes[dracoAttribute.unique_id()] = {
31088
33172
  unique_id: dracoAttribute.unique_id(),
31089
33173
  attribute_type: dracoAttribute.attribute_type(),
@@ -31093,7 +33177,7 @@ return true;`);
31093
33177
  byte_stride: dracoAttribute.byte_stride(),
31094
33178
  normalized: dracoAttribute.normalized(),
31095
33179
  attribute_index: attributeId,
31096
- metadata: metadata2
33180
+ metadata: metadata3
31097
33181
  };
31098
33182
  const quantization = this._getQuantizationTransform(dracoAttribute, options);
31099
33183
  if (quantization) {
@@ -31604,7 +33688,7 @@ return true;`);
31604
33688
  var init_draco_loader_types = __esm({
31605
33689
  "src/draco/draco-loader-types.ts"() {
31606
33690
  "use strict";
31607
- init_arrow_transport();
33691
+ init_arrow_worker_transport();
31608
33692
  init_version5();
31609
33693
  init_draco_format();
31610
33694
  init_draco_loader_options();
@@ -32038,7 +34122,7 @@ return true;`);
32038
34122
  var init_KHR_texture_transform = __esm({
32039
34123
  "src/gltf/lib/extensions/KHR_texture_transform.ts"() {
32040
34124
  "use strict";
32041
- init_dist();
34125
+ init_dist3();
32042
34126
  init_gltf_utils();
32043
34127
  init_gltf_constants();
32044
34128
  init_gltf_iterator();
@@ -32176,10 +34260,10 @@ return true;`);
32176
34260
  }
32177
34261
  function resolveTechniques(techniquesExtension, iterator) {
32178
34262
  const { programs = [], shaders = [], techniques = [] } = techniquesExtension;
32179
- const textDecoder = new TextDecoder();
34263
+ const textDecoder2 = new TextDecoder();
32180
34264
  shaders.forEach((shader) => {
32181
34265
  if (Number.isFinite(shader.bufferView)) {
32182
- shader.code = textDecoder.decode(
34266
+ shader.code = textDecoder2.decode(
32183
34267
  getTypedArrayForBufferView(iterator.data, iterator.gltf.buffers, shader.bufferView)
32184
34268
  );
32185
34269
  } else {
@@ -34090,7 +36174,7 @@ return true;`);
34090
36174
  var init_convert_gltf_v1_matrix_nodes = __esm({
34091
36175
  "src/gltf/lib/api/convert-gltf-v1-matrix-nodes.ts"() {
34092
36176
  "use strict";
34093
- init_dist();
36177
+ init_dist3();
34094
36178
  }
34095
36179
  });
34096
36180
 
@@ -34805,8 +36889,8 @@ return true;`);
34805
36889
  gltf.baseUri = options.core?.baseUrl;
34806
36890
  }
34807
36891
  if (data instanceof ArrayBuffer && !isGLB(data, byteOffset, options.glb)) {
34808
- const textDecoder = new TextDecoder();
34809
- data = textDecoder.decode(data);
36892
+ const textDecoder2 = new TextDecoder();
36893
+ data = textDecoder2.decode(data);
34810
36894
  }
34811
36895
  if (typeof data === "string") {
34812
36896
  gltf.json = parseJSON(data);
@@ -35791,9 +37875,9 @@ return true;`);
35791
37875
  * @param dracoGeometry - WASM Draco Object
35792
37876
  * @param metadata
35793
37877
  */
35794
- _addGeometryMetadata(dracoGeometry, metadata2) {
37878
+ _addGeometryMetadata(dracoGeometry, metadata3) {
35795
37879
  const dracoMetadata = new this.draco.Metadata();
35796
- this._populateDracoMetadata(dracoMetadata, metadata2);
37880
+ this._populateDracoMetadata(dracoMetadata, metadata3);
35797
37881
  this.dracoMeshBuilder.AddMetadata(dracoGeometry, dracoMetadata);
35798
37882
  }
35799
37883
  /**
@@ -35802,9 +37886,9 @@ return true;`);
35802
37886
  * @param uniqueAttributeId
35803
37887
  * @param metadata
35804
37888
  */
35805
- _addAttributeMetadata(dracoGeometry, uniqueAttributeId, metadata2) {
37889
+ _addAttributeMetadata(dracoGeometry, uniqueAttributeId, metadata3) {
35806
37890
  const dracoAttributeMetadata = new this.draco.Metadata();
35807
- this._populateDracoMetadata(dracoAttributeMetadata, metadata2);
37891
+ this._populateDracoMetadata(dracoAttributeMetadata, metadata3);
35808
37892
  this.dracoMeshBuilder.SetMetadataForAttribute(
35809
37893
  dracoGeometry,
35810
37894
  uniqueAttributeId,
@@ -35816,8 +37900,8 @@ return true;`);
35816
37900
  * @param dracoMetadata - WASM Draco Object
35817
37901
  * @param metadata
35818
37902
  */
35819
- _populateDracoMetadata(dracoMetadata, metadata2) {
35820
- for (const [key, value] of getEntries(metadata2)) {
37903
+ _populateDracoMetadata(dracoMetadata, metadata3) {
37904
+ for (const [key, value] of getEntries(metadata3)) {
35821
37905
  switch (typeof value) {
35822
37906
  case "number":
35823
37907
  if (Math.trunc(value) === value) {
@@ -37778,6 +39862,129 @@ Actual: ${this.attribValue}`
37778
39862
  }
37779
39863
  });
37780
39864
 
39865
+ // src/stl/parse-stl.ts
39866
+ function parseSTL(data) {
39867
+ const view = new DataView(data);
39868
+ const binary = data.byteLength >= 84 && 84 + view.getUint32(80, true) * 50 === data.byteLength;
39869
+ let positions;
39870
+ let normals;
39871
+ let header;
39872
+ if (binary) {
39873
+ const triangleCount = view.getUint32(80, true);
39874
+ positions = new Float32Array(triangleCount * 9);
39875
+ normals = new Float32Array(triangleCount * 9);
39876
+ header = new TextDecoder().decode(data.slice(0, 80));
39877
+ for (let triangle = 0; triangle < triangleCount; triangle++) {
39878
+ const offset = 84 + triangle * 50;
39879
+ for (let component = 0; component < 9; component++) {
39880
+ positions[triangle * 9 + component] = view.getFloat32(offset + 12 + component * 4, true);
39881
+ normals[triangle * 9 + component] = view.getFloat32(offset + component % 3 * 4, true);
39882
+ }
39883
+ }
39884
+ } else {
39885
+ const lines = new TextDecoder().decode(data).trim().split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
39886
+ const vertices = [];
39887
+ const normalValues = [];
39888
+ header = lines[0] || "";
39889
+ let lineIndex = 0;
39890
+ while (lineIndex < lines.length) {
39891
+ if (!/^solid(?:\s|$)/i.test(lines[lineIndex++]))
39892
+ throw new Error("STL: expected solid header or exact binary length");
39893
+ while (lineIndex < lines.length && !/^endsolid(?:\s|$)/i.test(lines[lineIndex])) {
39894
+ const normal = parseVector(lines[lineIndex++], "facet normal");
39895
+ if (!/^outer\s+loop$/i.test(lines[lineIndex++] || ""))
39896
+ throw new Error("STL: expected outer loop");
39897
+ for (let vertex = 0; vertex < 3; vertex++) {
39898
+ vertices.push(...parseVector(lines[lineIndex++], "vertex"));
39899
+ normalValues.push(...normal);
39900
+ }
39901
+ if (!/^endloop$/i.test(lines[lineIndex++] || "") || !/^endfacet$/i.test(lines[lineIndex++] || ""))
39902
+ throw new Error("STL: incomplete facet");
39903
+ }
39904
+ if (lineIndex >= lines.length) throw new Error("STL: missing endsolid");
39905
+ lineIndex++;
39906
+ }
39907
+ if (!lines.length) throw new Error("STL: empty input");
39908
+ positions = new Float32Array(vertices);
39909
+ normals = new Float32Array(normalValues);
39910
+ }
39911
+ if (!positions.every(Number.isFinite) || !normals.every(Number.isFinite))
39912
+ throw new Error("STL: non-finite coordinates");
39913
+ const attributes = { POSITION: { value: positions, size: 3 }, NORMAL: { value: normals, size: 3 } };
39914
+ return {
39915
+ topology: "triangle-list",
39916
+ mode: 4,
39917
+ attributes,
39918
+ schema: deduceMeshSchema(attributes),
39919
+ header: {
39920
+ vertexCount: positions.length / 3,
39921
+ boundingBox: getMeshBoundingBox(attributes) ?? void 0
39922
+ },
39923
+ loaderData: { header, format: binary ? "binary" : "ascii" }
39924
+ };
39925
+ }
39926
+ function parseVector(line, prefix) {
39927
+ const tokens = line?.split(/\s+/) || [];
39928
+ const prefixTokens = prefix.split(" ");
39929
+ const components = tokens.slice(prefixTokens.length);
39930
+ if (prefixTokens.some((token, index) => tokens[index]?.toLowerCase() !== token) || components.length !== 3 || components.some((value) => !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(value))) {
39931
+ throw new Error(`STL: invalid ${prefix} record`);
39932
+ }
39933
+ return components.map(Number);
39934
+ }
39935
+ var init_parse_stl = __esm({
39936
+ "src/stl/parse-stl.ts"() {
39937
+ "use strict";
39938
+ init_schema_utils();
39939
+ }
39940
+ });
39941
+
39942
+ // src/stl-loader.ts
39943
+ var stl_loader_exports = {};
39944
+ __export(stl_loader_exports, {
39945
+ STLLoaderWithParser: () => STLLoaderWithParser
39946
+ });
39947
+ var _preload2, metadata2, STLLoaderWithParser;
39948
+ var init_stl_loader = __esm({
39949
+ "src/stl-loader.ts"() {
39950
+ "use strict";
39951
+ init_stl_loader_types();
39952
+ init_parse_stl();
39953
+ ({ preload: _preload2, ...metadata2 } = STLLoader);
39954
+ STLLoaderWithParser = {
39955
+ ...metadata2,
39956
+ parse: async (data) => parseSTL(data),
39957
+ parseSync: parseSTL
39958
+ };
39959
+ }
39960
+ });
39961
+
39962
+ // src/stl-loader-types.ts
39963
+ async function preload10() {
39964
+ const { STLLoaderWithParser: STLLoaderWithParser2 } = await Promise.resolve().then(() => (init_stl_loader(), stl_loader_exports));
39965
+ return STLLoaderWithParser2;
39966
+ }
39967
+ var VERSION10, STLLoader;
39968
+ var init_stl_loader_types = __esm({
39969
+ "src/stl-loader-types.ts"() {
39970
+ "use strict";
39971
+ VERSION10 = typeof __VERSION__ !== "undefined" ? __VERSION__ : "latest";
39972
+ STLLoader = {
39973
+ name: "STL",
39974
+ id: "stl",
39975
+ module: "scene",
39976
+ version: VERSION10,
39977
+ extensions: ["stl"],
39978
+ mimeTypes: ["model/stl"],
39979
+ binary: true,
39980
+ dataType: null,
39981
+ batchType: null,
39982
+ options: {},
39983
+ preload: preload10
39984
+ };
39985
+ }
39986
+ });
39987
+
37781
39988
  // bundle.ts
37782
39989
  var bundle_exports = {};
37783
39990
  __export(bundle_exports, {
@@ -37805,6 +40012,7 @@ Actual: ${this.attribValue}`
37805
40012
  OBJWorkerLoader: () => OBJWorkerLoader,
37806
40013
  OBJWriter: () => OBJWriter,
37807
40014
  RequestScheduler: () => import_core4.RequestScheduler,
40015
+ STLLoader: () => STLLoader,
37808
40016
  USDLoader: () => USDLoader,
37809
40017
  _BrowserFileSystem: () => import_core4._BrowserFileSystem,
37810
40018
  _fetchProgress: () => import_core4._fetchProgress,
@@ -38388,6 +40596,7 @@ Actual: ${this.attribValue}`
38388
40596
  init_draco_format();
38389
40597
  init_draco_libraries();
38390
40598
  init_materialx_loader_types();
40599
+ init_stl_loader_types();
38391
40600
  return __toCommonJS(bundle_exports);
38392
40601
  })();
38393
40602
  return __exports__;