@embedpdf/engine-core 3.0.0-next.13 → 3.0.0-next.14

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 (58) hide show
  1. package/dist/{AbortError-DHqPBnYc.js → AbortError-DwuHPK_I.js} +2 -2
  2. package/dist/{AbortError-DHqPBnYc.js.map → AbortError-DwuHPK_I.js.map} +1 -1
  3. package/dist/{AbortError-Cq2igpZ6.cjs → AbortError-P0RU0Mgg.cjs} +4 -4
  4. package/dist/{AbortError-Cq2igpZ6.cjs.map → AbortError-P0RU0Mgg.cjs.map} +1 -1
  5. package/dist/{AnnotationListSnapshot-D3mFut1e.d.cts → AnnotationListSnapshot-D9R5n2Kf.d.cts} +237 -7
  6. package/dist/{AnnotationListSnapshot-D3mFut1e.d.ts → AnnotationListSnapshot-D9R5n2Kf.d.ts} +237 -7
  7. package/dist/{DocumentSecurityService-ClTZc0zO.d.cts → DocumentSecurityService-CIx1MT0T.d.cts} +2 -2
  8. package/dist/{DocumentSecurityService-_JRjqvoI.d.ts → DocumentSecurityService-Ca6EK3-3.d.ts} +2 -2
  9. package/dist/{Engine-Bx0NOfmd.d.cts → Engine-EWWHhEIi.d.ts} +17 -4
  10. package/dist/{Engine-DxtpCYcP.d.ts → Engine-FNaAEjfb.d.cts} +17 -4
  11. package/dist/conformance.cjs +382 -95
  12. package/dist/conformance.cjs.map +1 -1
  13. package/dist/conformance.d.cts +7 -3
  14. package/dist/conformance.d.ts +7 -3
  15. package/dist/conformance.js +302 -16
  16. package/dist/conformance.js.map +1 -1
  17. package/dist/derive-BbsDk_Kz.cjs +880 -0
  18. package/dist/derive-BbsDk_Kz.cjs.map +1 -0
  19. package/dist/derive-DAFJolWu.js +647 -0
  20. package/dist/derive-DAFJolWu.js.map +1 -0
  21. package/dist/{PageInsertBlankInput-cHq9-i-z.js → format-Bbphf4zR.js} +59 -2
  22. package/dist/format-Bbphf4zR.js.map +1 -0
  23. package/dist/{PageInsertBlankInput-CqXBmFhN.cjs → format-D_epWlob.cjs} +70 -1
  24. package/dist/format-D_epWlob.cjs.map +1 -0
  25. package/dist/index.cjs +127 -107
  26. package/dist/index.d.cts +2 -2
  27. package/dist/index.d.ts +2 -2
  28. package/dist/index.js +4 -4
  29. package/dist/runtime.cjs +137 -117
  30. package/dist/runtime.cjs.map +1 -1
  31. package/dist/runtime.d.cts +29 -5
  32. package/dist/runtime.d.ts +29 -5
  33. package/dist/runtime.js +5 -5
  34. package/dist/{schemas-BLARNCgx.js → schemas-CFQGvWiu.js} +134 -4
  35. package/dist/schemas-CFQGvWiu.js.map +1 -0
  36. package/dist/{schemas-DIqFMmrC.cjs → schemas-D0g6tKa9.cjs} +250 -24
  37. package/dist/schemas-D0g6tKa9.cjs.map +1 -0
  38. package/dist/{builders-Bqm8yTpi.cjs → viewport-BWeNHZmb.cjs} +71 -132
  39. package/dist/viewport-BWeNHZmb.cjs.map +1 -0
  40. package/dist/{builders-Dqo2X-dt.js → viewport-CvMcadfQ.js} +39 -88
  41. package/dist/viewport-CvMcadfQ.js.map +1 -0
  42. package/dist/wire.cjs +25 -2
  43. package/dist/wire.cjs.map +1 -1
  44. package/dist/wire.d.cts +2739 -8
  45. package/dist/wire.d.ts +2739 -8
  46. package/dist/wire.js +10 -3
  47. package/dist/wire.js.map +1 -1
  48. package/package.json +1 -1
  49. package/dist/PageInsertBlankInput-CqXBmFhN.cjs.map +0 -1
  50. package/dist/PageInsertBlankInput-cHq9-i-z.js.map +0 -1
  51. package/dist/builders-Bqm8yTpi.cjs.map +0 -1
  52. package/dist/builders-Dqo2X-dt.js.map +0 -1
  53. package/dist/fold-2V29cxCV.cjs +0 -447
  54. package/dist/fold-2V29cxCV.cjs.map +0 -1
  55. package/dist/fold-CdEJTBTn.js +0 -334
  56. package/dist/fold-CdEJTBTn.js.map +0 -1
  57. package/dist/schemas-BLARNCgx.js.map +0 -1
  58. package/dist/schemas-DIqFMmrC.cjs.map +0 -1
