@margoengine/loaders 0.0.0-stage → 1.0.0

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 (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
package/dist/xml.js ADDED
@@ -0,0 +1,843 @@
1
+ import { LoaderError } from './types.js';
2
+ // Read against Extensible Markup Language (XML) 1.0, Fifth Edition (W3C Recommendation, 2008),
3
+ // https://www.w3.org/TR/xml/: section numbers below are that document's.
4
+ const PREDEFINED = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };
5
+ /** Default for {@link XMLReadOptions.maxExpansion}: characters entity references may bring in, in one document. */
6
+ const MAX_EXPANSION = 1 << 20;
7
+ /** A text declaration (4.3.1) at the start of an external parsed entity, and a byte order mark. */
8
+ const TEXT_DECLARATION = /^?(?:<\?xml\s[\s\S]*?\?>)?/;
9
+ /** One entity or character reference in content or an attribute value (4.1). */
10
+ const REFERENCE = /&(#x[0-9a-fA-F]+|#\d+|[^\s&;<>"']+);/g;
11
+ /** The characters a DTD name runs to (looser than the Name production, as before). */
12
+ const NAME = /[^\s%&;<>"'()|,=[\]]+/y;
13
+ /** The Char production (section 2.2): what a character reference may name. */
14
+ const legalChar = (code) => code === 0x9 ||
15
+ code === 0xa ||
16
+ code === 0xd ||
17
+ (code >= 0x20 && code <= 0xd7ff) ||
18
+ (code >= 0xe000 && code <= 0xfffd) ||
19
+ (code >= 0x10000 && code <= 0x10ffff);
20
+ function newDTD(format, options, standalone) {
21
+ const left = options.maxExpansion ?? MAX_EXPANSION;
22
+ if (!(left >= 0))
23
+ throw new LoaderError(format, 'range', 'maxExpansion must be 0 or more');
24
+ return {
25
+ format,
26
+ general: new Map(),
27
+ parameter: new Map(),
28
+ attributes: new Map(),
29
+ left,
30
+ incomplete: false,
31
+ skipping: false,
32
+ standalone,
33
+ external: options.external,
34
+ missing: new Map(),
35
+ };
36
+ }
37
+ const syntax = (dtd, message) => new LoaderError(dtd.format, 'syntax', message);
38
+ function characterReference(match, name, format) {
39
+ const code = name[1] === 'x' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
40
+ if (!legalChar(code))
41
+ throw new LoaderError(format, 'syntax', `invalid character reference ${match.slice(0, 32)}`);
42
+ return String.fromCodePoint(code);
43
+ }
44
+ /** A relative system identifier against the identifier of the entity that declares it (4.2.2). */
45
+ function resolveId(system, base) {
46
+ if (!base)
47
+ return system;
48
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(base))
49
+ return new URL(system, base).href;
50
+ if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(system) || system.startsWith('/'))
51
+ return system;
52
+ return base.slice(0, base.lastIndexOf('/') + 1) + system;
53
+ }
54
+ /** Counts `count` characters an entity reference brings in against the document's limit. */
55
+ function charge(dtd, count) {
56
+ if ((dtd.left -= count) < 0)
57
+ throw new LoaderError(dtd.format, 'limit', 'entities expand past the limit of maxExpansion characters');
58
+ }
59
+ /** The text of an external entity from `external`, its text declaration removed; undefined and noted if absent. */
60
+ function externalText(dtd, id, publicId) {
61
+ const text = dtd.external?.get(id);
62
+ if (text === undefined) {
63
+ dtd.missing.set(id, publicId);
64
+ return undefined;
65
+ }
66
+ return text.replace(/\r\n?/g, '\n').replace(TEXT_DECLARATION, '');
67
+ }
68
+ /** Marks part of the DTD unread; later entity and attribute declarations are then skipped unless standalone (5.1). */
69
+ function unread(dtd) {
70
+ dtd.incomplete = true;
71
+ if (!dtd.standalone)
72
+ dtd.skipping = true;
73
+ }
74
+ /** The replacement text of parameter entity `name` and the context it is read in, or undefined when not read. */
75
+ function parameter(name, dtd, ctx) {
76
+ const entity = dtd.parameter.get(name);
77
+ if (!entity) {
78
+ // Entity Declared (4.1) binds only a DTD read in full; otherwise a part not read may declare it.
79
+ if (dtd.incomplete || ctx.external) {
80
+ unread(dtd);
81
+ return undefined;
82
+ }
83
+ throw syntax(dtd, `unknown parameter entity %${name.slice(0, 64)};`);
84
+ }
85
+ if (ctx.open.includes(`%${name}`))
86
+ throw syntax(dtd, `parameter entity %${name.slice(0, 64)}; refers to itself`);
87
+ const text = entity.value ?? externalText(dtd, entity.system, entity.publicId);
88
+ if (text === undefined) {
89
+ unread(dtd);
90
+ return undefined;
91
+ }
92
+ charge(dtd, text.length);
93
+ return {
94
+ text,
95
+ ctx: {
96
+ external: ctx.external || entity.inExternal || entity.value === undefined,
97
+ base: entity.value === undefined ? entity.system : entity.base,
98
+ open: [...ctx.open, `%${name}`],
99
+ },
100
+ };
101
+ }
102
+ /** A small reader over one markup declaration's text. */
103
+ class Cursor {
104
+ constructor(s, dtd) {
105
+ this.s = s;
106
+ this.dtd = dtd;
107
+ this.i = 0;
108
+ }
109
+ fail(message) {
110
+ throw syntax(this.dtd, `${message} in a declaration, at ${JSON.stringify(this.s.slice(this.i, this.i + 32))}`);
111
+ }
112
+ /** Skips whitespace; true when there was some. */
113
+ skip() {
114
+ const from = this.i;
115
+ while (this.i < this.s.length && /\s/.test(this.s[this.i]))
116
+ this.i++;
117
+ return this.i > from;
118
+ }
119
+ space() {
120
+ if (!this.skip())
121
+ this.fail('whitespace expected');
122
+ }
123
+ name() {
124
+ NAME.lastIndex = this.i;
125
+ const match = NAME.exec(this.s);
126
+ if (!match)
127
+ this.fail('a name expected');
128
+ this.i = NAME.lastIndex;
129
+ return match[0];
130
+ }
131
+ literal() {
132
+ const quote = this.s[this.i];
133
+ if (quote !== '"' && quote !== "'")
134
+ this.fail('a quoted literal expected');
135
+ const end = this.s.indexOf(quote, this.i + 1);
136
+ if (end < 0)
137
+ this.fail('an unterminated literal');
138
+ const value = this.s.slice(this.i + 1, end);
139
+ this.i = end + 1;
140
+ return value;
141
+ }
142
+ /** Skips a parenthesized enumeration or notation list. */
143
+ group() {
144
+ const end = this.s.indexOf(')', this.i);
145
+ if (this.s[this.i] !== '(' || end < 0)
146
+ this.fail('a list in parentheses expected');
147
+ this.i = end + 1;
148
+ }
149
+ peek() {
150
+ return this.s[this.i] ?? '';
151
+ }
152
+ done() {
153
+ this.skip();
154
+ return this.i >= this.s.length;
155
+ }
156
+ }
157
+ /**
158
+ * The replacement text of an entity value literal (4.5): character references expand now, general entity
159
+ * references are kept for later, and in the external subset parameter entity references are included in the
160
+ * literal (4.4.5); in the internal subset they are not allowed there (WFC PEs in Internal Subset, 2.8).
161
+ */
162
+ function entityValue(raw, dtd, ctx) {
163
+ let out = '', last = 0;
164
+ const reference = /&#x[0-9a-fA-F]+;|&#\d+;|%([^\s%&;<>"']+);/g;
165
+ for (let match = reference.exec(raw); match; match = reference.exec(raw)) {
166
+ out += raw.slice(last, match.index);
167
+ last = reference.lastIndex;
168
+ if (match[1] === undefined) {
169
+ out += characterReference(match[0], match[0].slice(1, -1), dtd.format);
170
+ continue;
171
+ }
172
+ if (!ctx.external)
173
+ throw syntax(dtd, `parameter entity reference ${match[0].slice(0, 64)} inside a declaration of the internal subset`);
174
+ const included = parameter(match[1], dtd, ctx);
175
+ const value = included && entityValue(included.text, dtd, included.ctx);
176
+ if (value === undefined)
177
+ return undefined;
178
+ out += value;
179
+ }
180
+ return out + raw.slice(last);
181
+ }
182
+ /**
183
+ * A markup declaration's text with the parameter entity references outside its literals replaced, each with a
184
+ * space either side (4.4.8); undefined when one was not read. In the internal subset such a reference is not
185
+ * allowed inside a declaration (WFC PEs in Internal Subset).
186
+ */
187
+ function expandDeclaration(body, dtd, ctx) {
188
+ let out = '', quote = '';
189
+ for (let i = 0; i < body.length; i++) {
190
+ const c = body[i];
191
+ if (quote) {
192
+ if (c === quote)
193
+ quote = '';
194
+ }
195
+ else if (c === '"' || c === "'")
196
+ quote = c;
197
+ else if (c === '%') {
198
+ const end = body.indexOf(';', i);
199
+ const name = end < 0 ? '' : body.slice(i + 1, end);
200
+ NAME.lastIndex = 0;
201
+ if (name && NAME.exec(name)?.[0] === name) {
202
+ if (!ctx.external)
203
+ throw syntax(dtd, `parameter entity reference %${name.slice(0, 64)}; inside a declaration of the internal subset`);
204
+ const included = parameter(name, dtd, ctx);
205
+ const text = included && expandDeclaration(included.text, dtd, included.ctx);
206
+ if (text === undefined)
207
+ return undefined;
208
+ out += ` ${text} `;
209
+ i = end;
210
+ continue;
211
+ }
212
+ }
213
+ out += c;
214
+ }
215
+ return out;
216
+ }
217
+ /** `<!ENTITY ...>` (4.2): the first declaration of a name binds; none bind after an unread parameter entity. */
218
+ function entityDeclaration(cursor, dtd, ctx) {
219
+ cursor.space();
220
+ let isParameter = false;
221
+ if (cursor.peek() === '%') {
222
+ cursor.i++;
223
+ cursor.space();
224
+ isParameter = true;
225
+ }
226
+ const name = cursor.name();
227
+ cursor.space();
228
+ let entity;
229
+ if (cursor.peek() === '"' || cursor.peek() === "'") {
230
+ const value = entityValue(cursor.literal(), dtd, ctx);
231
+ if (value !== undefined)
232
+ entity = { value, inExternal: ctx.external, base: ctx.base };
233
+ }
234
+ else {
235
+ const keyword = cursor.name();
236
+ let publicId;
237
+ if (keyword === 'PUBLIC') {
238
+ cursor.space();
239
+ publicId = cursor.literal();
240
+ }
241
+ else if (keyword !== 'SYSTEM')
242
+ cursor.fail('SYSTEM, PUBLIC or a quoted value expected');
243
+ cursor.space();
244
+ entity = { system: resolveId(cursor.literal(), ctx.base), publicId, inExternal: ctx.external, base: ctx.base };
245
+ if (cursor.skip() && !isParameter && cursor.peek() === 'N') {
246
+ if (cursor.name() !== 'NDATA')
247
+ cursor.fail('NDATA expected');
248
+ cursor.space();
249
+ cursor.name();
250
+ entity.unparsed = true;
251
+ }
252
+ }
253
+ if (!cursor.done())
254
+ cursor.fail('unexpected text');
255
+ if (!entity || dtd.skipping)
256
+ return;
257
+ const map = isParameter ? dtd.parameter : dtd.general;
258
+ if (map.has(name) || (!isParameter && Object.hasOwn(PREDEFINED, name)))
259
+ return;
260
+ map.set(name, entity);
261
+ }
262
+ const TYPES = new Set(['CDATA', 'ID', 'IDREF', 'IDREFS', 'ENTITY', 'ENTITIES', 'NMTOKEN', 'NMTOKENS']);
263
+ /** Normalization of a tokenized or enumerated attribute (3.3.3): spaces collapse and trim; CDATA stays. */
264
+ const tokens = (value, cdata) => (cdata ? value : value.replace(/ +/g, ' ').trim());
265
+ /** `<!ATTLIST ...>` (3.3): types and default values; the first declaration of an attribute binds. */
266
+ function attributeDeclaration(cursor, dtd) {
267
+ cursor.space();
268
+ const element = cursor.name();
269
+ while (!cursor.done()) {
270
+ const name = cursor.name();
271
+ cursor.space();
272
+ let cdata = false;
273
+ if (cursor.peek() === '(')
274
+ cursor.group();
275
+ else {
276
+ const type = cursor.name();
277
+ if (type === 'NOTATION') {
278
+ cursor.space();
279
+ cursor.group();
280
+ }
281
+ else if (!TYPES.has(type))
282
+ cursor.fail(`unknown attribute type ${type.slice(0, 32)}`);
283
+ cdata = type === 'CDATA';
284
+ }
285
+ cursor.space();
286
+ let value;
287
+ if (cursor.peek() === '#') {
288
+ const keyword = cursor.name();
289
+ if (keyword === '#FIXED') {
290
+ cursor.space();
291
+ value = cursor.literal();
292
+ }
293
+ else if (keyword !== '#REQUIRED' && keyword !== '#IMPLIED')
294
+ cursor.fail(`unknown default ${keyword.slice(0, 32)}`);
295
+ }
296
+ else
297
+ value = cursor.literal();
298
+ if (dtd.skipping)
299
+ continue;
300
+ let declared = dtd.attributes.get(element);
301
+ if (!declared)
302
+ dtd.attributes.set(element, (declared = new Map()));
303
+ if (declared.has(name))
304
+ continue;
305
+ declared.set(name, { cdata, value: value === undefined ? undefined : tokens(attributeValue(value, dtd), cdata) });
306
+ }
307
+ }
308
+ /** One markup declaration, `body` being its text between `<!` and `>`. ELEMENT and NOTATION are not needed. */
309
+ function markup(body, dtd, ctx) {
310
+ const text = expandDeclaration(body, dtd, ctx);
311
+ if (text === undefined)
312
+ return;
313
+ const keyword = /^[A-Z]+/.exec(text)?.[0];
314
+ const cursor = new Cursor(text, dtd);
315
+ cursor.i = keyword?.length ?? 0;
316
+ if (keyword === 'ENTITY')
317
+ entityDeclaration(cursor, dtd, ctx);
318
+ else if (keyword === 'ATTLIST')
319
+ attributeDeclaration(cursor, dtd);
320
+ else if (keyword !== 'ELEMENT' && keyword !== 'NOTATION')
321
+ cursor.fail('unknown declaration');
322
+ }
323
+ /** The index of the `>` that ends the declaration at `at`, outside quoted literals. */
324
+ function declarationEnd(text, at, dtd) {
325
+ let quote = 0;
326
+ for (let i = at + 2; i < text.length; i++) {
327
+ const code = text.charCodeAt(i);
328
+ if (quote) {
329
+ if (code === quote)
330
+ quote = 0;
331
+ }
332
+ else if (code === 34 || code === 39)
333
+ quote = code;
334
+ else if (code === 62)
335
+ return i;
336
+ }
337
+ throw new LoaderError(dtd.format, 'truncated', 'unterminated declaration in the DTD');
338
+ }
339
+ /** A conditional section (3.4) at `at`, allowed only in the external subset; returns the index past its `]]>`. */
340
+ function conditional(text, at, dtd, ctx) {
341
+ if (!ctx.external)
342
+ throw syntax(dtd, 'a conditional section outside the external subset');
343
+ let i = at + 3;
344
+ while (/\s/.test(text[i] ?? ''))
345
+ i++;
346
+ let keyword;
347
+ if (text[i] === '%') {
348
+ const end = text.indexOf(';', i);
349
+ if (end < 0)
350
+ throw syntax(dtd, 'an unterminated parameter entity reference');
351
+ keyword = parameter(text.slice(i + 1, end), dtd, ctx)?.text.trim();
352
+ i = end + 1;
353
+ }
354
+ else {
355
+ const match = /^[A-Z]+/.exec(text.slice(i, i + 8));
356
+ keyword = match?.[0];
357
+ if (keyword !== 'INCLUDE' && keyword !== 'IGNORE')
358
+ throw syntax(dtd, 'INCLUDE or IGNORE expected');
359
+ i += keyword.length;
360
+ }
361
+ while (/\s/.test(text[i] ?? ''))
362
+ i++;
363
+ if (text[i] !== '[')
364
+ throw syntax(dtd, '[ expected after INCLUDE or IGNORE');
365
+ const start = i + 1;
366
+ let depth = 1;
367
+ for (i = start; depth;) {
368
+ const open = text.indexOf('<![', i), close = text.indexOf(']]>', i);
369
+ if (close < 0)
370
+ throw new LoaderError(dtd.format, 'truncated', 'unterminated conditional section');
371
+ if (open >= 0 && open < close) {
372
+ depth++;
373
+ i = open + 3;
374
+ }
375
+ else {
376
+ depth--;
377
+ i = close + 3;
378
+ }
379
+ }
380
+ // An unread parameter entity as the keyword: the section's contents cannot be known.
381
+ if (keyword === 'INCLUDE')
382
+ declarations(text.slice(start, i - 3), dtd, ctx);
383
+ else if (keyword !== 'IGNORE' && keyword !== undefined)
384
+ throw syntax(dtd, 'INCLUDE or IGNORE expected');
385
+ return i;
386
+ }
387
+ /** Reads a run of markup declarations, parameter entity references, comments and processing instructions (2.8). */
388
+ function declarations(text, dtd, ctx) {
389
+ for (let i = 0; i < text.length;) {
390
+ const code = text.charCodeAt(i);
391
+ if (code === 32 || code === 9 || code === 10 || code === 13)
392
+ i++;
393
+ else if (code === 37 /* % */) {
394
+ const end = text.indexOf(';', i);
395
+ if (end < 0)
396
+ throw syntax(dtd, 'a % in the DTD that is not a parameter entity reference');
397
+ const included = parameter(text.slice(i + 1, end), dtd, ctx);
398
+ // Included as PE (4.4.8): it must hold whole declarations (WFC PE Between Declarations).
399
+ if (included)
400
+ declarations(included.text, dtd, included.ctx);
401
+ i = end + 1;
402
+ }
403
+ else if (text.startsWith('<!--', i)) {
404
+ const end = text.indexOf('-->', i + 4);
405
+ if (end < 0)
406
+ throw new LoaderError(dtd.format, 'truncated', 'unterminated comment in the DTD');
407
+ i = end + 3;
408
+ }
409
+ else if (text.startsWith('<?', i)) {
410
+ const end = text.indexOf('?>', i + 2);
411
+ if (end < 0)
412
+ throw new LoaderError(dtd.format, 'truncated', 'unterminated processing instruction in the DTD');
413
+ i = end + 2;
414
+ }
415
+ else if (text.startsWith('<![', i))
416
+ i = conditional(text, i, dtd, ctx);
417
+ else if (text.startsWith('<!', i)) {
418
+ const end = declarationEnd(text, i, dtd);
419
+ markup(text.slice(i + 2, end), dtd, ctx);
420
+ i = end + 1;
421
+ }
422
+ else
423
+ throw syntax(dtd, `unexpected ${JSON.stringify(text.slice(i, i + 16))} in the DTD`);
424
+ }
425
+ }
426
+ /**
427
+ * The `<!DOCTYPE` at `lt` (2.8): reads the internal subset, then the external subset when `external` holds it, and
428
+ * returns the index past the declaration.
429
+ */
430
+ function doctype(xml, lt, dtd, base) {
431
+ const truncated = () => new LoaderError(dtd.format, 'truncated', 'unterminated DOCTYPE');
432
+ const cursor = new Cursor(xml, dtd);
433
+ cursor.i = lt + 9;
434
+ cursor.space();
435
+ cursor.name();
436
+ let system, publicId;
437
+ if (cursor.skip() && (cursor.peek() === 'S' || cursor.peek() === 'P')) {
438
+ const keyword = cursor.name();
439
+ if (keyword === 'PUBLIC') {
440
+ cursor.space();
441
+ publicId = cursor.literal();
442
+ }
443
+ else if (keyword !== 'SYSTEM')
444
+ cursor.fail('SYSTEM or PUBLIC expected');
445
+ cursor.space();
446
+ system = cursor.literal();
447
+ cursor.skip();
448
+ }
449
+ let subset = '';
450
+ if (cursor.peek() === '[') {
451
+ // The internal subset ends at the first ] outside literals, comments and processing instructions.
452
+ let quote = 0, i = cursor.i + 1;
453
+ for (; i < xml.length; i++) {
454
+ const code = xml.charCodeAt(i);
455
+ if (quote) {
456
+ if (code === quote)
457
+ quote = 0;
458
+ }
459
+ else if (code === 34 || code === 39)
460
+ quote = code;
461
+ else if (code === 93 /* ] */)
462
+ break;
463
+ else if (code === 60 /* < */ && xml.startsWith('<![', i))
464
+ throw syntax(dtd, 'a conditional section outside the external subset');
465
+ else if (code === 60 /* < */ && (xml.startsWith('<!--', i) || xml.startsWith('<?', i))) {
466
+ const end = xml.indexOf(xml[i + 1] === '!' ? '-->' : '?>', i + 2);
467
+ if (end < 0)
468
+ throw truncated();
469
+ i = end + 1;
470
+ }
471
+ }
472
+ if (i >= xml.length)
473
+ throw truncated();
474
+ subset = xml.slice(cursor.i + 1, i);
475
+ cursor.i = i + 1;
476
+ cursor.skip();
477
+ }
478
+ if (cursor.i >= xml.length)
479
+ throw truncated();
480
+ if (cursor.peek() !== '>')
481
+ cursor.fail('> expected');
482
+ declarations(subset, dtd, { external: false, base, open: [] });
483
+ // The external subset is read after the internal one, whose declarations therefore bind first.
484
+ if (system !== undefined) {
485
+ const id = resolveId(system, base);
486
+ const text = externalText(dtd, id, publicId);
487
+ if (text === undefined)
488
+ dtd.incomplete = true;
489
+ else
490
+ declarations(text, dtd, { external: true, base: id, open: [] });
491
+ }
492
+ return cursor.i + 1;
493
+ }
494
+ /**
495
+ * The replacement text of general entity `name` in content or (`attribute`) an attribute value, checked against the
496
+ * well-formedness constraints of 4.1: declared, not recursive, parsed, and not external inside an attribute value.
497
+ */
498
+ function general(name, dtd, open, attribute) {
499
+ const shown = `&${name.slice(0, 64)};`;
500
+ const entity = dtd.general.get(name);
501
+ if (!entity) {
502
+ if (dtd.incomplete && !dtd.standalone)
503
+ throw new LoaderError(dtd.format, 'unsupported', `entity ${shown} is not declared in the part of the DTD that was read; read the external DTD with resolveDTD and pass the result as external`);
504
+ throw syntax(dtd, `unknown entity ${shown}`);
505
+ }
506
+ if (open.includes(name))
507
+ throw syntax(dtd, `entity ${shown} refers to itself`);
508
+ if (entity.unparsed)
509
+ throw syntax(dtd, `entity ${shown} is an unparsed (NDATA) entity, which may not be referenced`);
510
+ let text = entity.value;
511
+ if (text === undefined) {
512
+ if (attribute)
513
+ throw syntax(dtd, `an attribute value refers to the external entity ${shown}`);
514
+ text = externalText(dtd, entity.system, entity.publicId);
515
+ if (text === undefined)
516
+ throw new LoaderError(dtd.format, 'unsupported', `entity ${shown} is external (${entity.system.slice(0, 128)}) and was not read; read it with resolveDTD and pass the result as external`);
517
+ }
518
+ charge(dtd, text.length);
519
+ return text;
520
+ }
521
+ /**
522
+ * Attribute-value normalization (3.3.3): each literal tab, line feed and carriage return becomes a space, character
523
+ * references expand, and entity references expand with the same normalization applied to their replacement text.
524
+ */
525
+ function attributeValue(raw, dtd, open = []) {
526
+ const value = raw.replace(/[\t\n\r]/g, ' ');
527
+ if (value.indexOf('&') < 0)
528
+ return value;
529
+ return value.replace(REFERENCE, (match, name) => {
530
+ if (name[0] === '#')
531
+ return characterReference(match, name, dtd.format);
532
+ if (Object.hasOwn(PREDEFINED, name))
533
+ return PREDEFINED[name];
534
+ const text = general(name, dtd, open, true);
535
+ // Well-formedness constraint No < in Attribute Values (3.1).
536
+ if (text.includes('<'))
537
+ throw syntax(dtd, `entity ${match.slice(0, 64)} puts < in an attribute value`);
538
+ return attributeValue(text, dtd, [...open, name]);
539
+ });
540
+ }
541
+ // The lookbehind starts a name only at a token boundary, so a long run with no `=` is scanned once, not once per
542
+ // character (quadratic, ReDoS).
543
+ const ATTRIBUTE = /(?<![^\s=/"'])([^\s=/]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
544
+ /**
545
+ * Non-validating streaming XML reader (XML 1.0 Fifth Edition, 5.1). Skips comments and processing instructions,
546
+ * keeps CDATA as text, normalizes line ends and attribute whitespace, and checks that tags nest. From the DOCTYPE it
547
+ * reads the internal subset in full: general and parameter entities (parameter entity references between and, in
548
+ * the external subset, inside declarations), attribute defaults and types, and conditional sections in the external
549
+ * subset. An entity holding markup is read as content and must hold whole elements. The external subset and
550
+ * external entities are read only from `options.external` ({@link resolveDTD}); nothing is fetched here. At most
551
+ * `maxExpansion` characters (default 1 Mi) come from entity references.
552
+ *
553
+ * @param maxDepth Deepest element nesting (default 256), or the options.
554
+ */
555
+ export function readXML(xml, handler, format = 'XML', maxDepth = 256) {
556
+ const options = typeof maxDepth === 'number' ? { maxDepth } : maxDepth;
557
+ const depthLimit = options.maxDepth ?? 256;
558
+ // End-of-line handling (2.11): CR LF and a lone CR read as LF.
559
+ if (xml.indexOf('\r') >= 0)
560
+ xml = xml.replace(/\r\n?/g, '\n');
561
+ const standalone = /^?<\?xml\s[^>]*?\bstandalone\s*=\s*["']yes["']/.test(xml);
562
+ const dtd = newDTD(format, options, standalone);
563
+ const stack = [];
564
+ /** A run of character data: references expand; an entity holding markup or references is read as content. */
565
+ const characters = (raw, open) => {
566
+ if (!stack.length)
567
+ return;
568
+ if (raw.indexOf('&') < 0) {
569
+ if (raw && handler.text)
570
+ handler.text(raw);
571
+ return;
572
+ }
573
+ let out = '', last = 0;
574
+ const flush = () => {
575
+ if (out && handler.text)
576
+ handler.text(out);
577
+ out = '';
578
+ };
579
+ // Its own copy: reading an entity's content below runs this function again.
580
+ const reference = new RegExp(REFERENCE);
581
+ for (let match = reference.exec(raw); match; match = reference.exec(raw)) {
582
+ out += raw.slice(last, match.index);
583
+ last = reference.lastIndex;
584
+ const name = match[1];
585
+ if (name[0] === '#')
586
+ out += characterReference(match[0], name, format);
587
+ else if (Object.hasOwn(PREDEFINED, name))
588
+ out += PREDEFINED[name];
589
+ else {
590
+ const text = general(name, dtd, open, false);
591
+ if (text.indexOf('<') < 0 && text.indexOf('&') < 0)
592
+ out += text;
593
+ else {
594
+ flush();
595
+ // Included (4.4.2): the replacement text is read as content, and must be well-formed on its own (4.3.2).
596
+ content(text, [...open, name]);
597
+ }
598
+ }
599
+ }
600
+ out += raw.slice(last);
601
+ flush();
602
+ };
603
+ /** Reads `text` as content: the document itself, or the replacement text of entity `open.at(-1)`. */
604
+ const content = (text, open) => {
605
+ const base = stack.length, length = text.length, inEntity = open.length > 0;
606
+ let pos = 0;
607
+ while (pos < length) {
608
+ const lt = text.indexOf('<', pos);
609
+ if (lt < 0) {
610
+ characters(text.slice(pos), open);
611
+ break;
612
+ }
613
+ if (lt > pos)
614
+ characters(text.slice(pos, lt), open);
615
+ const next = text.charCodeAt(lt + 1);
616
+ if (next === 33 /* ! */) {
617
+ if (text.startsWith('<!DOCTYPE', lt)) {
618
+ if (inEntity || stack.length)
619
+ throw new LoaderError(format, 'syntax', 'a DOCTYPE inside the document');
620
+ pos = doctype(text, lt, dtd, options.base);
621
+ continue;
622
+ }
623
+ const terminator = text.startsWith('<!--', lt) ? '-->' : text.startsWith('<![CDATA[', lt) ? ']]>' : '>';
624
+ const end = text.indexOf(terminator, lt + 2);
625
+ if (end < 0)
626
+ throw new LoaderError(format, 'truncated', 'unterminated comment, CDATA or declaration');
627
+ if (terminator === ']]>' && stack.length && handler.text)
628
+ handler.text(text.slice(lt + 9, end));
629
+ pos = end + terminator.length;
630
+ continue;
631
+ }
632
+ if (next === 63 /* ? */) {
633
+ const end = text.indexOf('?>', lt + 2);
634
+ if (end < 0)
635
+ throw new LoaderError(format, 'truncated', 'unterminated processing instruction');
636
+ pos = end + 2;
637
+ continue;
638
+ }
639
+ // Find the closing '>' outside quoted attribute values.
640
+ let end = lt + 1, quote = 0;
641
+ for (; end < length; end++) {
642
+ const code = text.charCodeAt(end);
643
+ if (quote) {
644
+ if (code === quote)
645
+ quote = 0;
646
+ }
647
+ else if (code === 34 || code === 39)
648
+ quote = code;
649
+ else if (code === 62)
650
+ break;
651
+ }
652
+ if (end >= length)
653
+ throw new LoaderError(format, 'truncated', 'unterminated tag');
654
+ const body = text.slice(lt + 1, end);
655
+ pos = end + 1;
656
+ if (body[0] === '/') {
657
+ const name = local(body.slice(1).trim());
658
+ if (inEntity && stack.length === base)
659
+ throw new LoaderError(format, 'syntax', `</${name}> in entity &${open[open.length - 1]}; closes an element opened outside it`);
660
+ const opened = stack.pop();
661
+ if (opened !== name)
662
+ throw new LoaderError(format, 'syntax', `closing tag </${name}> does not match <${opened ?? 'nothing'}>`);
663
+ handler.close(name);
664
+ continue;
665
+ }
666
+ const selfClosing = body.endsWith('/');
667
+ const inner = selfClosing ? body.slice(0, -1) : body;
668
+ const nameEnd = inner.search(/[\s]/);
669
+ const raw = nameEnd < 0 ? inner : inner.slice(0, nameEnd);
670
+ if (!raw)
671
+ throw new LoaderError(format, 'syntax', 'empty tag name');
672
+ const name = local(raw);
673
+ // Null prototype: attribute names come from the file (`__proto__="..."`, `constructor="..."`).
674
+ const attributes = Object.create(null);
675
+ if (nameEnd >= 0) {
676
+ ATTRIBUTE.lastIndex = 0;
677
+ const rest = inner.slice(nameEnd);
678
+ let match;
679
+ while ((match = ATTRIBUTE.exec(rest)))
680
+ attributes[match[1]] = attributeValue(match[2] ?? match[3], dtd);
681
+ }
682
+ // Declared attributes (3.3): tokenized types normalize further, and defaults fill in missing ones (5.1).
683
+ const declared = dtd.attributes.get(raw);
684
+ if (declared)
685
+ for (const [attribute, declaration] of declared) {
686
+ const value = attributes[attribute];
687
+ if (value !== undefined)
688
+ attributes[attribute] = tokens(value, declaration.cdata);
689
+ else if (declaration.value !== undefined)
690
+ attributes[attribute] = declaration.value;
691
+ }
692
+ if (stack.length >= depthLimit)
693
+ throw new LoaderError(format, 'limit', `elements nest deeper than ${depthLimit}`);
694
+ stack.push(name);
695
+ handler.open(name, attributes);
696
+ if (selfClosing) {
697
+ stack.pop();
698
+ handler.close(name);
699
+ }
700
+ }
701
+ if (inEntity && stack.length !== base)
702
+ throw new LoaderError(format, 'syntax', `entity &${open[open.length - 1]}; ends inside <${stack[stack.length - 1]}>, which it opened`);
703
+ };
704
+ content(xml, []);
705
+ if (stack.length)
706
+ throw new LoaderError(format, 'truncated', `document ends inside <${stack[stack.length - 1]}>`);
707
+ }
708
+ /** Reads a whole document into elements; returns a nameless root whose children are the top-level elements. */
709
+ export function readXMLTree(xml, format, options = {}) {
710
+ const root = { name: '', attributes: Object.create(null), children: [], text: '' }, stack = [root];
711
+ readXML(xml, {
712
+ open(name, attributes) {
713
+ const element = { name, attributes, children: [], text: '' };
714
+ stack[stack.length - 1].children.push(element);
715
+ stack.push(element);
716
+ },
717
+ close() {
718
+ stack.pop();
719
+ },
720
+ text(text) {
721
+ stack[stack.length - 1].text += text;
722
+ },
723
+ }, format, options);
724
+ return root;
725
+ }
726
+ /** The index of the document's `<!DOCTYPE`, past its XML declaration, comments and processing instructions; -1 if none. */
727
+ function findDoctype(xml) {
728
+ for (let i = xml.charCodeAt(0) === 0xfeff ? 1 : 0; i < xml.length;) {
729
+ if (/\s/.test(xml[i]))
730
+ i++;
731
+ else if (xml.startsWith('<?', i) || xml.startsWith('<!--', i)) {
732
+ const end = xml.indexOf(xml[i + 1] === '?' ? '?>' : '-->', i + 2);
733
+ if (end < 0)
734
+ return -1;
735
+ i = end + (xml[i + 1] === '?' ? 2 : 3);
736
+ }
737
+ else
738
+ return xml.startsWith('<!DOCTYPE', i) ? i : -1;
739
+ }
740
+ return -1;
741
+ }
742
+ /**
743
+ * Reads what a document's DOCTYPE needs from outside it: the external DTD subset, the external parameter entities it
744
+ * uses, and the external general entities the document references, each through `options.resolve`, until nothing
745
+ * more is needed. Pass the result to `readXML` or `readXMLTree` as `external`. This is the only way external
746
+ * entities are read: fetching is opt-in, as XML from untrusted sources should not make a reader fetch URLs it names.
747
+ *
748
+ * @throws LoaderError with code `limit` past `maxFiles` or `maxCharacters`, `aborted` when `signal` fires, `fetch`
749
+ * when `resolve` fails (its error is the `cause`), and the reader's own codes for a malformed DTD.
750
+ * @example
751
+ * ```ts
752
+ * import { readXMLTree, resolveDTD } from '@margoengine/loaders/xml';
753
+ *
754
+ * const files = new Map([['parts.dtd', '<!ENTITY bolt "M6 bolt"><!ATTLIST part unit CDATA "mm">']]);
755
+ * const xml = '<!DOCTYPE parts SYSTEM "parts.dtd"><parts><part>&bolt;</part></parts>';
756
+ * const external = await resolveDTD(xml, { resolve: (id) => files.get(id) ?? '' });
757
+ * const part = readXMLTree(xml, 'Parts', { external }).children[0].children[0];
758
+ * console.log(part.text, part.attributes.unit); // M6 bolt mm
759
+ * ```
760
+ */
761
+ export async function resolveDTD(xml, options, format = 'XML') {
762
+ const { signal } = options, maxFiles = options.maxFiles ?? 64, maxCharacters = options.maxCharacters ?? 1 << 24;
763
+ if (!(maxFiles >= 0) || !(maxCharacters >= 0))
764
+ throw new LoaderError(format, 'range', 'maxFiles and maxCharacters must be 0 or more');
765
+ if (xml.indexOf('\r') >= 0)
766
+ xml = xml.replace(/\r\n?/g, '\n');
767
+ const external = new Map(), lt = findDoctype(xml), standalone = /^?<\?xml\s[^>]*?\bstandalone\s*=\s*["']yes["']/.test(xml);
768
+ let characters = 0;
769
+ while (lt >= 0) {
770
+ if (signal?.aborted)
771
+ throw new LoaderError(format, 'aborted', 'aborted');
772
+ const dtd = newDTD(format, { external, maxExpansion: Infinity }, standalone);
773
+ doctype(xml, lt, dtd, options.base);
774
+ const wanted = dtd.missing, texts = [xml, ...external.values()];
775
+ for (const [name, entity] of dtd.general)
776
+ if (entity.system &&
777
+ !entity.unparsed &&
778
+ !external.has(entity.system) &&
779
+ texts.some((t) => t.includes(`&${name};`)))
780
+ wanted.set(entity.system, entity.publicId);
781
+ if (!wanted.size)
782
+ break;
783
+ if (external.size + wanted.size > maxFiles)
784
+ throw new LoaderError(format, 'limit', `the DTD needs more than maxFiles (${maxFiles}) external entities`);
785
+ const read = await Promise.all([...wanted].map(async ([id, publicId]) => {
786
+ let got;
787
+ try {
788
+ got = await options.resolve(id, { publicId, signal });
789
+ }
790
+ catch (cause) {
791
+ if (signal?.aborted)
792
+ throw new LoaderError(format, 'aborted', 'aborted');
793
+ const error = new LoaderError(format, 'fetch', `could not read the external entity ${id.slice(0, 128)}`);
794
+ error.cause = cause;
795
+ throw error;
796
+ }
797
+ return [
798
+ id,
799
+ typeof got === 'string' ? got : decodeXML(got instanceof Uint8Array ? got : new Uint8Array(got)),
800
+ ];
801
+ }));
802
+ if (signal?.aborted)
803
+ throw new LoaderError(format, 'aborted', 'aborted');
804
+ for (const [id, text] of read) {
805
+ if ((characters += text.length) > maxCharacters)
806
+ throw new LoaderError(format, 'limit', `external entities hold more than maxCharacters (${maxCharacters})`);
807
+ external.set(id, text);
808
+ }
809
+ }
810
+ return external;
811
+ }
812
+ function local(name) {
813
+ const colon = name.indexOf(':');
814
+ return colon < 0 ? name : name.slice(colon + 1);
815
+ }
816
+ /**
817
+ * Decodes XML bytes (4.3.3): UTF-16 when a byte order mark says so, otherwise the `encoding` of the XML
818
+ * declaration (such as ISO-8859-1 or windows-1252), otherwise UTF-8. An encoding this runtime cannot decode
819
+ * throws a LoaderError with code `unsupported`, the fatal error the specification asks for.
820
+ */
821
+ export function decodeXML(bytes) {
822
+ if (bytes[0] === 0xff && bytes[1] === 0xfe)
823
+ return new TextDecoder('utf-16le').decode(bytes);
824
+ if (bytes[0] === 0xfe && bytes[1] === 0xff)
825
+ return new TextDecoder('utf-16be').decode(bytes);
826
+ let head = '';
827
+ for (let i = bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? 3 : 0; i < bytes.length && i < 256; i++) {
828
+ head += String.fromCharCode(bytes[i]);
829
+ if (bytes[i] === 0x3e /* > */)
830
+ break;
831
+ }
832
+ const label = /^<\?xml\s[^>]*?\bencoding\s*=\s*["']([A-Za-z][A-Za-z0-9._-]*)["']/.exec(head)?.[1].toLowerCase();
833
+ if (!label || label === 'utf-8' || label === 'utf8' || /^utf-16/.test(label))
834
+ return new TextDecoder('utf-8').decode(bytes);
835
+ let decoder;
836
+ try {
837
+ decoder = new TextDecoder(label);
838
+ }
839
+ catch {
840
+ throw new LoaderError('XML', 'unsupported', `encoding "${label.slice(0, 40)}" cannot be decoded here`);
841
+ }
842
+ return decoder.decode(bytes);
843
+ }