@fedify/vocab-tools 2.5.0-dev.2513 → 2.5.0-dev.2516

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.js CHANGED
@@ -7,7 +7,7 @@ import { parse } from "yaml";
7
7
  import { pascalCase } from "es-toolkit";
8
8
  //#region deno.json
9
9
  var name = "@fedify/vocab-tools";
10
- var version = "2.5.0-dev.2513+d7ab5950";
10
+ var version = "2.5.0-dev.2516+42d3ed0b";
11
11
  //#endregion
12
12
  //#region src/type.ts
13
13
  const HEURISTICS_CONTEXTS = [
@@ -616,7 +616,7 @@ async function generateField(property, types, prefix = "#") {
616
616
  if (areAllScalarTypes(property.range, types)) return `${fieldName}: (${getTypeNames(property.range, types, true)})[] = [];\n`;
617
617
  else return `
618
618
  ${fieldName}: (${getTypeNames(property.range, types)} | URL)[] = [];
619
- ${await getFieldName(property.uri, `${prefix}_trust`)}: Set<number> = new Set();
619
+ ${await getFieldName(property.uri, `${prefix}_trust`)}: VocabTrustSet = new Set();
620
620
  `;
621
621
  }
622
622
  async function* generateFields(typeUri, types) {
@@ -1323,6 +1323,35 @@ async function* generateParametersType(typeUri, types, parentheses = true, exclu
1323
1323
  }
1324
1324
  if (parentheses) yield "}\n";
1325
1325
  }
1326
+ function generateValidatedArrayCopy(name, typeNames, typeGuards) {
1327
+ return `
1328
+ let copied!: (${typeNames})[];
1329
+ let valid = false;
1330
+ if (Array.isArray(values.${name})) {
1331
+ const array = values.${name};
1332
+ const test = (v: ${typeNames}): boolean => ${typeGuards};
1333
+ let checked: VocabArrayValidation | undefined;
1334
+ if (array.length < vocabSparseArrayMinimumLength
1335
+ ? array.every(test)
1336
+ : (checked = vocabValidatePropertyArray(array, test)).valid) {
1337
+ const input = values.${name};
1338
+ if (input.length < vocabSparseArrayMinimumLength && !checked?.sparse) {
1339
+ copied = input.slice();
1340
+ valid = true;
1341
+ } else {
1342
+ const result = vocabCopyValidatedPropertyArray(
1343
+ input, test, checked ?? { valid: true, sparse: false },
1344
+ );
1345
+ if (result.ok) {
1346
+ copied = result.array;
1347
+ valid = true;
1348
+ }
1349
+ }
1350
+ }
1351
+ }
1352
+ if (valid) {
1353
+ `.trimEnd() + "\n";
1354
+ }
1326
1355
  async function* generateConstructor(typeUri, types) {
1327
1356
  const type = types[typeUri];
1328
1357
  yield `
@@ -1414,16 +1443,13 @@ async function* generateConstructor(typeUri, types) {
1414
1443
  );
1415
1444
  }
1416
1445
  `;
1446
+ yield generateValidatedArrayCopy(property.pluralName, typeNames, typeGuards);
1417
1447
  yield `
1418
- if (Array.isArray(values.${property.pluralName}) &&
1419
- values.${property.pluralName}.every(v => ${typeGuards})) {
1420
1448
  // @ts-ignore: type is checked above.
1421
- this.${fieldName} = values.${property.pluralName}.slice();
1449
+ this.${fieldName} = copied;
1422
1450
  `;
1423
1451
  if (!allScalarTypes) yield `
1424
- for (let i = 0; i < values.${property.pluralName}.length; i++) {
1425
- this.${trustFieldName}.add(i);
1426
- }
1452
+ vocabSetTrustPrefix(this.${trustFieldName}, this.${fieldName}.length);
1427
1453
  `;
1428
1454
  yield `
1429
1455
  } else {
@@ -1452,8 +1478,8 @@ async function* generateCloner(typeUri, types) {
1452
1478
  * object. Hydrating a top-level property of the clone does not update this
1453
1479
  * instance's property.
1454
1480
  *
1455
- * To resolve properties without sharing nested objects, serialize and
1456
- * re-parse the instance before hydration rather than using this method.
1481
+ * To resolve properties without sharing nested objects, use
1482
+ * {@link ${type.name}.deepClone} before hydration.
1457
1483
  * See the [vocabulary manual](https://fedify.dev/manual/vocab#immutability)
1458
1484
  * for details, including how cached JSON-LD affects serialization.
1459
1485
  *
@@ -1502,8 +1528,11 @@ async function* generateCloner(typeUri, types) {
1502
1528
  const fieldName = await getFieldName(property.uri);
1503
1529
  const trustFieldName = await getFieldName(property.uri, "#_trust");
1504
1530
  const allScalarTypes = areAllScalarTypes(property.range, types);
1505
- yield `clone.${fieldName} = this.${fieldName}.slice();`;
1506
- if (!allScalarTypes) yield `clone.${trustFieldName} = new Set(this.${trustFieldName});`;
1531
+ yield `clone.${fieldName} = this.${fieldName}.length < vocabSparseArrayMinimumLength
1532
+ ? this.${fieldName}.slice() : vocabCopyPropertyArray(this.${fieldName});`;
1533
+ if (!allScalarTypes) yield `clone.${trustFieldName} = vocabCopyTrustSet(
1534
+ this.${trustFieldName}, clone.${trustFieldName},
1535
+ );`;
1507
1536
  if (hasSingularAccessor(property)) {
1508
1537
  let typeGuards = getTypeGuards(property.range, types, `values.${property.singularName}`);
1509
1538
  let typeNames = getTypeNames(property.range, types);
@@ -1518,7 +1547,8 @@ async function* generateCloner(typeUri, types) {
1518
1547
  // @ts-ignore: type is checked above.
1519
1548
  clone.${fieldName} = [values.${property.singularName}];
1520
1549
  `;
1521
- if (!allScalarTypes) yield `clone.${trustFieldName} = new Set([0]);`;
1550
+ if (!allScalarTypes) yield `clone.${trustFieldName} = new Set();
1551
+ clone.${trustFieldName}[vocabTrustPrefix] = 1;`;
1522
1552
  yield `
1523
1553
  } else {
1524
1554
  throw new TypeError(
@@ -1549,17 +1579,14 @@ async function* generateCloner(typeUri, types) {
1549
1579
  );
1550
1580
  }
1551
1581
  `;
1582
+ yield generateValidatedArrayCopy(property.pluralName, typeNames, typeGuards);
1552
1583
  yield `
1553
- if (Array.isArray(values.${property.pluralName}) &&
1554
- values.${property.pluralName}.every(v => ${typeGuards})) {
1555
1584
  // @ts-ignore: type is checked above.
1556
- clone.${fieldName} = values.${property.pluralName}.slice();
1585
+ clone.${fieldName} = copied;
1557
1586
  `;
1558
1587
  if (!allScalarTypes) yield `
1559
1588
  clone.${trustFieldName} = new Set();
1560
- for (let i = 0; i < values.${property.pluralName}.length; i++) {
1561
- clone.${trustFieldName}.add(i);
1562
- }
1589
+ vocabSetTrustPrefix(clone.${trustFieldName}, clone.${fieldName}.length);
1563
1590
  `;
1564
1591
  yield `
1565
1592
  } else {
@@ -1575,7 +1602,223 @@ async function* generateCloner(typeUri, types) {
1575
1602
  yield `
1576
1603
  return clone;
1577
1604
  }
1605
+ `.trimEnd() + "\n";
1606
+ }
1607
+ async function* generateDeepCloner(typeUri, types) {
1608
+ const type = types[typeUri];
1609
+ yield `
1610
+ /**
1611
+ * Copies this instance and its nested vocabulary objects, optionally
1612
+ * replacing property values. Replacement values are copied too.
1613
+ *
1614
+ * Property arrays, URLs and byte arrays are independent of the source.
1615
+ * Repeated references remain shared within the copy. References to this
1616
+ * source in replacement values receive a separate copy of its pre-update
1617
+ * values, rather than referring back to the updated root.
1618
+ * Other scalar values, including opaque cryptographic keys, are shared.
1619
+ *
1620
+ * Each copied object retains its own default loaders, tracer, verifier
1621
+ * and base URL. Options override defaults only on the root instance.
1622
+ * This method does not fetch or serialize objects. Cached JSON-LD and
1623
+ * retained signed representations are not copied; unknown JSON-LD
1624
+ * properties and original formatting are not preserved. Sign the copy
1625
+ * again if it needs a valid proof.
1626
+ *
1627
+ * Trust and portable provenance follow clone() rules at every level.
1628
+ * Historical referrers within the graph are copied without replacements;
1629
+ * referrers outside the graph still point at the original external objects.
1630
+ * Custom clone() overrides must return fresh, compatible instances and
1631
+ * remain responsible for their own constructor and cloning side effects.
1632
+ * Large sparse property arrays with ordinary data entries are copied using
1633
+ * a snapshot of their length and present indices. Entries added after a
1634
+ * snapshot are not visited; deleted entries are skipped, and values changed
1635
+ * after the snapshot are read when reached. Custom
1636
+ * clone() overrides must avoid structurally changing a field being copied
1637
+ * if they need all its nested objects to be independent of the source.
1638
+ *
1639
+ * @param values The values to replace before copying the graph.
1640
+ * @param options Root loader and verifier overrides. Undefined options
1641
+ * retain the corresponding defaults.
1642
+ * @returns An independent copy of the stored vocabulary graph.
1643
+ * @since 2.5.0
1644
+ */
1645
+ ${emitOverride$1(typeUri, types)} deepClone(values:
1578
1646
  `;
1647
+ for await (const code of generateParametersType(typeUri, types)) yield code;
1648
+ yield `= {}, options: {
1649
+ documentLoader?: DocumentLoader,
1650
+ contextLoader?: DocumentLoader,
1651
+ verifyPortableObject?: PortableObjectVerifier,
1652
+ } = {}): ${type.name} {
1653
+ const cloneOptions = {
1654
+ documentLoader: options.documentLoader ?? this._documentLoader,
1655
+ contextLoader: options.contextLoader ?? this._contextLoader,
1656
+ verifyPortableObject: options.verifyPortableObject ?? this._verifyPortableObject,
1657
+ tracerProvider: this._tracerProvider,
1658
+ baseUrl: this._baseUrl,
1659
+ };
1660
+ return deepCloneGraph(this, this.clone(values, cloneOptions));
1661
+ }\n`;
1662
+ }
1663
+ //#endregion
1664
+ //#region src/deep-clone.ts
1665
+ function needsCopy(property, types) {
1666
+ return property.range.some((uri) => uri in types || ["URL", "Uint8Array"].includes(getTypeName(uri, types)));
1667
+ }
1668
+ /** Emits module-private graph-copy support, shared by all generated classes. */
1669
+ function generateDeepCloneHelpers() {
1670
+ return `
1671
+ interface DeepCloneContext {
1672
+ value<T>(value: T): T;
1673
+ }
1674
+
1675
+ interface DeepCloneDescriptor {
1676
+ create(source: object): object;
1677
+ copy(destination: object, context: DeepCloneContext): void;
1678
+ }
1679
+
1680
+ const deepCloneDescriptors = new Map<object, DeepCloneDescriptor>();
1681
+
1682
+ function getDeepCloneDescriptor(value: object): DeepCloneDescriptor | undefined {
1683
+ let prototype: object | null = globalThis.Object.getPrototypeOf(value);
1684
+ while (prototype != null) {
1685
+ const descriptor = deepCloneDescriptors.get(prototype);
1686
+ if (descriptor != null) return descriptor;
1687
+ prototype = globalThis.Object.getPrototypeOf(prototype);
1688
+ }
1689
+ return undefined;
1690
+ }
1691
+
1692
+ function deepCloneGraph<T extends object>(source: object, root: T): T {
1693
+ const memo = new Map<object, object>();
1694
+ const destinations = new Set<object>();
1695
+ const shells: object[] = [];
1696
+ let next = 0;
1697
+
1698
+ function enqueue(original: object, destination: object): void {
1699
+ if (destination == null || typeof destination !== "object" ||
1700
+ original === destination || destinations.has(destination) ||
1701
+ !globalThis.Object.prototype.isPrototypeOf.call(
1702
+ globalThis.Object.getPrototypeOf(original), destination
1703
+ ) || getDeepCloneDescriptor(destination) == null) {
1704
+ throw new TypeError("clone() must return a fresh, compatible instance.");
1705
+ }
1706
+ destinations.add(destination);
1707
+ shells.push(destination);
1708
+ }
1709
+
1710
+ const context: DeepCloneContext = {
1711
+ value<V>(value: V): V {
1712
+ if (value == null || typeof value !== "object") return value;
1713
+ const existing = memo.get(value);
1714
+ if (existing != null) return existing as V;
1715
+ if (value instanceof URL) {
1716
+ const copy = new URL(value.href);
1717
+ memo.set(value, copy);
1718
+ return copy as V;
1719
+ }
1720
+ if (value instanceof Uint8Array) {
1721
+ const copy = new Uint8Array(value);
1722
+ memo.set(value, copy);
1723
+ return copy as V;
1724
+ }
1725
+ const descriptor = getDeepCloneDescriptor(value);
1726
+ // Other supported scalars (Temporal, LanguageString, Intl.Locale,
1727
+ // CryptoKey and class constructors) are shared as immutable values.
1728
+ if (descriptor == null) return value;
1729
+ const copy = descriptor.create(value);
1730
+ enqueue(value, copy);
1731
+ memo.set(value, copy);
1732
+ return copy as V;
1733
+ },
1734
+ };
1735
+
1736
+ function drain(): void {
1737
+ while (next < shells.length) {
1738
+ const shell = shells[next++];
1739
+ getDeepCloneDescriptor(shell)!.copy(shell, context);
1740
+ }
1741
+ }
1742
+
1743
+ // The effective root includes replacements. References to the source root
1744
+ // instead receive a separate copy of its pre-update values.
1745
+ enqueue(source, root);
1746
+ drain();
1747
+
1748
+ // Discover historical root ancestry without substituting replacement values
1749
+ // into it. The resolver deliberately returns undefined in this first pass.
1750
+ const count = shells.length;
1751
+ for (let i = 0; i < count; i++) {
1752
+ retargetPortableReferrer(shells[i], (original) => {
1753
+ if (original === source) context.value(source);
1754
+ return undefined;
1755
+ });
1756
+ }
1757
+ drain();
1758
+ for (const shell of shells) {
1759
+ retargetPortableReferrer(shell, (original) => memo.get(original));
1760
+ }
1761
+ return root;
1762
+ }
1763
+ `;
1764
+ }
1765
+ /** Emits private-field copiers inside static blocks, keeping them out of d.ts. */
1766
+ async function* generateDeepCloneDescriptor(typeUri, types) {
1767
+ const type = types[typeUri];
1768
+ const properties = type.properties.filter((p) => needsCopy(p, types));
1769
+ if (type.extends != null && properties.length < 1) return;
1770
+ yield `static {\n`;
1771
+ if (type.extends == null) yield `deepCloneDescriptors.set(this.prototype, {
1772
+ create(value: object): object {
1773
+ const source = value as ${type.name};
1774
+ const options = {
1775
+ documentLoader: source.#documentLoader,
1776
+ contextLoader: source.#contextLoader,
1777
+ tracerProvider: source.#tracerProvider,
1778
+ verifyPortableObject: source.#verifyPortableObject,
1779
+ baseUrl: source.#_baseUrl,
1780
+ };
1781
+ return source.clone({}, options);
1782
+ },
1783
+ copy(value: object, context: DeepCloneContext): void {
1784
+ const node = value as ${type.name};
1785
+ const identified = node as { id: URL | null };
1786
+ identified.id = context.value(identified.id);
1787
+ `;
1788
+ else yield `const base = getDeepCloneDescriptor(this.prototype)!;
1789
+ deepCloneDescriptors.set(this.prototype, {
1790
+ create: base.create,
1791
+ copy(value: object, context: DeepCloneContext): void {
1792
+ base.copy(value, context);
1793
+ const node = value as ${type.name};
1794
+ `;
1795
+ for (const property of properties) {
1796
+ const field = await getFieldName(property.uri);
1797
+ yield `
1798
+ {
1799
+ const array = node.${field};
1800
+ const snapshot = array.length < vocabSparseArrayMinimumLength
1801
+ ? undefined : vocabSparseArraySnapshot(array);
1802
+ if (snapshot != null) {
1803
+ for (const i of snapshot.indices) {
1804
+ if (!globalThis.Object.hasOwn(array, i)) continue;
1805
+ const value = array[i];
1806
+ if (value != null && typeof value === "object") {
1807
+ array[i] = context.value(value);
1808
+ }
1809
+ }
1810
+ } else {
1811
+ for (let i = 0; i < node.${field}.length; i++) {
1812
+ const value = node.${field}[i];
1813
+ if (value != null && typeof value === "object") {
1814
+ node.${field}[i] = context.value(value);
1815
+ }
1816
+ }
1817
+ }
1818
+ }
1819
+ `;
1820
+ }
1821
+ yield `} }); }\n`;
1579
1822
  }
1580
1823
  //#endregion
1581
1824
  //#region src/inspector.ts
@@ -2082,7 +2325,8 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2082
2325
  }
2083
2326
  let v = this.${await getFieldName(property.uri)}[0];
2084
2327
  if (!(v instanceof URL) &&
2085
- !this.${await getFieldName(property.uri, "#_trust")}.has(0)) {
2328
+ !(0 < (this.${await getFieldName(property.uri, "#_trust")}[vocabTrustPrefix] ?? 0) ||
2329
+ this.${await getFieldName(property.uri, "#_trust")}.has(0))) {
2086
2330
  if (v.id == null) {
2087
2331
  if (isUnsecuredPortableObject(this)) {
2088
2332
  warnUnverifiableEmbeddedObject(this, ${JSON.stringify(property.uri)});
@@ -2146,7 +2390,8 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2146
2390
  mustDereferencePortableObject(
2147
2391
  this, ${trustOwner}, v.id, options,
2148
2392
  )) &&
2149
- !this.${await getFieldName(property.uri, "#_trust")}.has(0)) {
2393
+ !(0 < (this.${await getFieldName(property.uri, "#_trust")}[vocabTrustPrefix] ?? 0) ||
2394
+ this.${await getFieldName(property.uri, "#_trust")}.has(0))) {
2150
2395
  if (options.crossOrigin === "throw") {
2151
2396
  throw new Error(
2152
2397
  "The property object's @id (" + v.id.href + ") has a different " +
@@ -2235,7 +2480,8 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2235
2480
  for (let i = 0; i < vs.length; i++) {
2236
2481
  let v = vs[i];
2237
2482
  if (!(v instanceof URL) &&
2238
- !this.${await getFieldName(property.uri, "#_trust")}.has(i)) {
2483
+ !(i < (this.${await getFieldName(property.uri, "#_trust")}[vocabTrustPrefix] ?? 0) ||
2484
+ this.${await getFieldName(property.uri, "#_trust")}.has(i))) {
2239
2485
  if (v.id == null) {
2240
2486
  if (isUnsecuredPortableObject(this)) {
2241
2487
  warnUnverifiableEmbeddedObject(this, ${JSON.stringify(property.uri)});
@@ -2303,7 +2549,8 @@ async function* generateProperty(type, property, types, moduleVarNames) {
2303
2549
  mustDereferencePortableObject(
2304
2550
  this, ${trustOwner}, v.id, options,
2305
2551
  )) &&
2306
- !this.${await getFieldName(property.uri, "#_trust")}.has(i)) {
2552
+ !(i < (this.${await getFieldName(property.uri, "#_trust")}[vocabTrustPrefix] ?? 0) ||
2553
+ this.${await getFieldName(property.uri, "#_trust")}.has(i))) {
2307
2554
  if (options.crossOrigin === "throw") {
2308
2555
  throw new Error(
2309
2556
  "The property object's @id (" + v.id.href + ") has a different " +
@@ -2336,6 +2583,206 @@ async function* generateProperties(typeUri, types, moduleVarNames) {
2336
2583
  for (const property of type.properties) yield* generateProperty(type, property, types, moduleVarNames);
2337
2584
  }
2338
2585
  //#endregion
2586
+ //#region src/property-array.ts
2587
+ /** Emits module-private sparse property-array validation and copying helpers. */
2588
+ function generatePropertyArrayHelpers() {
2589
+ return `
2590
+ interface VocabSparseArraySnapshot {
2591
+ length: number;
2592
+ indices: number[];
2593
+ }
2594
+
2595
+ interface VocabArrayValidation {
2596
+ valid: boolean;
2597
+ sparse: boolean;
2598
+ }
2599
+
2600
+ type VocabArrayCopy<T> = { ok: true; array: T[] } | { ok: false };
2601
+
2602
+ // Most fields have no trusted prefix. Keep that metadata on the existing Set
2603
+ // so empty fields need neither another object nor another instance slot.
2604
+ const vocabTrustPrefix: unique symbol = Symbol("vocabulary trust prefix");
2605
+ type VocabTrustSet = Set<number> & { [vocabTrustPrefix]?: number };
2606
+
2607
+ function vocabSetTrustPrefix(trust: VocabTrustSet, prefix: number): void {
2608
+ if (prefix > 0) trust[vocabTrustPrefix] = prefix;
2609
+ }
2610
+
2611
+ function vocabCopyTrustSet(
2612
+ trust: VocabTrustSet,
2613
+ destination: VocabTrustSet,
2614
+ ): VocabTrustSet {
2615
+ // clone() already constructed the destination. Reuse its empty Set only
2616
+ // when constructor defaults cannot contribute trust to the copied field.
2617
+ const copy: VocabTrustSet = trust !== destination && trust.size === 0 &&
2618
+ destination.size === 0 && destination[vocabTrustPrefix] == null
2619
+ ? destination : new Set(trust);
2620
+ const prefix = trust[vocabTrustPrefix];
2621
+ if (prefix != null && prefix > 0) copy[vocabTrustPrefix] = prefix;
2622
+ return copy;
2623
+ }
2624
+
2625
+ // These thresholds select an optimization, not a limit on property arrays.
2626
+ const vocabSparseArrayMinimumLength = 4096;
2627
+ const vocabSparseArrayProbeCount = 8;
2628
+ const vocabSparseArrayPresentProbeLimit = 4;
2629
+ const vocabArrayPrototype = Array.prototype;
2630
+ const vocabObjectPrototype = globalThis.Object.prototype;
2631
+ const vocabArrayDescriptors = ["constructor", "every", "slice"].map(
2632
+ key => globalThis.Object.getOwnPropertyDescriptor(vocabArrayPrototype, key),
2633
+ );
2634
+ const vocabArraySpeciesDescriptor = globalThis.Object.getOwnPropertyDescriptor(
2635
+ Array, Symbol.species,
2636
+ );
2637
+
2638
+ function vocabSameArrayDescriptor(
2639
+ actual: PropertyDescriptor | undefined,
2640
+ expected: PropertyDescriptor | undefined,
2641
+ ): boolean {
2642
+ return actual?.value === expected?.value && actual?.get === expected?.get &&
2643
+ actual?.set === expected?.set && actual?.writable === expected?.writable &&
2644
+ actual?.enumerable === expected?.enumerable &&
2645
+ actual?.configurable === expected?.configurable;
2646
+ }
2647
+
2648
+ function vocabArrayIndex(key: string): number | undefined {
2649
+ const index = Number(key);
2650
+ return Number.isInteger(index) && index >= 0 && index < 0xffffffff &&
2651
+ String(index) === key
2652
+ ? index
2653
+ : undefined;
2654
+ }
2655
+
2656
+ function vocabSparseArraySnapshot(
2657
+ array: unknown[],
2658
+ ): VocabSparseArraySnapshot | undefined {
2659
+ if (!Array.isArray(array)) return undefined;
2660
+ const length = array.length;
2661
+ // Small dense fields take no prototype or key-enumeration overhead.
2662
+ if (length < vocabSparseArrayMinimumLength) return undefined;
2663
+ if (!Number.isInteger(length) || length > 0xffffffff ||
2664
+ globalThis.Object.getPrototypeOf(array) !== vocabArrayPrototype ||
2665
+ globalThis.Object.getPrototypeOf(vocabArrayPrototype) !==
2666
+ vocabObjectPrototype ||
2667
+ globalThis.Object.getPrototypeOf(vocabObjectPrototype) !== null) {
2668
+ return undefined;
2669
+ }
2670
+ const methods = ["constructor", "every", "slice"];
2671
+ for (let i = 0; i < methods.length; i++) {
2672
+ const key = methods[i];
2673
+ if (globalThis.Object.hasOwn(array, key) ||
2674
+ !vocabSameArrayDescriptor(
2675
+ globalThis.Object.getOwnPropertyDescriptor(vocabArrayPrototype, key),
2676
+ vocabArrayDescriptors[i],
2677
+ )) return undefined;
2678
+ }
2679
+ if (!vocabSameArrayDescriptor(
2680
+ globalThis.Object.getOwnPropertyDescriptor(Array, Symbol.species),
2681
+ vocabArraySpeciesDescriptor,
2682
+ )) return undefined;
2683
+
2684
+ // Descriptor probes do not invoke element getters. Plainly dense arrays
2685
+ // keep native iteration without enumerating all their keys.
2686
+ let present = 0;
2687
+ for (let i = 0; i < vocabSparseArrayProbeCount; i++) {
2688
+ const index = Math.floor(i * (length - 1) / (vocabSparseArrayProbeCount - 1));
2689
+ if (globalThis.Object.getOwnPropertyDescriptor(array, index) != null &&
2690
+ ++present >= vocabSparseArrayPresentProbeLimit) return undefined;
2691
+ }
2692
+ for (const prototype of [vocabArrayPrototype, vocabObjectPrototype]) {
2693
+ for (const key of globalThis.Object.getOwnPropertyNames(prototype)) {
2694
+ if (vocabArrayIndex(key) != null) return undefined;
2695
+ }
2696
+ }
2697
+ const indices: number[] = [];
2698
+ for (const key of globalThis.Object.getOwnPropertyNames(array)) {
2699
+ const index = vocabArrayIndex(key);
2700
+ if (index != null && index < length) indices.push(index);
2701
+ }
2702
+ if (indices.length >= length / 2) return undefined;
2703
+ for (const index of indices) {
2704
+ const descriptor = globalThis.Object.getOwnPropertyDescriptor(array, index);
2705
+ if (descriptor == null || !("value" in descriptor)) return undefined;
2706
+ }
2707
+ // Ordinary array keys already have canonical index order. This guard is
2708
+ // not a Proxy detector; reflection traps and errors remain observable.
2709
+ return { length, indices };
2710
+ }
2711
+
2712
+ function vocabValidatePropertyArray<T>(
2713
+ array: T[],
2714
+ test: (value: T) => boolean,
2715
+ ): VocabArrayValidation {
2716
+ const snapshot = vocabSparseArraySnapshot(array);
2717
+ if (snapshot == null) return { valid: array.every(test), sparse: false };
2718
+ for (const index of snapshot.indices) {
2719
+ if (globalThis.Object.hasOwn(array, index) && !test(array[index])) {
2720
+ return { valid: false, sparse: true };
2721
+ }
2722
+ }
2723
+ return { valid: true, sparse: true };
2724
+ }
2725
+
2726
+ function vocabDefineArrayEntry<T>(array: T[], index: number, value: T): void {
2727
+ globalThis.Object.defineProperty(array, index, {
2728
+ value, writable: true, enumerable: true, configurable: true,
2729
+ });
2730
+ }
2731
+
2732
+ function vocabCopySparsePropertyArray<T>(
2733
+ array: T[],
2734
+ snapshot: VocabSparseArraySnapshot,
2735
+ test?: (value: T) => boolean,
2736
+ ): VocabArrayCopy<T> {
2737
+ const copy: T[] = [];
2738
+ // Seed dictionary storage before low indices or the final length can
2739
+ // allocate storage for every hole. The temporary entry stays private.
2740
+ if (snapshot.indices[snapshot.indices.length - 1] !== snapshot.length - 1) {
2741
+ globalThis.Object.defineProperty(copy, snapshot.length - 1, {
2742
+ value: undefined, writable: true, enumerable: true, configurable: true,
2743
+ });
2744
+ delete copy[snapshot.length - 1];
2745
+ }
2746
+ for (const index of snapshot.indices) {
2747
+ if (!globalThis.Object.hasOwn(array, index)) continue;
2748
+ const value = array[index];
2749
+ if (test != null && !test(value)) return { ok: false };
2750
+ vocabDefineArrayEntry(copy, index, value);
2751
+ }
2752
+ // A validation callback may have deleted the last snapshot entry.
2753
+ if (copy.length < snapshot.length) {
2754
+ globalThis.Object.defineProperty(copy, snapshot.length - 1, {
2755
+ value: undefined, writable: true, enumerable: true, configurable: true,
2756
+ });
2757
+ delete copy[snapshot.length - 1];
2758
+ }
2759
+ copy.length = snapshot.length;
2760
+ return { ok: true, array: copy };
2761
+ }
2762
+
2763
+ function vocabCopyPropertyArray<T>(array: T[]): T[] {
2764
+ const snapshot = vocabSparseArraySnapshot(array);
2765
+ if (snapshot == null) return array.slice();
2766
+ const copied = vocabCopySparsePropertyArray(array, snapshot);
2767
+ // Without a predicate the private copy cannot fail validation.
2768
+ return (copied as { ok: true; array: T[] }).array;
2769
+ }
2770
+
2771
+ function vocabCopyValidatedPropertyArray<T>(
2772
+ array: T[],
2773
+ test: (value: T) => boolean,
2774
+ previous: VocabArrayValidation,
2775
+ ): VocabArrayCopy<T> {
2776
+ const snapshot = vocabSparseArraySnapshot(array);
2777
+ if (snapshot != null) return vocabCopySparsePropertyArray(array, snapshot, test);
2778
+ // Sparse validation may have changed the next input's density, descriptors
2779
+ // or prototype. Validate that native-copy input before falling back.
2780
+ if (previous.sparse && !array.every(test)) return { ok: false };
2781
+ return { ok: true, array: array.slice() };
2782
+ }
2783
+ `;
2784
+ }
2785
+ //#endregion
2339
2786
  //#region src/class.ts
2340
2787
  const XSD_ANY_URI = "http://www.w3.org/2001/XMLSchema#anyURI";
2341
2788
  const FEDIFY_URL = "fedify:url";
@@ -2363,6 +2810,7 @@ const PORTABLE_DEREFERENCE_IMPORTS = [
2363
2810
  "parseCompatibleEf61Reference",
2364
2811
  "type PortableResponseClaim",
2365
2812
  "recordPortableReferrer",
2813
+ "retargetPortableReferrer",
2366
2814
  "rejectMalformedCompatibleReference",
2367
2815
  "warnUnverifiableEmbeddedObject"
2368
2816
  ].join(",\n ");
@@ -2504,6 +2952,8 @@ async function* generateClass(typeUri, types, moduleVarNames) {
2504
2952
  for await (const code of generateFields(typeUri, types)) yield code;
2505
2953
  for await (const code of generateConstructor(typeUri, types)) yield code;
2506
2954
  for await (const code of generateCloner(typeUri, types)) yield code;
2955
+ for await (const code of generateDeepCloner(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
2956
+ for await (const code of generateDeepCloneDescriptor(typeUri, types)) yield code.replace(/[ \t]+$/gm, "");
2507
2957
  for await (const code of generateProperties(typeUri, types, moduleVarNames)) yield code;
2508
2958
  for await (const code of generateEncoder(typeUri, types)) yield code;
2509
2959
  for await (const code of generateDecoder(typeUri, types, moduleVarNames)) yield code;
@@ -2601,6 +3051,8 @@ function inspectIri(iri: URL): string {
2601
3051
  try { return formatIri(iri); } catch { return iri.href; }
2602
3052
  }
2603
3053
  `;
3054
+ yield generatePropertyArrayHelpers();
3055
+ yield generateDeepCloneHelpers();
2604
3056
  yield `
2605
3057
  function isValidLanguageTag(language: string): boolean {
2606
3058
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/vocab-tools",
3
- "version": "2.5.0-dev.2513+d7ab5950",
3
+ "version": "2.5.0-dev.2516+42d3ed0b",
4
4
  "description": "Code generator for Activity Vocabulary APIs",
5
5
  "homepage": "https://fedify.dev/",
6
6
  "repository": {
@@ -51,7 +51,7 @@
51
51
  "@types/node": "^24.12.2",
52
52
  "tsdown": "^0.22.0",
53
53
  "typescript": "^6.0.0",
54
- "@fedify/vocab-runtime": "^2.5.0-dev.2513+d7ab5950"
54
+ "@fedify/vocab-runtime": "^2.5.0-dev.2516+42d3ed0b"
55
55
  },
56
56
  "dependencies": {
57
57
  "@cfworker/json-schema": "^4.1.1",