@@ -0,0 +1,880 @@
1
+ const require_format = require("./format-D_epWlob.cjs");
2
+ //#region src/geometry/convert.ts
3
+ /**
4
+ * Normalize a `PdfRect` to the y-up invariant (`left <= right`, `bottom <= top`),
5
+ * regardless of how the PDF ordered the corners (a `/Rect` array or `FS_RECTF`
6
+ * may carry them in any order). THE enforcement point for the "PdfRect is always
7
+ * normalized" rule: every producer that reads a raw box from PDFium passes it
8
+ * through here, so the invariant holds once, centrally — downstream `width =
9
+ * right - left` is never negative.
10
+ */
11
+ function normalizePdfRect(r) {
12
+ return {
13
+ left: Math.min(r.left, r.right),
14
+ right: Math.max(r.left, r.right),
15
+ bottom: Math.min(r.top, r.bottom),
16
+ top: Math.max(r.top, r.bottom)
17
+ };
18
+ }
19
+ function pdfRectWidth(r) {
20
+ return r.right - r.left;
21
+ }
22
+ function pdfRectHeight(r) {
23
+ return r.top - r.bottom;
24
+ }
25
+ function pdfRectSize(r) {
26
+ return {
27
+ width: r.right - r.left,
28
+ height: r.top - r.bottom
29
+ };
30
+ }
31
+ /** Convert edges -> origin+size, staying y-up (origin at bottom-left). */
32
+ function pdfRectToOriginSize(r) {
33
+ return {
34
+ x: r.left,
35
+ y: r.bottom,
36
+ width: r.right - r.left,
37
+ height: r.top - r.bottom
38
+ };
39
+ }
40
+ /** Convert y-up origin+size back to edges. */
41
+ function pdfRectFromOriginSize(o) {
42
+ return {
43
+ left: o.x,
44
+ bottom: o.y,
45
+ right: o.x + o.width,
46
+ top: o.y + o.height
47
+ };
48
+ }
49
+ /**
50
+ * Enclosing axis-aligned box of a quad, in PDF user space. Orientation
51
+ * agnostic (correct for rotated/skewed quads) — this is what highlight
52
+ * rendering and hit-testing want.
53
+ */
54
+ function pdfQuadBounds(q) {
55
+ const xs = [
56
+ q.p1.x,
57
+ q.p2.x,
58
+ q.p3.x,
59
+ q.p4.x
60
+ ];
61
+ const ys = [
62
+ q.p1.y,
63
+ q.p2.y,
64
+ q.p3.y,
65
+ q.p4.y
66
+ ];
67
+ return {
68
+ left: Math.min(...xs),
69
+ right: Math.max(...xs),
70
+ bottom: Math.min(...ys),
71
+ top: Math.max(...ys)
72
+ };
73
+ }
74
+ /**
75
+ * Axis-aligned named-corner interpretation of a quad.
76
+ *
77
+ * VALID ONLY for upright (non-rotated, non-skewed) quads: it is derived from
78
+ * the enclosing bounds, so for rotated/skewed quads it returns the bounding
79
+ * box corners, not the true geometric corners. For arbitrary quads use the
80
+ * positional `p1..p4` or `pdfQuadBounds` directly.
81
+ */
82
+ function pdfQuadCorners(q) {
83
+ const b = pdfQuadBounds(q);
84
+ return {
85
+ topLeft: {
86
+ x: b.left,
87
+ y: b.top
88
+ },
89
+ topRight: {
90
+ x: b.right,
91
+ y: b.top
92
+ },
93
+ bottomLeft: {
94
+ x: b.left,
95
+ y: b.bottom
96
+ },
97
+ bottomRight: {
98
+ x: b.right,
99
+ y: b.bottom
100
+ }
101
+ };
102
+ }
103
+ /**
104
+ * Build a quad from named corners, in PDFium `FS_QUADPOINTSF` slot order
105
+ * (`p1 = topLeft`, `p2 = topRight`, `p3 = bottomLeft`, `p4 = bottomRight`).
106
+ * The inverse of `pdfQuadCorners` for upright quads.
107
+ */
108
+ function pdfQuadFromCorners(c) {
109
+ return {
110
+ p1: c.topLeft,
111
+ p2: c.topRight,
112
+ p3: c.bottomLeft,
113
+ p4: c.bottomRight
114
+ };
115
+ }
116
+ //#endregion
117
+ //#region src/dto/PageGeometrySnapshot.ts
118
+ /** Narrowing guard: is this run the rotated (non-upright) variant? */
119
+ function isRotatedGeometryRun(run) {
120
+ return "rotation" in run;
121
+ }
122
+ /**
123
+ * Uniform oriented-cell view over either run variant: the glyph's loose cell
124
+ * as a quad (synthesized from the box corners when the run is upright, in
125
+ * the same frame-geometric slot order).
126
+ */
127
+ function glyphLooseQuad(run, index) {
128
+ if (isRotatedGeometryRun(run)) return run.glyphs[index].looseQuad;
129
+ const b = run.glyphs[index].looseBox;
130
+ return {
131
+ p1: {
132
+ x: b.left,
133
+ y: b.top
134
+ },
135
+ p2: {
136
+ x: b.right,
137
+ y: b.top
138
+ },
139
+ p3: {
140
+ x: b.left,
141
+ y: b.bottom
142
+ },
143
+ p4: {
144
+ x: b.right,
145
+ y: b.bottom
146
+ }
147
+ };
148
+ }
149
+ /**
150
+ * Uniform AABB view over either run variant: the glyph's loose box, or the
151
+ * enclosing bounds of its oriented cell when the run is rotated. The
152
+ * conservative envelope for consumers that genuinely want a box (culling,
153
+ * scroll targets) — never a substitute for handling orientation in geometry
154
+ * that gets DRAWN.
155
+ */
156
+ function glyphLooseBounds(run, index) {
157
+ if (isRotatedGeometryRun(run)) return pdfQuadBounds(run.glyphs[index].looseQuad);
158
+ return run.glyphs[index].looseBox;
159
+ }
160
+ //#endregion
161
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/typeof.js
162
+ function _typeof(o) {
163
+ "@babel/helpers - typeof";
164
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
165
+ return typeof o;
166
+ } : function(o) {
167
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
168
+ }, _typeof(o);
169
+ }
170
+ //#endregion
171
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPrimitive.js
172
+ function toPrimitive(t, r) {
173
+ if ("object" != _typeof(t) || !t) return t;
174
+ var e = t[Symbol.toPrimitive];
175
+ if (void 0 !== e) {
176
+ var i = e.call(t, r || "default");
177
+ if ("object" != _typeof(i)) return i;
178
+ throw new TypeError("@@toPrimitive must return a primitive value.");
179
+ }
180
+ return ("string" === r ? String : Number)(t);
181
+ }
182
+ //#endregion
183
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/toPropertyKey.js
184
+ function toPropertyKey(t) {
185
+ var i = toPrimitive(t, "string");
186
+ return "symbol" == _typeof(i) ? i : i + "";
187
+ }
188
+ //#endregion
189
+ //#region \0@oxc-project+runtime@0.140.0/helpers/esm/defineProperty.js
190
+ function _defineProperty(e, r, t) {
191
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
192
+ value: t,
193
+ enumerable: !0,
194
+ configurable: !0,
195
+ writable: !0
196
+ }) : e[r] = t, e;
197
+ }
198
+ //#endregion
199
+ //#region src/errors/EngineError.ts
200
+ /**
201
+ * Single error class shared across engine implementations. Has a stable
202
+ * machine-readable `code` (see EngineErrorCode) so callers can match without
203
+ * sniffing message strings.
204
+ */
205
+ var EngineError = class EngineError extends Error {
206
+ constructor(code, message, opts = {}) {
207
+ super(message ?? code, opts.cause === void 0 ? void 0 : { cause: opts.cause });
208
+ _defineProperty(this, "name", "EngineError");
209
+ _defineProperty(this, "code", void 0);
210
+ _defineProperty(this, "details", void 0);
211
+ this.code = code;
212
+ this.details = opts.details;
213
+ }
214
+ static is(value, code) {
215
+ if (!(value instanceof EngineError) && value?.name !== "EngineError") return false;
216
+ if (code === void 0) return true;
217
+ return value.code === code;
218
+ }
219
+ toJSON() {
220
+ return {
221
+ name: "EngineError",
222
+ code: this.code,
223
+ message: this.message,
224
+ details: this.details
225
+ };
226
+ }
227
+ };
228
+ function serializeError(err) {
229
+ if (EngineError.is(err)) return err.toJSON();
230
+ if (err instanceof Error) return {
231
+ name: "EngineError",
232
+ code: err.name === "AbortError" ? require_format.EngineErrorCode.Aborted : require_format.EngineErrorCode.Unknown,
233
+ message: err.message
234
+ };
235
+ return {
236
+ name: "EngineError",
237
+ code: require_format.EngineErrorCode.Unknown,
238
+ message: String(err ?? "unknown error")
239
+ };
240
+ }
241
+ function deserializeError(payload) {
242
+ return new EngineError(payload.code, payload.message, { details: payload.details });
243
+ }
244
+ //#endregion
245
+ //#region src/annotation/relationships.ts
246
+ /**
247
+ * Classify one annotation by its relationship edge alone. Mirrors the
248
+ * spec's "practical parser rule": no `/IRT` is top-level; `/RT /Group` is
249
+ * a grouped subordinate; anything else with an `/IRT` is a reply (the
250
+ * engine has already normalized a missing `/RT` to `'reply'`).
251
+ */
252
+ function classifyRelation(a) {
253
+ if (!a.inReplyTo) return "top-level";
254
+ return a.replyType === "group" ? "grouped-subordinate" : "reply";
255
+ }
256
+ /**
257
+ * Stable string key for an {@link AnnotationRef}, used to match a child's
258
+ * `inReplyTo` against a candidate parent's `ref`. Both sides are produced
259
+ * by the engine with the same identity precedence (objectNumber, then nm,
260
+ * then index), so equal keys mean "same annotation".
261
+ */
262
+ function refKey(ref) {
263
+ switch (ref.kind) {
264
+ case "objectNumber": return `obj:${ref.pageObjectNumber}:${ref.annotObjectNumber}`;
265
+ case "nm": return `nm:${ref.pageObjectNumber}:${ref.nm}`;
266
+ case "index": return `idx:${ref.pageObjectNumber}:${ref.index}`;
267
+ }
268
+ }
269
+ /**
270
+ * Compose a flat annotation list (one page, or a whole document via
271
+ * `listRawAll()` flattened) into {@link AnnotationThread}s in primary
272
+ * order.
273
+ *
274
+ * Rules (ISO 32000 §12.5.6.2 + the spec's UI rule):
275
+ * - Annotations with no `/IRT` become thread primaries, in input order.
276
+ * - A `/RT /Group` child is attached to its primary's `groupedParts`.
277
+ * - A `/RT /R` (or default) child is attached to its primary's `replies`.
278
+ * - A child whose parent is not in the input set is treated as an
279
+ * orphan primary (defensive — e.g. a partial/filtered page slice).
280
+ *
281
+ * Limitations (v1, matches the legacy stack): threading is one level deep
282
+ * — a reply-to-a-reply is keyed to its direct parent, so it only appears
283
+ * nested if that direct parent is itself a primary. Callers that want a
284
+ * sidebar of "most annotations, not widgets/popups" should pre-filter the
285
+ * input; this helper is intentionally unopinionated about eligibility.
286
+ */
287
+ function buildThreads(annotations) {
288
+ const byKey = /* @__PURE__ */ new Map();
289
+ for (const a of annotations) {
290
+ byKey.set(refKey(a.ref), a);
291
+ if (a.nm && a.nm.length > 0) byKey.set(`nm:${a.ref.pageObjectNumber}:${a.nm}`, a);
292
+ }
293
+ const threads = [];
294
+ const threadByPrimaryKey = /* @__PURE__ */ new Map();
295
+ const primaryThread = (primary) => {
296
+ const key = refKey(primary.ref);
297
+ let thread = threadByPrimaryKey.get(key);
298
+ if (!thread) {
299
+ thread = {
300
+ primary,
301
+ groupedParts: [],
302
+ replies: []
303
+ };
304
+ threadByPrimaryKey.set(key, thread);
305
+ threads.push(thread);
306
+ }
307
+ return thread;
308
+ };
309
+ for (const a of annotations) if (!a.inReplyTo) primaryThread(a);
310
+ for (const a of annotations) {
311
+ if (!a.inReplyTo) continue;
312
+ const parent = byKey.get(refKey(a.inReplyTo));
313
+ if (!parent || parent.inReplyTo) {
314
+ primaryThread(a);
315
+ continue;
316
+ }
317
+ const thread = primaryThread(parent);
318
+ if (a.replyType === "group") thread.groupedParts.push(a);
319
+ else thread.replies.push(a);
320
+ }
321
+ return threads;
322
+ }
323
+ //#endregion
324
+ //#region src/search/fold.ts
325
+ /**
326
+ * Text folding for literal search: the deterministic normalization applied
327
+ * to BOTH the page text and the needle so that "Café" finds "cafe" and a
328
+ * line-wrapped "hello\n world" finds "hello world".
329
+ *
330
+ * Fold version 1:
331
+ * - whitespace runs collapse to a single space (any `\s`, including the
332
+ * spaces some compatibility decompositions emit) — or are dropped
333
+ * entirely with `dropWhitespace` (ignoreWhitespace),
334
+ * - each code point is NFKD-decomposed (ligatures split: "fi" → "fi",
335
+ * "²" → "2"),
336
+ * - combining marks are stripped unless `keepMarks`,
337
+ * - case is folded via upper→lower round-trip unless `keepCase` (this
338
+ * poor-man's full fold catches "ß"→"ss" and "ς"→"σ", which a plain
339
+ * `toLowerCase` misses).
340
+ *
341
+ * Every folded code unit remembers which original code point produced it
342
+ * (`map`), so match ranges found in folded space translate back to exact
343
+ * original-text ranges — the property the whole anchor stage rests on.
344
+ *
345
+ * Pre-folded corpus artifacts store this fold's output; bump
346
+ * `SEARCH_FOLD_VERSION` on ANY semantic change so stored corpora are
347
+ * rebuilt instead of silently mismatching fresh needles.
348
+ */
349
+ /** Version stamp for persisted pre-folded corpus artifacts. */
350
+ const SEARCH_FOLD_VERSION = 1;
351
+ const WHITESPACE = /\s/;
352
+ const MARKS = /\p{M}/gu;
353
+ function foldText(original, options = {}) {
354
+ const units = [];
355
+ const map = [];
356
+ let lastWasSpace = false;
357
+ let index = 0;
358
+ for (const cp of original) {
359
+ let piece;
360
+ if (WHITESPACE.test(cp)) piece = " ";
361
+ else {
362
+ piece = cp.normalize("NFKD");
363
+ if (!options.keepMarks) piece = piece.replace(MARKS, "");
364
+ if (!options.keepCase) piece = piece.toUpperCase().toLowerCase();
365
+ }
366
+ for (let u = 0; u < piece.length; u++) {
367
+ const unit = piece[u];
368
+ if (WHITESPACE.test(unit)) {
369
+ if (options.dropWhitespace || lastWasSpace) continue;
370
+ units.push(" ");
371
+ map.push(index);
372
+ lastWasSpace = true;
373
+ } else {
374
+ units.push(unit);
375
+ map.push(index);
376
+ lastWasSpace = false;
377
+ }
378
+ }
379
+ index += cp.length;
380
+ }
381
+ return {
382
+ folded: units.join(""),
383
+ map: Uint32Array.from(map),
384
+ original
385
+ };
386
+ }
387
+ /** Code-unit length of the code point starting at `index` (1 or 2). */
388
+ function codePointLengthAt(text, index) {
389
+ const unit = text.charCodeAt(index);
390
+ if (unit >= 55296 && unit <= 56319 && index + 1 < text.length) {
391
+ const next = text.charCodeAt(index + 1);
392
+ if (next >= 56320 && next <= 57343) return 2;
393
+ }
394
+ return 1;
395
+ }
396
+ /**
397
+ * Translate a match found in folded space back to the original text.
398
+ * The range covers whole original code points: a hit on either folded
399
+ * half of "fi" spans the full ligature, and a hit ending on a collapsed
400
+ * space extends only through the first whitespace char of the run (the
401
+ * remainder is presentation, not match).
402
+ */
403
+ function toOriginalRange(folded, foldedStart, foldedLength) {
404
+ const start = folded.map[foldedStart];
405
+ const lastOriginal = folded.map[foldedStart + foldedLength - 1];
406
+ return {
407
+ start,
408
+ length: lastOriginal + codePointLengthAt(folded.original, lastOriginal) - start
409
+ };
410
+ }
411
+ //#endregion
412
+ //#region src/measure/validate.ts
413
+ /** Shared preflight for HTTP, workers and calibration helpers. Does not write. */
414
+ function assertWritableMeasure(value) {
415
+ if (value.subtype !== "RL") throw new RangeError("Only rectilinear measures can be authored");
416
+ if (value.ratio !== void 0 && (typeof value.ratio !== "string" || value.ratio.includes("\0"))) throw new RangeError("Invalid scale ratio");
417
+ for (const key of [
418
+ "x",
419
+ "y",
420
+ "distance",
421
+ "area",
422
+ "angle",
423
+ "slope"
424
+ ]) {
425
+ const list = value[key];
426
+ if (list === void 0 && (key === "y" || key === "angle" || key === "slope")) continue;
427
+ if (!Array.isArray(list)) throw new RangeError(`Missing ${key} formats`);
428
+ for (const nf of list) {
429
+ if (!nf || typeof nf.unit !== "string" || !require_format.validNumberFormat(nf)) throw new RangeError("Invalid number format");
430
+ if (nf.fraction !== void 0 && ![
431
+ "decimal",
432
+ "fraction",
433
+ "round",
434
+ "truncate"
435
+ ].includes(nf.fraction)) throw new RangeError("Invalid fraction mode");
436
+ if (nf.labelPosition !== void 0 && !["prefix", "suffix"].includes(nf.labelPosition)) throw new RangeError("Invalid label position");
437
+ if (nf.fixed !== void 0 && typeof nf.fixed !== "boolean") throw new RangeError("Invalid fixed precision");
438
+ for (const key of [
439
+ "unit",
440
+ "thousands",
441
+ "decimal",
442
+ "prefixSpacing",
443
+ "suffixSpacing"
444
+ ]) {
445
+ const text = nf[key];
446
+ if (text !== void 0 && (typeof text !== "string" || text.includes("\0"))) throw new RangeError("Invalid measurement text");
447
+ }
448
+ }
449
+ }
450
+ if (value.origin !== void 0) for (const n of [value.origin.x, value.origin.y]) assertPdfFloat(n);
451
+ if (value.cyx !== void 0) {
452
+ assertPdfFloat(value.cyx);
453
+ if (Math.fround(value.cyx) <= 0) throw new RangeError("Invalid CYX");
454
+ }
455
+ }
456
+ function assertPdfFloat(n) {
457
+ if (typeof n !== "number" || !Number.isFinite(Math.fround(n))) throw new RangeError("Value is outside PDF float range");
458
+ }
459
+ //#endregion
460
+ //#region src/measure/units.ts
461
+ const METRES = {
462
+ pt: .0254 / 72,
463
+ mm: .001,
464
+ cm: .01,
465
+ m: 1,
466
+ km: 1e3,
467
+ in: .0254,
468
+ ft: .3048,
469
+ yd: .9144,
470
+ mi: 1609.344
471
+ };
472
+ const squareOf = (unit) => `${unit}2`;
473
+ function squareMetres(unit) {
474
+ return unit === "ha" ? 1e4 : unit === "acre" ? 4046.8564224 : METRES[unit.slice(0, -1)] ** 2;
475
+ }
476
+ const areaUnitLabel = (unit) => unit.endsWith("2") ? unit.slice(0, -1) + "²" : unit;
477
+ //#endregion
478
+ //#region src/measure/calibrate.ts
479
+ function positive$1(value) {
480
+ if (!Number.isFinite(value) || value <= 0) throw new RangeError("Calibration requires finite positive lengths and scales");
481
+ }
482
+ function build(perPoint, unit, ratio, format) {
483
+ positive$1(Math.fround(perPoint));
484
+ if (!Number.isInteger(Math.log10(format.precision)) || format.precision < 1 || format.precision > 1e9) throw new RangeError("Invalid decimal precision");
485
+ const areaUnit = format.areaUnit ?? squareOf(unit);
486
+ const common = {
487
+ precision: format.precision,
488
+ ...format.fixed === void 0 ? {} : { fixed: format.fixed }
489
+ };
490
+ const distance = format.imperialFeetInches ? [{
491
+ unit: "ft",
492
+ conversion: Math.fround(METRES[unit] / METRES.ft)
493
+ }, {
494
+ unit: "in",
495
+ conversion: 12,
496
+ fraction: "fraction",
497
+ precision: format.fractionalPrecision ?? 16,
498
+ ..."fixed" in common ? { fixed: common.fixed } : {}
499
+ }] : [{
500
+ unit,
501
+ conversion: 1,
502
+ ...common
503
+ }];
504
+ if (format.imperialFeetInches && (!Number.isInteger(distance[1].precision) || distance[1].precision < 1 || distance[1].precision > 2147483647)) throw new RangeError("Invalid fraction denominator");
505
+ const measure = {
506
+ subtype: "RL",
507
+ ratio,
508
+ x: [{
509
+ unit,
510
+ conversion: Math.fround(perPoint),
511
+ ...common
512
+ }],
513
+ distance,
514
+ area: [{
515
+ unit: areaUnitLabel(areaUnit),
516
+ conversion: Math.fround(METRES[unit] ** 2 / squareMetres(areaUnit)),
517
+ ...common
518
+ }]
519
+ };
520
+ assertWritableMeasure(measure);
521
+ return measure;
522
+ }
523
+ function measureFromKnownLength(userSpaceLength, real, format = { precision: 100 }) {
524
+ positive$1(userSpaceLength);
525
+ positive$1(real.value);
526
+ const perPoint = real.value / userSpaceLength;
527
+ return build(perPoint, real.unit, `1 in = ${Number((perPoint * 72).toPrecision(8))} ${real.unit}`, format);
528
+ }
529
+ function measureFromRatio(paper, real, unit, userUnit = 1, format = { precision: 100 }) {
530
+ positive$1(paper);
531
+ positive$1(real);
532
+ positive$1(userUnit);
533
+ return build(userUnit / 72 * .0254 * (real / paper) / METRES[unit], unit, `${paper}:${real}`, format);
534
+ }
535
+ //#endregion
536
+ //#region src/measure/compute.ts
537
+ const positive = (n) => Number.isFinite(n) && n > 0;
538
+ function scaleOf(measure) {
539
+ const sx = Math.fround(measure.x[0]?.conversion ?? NaN);
540
+ if (!positive(sx)) return null;
541
+ if (!measure.y) return {
542
+ sx,
543
+ sy: sx
544
+ };
545
+ const cy = Math.fround(measure.y[0]?.conversion ?? NaN);
546
+ const cyx = Math.fround(measure.cyx ?? NaN);
547
+ const sy = cy * cyx;
548
+ return positive(cy) && positive(cyx) && positive(sy) ? {
549
+ sx,
550
+ sy
551
+ } : null;
552
+ }
553
+ const measurementPoint = (p) => ({
554
+ x: Math.fround(p.x),
555
+ y: Math.fround(p.y)
556
+ });
557
+ function pathLength(points, closed, scale) {
558
+ let total = 0;
559
+ const normalized = points.map(measurementPoint);
560
+ for (let i = 0; i < (closed ? normalized.length : normalized.length - 1); i++) {
561
+ const a = normalized[i], b = normalized[(i + 1) % normalized.length];
562
+ total += Math.hypot((b.x - a.x) * scale.sx, (b.y - a.y) * scale.sy);
563
+ }
564
+ return total;
565
+ }
566
+ function polygonArea(points, scale) {
567
+ if (points.length < 3) return 0;
568
+ const normalized = points.map(measurementPoint);
569
+ const origin = normalized[0];
570
+ let twice = 0;
571
+ for (let i = 1; i < normalized.length - 1; i++) {
572
+ const a = normalized[i], b = normalized[i + 1];
573
+ twice += (a.x - origin.x) * (b.y - origin.y) - (b.x - origin.x) * (a.y - origin.y);
574
+ }
575
+ return Math.abs(twice * scale.sx * scale.sy) / 2;
576
+ }
577
+ /** A measured area must have one simple, nonzero boundary. Repeated closing
578
+ * vertices are allowed in imported PDFs; crossings and overlapping edges are not. */
579
+ function validAreaBoundary(points) {
580
+ const boundary = points.map(measurementPoint);
581
+ const same = (a, b) => a.x === b.x && a.y === b.y;
582
+ if (boundary.length > 1 && same(boundary[0], boundary[boundary.length - 1])) boundary.pop();
583
+ if (boundary.length < 3 || polygonArea(boundary, {
584
+ sx: 1,
585
+ sy: 1
586
+ }) === 0) return false;
587
+ const cross = (a, b, c) => (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
588
+ const onSegment = (a, b, p) => cross(a, b, p) === 0 && p.x >= Math.min(a.x, b.x) && p.x <= Math.max(a.x, b.x) && p.y >= Math.min(a.y, b.y) && p.y <= Math.max(a.y, b.y);
589
+ for (let i = 0; i < boundary.length; i++) {
590
+ const a = boundary[i];
591
+ const b = boundary[(i + 1) % boundary.length];
592
+ if (same(a, b)) return false;
593
+ const next = boundary[(i + 2) % boundary.length];
594
+ const doublesBack = (b.x - a.x) * (next.x - b.x) + (b.y - a.y) * (next.y - b.y) < 0;
595
+ if (cross(a, b, next) === 0 && doublesBack) return false;
596
+ for (let j = i + 1; j < boundary.length; j++) {
597
+ if (j === i + 1 || i === 0 && j === boundary.length - 1) continue;
598
+ const c = boundary[j];
599
+ const d = boundary[(j + 1) % boundary.length];
600
+ if (onSegment(a, b, c) || onSegment(a, b, d) || onSegment(c, d, a) || onSegment(c, d, b)) return false;
601
+ if (Math.sign(cross(a, b, c)) !== Math.sign(cross(a, b, d)) && Math.sign(cross(c, d, a)) !== Math.sign(cross(c, d, b))) return false;
602
+ }
603
+ }
604
+ return true;
605
+ }
606
+ //#endregion
607
+ //#region src/measure/derive.ts
608
+ function isDimension(dto) {
609
+ return dto.subtype === "line" && dto.intent === "LineDimension" || dto.subtype === "polyline" && dto.intent === "PolyLineDimension" || dto.subtype === "polygon" && dto.intent === "PolygonDimension";
610
+ }
611
+ const isReadout = (r) => !("unavailable" in r);
612
+ function measurementReadout(dto) {
613
+ if (!isDimension(dto)) return { unavailable: "not-dimension" };
614
+ if (!dto.measure) return { unavailable: "no-measure" };
615
+ if (dto.measure.subtype !== "RL") return { unavailable: "foreign-measure" };
616
+ const m = dto.measure, scale = scaleOf(m);
617
+ if (!scale) return { unavailable: "no-scale" };
618
+ const points = dto.subtype === "line" ? dto.linePoints ? [dto.linePoints.start, dto.linePoints.end] : [] : dto.vertices ?? [];
619
+ if (points.length < (dto.subtype === "polygon" ? 3 : 2) || points.some((p) => !Number.isFinite(Math.fround(p.x)) || !Number.isFinite(Math.fround(p.y)))) return { unavailable: "invalid-geometry" };
620
+ const area = dto.subtype === "polygon";
621
+ if (area && !validAreaBoundary(points)) return { unavailable: "invalid-geometry" };
622
+ const formats = area ? m.area : m.distance;
623
+ if (!formats.length) return { unavailable: area ? "no-area-format" : "no-distance-format" };
624
+ if (!formats.every(require_format.validNumberFormat)) return { unavailable: "invalid-format" };
625
+ const value = area ? polygonArea(points, scale) : pathLength(points, false, scale);
626
+ try {
627
+ return {
628
+ kind: area ? "area" : dto.subtype === "line" ? "distance" : "perimeter",
629
+ value: value * Math.fround(formats[0].conversion),
630
+ label: require_format.formatMeasurement(value, formats),
631
+ ...area && m.distance.length && m.distance.every(require_format.validNumberFormat) ? { perimeter: require_format.formatMeasurement(pathLength(points, true, scale), m.distance) } : {}
632
+ };
633
+ } catch {
634
+ return { unavailable: "invalid-format" };
635
+ }
636
+ }
637
+ function deriveMeasurementLabel(dto) {
638
+ const readout = measurementReadout(dto);
639
+ return isReadout(readout) && dto.contents !== readout.label ? {
640
+ ...dto,
641
+ contents: readout.label
642
+ } : dto;
643
+ }
644
+ //#endregion
645
+ Object.defineProperty(exports, "EngineError", {
646
+ enumerable: true,
647
+ get: function() {
648
+ return EngineError;
649
+ }
650
+ });
651
+ Object.defineProperty(exports, "METRES", {
652
+ enumerable: true,
653
+ get: function() {
654
+ return METRES;
655
+ }
656
+ });
657
+ Object.defineProperty(exports, "SEARCH_FOLD_VERSION", {
658
+ enumerable: true,
659
+ get: function() {
660
+ return SEARCH_FOLD_VERSION;
661
+ }
662
+ });
663
+ Object.defineProperty(exports, "_defineProperty", {
664
+ enumerable: true,
665
+ get: function() {
666
+ return _defineProperty;
667
+ }
668
+ });
669
+ Object.defineProperty(exports, "areaUnitLabel", {
670
+ enumerable: true,
671
+ get: function() {
672
+ return areaUnitLabel;
673
+ }
674
+ });
675
+ Object.defineProperty(exports, "assertPdfFloat", {
676
+ enumerable: true,
677
+ get: function() {
678
+ return assertPdfFloat;
679
+ }
680
+ });
681
+ Object.defineProperty(exports, "assertWritableMeasure", {
682
+ enumerable: true,
683
+ get: function() {
684
+ return assertWritableMeasure;
685
+ }
686
+ });
687
+ Object.defineProperty(exports, "buildThreads", {
688
+ enumerable: true,
689
+ get: function() {
690
+ return buildThreads;
691
+ }
692
+ });
693
+ Object.defineProperty(exports, "classifyRelation", {
694
+ enumerable: true,
695
+ get: function() {
696
+ return classifyRelation;
697
+ }
698
+ });
699
+ Object.defineProperty(exports, "deriveMeasurementLabel", {
700
+ enumerable: true,
701
+ get: function() {
702
+ return deriveMeasurementLabel;
703
+ }
704
+ });
705
+ Object.defineProperty(exports, "deserializeError", {
706
+ enumerable: true,
707
+ get: function() {
708
+ return deserializeError;
709
+ }
710
+ });
711
+ Object.defineProperty(exports, "foldText", {
712
+ enumerable: true,
713
+ get: function() {
714
+ return foldText;
715
+ }
716
+ });
717
+ Object.defineProperty(exports, "glyphLooseBounds", {
718
+ enumerable: true,
719
+ get: function() {
720
+ return glyphLooseBounds;
721
+ }
722
+ });
723
+ Object.defineProperty(exports, "glyphLooseQuad", {
724
+ enumerable: true,
725
+ get: function() {
726
+ return glyphLooseQuad;
727
+ }
728
+ });
729
+ Object.defineProperty(exports, "isDimension", {
730
+ enumerable: true,
731
+ get: function() {
732
+ return isDimension;
733
+ }
734
+ });
735
+ Object.defineProperty(exports, "isReadout", {
736
+ enumerable: true,
737
+ get: function() {
738
+ return isReadout;
739
+ }
740
+ });
741
+ Object.defineProperty(exports, "isRotatedGeometryRun", {
742
+ enumerable: true,
743
+ get: function() {
744
+ return isRotatedGeometryRun;
745
+ }
746
+ });
747
+ Object.defineProperty(exports, "measureFromKnownLength", {
748
+ enumerable: true,
749
+ get: function() {
750
+ return measureFromKnownLength;
751
+ }
752
+ });
753
+ Object.defineProperty(exports, "measureFromRatio", {
754
+ enumerable: true,
755
+ get: function() {
756
+ return measureFromRatio;
757
+ }
758
+ });
759
+ Object.defineProperty(exports, "measurementPoint", {
760
+ enumerable: true,
761
+ get: function() {
762
+ return measurementPoint;
763
+ }
764
+ });
765
+ Object.defineProperty(exports, "measurementReadout", {
766
+ enumerable: true,
767
+ get: function() {
768
+ return measurementReadout;
769
+ }
770
+ });
771
+ Object.defineProperty(exports, "normalizePdfRect", {
772
+ enumerable: true,
773
+ get: function() {
774
+ return normalizePdfRect;
775
+ }
776
+ });
777
+ Object.defineProperty(exports, "pathLength", {
778
+ enumerable: true,
779
+ get: function() {
780
+ return pathLength;
781
+ }
782
+ });
783
+ Object.defineProperty(exports, "pdfQuadBounds", {
784
+ enumerable: true,
785
+ get: function() {
786
+ return pdfQuadBounds;
787
+ }
788
+ });
789
+ Object.defineProperty(exports, "pdfQuadCorners", {
790
+ enumerable: true,
791
+ get: function() {
792
+ return pdfQuadCorners;
793
+ }
794
+ });
795
+ Object.defineProperty(exports, "pdfQuadFromCorners", {
796
+ enumerable: true,
797
+ get: function() {
798
+ return pdfQuadFromCorners;
799
+ }
800
+ });
801
+ Object.defineProperty(exports, "pdfRectFromOriginSize", {
802
+ enumerable: true,
803
+ get: function() {
804
+ return pdfRectFromOriginSize;
805
+ }
806
+ });
807
+ Object.defineProperty(exports, "pdfRectHeight", {
808
+ enumerable: true,
809
+ get: function() {
810
+ return pdfRectHeight;
811
+ }
812
+ });
813
+ Object.defineProperty(exports, "pdfRectSize", {
814
+ enumerable: true,
815
+ get: function() {
816
+ return pdfRectSize;
817
+ }
818
+ });
819
+ Object.defineProperty(exports, "pdfRectToOriginSize", {
820
+ enumerable: true,
821
+ get: function() {
822
+ return pdfRectToOriginSize;
823
+ }
824
+ });
825
+ Object.defineProperty(exports, "pdfRectWidth", {
826
+ enumerable: true,
827
+ get: function() {
828
+ return pdfRectWidth;
829
+ }
830
+ });
831
+ Object.defineProperty(exports, "polygonArea", {
832
+ enumerable: true,
833
+ get: function() {
834
+ return polygonArea;
835
+ }
836
+ });
837
+ Object.defineProperty(exports, "refKey", {
838
+ enumerable: true,
839
+ get: function() {
840
+ return refKey;
841
+ }
842
+ });
843
+ Object.defineProperty(exports, "scaleOf", {
844
+ enumerable: true,
845
+ get: function() {
846
+ return scaleOf;
847
+ }
848
+ });
849
+ Object.defineProperty(exports, "serializeError", {
850
+ enumerable: true,
851
+ get: function() {
852
+ return serializeError;
853
+ }
854
+ });
855
+ Object.defineProperty(exports, "squareMetres", {
856
+ enumerable: true,
857
+ get: function() {
858
+ return squareMetres;
859
+ }
860
+ });
861
+ Object.defineProperty(exports, "squareOf", {
862
+ enumerable: true,
863
+ get: function() {
864
+ return squareOf;
865
+ }
866
+ });
867
+ Object.defineProperty(exports, "toOriginalRange", {
868
+ enumerable: true,
869
+ get: function() {
870
+ return toOriginalRange;
871
+ }
872
+ });
873
+ Object.defineProperty(exports, "validAreaBoundary", {
874
+ enumerable: true,
875
+ get: function() {
876
+ return validAreaBoundary;
877
+ }
878
+ });
879
+
880
+ //# sourceMappingURL=derive-BbsDk_Kz.cjs.map