@graphty/graph-format 0.0.0 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +216 -43
- package/dist/graph-format.d.ts +1 -0
- package/dist/graph-format.d.ts.map +1 -0
- package/dist/graph-format.js +15798 -0
- package/dist/graph-format.js.map +1 -0
- package/dist/src/builder/arena.d.ts +85 -0
- package/dist/src/builder/arena.d.ts.map +1 -0
- package/dist/src/builder/arena.js +154 -0
- package/dist/src/builder/arena.js.map +1 -0
- package/dist/src/builder/compact.d.ts +515 -0
- package/dist/src/builder/compact.d.ts.map +1 -0
- package/dist/src/builder/compact.js +1553 -0
- package/dist/src/builder/compact.js.map +1 -0
- package/dist/src/builder/counting-sort.d.ts +96 -0
- package/dist/src/builder/counting-sort.d.ts.map +1 -0
- package/dist/src/builder/counting-sort.js +430 -0
- package/dist/src/builder/counting-sort.js.map +1 -0
- package/dist/src/builder/freeze.d.ts +72 -0
- package/dist/src/builder/freeze.d.ts.map +1 -0
- package/dist/src/builder/freeze.js +548 -0
- package/dist/src/builder/freeze.js.map +1 -0
- package/dist/src/builder/graph-builder.d.ts +602 -0
- package/dist/src/builder/graph-builder.d.ts.map +1 -0
- package/dist/src/builder/graph-builder.js +1940 -0
- package/dist/src/builder/graph-builder.js.map +1 -0
- package/dist/src/builder/options.d.ts +16 -0
- package/dist/src/builder/options.d.ts.map +1 -0
- package/dist/src/builder/options.js +21 -0
- package/dist/src/builder/options.js.map +1 -0
- package/dist/src/columns/bitmap.d.ts +96 -0
- package/dist/src/columns/bitmap.d.ts.map +1 -0
- package/dist/src/columns/bitmap.js +184 -0
- package/dist/src/columns/bitmap.js.map +1 -0
- package/dist/src/columns/column.d.ts +220 -0
- package/dist/src/columns/column.d.ts.map +1 -0
- package/dist/src/columns/column.js +2109 -0
- package/dist/src/columns/column.js.map +1 -0
- package/dist/src/columns/dictionary.d.ts +60 -0
- package/dist/src/columns/dictionary.d.ts.map +1 -0
- package/dist/src/columns/dictionary.js +102 -0
- package/dist/src/columns/dictionary.js.map +1 -0
- package/dist/src/columns/growable.d.ts +198 -0
- package/dist/src/columns/growable.d.ts.map +1 -0
- package/dist/src/columns/growable.js +296 -0
- package/dist/src/columns/growable.js.map +1 -0
- package/dist/src/columns/infer.d.ts +121 -0
- package/dist/src/columns/infer.d.ts.map +1 -0
- package/dist/src/columns/infer.js +268 -0
- package/dist/src/columns/infer.js.map +1 -0
- package/dist/src/columns/remap.d.ts +143 -0
- package/dist/src/columns/remap.d.ts.map +1 -0
- package/dist/src/columns/remap.js +588 -0
- package/dist/src/columns/remap.js.map +1 -0
- package/dist/src/columns/table.d.ts +184 -0
- package/dist/src/columns/table.d.ts.map +1 -0
- package/dist/src/columns/table.js +485 -0
- package/dist/src/columns/table.js.map +1 -0
- package/dist/src/constants.d.ts +34 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/constants.js +79 -0
- package/dist/src/constants.js.map +1 -0
- package/dist/src/errors.d.ts +76 -0
- package/dist/src/errors.d.ts.map +1 -0
- package/dist/src/errors.js +32 -0
- package/dist/src/errors.js.map +1 -0
- package/dist/src/ids/edge-id-index.d.ts +77 -0
- package/dist/src/ids/edge-id-index.d.ts.map +1 -0
- package/dist/src/ids/edge-id-index.js +155 -0
- package/dist/src/ids/edge-id-index.js.map +1 -0
- package/dist/src/ids/node-id-map.d.ts +280 -0
- package/dist/src/ids/node-id-map.d.ts.map +1 -0
- package/dist/src/ids/node-id-map.js +1139 -0
- package/dist/src/ids/node-id-map.js.map +1 -0
- package/dist/src/ids/string-store.d.ts +219 -0
- package/dist/src/ids/string-store.d.ts.map +1 -0
- package/dist/src/ids/string-store.js +526 -0
- package/dist/src/ids/string-store.js.map +1 -0
- package/dist/src/index.d.ts +30 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +29 -0
- package/dist/src/index.js.map +1 -0
- package/dist/src/populate/from-csr.d.ts +61 -0
- package/dist/src/populate/from-csr.d.ts.map +1 -0
- package/dist/src/populate/from-csr.js +706 -0
- package/dist/src/populate/from-csr.js.map +1 -0
- package/dist/src/populate/from-edge-arrays.d.ts +51 -0
- package/dist/src/populate/from-edge-arrays.d.ts.map +1 -0
- package/dist/src/populate/from-edge-arrays.js +217 -0
- package/dist/src/populate/from-edge-arrays.js.map +1 -0
- package/dist/src/populate/from-records.d.ts +51 -0
- package/dist/src/populate/from-records.d.ts.map +1 -0
- package/dist/src/populate/from-records.js +447 -0
- package/dist/src/populate/from-records.js.map +1 -0
- package/dist/src/snapshot/derived.d.ts +211 -0
- package/dist/src/snapshot/derived.d.ts.map +1 -0
- package/dist/src/snapshot/derived.js +1254 -0
- package/dist/src/snapshot/derived.js.map +1 -0
- package/dist/src/snapshot/graph-meta.d.ts +23 -0
- package/dist/src/snapshot/graph-meta.d.ts.map +1 -0
- package/dist/src/snapshot/graph-meta.js +159 -0
- package/dist/src/snapshot/graph-meta.js.map +1 -0
- package/dist/src/snapshot/graph-snapshot.d.ts +509 -0
- package/dist/src/snapshot/graph-snapshot.d.ts.map +1 -0
- package/dist/src/snapshot/graph-snapshot.js +1247 -0
- package/dist/src/snapshot/graph-snapshot.js.map +1 -0
- package/dist/src/snapshot/hash.d.ts +90 -0
- package/dist/src/snapshot/hash.d.ts.map +1 -0
- package/dist/src/snapshot/hash.js +228 -0
- package/dist/src/snapshot/hash.js.map +1 -0
- package/dist/src/snapshot/queries.d.ts +74 -0
- package/dist/src/snapshot/queries.d.ts.map +1 -0
- package/dist/src/snapshot/queries.js +131 -0
- package/dist/src/snapshot/queries.js.map +1 -0
- package/dist/src/snapshot/validate.d.ts +192 -0
- package/dist/src/snapshot/validate.d.ts.map +1 -0
- package/dist/src/snapshot/validate.js +990 -0
- package/dist/src/snapshot/validate.js.map +1 -0
- package/dist/src/snapshot/views.d.ts +274 -0
- package/dist/src/snapshot/views.d.ts.map +1 -0
- package/dist/src/snapshot/views.js +856 -0
- package/dist/src/snapshot/views.js.map +1 -0
- package/dist/src/types/builder.d.ts +456 -0
- package/dist/src/types/builder.d.ts.map +1 -0
- package/dist/src/types/builder.js +11 -0
- package/dist/src/types/builder.js.map +1 -0
- package/dist/src/types/columns.d.ts +615 -0
- package/dist/src/types/columns.d.ts.map +1 -0
- package/dist/src/types/columns.js +14 -0
- package/dist/src/types/columns.js.map +1 -0
- package/dist/src/types/index.d.ts +14 -0
- package/dist/src/types/index.d.ts.map +1 -0
- package/dist/src/types/index.js +11 -0
- package/dist/src/types/index.js.map +1 -0
- package/dist/src/types/internal.d.ts +172 -0
- package/dist/src/types/internal.d.ts.map +1 -0
- package/dist/src/types/internal.js +13 -0
- package/dist/src/types/internal.js.map +1 -0
- package/dist/src/types/snapshot.d.ts +801 -0
- package/dist/src/types/snapshot.d.ts.map +1 -0
- package/dist/src/types/snapshot.js +14 -0
- package/dist/src/types/snapshot.js.map +1 -0
- package/dist/src/types/wire.d.ts +196 -0
- package/dist/src/types/wire.d.ts.map +1 -0
- package/dist/src/types/wire.js +8 -0
- package/dist/src/types/wire.js.map +1 -0
- package/dist/src/util/mask.d.ts +55 -0
- package/dist/src/util/mask.d.ts.map +1 -0
- package/dist/src/util/mask.js +71 -0
- package/dist/src/util/mask.js.map +1 -0
- package/dist/src/util/options.d.ts +22 -0
- package/dist/src/util/options.d.ts.map +1 -0
- package/dist/src/util/options.js +49 -0
- package/dist/src/util/options.js.map +1 -0
- package/dist/src/util/shared-buffers.d.ts +42 -0
- package/dist/src/util/shared-buffers.d.ts.map +1 -0
- package/dist/src/util/shared-buffers.js +52 -0
- package/dist/src/util/shared-buffers.js.map +1 -0
- package/dist/src/util/typed-array.d.ts +205 -0
- package/dist/src/util/typed-array.d.ts.map +1 -0
- package/dist/src/util/typed-array.js +289 -0
- package/dist/src/util/typed-array.js.map +1 -0
- package/dist/src/wire/bytes.d.ts +69 -0
- package/dist/src/wire/bytes.d.ts.map +1 -0
- package/dist/src/wire/bytes.js +361 -0
- package/dist/src/wire/bytes.js.map +1 -0
- package/dist/src/wire/carried-views.d.ts +111 -0
- package/dist/src/wire/carried-views.d.ts.map +1 -0
- package/dist/src/wire/carried-views.js +286 -0
- package/dist/src/wire/carried-views.js.map +1 -0
- package/dist/src/wire/from-wire.d.ts +144 -0
- package/dist/src/wire/from-wire.d.ts.map +1 -0
- package/dist/src/wire/from-wire.js +1425 -0
- package/dist/src/wire/from-wire.js.map +1 -0
- package/dist/src/wire/to-wire.d.ts +171 -0
- package/dist/src/wire/to-wire.d.ts.map +1 -0
- package/dist/src/wire/to-wire.js +652 -0
- package/dist/src/wire/to-wire.js.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/package.json +72 -7
- package/src/builder/arena.ts +192 -0
- package/src/builder/compact.ts +1811 -0
- package/src/builder/counting-sort.ts +506 -0
- package/src/builder/freeze.ts +689 -0
- package/src/builder/graph-builder.ts +2264 -0
- package/src/builder/options.ts +29 -0
- package/src/columns/bitmap.ts +196 -0
- package/src/columns/column.ts +2574 -0
- package/src/columns/dictionary.ts +114 -0
- package/src/columns/growable.ts +350 -0
- package/src/columns/infer.ts +285 -0
- package/src/columns/remap.ts +663 -0
- package/src/columns/table.ts +568 -0
- package/src/constants.ts +89 -0
- package/src/errors.ts +115 -0
- package/src/ids/edge-id-index.ts +179 -0
- package/src/ids/node-id-map.ts +1340 -0
- package/src/ids/string-store.ts +589 -0
- package/src/index.ts +139 -0
- package/src/lib-resizable-array-buffer.d.ts +34 -0
- package/src/populate/from-csr.ts +802 -0
- package/src/populate/from-edge-arrays.ts +257 -0
- package/src/populate/from-records.ts +536 -0
- package/src/snapshot/derived.ts +1486 -0
- package/src/snapshot/graph-meta.ts +167 -0
- package/src/snapshot/graph-snapshot.ts +1503 -0
- package/src/snapshot/hash.ts +241 -0
- package/src/snapshot/queries.ts +136 -0
- package/src/snapshot/validate.ts +1108 -0
- package/src/snapshot/views.ts +943 -0
- package/src/types/builder.ts +480 -0
- package/src/types/columns.ts +727 -0
- package/src/types/index.ts +14 -0
- package/src/types/internal.ts +195 -0
- package/src/types/snapshot.ts +886 -0
- package/src/types/wire.ts +207 -0
- package/src/util/mask.ts +89 -0
- package/src/util/options.ts +57 -0
- package/src/util/shared-buffers.ts +56 -0
- package/src/util/typed-array.ts +371 -0
- package/src/wire/bytes.ts +440 -0
- package/src/wire/carried-views.ts +327 -0
- package/src/wire/from-wire.ts +1690 -0
- package/src/wire/to-wire.ts +755 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph-format.js","sources":["../src/constants.ts","../src/errors.ts","../src/util/shared-buffers.ts","../src/ids/string-store.ts","../src/util/typed-array.ts","../src/columns/bitmap.ts","../src/columns/dictionary.ts","../src/columns/infer.ts","../src/columns/column.ts","../src/util/options.ts","../src/ids/node-id-map.ts","../src/snapshot/graph-meta.ts","../src/columns/growable.ts","../src/builder/compact.ts","../src/columns/table.ts","../src/ids/edge-id-index.ts","../src/builder/arena.ts","../src/snapshot/queries.ts","../src/snapshot/views.ts","../src/snapshot/validate.ts","../src/wire/carried-views.ts","../src/wire/to-wire.ts","../src/wire/from-wire.ts","../src/wire/bytes.ts","../src/builder/counting-sort.ts","../src/columns/remap.ts","../src/util/mask.ts","../src/snapshot/derived.ts","../src/snapshot/hash.ts","../src/snapshot/graph-snapshot.ts","../src/builder/options.ts","../src/builder/freeze.ts","../src/builder/graph-builder.ts","../src/populate/from-csr.ts","../src/populate/from-edge-arrays.ts","../src/populate/from-records.ts"],"sourcesContent":["/**\n * Package-wide constants of @graphty/graph-format (design sections 2, 3.2, 9.2, 10.3 and 12.2).\n *\n * The four constants listed in design section 12.2 (INVALID_INDEX, MAX_COUNT, FORMAT_VERSION and\n * SNAPSHOT_BRAND) are public and re-exported by src/index.ts. The remaining constants are shared by\n * the builder, arena and wire modules but are not part of the public surface.\n */\n\n/**\n * The one and only \"no index\" sentinel: 0xFFFFFFFF. Used for node, edge and arc indices alike, both as\n * a JS return value (indexOf, findArc, edgeIndexOf, nodeColumn, edgeColumn, codeOf) and inside\n * Uint32Array vectors (remaps, parents, labels). It never appears in rowPtr, colIdx, arcToEdge,\n * edgeToArc or any view array (invariant I2), and because every count is bounded by MAX_COUNT it can\n * never collide with a valid index (invariant I3).\n */\nexport const INVALID_INDEX = 0xffffffff;\n\n/**\n * Upper bound on nodeCount, edgeCount and arcCount: 0xFFFFFFFE (invariant I3). Crossing it at an add*\n * call throws E_TOO_LARGE. One below INVALID_INDEX so the sentinel is always free.\n */\nexport const MAX_COUNT = 0xfffffffe;\n\n/**\n * The data-model major version carried by every snapshot as `formatVersion` and compared by\n * isGraphSnapshot(), fromWire() and fromBytes() (design section 13.5). A mismatch is\n * E_UNSUPPORTED_VERSION with details.kind \"format\". It bumps only when the meaning of an invariant, a\n * field, a flag or a sentinel changes.\n */\nexport const FORMAT_VERSION = 1;\n\n/**\n * Brand property read by isGraphSnapshot() (design section 7.5). It is a Symbol.for() symbol rather\n * than a private one so that two copies of the package inside one application still recognise each\n * other's snapshots structurally, without instanceof.\n */\nexport const SNAPSHOT_BRAND: unique symbol = Symbol.for(\"@graphty/graph-format/snapshot\");\n\n/**\n * Alignment, in bytes, of every core-array segment inside the arena and of every segment inside the\n * GSNP byte container (design sections 9.2 and 10.3). It is WebGPU's minStorageBufferOffsetAlignment\n * default, so each segment can be bound as a storage buffer window without copying.\n * @internal\n */\nexport const ALIGNMENT = 256;\n\n/**\n * Whether this host stores multi-byte integers little-endian, computed once at module load. Every\n * supported platform (x86-64, ARM64, WebAssembly) is little-endian; on a big-endian host toBytes() and\n * toWire() throw E_UNSUPPORTED with details.reason \"big-endian host\" so that no file is ever written\n * that other hosts would reject (design section 9.2).\n * @internal\n */\nexport const IS_LITTLE_ENDIAN: boolean = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;\n\n/**\n * Wire major version written into the GSNP container header and the manifest (design section 9.2).\n * A reader refuses any other major with E_UNSUPPORTED_VERSION (details.kind \"wire\").\n * @internal\n */\nexport const WIRE_MAJOR = 1;\n\n/**\n * Wire minor version written into the GSNP container header and the manifest (design section 9.2).\n * Minors are additive: older readers ignore unknown manifest fields. Wire 1.0 tags non-finite\n * numbers as `{ \"$num\": ... }` and wraps a JSON object whose only key is a tag name as\n * `{ \"$esc\": ... }` (design section 5.9).\n * @internal\n */\nexport const WIRE_MINOR = 0;\n\n/**\n * The manifest `format` discriminator of a WireManifest (design section 9.1).\n * @internal\n */\nexport const WIRE_FORMAT = \"graphty-snapshot\";\n\n/**\n * The four magic bytes at the start of a GSNP byte container: \"GSNP\" in ASCII (design section 9.2).\n * @internal\n */\nexport const CONTAINER_MAGIC: readonly [number, number, number, number] = [0x47, 0x53, 0x4e, 0x50];\n\n/**\n * The u32 value written through a host-order Uint32Array at container offset 8 so a reader can detect\n * an endianness mismatch (design section 9.2): a little-endian reader sees the bytes 04 03 02 01.\n * @internal\n */\nexport const ENDIAN_PROBE = 0x01020304;\n","/**\n * The error class and the closed set of error codes of @graphty/graph-format (design section 11).\n *\n * Policy (design section 11.1): the builder and the constructors throw on malformed input, on the\n * first error, with a GraphFormatError carrying a stable `code`; snapshot methods that take an index\n * are total for in-range arguments and unchecked otherwise; only GraphFormatError instances are ever\n * thrown by this package. Messages are plain ASCII and name the offending index, id or value when it\n * is a number or a short string. ImportError (code E_IMPORT) is declared by @graphty/graph-io.\n */\n\n/**\n * The closed union of error codes a GraphFormatError can carry (design section 11.2). Each code is\n * stable across versions and is the value consumers branch on; the message is for humans.\n *\n * - E_INVALID_ID: NaN, a non-finite number, a bigint, an object, null, undefined or a string with a\n * lone surrogate used as an id (details.reason \"lone surrogate\").\n * - E_UNKNOWN_NODE: addEdge with addMissingNodes false, addEdgeByIndex with a dead or out-of-range\n * index (details.index), or a requireIndex miss.\n * - E_INDEX_RANGE: ids.idOf / table.value out of range; inducedSubgraph with a repeated or\n * out-of-range index.\n * - E_TOO_LARGE: nodeCount, edgeCount or arcCount would exceed MAX_COUNT.\n * - E_INVALID_WEIGHT: a NaN weight at addEdge / setEdgeWeight / addEdges.\n * - E_DIRECTED: mate() on a directed snapshot; setDirected() refused (locked, or a change the edge\n * set does not allow).\n * - E_SELF_LOOP: a self-loop under selfLoops \"error\".\n * - E_DUPLICATE_EDGE: a parallel edge under duplicateEdges \"error\" (details source, target, edges).\n * - E_DUPLICATE_EDGE_ID: a unique role \"id\" edge column violated (both edge indices in details).\n * - E_DUPLICATE_ID: a unique node column violated; addGraph with onDuplicateNode \"error\"; a\n * repeated id in the `ids` array or F64 given to fromEdgeArrays / fromCsr.\n * - E_DUPLICATE_ROLE: two columns with the same role in one table.\n * - E_UNKNOWN_COLUMN: require() of an absent column.\n * - E_COLUMN_TYPE: requireTyped() dtype mismatch; a non-JSON default / fill / options / extra value\n * (details.field); a string value with a lone surrogate.\n * - E_COLUMN_LENGTH: set() with data.length !== rowCount * components.\n * - E_COLUMN_ALIGNMENT: a u8 array without a constructible padded u32 view under adopt \"strict\".\n * - E_COLUMN_EXISTS: declareNodeColumn / declareEdgeColumn twice with a different declaration.\n * - E_COLUMN_IMMUTABLE: mutableData() / markDirty() / mutableValidity() / setAll() on an immutable\n * column.\n * - E_NO_DEFAULT: materializeDefault() on a column without a declared default.\n * - E_PARTITION: contract() partition of the wrong length or holding INVALID_INDEX.\n * - E_INVALID_PERMUTATION: relabel() with a perm that is not a permutation of 0..n-1.\n * - E_MASK_LENGTH: filterEdges() / inducedSubgraph({ mask }) with a short mask.\n * - E_GPU_INELIGIBLE: gpuView() / paddedU32View() on a string, list or json column.\n * - E_INVALID_SNAPSHOT: validate() failure (details.invariant, row / arc / edge / column) or\n * validate({ checksum: true }) on a snapshot without recorded checksums (details.reason\n * \"no-checksum\").\n * - E_BAD_SERIALIZATION: bad magic, endianness probe, manifest or buffer reference (details.ref).\n * - E_UNSUPPORTED_VERSION: unknown wire major or formatVersion (details.kind \"wire\" | \"format\",\n * details.found, details.supported).\n * - E_DETACHED: a core accessor after a consuming transfer.\n * - E_BUILDER_DISPOSED: any call on a disposed builder.\n * - E_UNSUPPORTED: big-endian host (details.reason); unknown wire dtype (details.dtype) or id-map\n * kind (details.kind).\n * - E_IMPORT: reserved for @graphty/graph-io's ImportError.\n */\nexport type GraphFormatErrorCode =\n | \"E_INVALID_ID\"\n | \"E_UNKNOWN_NODE\"\n | \"E_INDEX_RANGE\"\n | \"E_TOO_LARGE\"\n | \"E_INVALID_WEIGHT\"\n | \"E_DIRECTED\"\n | \"E_SELF_LOOP\"\n | \"E_DUPLICATE_EDGE\"\n | \"E_DUPLICATE_EDGE_ID\"\n | \"E_DUPLICATE_ID\"\n | \"E_DUPLICATE_ROLE\"\n | \"E_UNKNOWN_COLUMN\"\n | \"E_COLUMN_TYPE\"\n | \"E_COLUMN_LENGTH\"\n | \"E_COLUMN_ALIGNMENT\"\n | \"E_COLUMN_EXISTS\"\n | \"E_COLUMN_IMMUTABLE\"\n | \"E_NO_DEFAULT\"\n | \"E_PARTITION\"\n | \"E_INVALID_PERMUTATION\"\n | \"E_MASK_LENGTH\"\n | \"E_GPU_INELIGIBLE\"\n | \"E_INVALID_SNAPSHOT\"\n | \"E_BAD_SERIALIZATION\"\n | \"E_UNSUPPORTED_VERSION\"\n | \"E_DETACHED\"\n | \"E_BUILDER_DISPOSED\"\n | \"E_UNSUPPORTED\"\n | \"E_IMPORT\";\n\nconst EMPTY_DETAILS: Readonly<Record<string, unknown>> = Object.freeze({});\n\n/**\n * The only error type this package throws (design section 11.2). `code` is the stable, programmatic\n * discriminator; `details` carries the machine-readable context named per code in the\n * GraphFormatErrorCode documentation (index, id, edge, invariant, row, found, supported, ...) as a\n * frozen shallow copy of what the thrower supplied. `name` is \"GraphFormatError\" so stack traces and\n * test matchers read naturally.\n */\nexport class GraphFormatError extends Error {\n /** The stable error code (design section 11.2). */\n readonly code: GraphFormatErrorCode;\n\n /** Machine-readable context for the failure; an empty frozen object when none was supplied. */\n readonly details: Readonly<Record<string, unknown>>;\n\n /**\n * Create a GraphFormatError.\n * @param code - the stable error code the caller can branch on\n * @param message - a plain-ASCII human-readable message naming the offending index, id or value\n * @param details - optional machine-readable context; copied shallowly and frozen\n */\n constructor(code: GraphFormatErrorCode, message: string, details?: Readonly<Record<string, unknown>>) {\n super(message);\n this.name = \"GraphFormatError\";\n this.code = code;\n this.details = details === undefined ? EMPTY_DETAILS : Object.freeze({ ...details });\n }\n}\n","/**\n * The conservative owner count of design section 9.1. The format shares storage deliberately:\n * `withColumns()` shares the core, same-node-space derived graphs share the node table and the id\n * map, `clone()` and `set(name, column)` share Column objects between tables, `transpose()` adopts\n * the cached reverse arrays as its core. Every holder of a buffer, column, table or id map claims it\n * once (the snapshot and table constructors do so); a target claimed by more than one holder is\n * SHARED, and `toWire({ transfer: true })` / `transferables()` copy its buffers instead of\n * transferring them, so no sibling snapshot is ever silently emptied. The count is never decremented\n * (conservative: a holder that is garbage-collected still counts, which only ever causes a copy).\n *\n * Holders are tracked at three granularities because a shared holder materialises buffers lazily\n * (the Utf8 store of a string column or a string id map, the Float64Array of a numeric id map): a\n * buffer, a Column (or a NodeIdMap) and an AttributeTable. The wire module treats a buffer as shared\n * when the buffer itself, the column that holds it or the table that holds the column is shared.\n * This module is a leaf (it imports nothing) so every module may use it without a cycle.\n */\n\n/** Target (ArrayBuffer, Column, AttributeTable or NodeIdMap) -> number of holders recorded. */\nconst HOLDERS = new WeakMap<object, number>();\n\n/**\n * Record one holder of a buffer, column, table or id map. Called by every constructor that keeps a\n * reference to storage it did not allocate itself; the second claim of the same target marks it\n * shared.\n * @param target - the buffer, Column, AttributeTable or NodeIdMap now held\n */\nexport function claimHolder(target: object): void {\n HOLDERS.set(target, (HOLDERS.get(target) ?? 0) + 1);\n}\n\n/**\n * Record that a target has gained another holder (design section 9.1), so it is treated as shared\n * from now on whatever its previous count.\n * @param target - the buffer, Column, AttributeTable or NodeIdMap that is now held by more than one holder\n */\nexport function noteShared(target: object): void {\n HOLDERS.set(target, Math.max(HOLDERS.get(target) ?? 0, 1) + 1);\n}\n\n/**\n * The number of holders recorded for a target.\n * @param target - the buffer, Column, AttributeTable or NodeIdMap\n * @returns the count, 0 when never claimed\n */\nexport function holderCount(target: object): number {\n return HOLDERS.get(target) ?? 0;\n}\n\n/**\n * Whether a target has been recorded as held by more than one holder.\n * @param target - the buffer, Column, AttributeTable or NodeIdMap\n * @returns true when at least two holders were recorded\n */\nexport function isShared(target: object): boolean {\n return (HOLDERS.get(target) ?? 0) > 1;\n}\n","/**\n * The Arrow Utf8 string store (design sections 4.2 and 5.1): `Uint32Array(rows + 1)` offsets plus one\n * `Uint8Array` of concatenated UTF-8 bytes, kept next to a decoded JS-string representation. The two\n * are caches of one logical value and are materialised lazily in either direction:\n *\n * - a store built from strings (`Utf8Store.fromStrings`, what the builder has) shares the source\n * array by reference and encodes on the first read of `offsets` / `utf8` (toWire / toBytes /\n * transferables), caching the result;\n * - a store built from a wire buffer (`Utf8Store.fromEncoded`) decodes per row on `at()`, cached in\n * a sparse array, and in bulk on `slice()` / `decodeAll()`, which are not cached.\n *\n * Nothing is encoded or decoded at construction. Row `i` occupies the byte range\n * `[offsets[i], offsets[i + 1])`; `offsets[0]` need not be zero so that a zero-copy slice of a\n * string column can share its parent's arrays. The encoder is a plain JS UTF-8 encoder that\n * produces exactly the bytes `TextEncoder` would (a lone surrogate becomes U+FFFD); the decoder is\n * `TextDecoder` behind an ASCII fast path.\n */\n\nimport { GraphFormatError } from \"../errors.js\";\nimport { type U8, type U32 } from \"../types/index.js\";\nimport { claimHolder } from \"../util/shared-buffers.js\";\n\n/**\n * Rows of at most this many bytes are decoded by a char-code loop when they are pure ASCII, which is\n * about three times faster than TextDecoder for short ids; longer rows go straight to TextDecoder.\n */\nconst ASCII_FAST_PATH_MAX_BYTES = 32;\n\n/** The instance type of the host's TextDecoder (a global value in Node and in browsers; typed through its constructor). */\ntype Decoder = InstanceType<typeof TextDecoder>;\n\nlet sharedDecoder: Decoder | null = null;\nlet fatalDecoder: Decoder | null = null;\n\n/**\n * The lazily created shared (replacing) decoder.\n * @returns a TextDecoder that replaces malformed sequences with U+FFFD\n */\nfunction replacingDecoder(): Decoder {\n sharedDecoder ??= new TextDecoder(\"utf-8\");\n return sharedDecoder;\n}\n\n/**\n * The lazily created fatal decoder used by validation.\n * @returns a TextDecoder that throws on a malformed sequence\n */\nfunction strictDecoder(): Decoder {\n fatalDecoder ??= new TextDecoder(\"utf-8\", { fatal: true });\n return fatalDecoder;\n}\n\n/**\n * Number of UTF-8 bytes `encodeUtf8Into` writes for a string (a lone surrogate counts as the three\n * bytes of U+FFFD, matching TextEncoder).\n * @param s - the string\n * @returns the encoded byte length\n */\nexport function utf8ByteLength(s: string): number {\n let bytes = 0;\n const n = s.length;\n for (let i = 0; i < n; i++) {\n const c = s.charCodeAt(i);\n if (c < 0x80) {\n bytes += 1;\n } else if (c < 0x800) {\n bytes += 2;\n } else if (c >= 0xd800 && c <= 0xdbff && i + 1 < n) {\n const d = s.charCodeAt(i + 1);\n if (d >= 0xdc00 && d <= 0xdfff) {\n bytes += 4;\n i++;\n } else {\n bytes += 3;\n }\n } else {\n bytes += 3;\n }\n }\n return bytes;\n}\n\n/**\n * Encode a string as UTF-8 into `out` starting at `position`; the caller has sized `out` with\n * `utf8ByteLength`. Produces the bytes TextEncoder would, including U+FFFD for a lone surrogate.\n * @param s - the string\n * @param out - the destination bytes\n * @param position - the first byte to write\n * @returns one past the last byte written\n */\nexport function encodeUtf8Into(s: string, out: Uint8Array, position: number): number {\n let p = position;\n const n = s.length;\n for (let i = 0; i < n; i++) {\n let c = s.charCodeAt(i);\n if (c < 0x80) {\n out[p++] = c;\n continue;\n }\n if (c < 0x800) {\n out[p++] = 0xc0 | (c >> 6);\n out[p++] = 0x80 | (c & 0x3f);\n continue;\n }\n if (c >= 0xd800 && c <= 0xdfff) {\n if (c <= 0xdbff && i + 1 < n) {\n const d = s.charCodeAt(i + 1);\n if (d >= 0xdc00 && d <= 0xdfff) {\n c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);\n i++;\n out[p++] = 0xf0 | (c >> 18);\n out[p++] = 0x80 | ((c >> 12) & 0x3f);\n out[p++] = 0x80 | ((c >> 6) & 0x3f);\n out[p++] = 0x80 | (c & 0x3f);\n continue;\n }\n }\n c = 0xfffd;\n }\n out[p++] = 0xe0 | (c >> 12);\n out[p++] = 0x80 | ((c >> 6) & 0x3f);\n out[p++] = 0x80 | (c & 0x3f);\n }\n return p;\n}\n\n/**\n * The length from which V8 represents a substring as a SlicedString that keeps its parent alive\n * (`SlicedString::kMinLength`); shorter substrings are copied.\n */\nconst SLICED_STRING_MIN_LENGTH = 13;\n\n/**\n * A copy of a string that no longer references the buffer it was sliced from. Importers cut ids\n * and cell texts out of decoded input chunks, and V8 represents such a substring of 13 or more\n * characters as a view on the chunk, so a retained id or value would keep the whole chunk alive\n * for the life of the builder and the snapshot (measured: a 40 MiB CSV kept 47 MiB of decoded\n * text resident through 100k retained ids). Concatenating one character and slicing it off makes\n * V8 flatten the string into fresh storage; shorter strings are already copies and are returned\n * as they are.\n * @param s - the string\n * @returns an equal string that owns its characters\n */\nexport function detachString(s: string): string {\n return s.length < SLICED_STRING_MIN_LENGTH ? s : ` ${s}`.slice(1);\n}\n\n/**\n * Whether a string contains a lone UTF-16 surrogate, which TextEncoder would replace with U+FFFD on\n * the wire (design section 4.1: such an id is E_INVALID_ID).\n * @param s - the string\n * @returns true when a high surrogate lacks its low partner or a low surrogate stands alone\n */\nexport function hasLoneSurrogate(s: string): boolean {\n const n = s.length;\n for (let i = 0; i < n; i++) {\n const c = s.charCodeAt(i);\n if (c < 0xd800 || c > 0xdfff) {\n continue;\n }\n if (c > 0xdbff) {\n return true;\n }\n if (i + 1 >= n) {\n return true;\n }\n const d = s.charCodeAt(i + 1);\n if (d < 0xdc00 || d > 0xdfff) {\n return true;\n }\n i++;\n }\n return false;\n}\n\n/**\n * Decode one row of UTF-8 bytes with an ASCII fast path.\n * @param utf8 - the byte store\n * @param start - first byte of the row\n * @param end - one past the last byte of the row\n * @returns the decoded string (malformed sequences become U+FFFD)\n */\nexport function decodeUtf8Row(utf8: Uint8Array, start: number, end: number): string {\n const len = end - start;\n if (len === 0) {\n return \"\";\n }\n if (len <= ASCII_FAST_PATH_MAX_BYTES) {\n let s = \"\";\n let i = start;\n for (; i < end; i++) {\n const b = utf8[i];\n if (b >= 0x80) {\n break;\n }\n s += String.fromCharCode(b);\n }\n if (i === end) {\n return s;\n }\n }\n return replacingDecoder().decode(utf8.subarray(start, end));\n}\n\n/**\n * Whether every byte of a range is ASCII.\n * @param utf8 - the byte store\n * @param start - first byte\n * @param end - one past the last byte\n * @returns true when no byte is >= 0x80\n */\nfunction isAsciiRange(utf8: Uint8Array, start: number, end: number): boolean {\n for (let i = start; i < end; i++) {\n if (utf8[i] >= 0x80) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Decode a range of rows in one pass: when the whole byte range is ASCII, one TextDecoder call plus\n * one substring per row (byte offsets equal char offsets); otherwise one decode per row.\n * @param utf8 - the byte store\n * @param offsets - the row offsets\n * @param from - first row\n * @param to - one past the last row\n * @returns the decoded rows in order\n */\nexport function decodeUtf8Rows(utf8: Uint8Array, offsets: Uint32Array, from: number, to: number): string[] {\n const out = new Array<string>(to - from);\n if (to <= from) {\n return out;\n }\n const base = offsets[from];\n const end = offsets[to];\n if (isAsciiRange(utf8, base, end)) {\n const whole = replacingDecoder().decode(utf8.subarray(base, end));\n for (let i = from; i < to; i++) {\n out[i - from] = whole.substring(offsets[i] - base, offsets[i + 1] - base);\n }\n return out;\n }\n for (let i = from; i < to; i++) {\n out[i - from] = decodeUtf8Row(utf8, offsets[i], offsets[i + 1]);\n }\n return out;\n}\n\n/**\n * Whether one row of bytes is well-formed UTF-8 (a fatal decode).\n * @param utf8 - the byte store\n * @param start - first byte of the row\n * @param end - one past the last byte of the row\n * @returns true when the row decodes without error\n */\nfunction isWellFormedUtf8Row(utf8: Uint8Array, start: number, end: number): boolean {\n let ascii = true;\n for (let i = start; i < end; i++) {\n if (utf8[i] >= 0x80) {\n ascii = false;\n break;\n }\n }\n if (ascii) {\n return true;\n }\n try {\n strictDecoder().decode(utf8.subarray(start, end));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Encode the first `length` entries of an array as an Arrow Utf8 store in one sizing pass and one\n * writing pass. Entries that are not strings (the number rows of a mixed id map) encode as empty\n * rows; offsets start at 0.\n * @param source - the rows; only entries below `length` are read\n * @param length - the number of rows to encode\n * @returns fresh, exactly sized offsets (length + 1) and utf8 arrays\n */\nexport function encodeUtf8Rows(source: ArrayLike<unknown>, length: number): EncodedUtf8 {\n const offsets = new Uint32Array(length + 1);\n let total = 0;\n for (let i = 0; i < length; i++) {\n const v = source[i];\n if (typeof v === \"string\") {\n total += utf8ByteLength(v);\n }\n offsets[i + 1] = total;\n }\n const utf8 = new Uint8Array(total);\n let p = 0;\n for (let i = 0; i < length; i++) {\n const v = source[i];\n if (typeof v === \"string\") {\n p = encodeUtf8Into(v, utf8, p);\n }\n }\n return { offsets, utf8 };\n}\n\n/**\n * Structure-level check of a Utf8 store's layout (design section 9.5): `rows + 1` offsets,\n * non-decreasing, ending inside the byte store.\n * @param offsets - the offsets array\n * @param utf8 - the byte store\n * @param rows - the expected row count\n * @param ref - the manifest path named in the error, e.g. \"ids.offsets\"\n */\nexport function checkUtf8Layout(offsets: Uint32Array, utf8: Uint8Array, rows: number, ref: string): void {\n if (offsets.length !== rows + 1) {\n throw new GraphFormatError(\n \"E_BAD_SERIALIZATION\",\n `${ref}: expected ${rows + 1} offsets, found ${offsets.length}`,\n { ref, reason: \"offsets length\", expected: rows + 1, found: offsets.length },\n );\n }\n let previous = offsets[0];\n for (let i = 1; i <= rows; i++) {\n const current = offsets[i];\n if (current < previous) {\n throw new GraphFormatError(\"E_BAD_SERIALIZATION\", `${ref}: offsets decrease at row ${i - 1}`, {\n ref,\n reason: \"offsets not monotonic\",\n row: i - 1,\n });\n }\n previous = current;\n }\n if (previous > utf8.length) {\n throw new GraphFormatError(\n \"E_BAD_SERIALIZATION\",\n `${ref}: offsets end at ${previous} but the byte store has ${utf8.length} bytes`,\n { ref, reason: \"offsets exceed utf8\", end: previous, byteLength: utf8.length },\n );\n }\n}\n\n/** The encoded representation of a store: offsets plus bytes, always materialised together. */\nexport interface EncodedUtf8 {\n /** rows + 1 non-decreasing offsets. */\n readonly offsets: U32;\n /** The concatenated UTF-8 bytes. */\n readonly utf8: U8;\n}\n\n/**\n * An Arrow Utf8 string store with lazily materialised encoded and decoded representations (design\n * sections 4.2 and 5.1). Immutable once built; every lazily computed representation is cached.\n */\nexport class Utf8Store {\n /** Number of rows. */\n readonly length: number;\n\n /**\n * The decoded rows, shared by reference for a store built from strings (only entries below\n * `length` are read) or produced by `materialiseDecoded()` for an encoded store.\n */\n private source: ArrayLike<string> | null;\n\n /** Sparse per-row decode cache of an encoded-only store; allocated on the first decode. */\n private cache: (string | undefined)[] | null;\n\n /** The offsets and bytes, once encoded or when adopted. */\n private encodedArrays: EncodedUtf8 | null;\n\n /**\n * Construct a store; use the static factories. At least one representation is always given.\n * @param length - the row count\n * @param source - the decoded rows or null\n * @param encoded - the offsets and bytes or null\n */\n private constructor(length: number, source: ArrayLike<string> | null, encoded: EncodedUtf8 | null) {\n this.length = length;\n this.source = source;\n this.cache = null;\n this.encodedArrays = encoded;\n }\n\n /**\n * A store over decoded strings, shared by reference: the builder-side representation. Encoding\n * happens on the first read of `offsets` / `utf8`.\n * @param source - the rows; only entries below `length` are ever read, so a builder array that\n * keeps growing can be shared (design section 4.2)\n * @param length - the row count; default source.length\n * @returns the store\n */\n static fromStrings(source: ArrayLike<string>, length: number = source.length): Utf8Store {\n return new Utf8Store(length, source, null);\n }\n\n /**\n * A store over an encoded Utf8 layout, adopted by reference: the wire-side representation.\n * Decoding happens per row on `at()` and in bulk on `slice()` / `decodeAll()`. The layout is not\n * checked here; `checkUtf8Layout` does that for untrusted input.\n * @param offsets - rows + 1 non-decreasing offsets\n * @param utf8 - the concatenated bytes\n * @returns the store\n */\n static fromEncoded(offsets: U32, utf8: U8): Utf8Store {\n return new Utf8Store(Math.max(0, offsets.length - 1), null, { offsets, utf8 });\n }\n\n /**\n * Whether the encoded representation exists (adopted or already materialised).\n * @returns true when `offsets` / `utf8` can be read without encoding\n */\n get encoded(): boolean {\n return this.encodedArrays !== null;\n }\n\n /**\n * Whether the store is backed by a decoded source array, so `at()` never decodes.\n * @returns true for a store built from strings\n */\n get decoded(): boolean {\n return this.source !== null;\n }\n\n /**\n * Whether the encoded arrays were transferred away while rows still depend on them (design\n * section 9.1): a transferred buffer leaves zero-length views.\n * @returns true when detached\n */\n get detached(): boolean {\n return (\n this.source === null &&\n this.length > 0 &&\n this.encodedArrays !== null &&\n this.encodedArrays.offsets.length === 0\n );\n }\n\n /**\n * The `length + 1` offsets, encoding the source on first access.\n * @returns the offsets array (cached)\n */\n get offsets(): U32 {\n return this.ensureEncoded().offsets;\n }\n\n /**\n * The concatenated UTF-8 bytes, encoding the source on first access.\n * @returns the byte array (cached)\n */\n get utf8(): U8 {\n return this.ensureEncoded().utf8;\n }\n\n /**\n * The string of one row, decoded on first access and cached per row.\n * @param row - the row index\n * @returns the string; E_INDEX_RANGE when row is out of range\n */\n at(row: number): string {\n if (!(row >= 0 && row < this.length) || !Number.isInteger(row)) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `row ${row} out of range (length ${this.length})`, {\n index: row,\n size: this.length,\n });\n }\n if (this.source !== null) {\n return this.source[row];\n }\n this.cache ??= new Array<string | undefined>(this.length);\n const cached = this.cache[row];\n if (cached !== undefined) {\n return cached;\n }\n const { offsets, utf8 } = this.ensureEncoded();\n const value = decodeUtf8Row(utf8, offsets[row], offsets[row + 1]);\n this.cache[row] = value;\n return value;\n }\n\n /**\n * The strings of a row range decoded in one pass (one TextDecoder call for an all-ASCII range);\n * nothing is cached. Bounds follow Array.prototype.slice (negative values count from the end,\n * out-of-range values are clamped).\n * @param start - first row (default 0)\n * @param end - one past the last row (default length)\n * @returns a fresh array of the rows in order\n */\n slice(start = 0, end = this.length): string[] {\n const [from, to] = resolveRange(start, end, this.length);\n const { source } = this;\n if (source !== null) {\n const out = new Array<string>(to - from);\n for (let i = from; i < to; i++) {\n out[i - from] = source[i];\n }\n return out;\n }\n const { offsets, utf8 } = this.ensureEncoded();\n return decodeUtf8Rows(utf8, offsets, from, to);\n }\n\n /**\n * Every row decoded in one pass; not cached.\n * @returns a fresh array of all rows\n */\n decodeAll(): string[] {\n return this.slice(0, this.length);\n }\n\n /**\n * Decode every row of an encoded store once, in bulk, and keep the result as the decoded\n * representation so that later `at()` calls are O(1) without a per-row decode. For a store that\n * already has its decoded rows this is a no-op. Used before a pass that will touch every row\n * anyway (building the reverse map of a wire-decoded id map).\n */\n materialiseDecoded(): void {\n if (this.source === null) {\n this.source = this.decodeAll();\n this.cache = null;\n }\n }\n\n /**\n * Bytes of typed storage: the offsets and utf8 arrays when they exist, 0 for a store that has not\n * been encoded yet. JS strings are never counted.\n * @returns the byte count\n */\n byteLength(): number {\n const enc = this.encodedArrays;\n return enc === null ? 0 : enc.offsets.byteLength + enc.utf8.byteLength;\n }\n\n /**\n * The first row whose bytes are not well-formed UTF-8, for full validation of untrusted input\n * (design section 9.5: string ids are decoded with a fatal decoder). A source-backed store is\n * always well-formed.\n * @returns the row index, or -1 when every row is well-formed\n */\n firstMalformedRow(): number {\n const enc = this.encodedArrays;\n if (this.source !== null || enc === null) {\n return -1;\n }\n const { offsets, utf8 } = enc;\n for (let i = 0; i < this.length; i++) {\n if (!isWellFormedUtf8Row(utf8, offsets[i], offsets[i + 1])) {\n return i;\n }\n }\n return -1;\n }\n\n /**\n * The encoded representation, encoding the source once on first use. A store always has a source\n * when it has no encoded arrays (the private constructor is only reached through the factories).\n * @returns the offsets and bytes\n */\n private ensureEncoded(): EncodedUtf8 {\n let enc = this.encodedArrays;\n if (enc === null) {\n enc = encodeUtf8Rows(this.source as ArrayLike<string>, this.length);\n this.encodedArrays = enc;\n // the store is the first holder of the buffers it materialises (design section 9.1)\n claimHolder(enc.offsets.buffer);\n claimHolder(enc.utf8.buffer);\n }\n return enc;\n }\n}\n\n/**\n * Resolve Array.prototype.slice-style bounds against a length.\n * @param start - the requested start (negative counts from the end)\n * @param end - the requested end (negative counts from the end)\n * @param length - the length of the sequence\n * @returns the clamped [from, to] with from <= to\n */\nexport function resolveRange(start: number, end: number, length: number): [from: number, to: number] {\n let from = Math.trunc(start);\n let to = Math.trunc(end);\n if (Number.isNaN(from)) {\n from = 0;\n }\n if (Number.isNaN(to)) {\n to = 0;\n }\n from = from < 0 ? Math.max(length + from, 0) : Math.min(from, length);\n to = to < 0 ? Math.max(length + to, 0) : Math.min(to, length);\n return [from, Math.max(from, to)];\n}\n","/**\n * Low-level typed-array helpers shared by every module of @graphty/graph-format (design sections 5.7,\n * 6.2, 9.5, 10.2 and 10.3): rounding and alignment arithmetic, arena segment layout, the 4-byte\n * padding rules of I10, the u8 adoption predicate, the wire buffer-range check, per-dtype\n * typed-array constructors, and the growth primitive of the builder staging (doubling into a\n * resizable ArrayBuffer when the engine has one, allocate-and-copy doubling otherwise).\n *\n * Nothing here knows about graphs; everything is arithmetic over byte lengths and typed arrays.\n */\n\nimport { ALIGNMENT } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type Dtype, type TypedArrayData, type U8, type U32 } from \"../types/index.js\";\n\n// ============================================================ resizable ArrayBuffer detection\n\n/**\n * Probe once whether this engine supports resizable ArrayBuffer (ES2024: Node 20+, Chrome 111+,\n * Safari 16.4+, Firefox 128+). The probe constructs a tiny resizable buffer and grows it; any throw or\n * missing member means \"not supported\", in which case staging grows by allocate-and-copy (design\n * section 6.2).\n * @returns true when `new ArrayBuffer(n, { maxByteLength })` and `resize()` work\n */\nfunction detectResizableArrayBuffer(): boolean {\n try {\n const probe = new ArrayBuffer(0, { maxByteLength: 64 });\n if (!probe.resizable || typeof probe.resize !== \"function\") {\n return false;\n }\n probe.resize(64);\n return probe.byteLength === 64 && probe.maxByteLength === 64;\n } catch {\n return false;\n }\n}\n\n/**\n * Whether resizable ArrayBuffer is available, detected once at module load (design section 6.2). The\n * growth helpers take it as their default; tests pass an explicit value to exercise both paths.\n */\nexport const HAS_RESIZABLE_ARRAY_BUFFER: boolean = detectResizableArrayBuffer();\n\n// ============================================================ staging growth constants\n\n/** Staging capacities are rounded up to this many elements (design section 6.2). */\nexport const STAGING_ELEMENT_GRANULE = 16;\n\n/** Staging backing buffers are a multiple of this many bytes (design section 6.2). */\nexport const STAGING_BYTE_GRANULE = 64;\n\n/**\n * Virtual address space reserved (`maxByteLength`) for a fresh resizable staging buffer: 256 MiB, so\n * a staging array grows in place without copying up to 64M u32 elements. Reservations are\n * address-space only (pages are committed as the buffer grows), and a buffer that outgrows its\n * reservation is reallocated with a doubled one, so the constant bounds the number of copies rather\n * than the size of anything.\n */\nexport const STAGING_RESERVE_BYTES = 256 * 1024 * 1024;\n\n// ============================================================ rounding and alignment\n\n/**\n * Round `value` up to the next multiple of `multiple`. Written with `%`, not bit masks, because arc\n * counts and byte lengths exceed 2^31 (invariant I3, design section 10.6).\n * @param value - a non-negative integer\n * @param multiple - a positive integer\n * @returns the smallest multiple of `multiple` that is >= value\n */\nexport function roundUp(value: number, multiple: number): number {\n const remainder = value % multiple;\n return remainder === 0 ? value : value + multiple - remainder;\n}\n\n/**\n * Pad a byte length to the next multiple of 4: the size of the padded u32 view of a u8 column and\n * the rule every GPU-bound array satisfies (design sections 5.7 and 10.2).\n * @param byteLength - a non-negative byte count\n * @returns roundUp(byteLength, 4)\n */\nexport function padTo4(byteLength: number): number {\n return roundUp(byteLength, 4);\n}\n\n/**\n * The number of u32 words that span a byte range: ceil(byteLength / 4) (design section 10.2).\n * @param byteLength - a non-negative byte count\n * @returns the word count of the padded u32 view\n */\nexport function paddedWordCount(byteLength: number): number {\n return Math.ceil(byteLength / 4);\n}\n\n/**\n * Align a byte offset up to the next arena segment boundary (design section 10.3; 256 bytes, the\n * WebGPU minStorageBufferOffsetAlignment default).\n * @param byteOffset - a non-negative byte offset\n * @param alignment - the alignment in bytes; defaults to ALIGNMENT (256)\n * @returns roundUp(byteOffset, alignment)\n */\nexport function alignUp(byteOffset: number, alignment: number = ALIGNMENT): number {\n return roundUp(byteOffset, alignment);\n}\n\n// ============================================================ arena segment layout\n\n/**\n * The result of laying out consecutive segments at aligned offsets (design section 10.3).\n */\ninterface SegmentLayout {\n /**\n * One entry per input length: the segment's byte offset relative to the start of the arena, or null for\n * a zero-length segment, which occupies nothing.\n */\n readonly offsets: readonly (number | null)[];\n /** One entry per input length: offset + length, or null for a zero-length segment. */\n readonly ends: readonly (number | null)[];\n /** The end of the last non-empty segment; 0 when every segment is empty. No trailing padding is added. */\n readonly byteLength: number;\n /** The bytes spent on inter-segment padding. */\n readonly padding: number;\n}\n\n/**\n * Lay out segments back to back, each non-empty one starting at a multiple of `alignment`, in the\n * given order (design section 10.3: hot to cold). Zero-length segments get a null offset and occupy\n * nothing, which is how an absent `weights`, a zero-arc `colIdx` and an identity permutation stay out\n * of the arena. For the worked example of section 10.3 (400,004 / 8,000,000 / 8,000,000 / 8,000,000 /\n * 4,000,000) the offsets are 0 / 400,128 / 8,400,128 / 16,400,128 / 24,400,128 and the total is\n * 28,400,128 with 124 bytes of padding.\n * @param byteLengths - the unpadded byte length of every segment in arena order (0 = absent)\n * @param alignment - the segment alignment in bytes; defaults to ALIGNMENT (256)\n * @returns the offsets, ends, total byte length and padding of the layout\n */\nexport function layoutSegments(byteLengths: readonly number[], alignment: number = ALIGNMENT): SegmentLayout {\n const offsets: (number | null)[] = [];\n const ends: (number | null)[] = [];\n let cursor = 0;\n let padding = 0;\n for (const byteLength of byteLengths) {\n if (byteLength === 0) {\n offsets.push(null);\n ends.push(null);\n continue;\n }\n const offset = alignUp(cursor, alignment);\n padding += offset - cursor;\n offsets.push(offset);\n cursor = offset + byteLength;\n ends.push(cursor);\n }\n return { offsets, ends, byteLength: cursor, padding };\n}\n\n// ============================================================ 4-byte rules and adoption (I10, 5.7)\n\n/**\n * The I10 predicate for a GPU-bound array: a view whose byteOffset and byteLength are both multiples\n * of 4 (design section 10.2).\n * @param view - any ArrayBufferView\n * @returns true when both byteOffset and byteLength are multiples of 4\n */\nexport function isFourByteAligned(view: ArrayBufferView): boolean {\n return view.byteOffset % 4 === 0 && view.byteLength % 4 === 0;\n}\n\n/**\n * The \"plain ArrayBuffer\" half of invariant I10 (decision D-SAB, design section 9.4): the view's\n * buffer is an `ArrayBuffer` that is neither a `SharedArrayBuffer` nor resizable, so its bytes are a\n * `BufferSource` for `GPUQueue.writeBuffer`, transferable, and of fixed length for the life of the\n * snapshot (invariant I17).\n * @param view - any ArrayBufferView\n * @returns true when the buffer is a plain, fixed-length ArrayBuffer\n */\nexport function isOverPlainBuffer(view: ArrayBufferView): boolean {\n const { buffer } = view;\n return buffer instanceof ArrayBuffer && !buffer.resizable;\n}\n\n/**\n * The u8 adoption predicate of design section 5.7: \"a zero-copy padded Uint32Array view is\n * constructible\", i.e. `byteOffset % 4 === 0 && byteOffset + roundUp(byteLength, 4) <=\n * buffer.byteLength`.\n * @param data - the u8 array a column would adopt\n * @returns true when paddedU32View(data) can be built without copying\n */\nexport function canViewAsPaddedU32(data: U8): boolean {\n return data.byteOffset % 4 === 0 && data.byteOffset + padTo4(data.byteLength) <= data.buffer.byteLength;\n}\n\n/**\n * The zero-copy Uint32Array of ceil(byteLength / 4) words over a u8 array's own byte range (design\n * sections 5.7 and 10.2); the trailing lanes of the last word are whatever the buffer holds there.\n * @param data - a u8 array satisfying canViewAsPaddedU32()\n * @returns the padded u32 view; E_COLUMN_ALIGNMENT when the view is not constructible\n */\nexport function paddedU32View(data: U8): U32 {\n if (!canViewAsPaddedU32(data)) {\n throw new GraphFormatError(\n \"E_COLUMN_ALIGNMENT\",\n `u8 array at byteOffset ${data.byteOffset} with byteLength ${data.byteLength} has no zero-copy padded u32 view`,\n { byteOffset: data.byteOffset, byteLength: data.byteLength, bufferByteLength: data.buffer.byteLength },\n );\n }\n return new Uint32Array(data.buffer, data.byteOffset, paddedWordCount(data.byteLength));\n}\n\n/**\n * Copy a u8 array into a fresh store over which the padded u32 view is constructible: a new\n * ArrayBuffer of roundUp(length, 4) bytes viewed at offset 0 with the original length (design section\n * 5.7, the `adopt: \"copy\"` path). The padding bytes are zero.\n * @param data - the u8 array to copy\n * @returns a new U8 of the same length whose store satisfies canViewAsPaddedU32()\n */\nexport function copyToPaddedStore(data: U8): U8 {\n const store = new Uint8Array(new ArrayBuffer(padTo4(data.byteLength)), 0, data.byteLength);\n store.set(data);\n return store;\n}\n\n// ============================================================ per-dtype typed arrays\n\n/**\n * The dtypes whose storage is one flat typed array: the five numeric dtypes plus bool (packed u32\n * words) and dict (u32 codes). string, list and json have offsets, children or JS values instead.\n */\nexport type TypedDtype = Exclude<Dtype, \"string\" | \"list\" | \"json\">;\n\n/**\n * A typed-array class as the helpers use it: BYTES_PER_ELEMENT plus the (buffer, byteOffset, length)\n * constructor. Every concrete typed-array constructor satisfies it with T fixed to its\n * ArrayBuffer-parameterised instance type.\n */\nexport interface TypedArrayCtor<T extends TypedArrayData> {\n /** Bytes per element. */\n readonly BYTES_PER_ELEMENT: number;\n /**\n * Construct a view of `length` elements over `buffer` starting at `byteOffset`.\n * @param buffer - the backing buffer\n * @param byteOffset - the start of the view in bytes\n * @param length - the element count of the view\n */\n new (buffer: ArrayBuffer, byteOffset: number, length: number): T;\n}\n\n/**\n * Throw E_UNSUPPORTED for a dtype value outside the union; the `default` branch of every dtype switch\n * (design section 13.4) calls this so an unknown dtype coming from untrusted data fails loudly. Always\n * throws.\n * @param dtype - the value that reached the default branch\n */\nexport function unsupportedDtype(dtype: never): never {\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unsupported dtype ${String(dtype)}`, { dtype });\n}\n\n/**\n * The typed-array class that stores a flat dtype (design section 5.1): Float32Array for f32,\n * Float64Array for f64, Int32Array for i32, Uint8Array for u8, and Uint32Array for u32, for the packed\n * words of bool and for the codes of dict.\n * @param dtype - a flat dtype\n * @returns the constructor; E_UNSUPPORTED for an unknown dtype\n */\nexport function typedArrayCtorOf(dtype: TypedDtype): TypedArrayCtor<TypedArrayData> {\n switch (dtype) {\n case \"f32\":\n return Float32Array;\n case \"f64\":\n return Float64Array;\n case \"i32\":\n return Int32Array;\n case \"u8\":\n return Uint8Array;\n case \"u32\":\n case \"bool\":\n case \"dict\":\n return Uint32Array;\n default:\n return unsupportedDtype(dtype);\n }\n}\n\n// ============================================================ staging growth\n\n/**\n * The next staging capacity, in elements, that holds at least `needed`: doubling from `current`,\n * rounded up to STAGING_ELEMENT_GRANULE (design section 6.2). A capacity of 0 grows to the granule.\n * @param current - the present capacity in elements\n * @param needed - the minimum capacity required\n * @returns the new capacity, >= needed, >= 2 * current, a multiple of 16\n */\nexport function growCapacity(current: number, needed: number): number {\n return roundUp(Math.max(needed, current * 2, STAGING_ELEMENT_GRANULE), STAGING_ELEMENT_GRANULE);\n}\n\n/**\n * The byte length of a staging backing buffer for `capacity` elements of `bytesPerElement` bytes each:\n * rounded up to STAGING_BYTE_GRANULE (design section 6.2). Because every element size divides 64 the\n * result is always a whole number of elements.\n * @param capacity - the capacity in elements\n * @param bytesPerElement - the element size in bytes (1, 4 or 8)\n * @returns the buffer byte length, a multiple of 64\n */\nexport function stagingByteLength(capacity: number, bytesPerElement: number): number {\n return roundUp(capacity * bytesPerElement, STAGING_BYTE_GRANULE);\n}\n\n/**\n * Allocate a staging buffer of `byteLength` bytes. With `resizable` true the buffer is created with a\n * `maxByteLength` of at least `reserveBytes` (and at least `byteLength`) so it can later grow in place;\n * should the engine refuse that reservation with a RangeError (an address-space limit, not a missing\n * capability) the buffer is created resizable with `maxByteLength === byteLength`, which simply means\n * its next growth reallocates. With `resizable` false a plain fixed-length buffer is returned.\n * @param byteLength - the initial byte length\n * @param resizable - whether to create a resizable buffer; defaults to HAS_RESIZABLE_ARRAY_BUFFER\n * @param reserveBytes - the address space to reserve for in-place growth; defaults to STAGING_RESERVE_BYTES\n * @returns the new buffer\n */\nexport function allocateStagingBuffer(\n byteLength: number,\n resizable: boolean = HAS_RESIZABLE_ARRAY_BUFFER,\n reserveBytes: number = STAGING_RESERVE_BYTES,\n): ArrayBuffer {\n if (!resizable) {\n return new ArrayBuffer(byteLength);\n }\n const maxByteLength = Math.max(byteLength, reserveBytes);\n try {\n return new ArrayBuffer(byteLength, { maxByteLength });\n } catch (err) {\n if (err instanceof RangeError && maxByteLength > byteLength) {\n return new ArrayBuffer(byteLength, { maxByteLength: byteLength });\n }\n throw err;\n }\n}\n\n/**\n * Grow a staging array so it holds at least `minLength` elements, preserving its contents (design\n * section 6.2). When the array is the leading view of a resizable buffer with room left, the buffer is\n * resized in place and no bytes move; otherwise a new buffer is allocated (resizable per `resizable`,\n * with a reservation of at least twice the old one so repeated overflow stays amortised) and the\n * contents copied. Either way the returned array is a fresh view object of exactly the new capacity;\n * the caller replaces its reference. Elements beyond the old length are zero on the copy path and on a\n * freshly resized region.\n * @param array - the current staging array, viewed from byteOffset 0 of its buffer\n * @param ctor - the array's constructor\n * @param minLength - the minimum element count required\n * @param resizable - whether new buffers are resizable; defaults to HAS_RESIZABLE_ARRAY_BUFFER\n * @returns a view of growCapacity(array.length, minLength) elements holding the old contents\n */\nexport function growTypedArray<T extends TypedArrayData>(\n array: T,\n ctor: TypedArrayCtor<T>,\n minLength: number,\n resizable: boolean = HAS_RESIZABLE_ARRAY_BUFFER,\n): T {\n if (minLength <= array.length) {\n return array;\n }\n const bytesPerElement = ctor.BYTES_PER_ELEMENT;\n const byteLength = stagingByteLength(growCapacity(array.length, minLength), bytesPerElement);\n const capacity = byteLength / bytesPerElement;\n const { buffer } = array;\n if (buffer.resizable && array.byteOffset === 0 && byteLength <= buffer.maxByteLength) {\n buffer.resize(byteLength);\n return new ctor(buffer, 0, capacity);\n }\n const reserve = Math.max(buffer.maxByteLength * 2, STAGING_RESERVE_BYTES);\n const next = new ctor(allocateStagingBuffer(byteLength, resizable, reserve), 0, capacity);\n next.set(array);\n return next;\n}\n","/**\n * The one packed-bitmap layout of @graphty/graph-format (design sections 5.1, 5.3 and 7.4, decision\n * C13): Uint32Array words, LSB-first, ceil(bits / 32) words, bit i of the bitmap at\n * `(words[i >>> 5] >>> (i & 31)) & 1`. Validity bitmaps, bool column data, NodeMask / EdgeMask and\n * the builder's alive / weightSet bitmaps all use these helpers, so a kernel reads every one of them\n * with the same expression and the layout is bit-for-bit Arrow's on a little-endian host.\n *\n * Convention: a bitmap over `bits` bits keeps every bit at position >= bits CLEAR. Every constructor\n * and mutator here maintains that, so word-level counts, ANDs and ORs stay exact without a length\n * argument; callers that write words directly call bitmapClearTrailing() afterwards. Bit indices are\n * plain numbers below 2^32 (invariant I3), so `>>> 5` and `& 31` are safe on them; word indices are\n * multiplied, never shifted, because a word index can exceed 2^26.\n */\n\nimport { type U32 } from \"../types/index.js\";\n\n/** Every bit set: the fill word of an all-true bitmap. */\nconst ALL_ONES = 0xffffffff;\n\n/**\n * The number of words a bitmap over `bits` bits needs: ceil(bits / 32). Computed with a division, not\n * `(bits + 31) >>> 5`, because bits may be as large as MAX_COUNT and the addition would wrap.\n * @param bits - the bit count, >= 0\n * @returns ceil(bits / 32)\n */\nexport function bitmapWordCount(bits: number): number {\n return Math.ceil(bits / 32);\n}\n\n/**\n * The mask of the bits of the last word that lie below `bits`: all ones when bits is a multiple of\n * 32, otherwise the low `bits % 32` bits. Computed with an unsigned shift so the result is a\n * non-negative number even when 31 bits are kept (`(1 << 31) - 1` is not an int32).\n * @param bits - the bit count\n * @returns the mask as an unsigned 32-bit value\n */\nfunction lastWordMask(bits: number): number {\n const remainder = bits % 32;\n return remainder === 0 ? ALL_ONES : ALL_ONES >>> (32 - remainder);\n}\n\n/**\n * Clear every bit at a position >= bits: the tail of the last word and every word beyond. Call it\n * after writing words directly so the bitmap keeps the trailing-bits-clear convention.\n * @param words - the bitmap words\n * @param bits - the bit count the bitmap covers\n */\nexport function bitmapClearTrailing(words: U32, bits: number): void {\n const wordCount = bitmapWordCount(bits);\n if (wordCount > 0 && wordCount <= words.length && bits % 32 !== 0) {\n words[wordCount - 1] &= lastWordMask(bits);\n }\n if (wordCount < words.length) {\n words.fill(0, wordCount);\n }\n}\n\n/**\n * Allocate a bitmap over `bits` bits: ceil(bits / 32) words, every bit clear or, with `fill`, every\n * bit below `bits` set (trailing bits clear).\n * @param bits - the bit count, >= 0\n * @param fill - the initial value of every bit; defaults to false\n * @returns the new words\n */\nexport function makeBitmap(bits: number, fill = false): U32 {\n const words = new Uint32Array(bitmapWordCount(bits));\n if (fill) {\n words.fill(ALL_ONES);\n bitmapClearTrailing(words, bits);\n }\n return words;\n}\n\n/**\n * Read bit i.\n * @param words - the bitmap words\n * @param i - the bit index, below the bitmap's bit count\n * @returns true when the bit is set\n */\nexport function bitmapGet(words: U32, i: number): boolean {\n return ((words[i >>> 5] >>> (i & 31)) & 1) === 1;\n}\n\n/**\n * Set bit i.\n * @param words - the bitmap words\n * @param i - the bit index, below the bitmap's bit count\n */\nexport function bitmapSet(words: U32, i: number): void {\n words[i >>> 5] |= 1 << (i & 31);\n}\n\n/**\n * Clear bit i.\n * @param words - the bitmap words\n * @param i - the bit index, below the bitmap's bit count\n */\nexport function bitmapClear(words: U32, i: number): void {\n words[i >>> 5] &= ~(1 << (i & 31));\n}\n\n/**\n * Write bit i.\n * @param words - the bitmap words\n * @param i - the bit index, below the bitmap's bit count\n * @param value - the value to write\n */\nexport function bitmapWrite(words: U32, i: number, value: boolean): void {\n if (value) {\n bitmapSet(words, i);\n } else {\n bitmapClear(words, i);\n }\n}\n\n/**\n * The number of set bits in one 32-bit word (SWAR popcount; the multiply goes through Math.imul so\n * it never leaves 32 bits).\n * @param word - the word, read as an unsigned 32-bit value\n * @returns the count, 0..32\n */\nexport function popcount32(word: number): number {\n let w = word - ((word >>> 1) & 0x55555555);\n w = (w & 0x33333333) + ((w >>> 2) & 0x33333333);\n w = (w + (w >>> 4)) & 0x0f0f0f0f;\n return Math.imul(w, 0x01010101) >>> 24;\n}\n\n/**\n * The number of set bits below `bits`. Bits at or above `bits` are ignored, so the count is exact\n * even for a bitmap whose trailing bits are dirty.\n * @param words - the bitmap words, at least ceil(bits / 32) of them\n * @param bits - the bit count to count over\n * @returns the number of set bits in [0, bits)\n */\nexport function bitmapCount(words: U32, bits: number): number {\n const fullWords = Math.floor(bits / 32);\n let count = 0;\n for (let k = 0; k < fullWords; k++) {\n count += popcount32(words[k]);\n }\n if (bits % 32 !== 0) {\n count += popcount32(words[fullWords] & lastWordMask(bits));\n }\n return count;\n}\n\n/**\n * The indices of the set bits below `bits`, ascending, as a fresh U32 of exactly bitmapCount()\n * entries (the maskToIndices of design section 7.4).\n * @param words - the bitmap words\n * @param bits - the bit count to collect over\n * @returns the set bit indices\n */\nexport function bitmapToIndices(words: U32, bits: number): U32 {\n const out = new Uint32Array(bitmapCount(words, bits));\n let n = 0;\n for (let i = 0; i < bits; i++) {\n if (((words[i >>> 5] >>> (i & 31)) & 1) === 1) {\n out[n++] = i;\n }\n }\n return out;\n}\n\n/**\n * The bits [start, end) of `words` as a fresh bitmap over end - start bits starting at bit 0 (the\n * copy behind Column.slice() for bool data and validity, design section 5.7). A word-aligned start\n * is a plain copy; any other start shifts across word boundaries.\n * @param words - the source words\n * @param start - the first bit to copy\n * @param end - one past the last bit to copy\n * @returns the new words, trailing bits clear\n */\nexport function bitmapSlice(words: U32, start: number, end: number): U32 {\n const bits = Math.max(0, end - start);\n const out = makeBitmap(bits);\n if (bits === 0) {\n return out;\n }\n const firstWord = start >>> 5;\n const shift = start & 31;\n if (shift === 0) {\n out.set(words.subarray(firstWord, firstWord + out.length));\n } else {\n const upper = 32 - shift;\n for (let j = 0; j < out.length; j++) {\n const k = firstWord + j;\n const lo = k < words.length ? words[k] >>> shift : 0;\n const hi = k + 1 < words.length ? words[k + 1] << upper : 0;\n out[j] = lo | hi;\n }\n }\n bitmapClearTrailing(out, bits);\n return out;\n}\n","/**\n * Dictionary encoding for `dict` columns (design section 5.4): a string dictionary in first-seen (or\n * declared) order, dense codes `0..size - 1`, a reverse map built eagerly by the builder and lazily\n * by a snapshot, and the re-interning pass that merges one dictionary into another (`GraphBuilder.from`\n * / `addGraph`, O(rows)). The lone-surrogate check every string value must pass (design section 11.3)\n * is `assertWellFormedString`, over the one `hasLoneSurrogate` of the string store.\n */\n\nimport { INVALID_INDEX } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { detachString, hasLoneSurrogate } from \"../ids/string-store.js\";\n\n/**\n * Reject a string value that contains a lone surrogate with E_COLUMN_TYPE (details.reason \"lone\n * surrogate\"); every string that enters a column or a dictionary passes through here.\n * @param value - the string to check\n * @param details - extra details (column, row, field) to attach to the error\n */\nexport function assertWellFormedString(value: string, details?: Readonly<Record<string, unknown>>): void {\n if (hasLoneSurrogate(value)) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", \"string value contains a lone surrogate\", {\n ...details,\n reason: \"lone surrogate\",\n });\n }\n}\n\n/**\n * Build the reverse map of a dictionary (value -> code). Used by a snapshot's DictColumn on the\n * first codeOf() call; the builder keeps one live in its DictionaryBuilder instead.\n * @param dictionary - the dictionary in code order\n * @returns a map from value to code\n */\nexport function buildCodeMap(dictionary: readonly string[]): Map<string, number> {\n const map = new Map<string, number>();\n for (let i = 0; i < dictionary.length; i++) {\n const value = dictionary[i];\n if (!map.has(value)) {\n map.set(value, i);\n }\n }\n return map;\n}\n\n/**\n * An interning dictionary: values are appended in first-seen order and every value has exactly one\n * dense code. The builder keeps one per dict column while staging and keeps interning into it across\n * freezes; a frozen column takes a COPY of the values array (invariant I17, design section 5.4).\n */\nexport class DictionaryBuilder {\n /** The dictionary in code order; copied by the frozen column. */\n readonly values: string[];\n\n private readonly codes: Map<string, number>;\n\n /**\n * Create a dictionary, optionally seeded with declared options (GEXF `<options>`) in order.\n * @param initial - the initial members in code order; duplicates keep their first code\n */\n constructor(initial?: readonly string[]) {\n this.values = [];\n this.codes = new Map();\n if (initial !== undefined) {\n for (const value of initial) {\n this.intern(value);\n }\n }\n }\n\n /**\n * Number of distinct values interned so far.\n * @returns the dictionary size\n */\n get size(): number {\n return this.values.length;\n }\n\n /**\n * The code of a value, appending it when unseen.\n * @param value - the string to intern; E_COLUMN_TYPE when it holds a lone surrogate\n * @returns the dense code of the value\n */\n intern(value: string): number {\n const existing = this.codes.get(value);\n if (existing !== undefined) {\n return existing;\n }\n assertWellFormedString(value);\n const code = this.values.length;\n const owned = detachString(value);\n this.values.push(owned);\n this.codes.set(owned, code);\n return code;\n }\n\n /**\n * The code of a value without interning it.\n * @param value - the string to look up\n * @returns its code, or INVALID_INDEX when absent\n */\n codeOf(value: string): number {\n const code = this.codes.get(value);\n return code === undefined ? INVALID_INDEX : code;\n }\n\n /**\n * Whether a value has been interned.\n * @param value - the string to test\n * @returns true when present\n */\n has(value: string): boolean {\n return this.codes.has(value);\n }\n}\n","/**\n * Type inference for untyped sources (design section 5.1, decision C4): CSV cells, GML values, DOT\n * strings, `fromRecords` and `addNodeRecord`. Inference runs per COLUMN, never per cell, widening\n * monotonically in the order `(unset) -> bool -> i32 -> f64 -> string -> json`; it never yields\n * `f32`. The lexical grammar for text is fixed so two implementations agree (invariant I15):\n *\n * - `bool` is exactly `true` / `false` (case-sensitive);\n * - `i32` is `/^-?(0|[1-9][0-9]*)$/` within `[-2^31, 2^31)`;\n * - `f64` is a decimal or exponent literal accepted by `Number()` that is not empty, not whitespace,\n * not `Infinity` / `NaN` and not a hex / octal / binary form (and whose value is finite);\n * - everything else is `string`. `0` / `1` text is `i32`, never `bool`.\n *\n * JS values map by `typeof`: `boolean -> bool`, integral `number` in i32 range -> `i32`, other\n * `number -> f64`, `string -> string`, array or plain object -> `json`; `null` and `undefined` are\n * unset and do not widen.\n */\n\nimport { GraphFormatError } from \"../errors.js\";\n\n/** The dtypes inference can produce, in widening order. */\nexport type InferredDtype = \"bool\" | \"i32\" | \"f64\" | \"string\" | \"json\";\n\n/** The widening order of design section 5.1; a column only ever moves to the right. */\nexport const WIDENING_ORDER: readonly InferredDtype[] = [\"bool\", \"i32\", \"f64\", \"string\", \"json\"];\n\nconst I32_TEXT = /^-?(0|[1-9][0-9]*)$/;\n// integer part without leading zeros (\"01\" is a string, design section 5.1), optional fraction, optional exponent\nconst F64_TEXT = /^[+-]?((0|[1-9][0-9]*)(\\.[0-9]*)?|\\.[0-9]+)([eE][+-]?[0-9]+)?$/;\nconst I32_MIN = -2147483648;\nconst I32_MAX = 2147483647;\n\n/**\n * The rank of a dtype in the widening order.\n * @param dtype - an inferred dtype\n * @returns 0 for bool up to 4 for json\n */\nexport function wideningRank(dtype: InferredDtype): number {\n return WIDENING_ORDER.indexOf(dtype);\n}\n\n/**\n * Widen a column's dtype by one observation: the wider of the two, where null (unset, nothing seen\n * yet) is narrower than everything.\n * @param current - the column's dtype so far, or null when no value has been seen\n * @param observed - the dtype of the newly observed value, or null for an unset cell\n * @returns the widened dtype (null only when both are null)\n */\nexport function widenDtype(current: InferredDtype | null, observed: InferredDtype | null): InferredDtype | null {\n if (current === null) {\n return observed;\n }\n if (observed === null) {\n return current;\n }\n return wideningRank(observed) > wideningRank(current) ? observed : current;\n}\n\n/**\n * Classify one text cell by the fixed lexical grammar. Exported as the reference implementation of\n * the text grammar of design section 5.1, which the text importers of graph-io must reproduce\n * exactly (invariant I15); the core itself only infers from JS values, so nothing in src/ calls it.\n * @public\n * @param text - the cell text, exactly as read (no trimming)\n * @returns bool, i32, f64 or string\n */\nexport function inferTextDtype(text: string): \"bool\" | \"i32\" | \"f64\" | \"string\" {\n if (text === \"true\" || text === \"false\") {\n return \"bool\";\n }\n if (I32_TEXT.test(text)) {\n const n = Number(text);\n if (n >= I32_MIN && n <= I32_MAX) {\n return \"i32\";\n }\n return Number.isFinite(n) ? \"f64\" : \"string\";\n }\n if (F64_TEXT.test(text) && Number.isFinite(Number(text))) {\n return \"f64\";\n }\n return \"string\";\n}\n\n/**\n * Classify one JS value by `typeof`.\n * @param value - the cell value\n * @returns the dtype, or null for an unset cell (`undefined` or `null`); E_COLUMN_TYPE for a bigint,\n * symbol or function, which no dtype can hold\n */\nexport function inferValueDtype(value: unknown): InferredDtype | null {\n if (value === undefined || value === null) {\n return null;\n }\n switch (typeof value) {\n case \"boolean\":\n return \"bool\";\n case \"number\":\n return Number.isInteger(value) && value >= I32_MIN && value <= I32_MAX ? \"i32\" : \"f64\";\n case \"string\":\n return \"string\";\n case \"object\":\n return \"json\";\n default:\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `a ${typeof value} value cannot be stored in a column`, {\n reason: \"unsupported value type\",\n found: typeof value,\n });\n }\n}\n\n/**\n * Parse a text cell into the storage value of a dtype the column has widened to. A text column\n * never widens to json, but a column that was inferred from JS values may later receive text; in\n * that case the text is stored as a string value. Part of the reference text grammar of design\n * section 5.1 (see inferTextDtype).\n * @public\n * @param text - the cell text\n * @param dtype - the column's current dtype\n * @returns a boolean for bool, a number for i32 / f64, the text itself for string / json\n */\nexport function parseText(text: string, dtype: InferredDtype): boolean | number | string {\n switch (dtype) {\n case \"bool\":\n if (text === \"true\") {\n return true;\n }\n if (text === \"false\") {\n return false;\n }\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `text \"${text}\" is not a bool`, { value: text, dtype });\n case \"i32\":\n case \"f64\": {\n const inferred = inferTextDtype(text);\n if (inferred === \"string\") {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `text \"${text}\" is not a ${dtype}`, { value: text, dtype });\n }\n if (inferred === \"bool\") {\n return text === \"true\" ? 1 : 0;\n }\n return Number(text);\n }\n case \"string\":\n case \"json\":\n return text;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Convert a JS value to the storage value of a (possibly wider) inferred dtype, applying the\n * widening conversions of design section 5.1: a bool widened to a number becomes 1 / 0, a number or\n * boolean widened to string becomes its canonical JS text, anything widened to json is kept as is.\n * @param value - the cell value (never undefined or null; unset cells are handled by the caller)\n * @param dtype - the column's dtype\n * @returns the storage value; E_COLUMN_TYPE when the value cannot be represented in the dtype\n */\nexport function coerceValue(value: unknown, dtype: InferredDtype): unknown {\n switch (dtype) {\n case \"bool\":\n if (typeof value === \"boolean\") {\n return value;\n }\n break;\n case \"i32\":\n case \"f64\":\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n break;\n case \"string\":\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n break;\n case \"json\":\n return value;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `a ${typeof value} value cannot be stored in a ${dtype} column`, {\n dtype,\n found: typeof value,\n });\n}\n\n/**\n * Infer the dtype of a whole column of JS values in one pass.\n * @param values - the cell values; undefined and null are unset\n * @returns the widened dtype, or null when every cell is unset\n */\nexport function inferValuesDtype(values: Iterable<unknown>): InferredDtype | null {\n let dtype: InferredDtype | null = null;\n for (const value of values) {\n dtype = widenDtype(dtype, inferValueDtype(value));\n if (dtype === \"json\") {\n break;\n }\n }\n return dtype;\n}\n\n/**\n * Infer the dtype of a whole column of text cells in one pass. Part of the reference text grammar\n * of design section 5.1 (see inferTextDtype).\n * @public\n * @param cells - the cell texts; an empty string is a string value, not an unset cell (the caller\n * decides how blanks map to unset before calling)\n * @returns the widened dtype, or null when the column is empty\n */\nexport function inferTextsDtype(cells: Iterable<string>): InferredDtype | null {\n let dtype: InferredDtype | null = null;\n for (const text of cells) {\n dtype = widenDtype(dtype, inferTextDtype(text));\n if (dtype === \"string\") {\n break;\n }\n }\n return dtype;\n}\n\n/**\n * A per-column inference accumulator for row-at-a-time sources (`addNodeRecord`, CSV streaming):\n * observe every cell and read `dtype`; each observe call reports whether the column widened so the\n * caller can reallocate storage and record the widening in FreezeReport.widened.\n */\nexport class DtypeInferrer {\n private current: InferredDtype | null = null;\n\n /**\n * The column's dtype so far.\n * @returns the widened dtype, or null until a set cell has been observed\n */\n get dtype(): InferredDtype | null {\n return this.current;\n }\n\n /**\n * Observe a JS value.\n * @param value - the cell value; undefined and null are unset and never widen\n * @returns true when the column's dtype changed\n */\n observeValue(value: unknown): boolean {\n return this.apply(inferValueDtype(value));\n }\n\n /**\n * Observe a text cell. Part of the reference text grammar of design section 5.1 (see\n * inferTextDtype).\n * @public\n * @param text - the cell text\n * @returns true when the column's dtype changed\n */\n observeText(text: string): boolean {\n return this.apply(inferTextDtype(text));\n }\n\n /**\n * Force the dtype to at least the given one (a declared lower bound, or the dtype of a column\n * being merged in).\n * @param dtype - the dtype to widen to\n * @returns true when the column's dtype changed\n */\n widenTo(dtype: InferredDtype): boolean {\n return this.apply(dtype);\n }\n\n private apply(observed: InferredDtype | null): boolean {\n const next = widenDtype(this.current, observed);\n if (next === this.current) {\n return false;\n }\n this.current = next;\n return true;\n }\n}\n","/**\n * Column implementations for every dtype of design section 5.1, the column factory that wraps raw\n * storage (MutableColumnParts) into a Column, the declaration resolver (ColumnDecl -> ColumnMeta,\n * design sections 5.3 and 5.5), the constructors the table uses for typed arrays, JS arrays and\n * empty declared columns. Bitmap and padding arithmetic comes from bitmap.ts and util/typed-array.ts.\n *\n * Storage follows Apache Arrow's layout without the dependency: a typed values buffer, an optional\n * validity bitmap (u32 words, LSB-first, ceil(rows / 32) words -- the one bitmap layout of the\n * package, decision C13), an optional dictionary, offsets or child, and per-column metadata. No\n * per-row objects exist anywhere. Column contents are frozen by contract unless meta.mutable is true\n * (design section 5.8); the mutable gating throws E_COLUMN_IMMUTABLE.\n */\n\nimport { INVALID_INDEX } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { encodeUtf8Rows } from \"../ids/string-store.js\";\nimport {\n type BoolColumn,\n type Column,\n type ColumnDeclPatch,\n type ColumnDomain,\n type ColumnMeta,\n type ColumnOf,\n type ColumnOrigin,\n type ColumnOriginInput,\n type DictColumn,\n type Dtype,\n type DtypeValue,\n type F32,\n type F32Column,\n type F64,\n type F64Column,\n type GpuEligibility,\n type I32,\n type I32Column,\n type JsonColumn,\n type ListColumn,\n type ScalarDtype,\n type StringColumn,\n type TypedArrayData,\n type U8,\n type U8Column,\n type U32,\n type U32Column,\n} from \"../types/index.js\";\nimport { type MutableColumnParts } from \"../types/internal.js\";\nimport { claimHolder, noteShared } from \"../util/shared-buffers.js\";\nimport { canViewAsPaddedU32, isOverPlainBuffer, paddedU32View, padTo4 } from \"../util/typed-array.js\";\nimport { bitmapClear, bitmapCount, bitmapGet, bitmapSet, bitmapSlice, bitmapWordCount, makeBitmap } from \"./bitmap.js\";\nimport { assertWellFormedString, buildCodeMap, DictionaryBuilder } from \"./dictionary.js\";\nimport { coerceValue, inferValuesDtype } from \"./infer.js\";\n\n// ============================================================ constants and small helpers\n\ntype NumericDtype = \"f32\" | \"f64\" | \"i32\" | \"u32\" | \"u8\";\n\nconst ALL_DTYPES: ReadonlySet<string> = new Set([\n \"f32\",\n \"f64\",\n \"i32\",\n \"u32\",\n \"u8\",\n \"bool\",\n \"dict\",\n \"string\",\n \"list\",\n \"json\",\n]);\nconst NUMERIC_DTYPES: ReadonlySet<string> = new Set([\"f32\", \"f64\", \"i32\", \"u32\", \"u8\"]);\nconst MAX_COMPONENTS = 16;\n/** The deepest nesting a JSON value (a json cell, a default, options or extra) may have. */\nconst MAX_JSON_DEPTH = 256;\nconst I32_MIN = -2147483648;\nconst I32_MAX = 2147483647;\nconst U32_MAX = 0xffffffff;\nconst U8_MAX = 0xff;\n\nconst decoder = new TextDecoder();\n\n/** Cached f32 copies of f64 columns for gpuView() (design section 10.4); dropped by markDirty(). */\nconst f32Cache = new WeakMap<object, F32>();\n\n/**\n * Allocate a u8 store from which a zero-copy padded u32 view is constructible (design section 5.7):\n * the backing buffer is a multiple of 4 bytes even when the length is not.\n * @param length - the number of bytes\n * @returns a fresh Uint8Array over a padded buffer\n */\nexport function allocU8(length: number): U8 {\n return new Uint8Array(new ArrayBuffer(padTo4(length)), 0, length);\n}\n\n/**\n * GPU eligibility of a dtype (design section 10.4).\n * @param dtype - the column dtype\n * @returns \"direct\" for u32 / i32 / f32 / dict, \"packed\" for u8 / bool, \"convert\" for f64, \"none\" otherwise\n */\nexport function gpuEligibility(dtype: Dtype): GpuEligibility {\n switch (dtype) {\n case \"f32\":\n case \"i32\":\n case \"u32\":\n case \"dict\":\n return \"direct\";\n case \"u8\":\n case \"bool\":\n return \"packed\";\n case \"f64\":\n return \"convert\";\n case \"string\":\n case \"list\":\n case \"json\":\n return \"none\";\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Whether a dtype name is one a list child may have (any dtype but list).\n * @param value - the dtype name\n * @returns true for a scalar dtype\n */\nfunction isScalarDtype(value: string): value is ScalarDtype {\n return value !== \"list\" && ALL_DTYPES.has(value);\n}\n\n/**\n * Whether a value is a plain object (prototype Object.prototype or null), the only object shape JSON\n * carries.\n * @param value - the value to test\n * @returns true for a plain object\n */\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const proto: unknown = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Reject a metadata value that JSON cannot carry (design section 5.9): only null, booleans, numbers\n * (non-finite and -0 included; the wire tags them), well-formed strings, arrays and plain objects of\n * such values are accepted. E_COLUMN_TYPE with details.field otherwise.\n * @param value - the value to check\n * @param field - the metadata field name for the error details\n * @param depth - the nesting depth of `value` (E_COLUMN_TYPE beyond MAX_JSON_DEPTH)\n */\nexport function assertJsonValue(value: unknown, field: string, depth = 0): void {\n if (value === null || typeof value === \"boolean\" || typeof value === \"number\") {\n return;\n }\n if (typeof value === \"string\") {\n assertWellFormedString(value, { field });\n return;\n }\n if (depth > MAX_JSON_DEPTH) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `${field} is nested deeper than ${MAX_JSON_DEPTH} levels`, {\n field,\n reason: \"nesting\",\n });\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n assertJsonValue(item, field, depth + 1);\n }\n return;\n }\n if (isPlainObject(value)) {\n for (const key of Object.keys(value)) {\n assertJsonValue(value[key], field, depth + 1);\n }\n return;\n }\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `${field} is not a JSON value`, {\n field,\n found: value === undefined ? \"undefined\" : typeof value,\n });\n}\n\n/**\n * A deep copy of a JSON value (already checked by assertJsonValue): arrays and plain objects are\n * copied at every level so a caller's live object never reaches a column's metadata, where a later\n * mutation of the caller's object would change what `value()` returns for unset rows (design\n * section 5.8). The copy is the column's own; like a typed array's contents it is immutable by\n * contract.\n * @param value - the JSON value\n * @returns the copy (primitives are returned as they are)\n */\nfunction cloneJson<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map((item: unknown) => cloneJson(item)) as T;\n }\n if (isPlainObject(value)) {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n out[key] = cloneJson(value[key]);\n }\n return out as T;\n }\n return value;\n}\n\n// ============================================================ declaration resolution\n\n/**\n * Whether a number is exactly representable in a numeric dtype: any number for f32 / f64, an integer\n * in range for i32 / u32 / u8.\n * @param dtype - the numeric dtype\n * @param value - the number\n * @returns true when the dtype stores the value without change\n */\nexport function representableNumber(dtype: NumericDtype, value: number): boolean {\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n return true;\n case \"i32\":\n return Number.isInteger(value) && value >= I32_MIN && value <= I32_MAX;\n case \"u32\":\n return Number.isInteger(value) && value >= 0 && value <= U32_MAX;\n case \"u8\":\n return Number.isInteger(value) && value >= 0 && value <= U8_MAX;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * The single number a declared numeric default reduces to, when it is representable: the number\n * itself for components 1, or the common value of an array of `components` equal numbers.\n * @param dtype - the numeric dtype\n * @param components - the column stride\n * @param value - the declared default\n * @returns the fill number, or null when the default is not representable as one fill value\n */\nfunction numericDefaultFill(dtype: NumericDtype, components: number, value: unknown): number | null {\n if (typeof value === \"number\") {\n return representableNumber(dtype, value) ? value : null;\n }\n if (components > 1 && Array.isArray(value) && value.length === components) {\n const first: unknown = value[0];\n if (typeof first !== \"number\" || !representableNumber(dtype, first)) {\n return null;\n }\n for (let k = 1; k < components; k++) {\n if (!Object.is(value[k], first)) {\n return null;\n }\n }\n return first;\n }\n return null;\n}\n\nfunction typeError(field: string, message: string, extra?: Readonly<Record<string, unknown>>): GraphFormatError {\n return new GraphFormatError(\"E_COLUMN_TYPE\", message, { ...extra, field });\n}\n\nfunction resolveOrigin(origin: ColumnOriginInput | undefined): ColumnOrigin | null {\n if (origin === undefined) {\n return null;\n }\n if (!isPlainObject(origin)) {\n throw typeError(\"origin\", \"origin must be a plain object\");\n }\n const pick = (key: keyof ColumnOrigin): string | null => {\n const value = origin[key];\n if (value === undefined || value === null) {\n return null;\n }\n if (typeof value !== \"string\") {\n throw typeError(\"origin\", `origin.${key} must be a string or null`, { found: typeof value });\n }\n return value;\n };\n return {\n format: pick(\"format\"),\n id: pick(\"id\"),\n title: pick(\"title\"),\n type: pick(\"type\"),\n namespace: pick(\"namespace\"),\n };\n}\n\nfunction resolveComponents(field: \"components\" | \"itemComponents\", value: number | undefined, dtype: string): number {\n if (value === undefined) {\n return 1;\n }\n if (!Number.isInteger(value) || value < 1 || value > MAX_COMPONENTS) {\n throw typeError(field, `${field} must be an integer in 1..${MAX_COMPONENTS}, found ${value}`, { found: value });\n }\n if (value > 1 && !NUMERIC_DTYPES.has(dtype)) {\n throw typeError(field, `${field} > 1 is only allowed for f32 / f64 / i32 / u32 / u8, not ${dtype}`, {\n found: value,\n dtype,\n });\n }\n return value;\n}\n\n/**\n * Resolve the fill value of design section 5.3: the explicit fill when given (type-checked against\n * the dtype), else the declared default when it is representable in the dtype, else the dtype's zero\n * (0 / false / \"\" ; INVALID_INDEX for a refersTo u32 column so unset references are never in range).\n * @param dtype - the column dtype\n * @param components - the stride\n * @param explicit - the declared fill, if any\n * @param defaultValue - the declared default, if any\n * @param options - the declared options (the initial dictionary of a dict column)\n * @param refersTo - the referenced index space, if any\n * @returns the resolved fill\n */\nfunction resolveFill(\n dtype: Dtype,\n components: number,\n explicit: number | string | boolean | undefined,\n defaultValue: unknown,\n options: readonly unknown[] | null,\n refersTo: \"node\" | \"edge\" | null,\n): number | string | boolean {\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n if (explicit !== undefined) {\n if (typeof explicit !== \"number\") {\n throw typeError(\"fill\", `fill of a ${dtype} column must be a number`, { found: typeof explicit });\n }\n return explicit;\n }\n if (refersTo !== null) {\n return INVALID_INDEX;\n }\n const fromDefault = numericDefaultFill(dtype, components, defaultValue);\n return fromDefault ?? 0;\n }\n case \"bool\": {\n if (explicit !== undefined) {\n if (typeof explicit !== \"boolean\") {\n throw typeError(\"fill\", \"fill of a bool column must be a boolean\", { found: typeof explicit });\n }\n return explicit;\n }\n return typeof defaultValue === \"boolean\" ? defaultValue : false;\n }\n case \"dict\": {\n if (explicit !== undefined) {\n if (typeof explicit !== \"string\") {\n throw typeError(\"fill\", \"fill of a dict column must be a string\", { found: typeof explicit });\n }\n return explicit;\n }\n if (typeof defaultValue === \"string\" && (options === null || options.includes(defaultValue))) {\n return defaultValue;\n }\n if (options !== null && options.length > 0 && typeof options[0] === \"string\") {\n return options[0];\n }\n return \"\";\n }\n case \"string\": {\n if (explicit !== undefined) {\n if (typeof explicit !== \"string\") {\n throw typeError(\"fill\", \"fill of a string column must be a string\", { found: typeof explicit });\n }\n return explicit;\n }\n return \"\";\n }\n case \"list\":\n case \"json\": {\n // the nominal fill of a list / json column is \"\"; unset rows physically hold an empty list / undefined\n if (explicit !== undefined && explicit !== \"\") {\n throw typeError(\"fill\", `a ${dtype} column takes no fill value`, { found: explicit });\n }\n return \"\";\n }\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Resolve a column declaration into the complete metadata of design section 5.5: every field\n * present, null for none, defaults applied, every rule checked (components, list child, refersTo,\n * JSON-ness of default / options / extra, fill typing). E_COLUMN_TYPE with details.field on every\n * violation.\n * @param name - the column name (overrides decl.name)\n * @param domain - the table the column belongs to\n * @param decl - the declaration; dtype is required\n * @returns the resolved metadata, frozen\n */\nexport function resolveColumnMeta(name: string, domain: ColumnDomain, decl: ColumnDeclPatch): ColumnMeta {\n const { dtype } = decl;\n if (dtype === undefined || !ALL_DTYPES.has(dtype)) {\n throw typeError(\"dtype\", `column \"${name}\" has no valid dtype`, { name, found: dtype });\n }\n const components = resolveComponents(\"components\", decl.components, dtype);\n let itemDtype: ScalarDtype | null = null;\n let itemComponents: number | null = null;\n if (dtype === \"list\") {\n const { itemDtype: declaredItem } = decl;\n if (declaredItem === undefined || !isScalarDtype(declaredItem)) {\n throw typeError(\"itemDtype\", `list column \"${name}\" needs a scalar itemDtype`, {\n name,\n found: declaredItem,\n });\n }\n itemDtype = declaredItem;\n itemComponents = resolveComponents(\"itemComponents\", decl.itemComponents, declaredItem);\n } else if (decl.itemDtype !== undefined || decl.itemComponents !== undefined) {\n throw typeError(\"itemDtype\", `itemDtype / itemComponents are only allowed on list columns, not ${dtype}`, {\n name,\n dtype,\n });\n }\n const refersTo = decl.refersTo ?? null;\n if (refersTo !== null) {\n if (refersTo !== \"node\" && refersTo !== \"edge\") {\n throw typeError(\"refersTo\", `refersTo must be \"node\" or \"edge\"`, { found: refersTo });\n }\n const indexColumn =\n (dtype === \"u32\" && components === 1) || (dtype === \"list\" && itemDtype === \"u32\" && itemComponents === 1);\n if (!indexColumn) {\n throw typeError(\"refersTo\", `refersTo requires a u32 column or a list of u32, not ${dtype}`, {\n name,\n dtype,\n });\n }\n }\n const defaultValue = decl.default;\n if (defaultValue !== undefined) {\n assertJsonValue(defaultValue, \"default\");\n }\n let options: readonly unknown[] | null = null;\n if (decl.options !== undefined) {\n if (!Array.isArray(decl.options)) {\n throw typeError(\"options\", \"options must be an array\");\n }\n assertJsonValue(decl.options, \"options\");\n if (dtype === \"dict\") {\n for (const option of decl.options) {\n if (typeof option !== \"string\") {\n throw typeError(\"options\", \"options of a dict column must be strings\", { found: typeof option });\n }\n }\n }\n options = Object.freeze(cloneJson([...decl.options]));\n }\n const extra = decl.extra ?? {};\n if (!isPlainObject(extra)) {\n throw typeError(\"extra\", \"extra must be a plain object\");\n }\n assertJsonValue(extra, \"extra\");\n const role = decl.role ?? null;\n if (role !== null && typeof role !== \"string\") {\n throw typeError(\"role\", \"role must be a string\", { found: typeof role });\n }\n const fill = resolveFill(dtype, components, decl.fill, defaultValue, options, refersTo);\n return Object.freeze({\n name,\n domain,\n dtype,\n components,\n itemDtype,\n itemComponents,\n nullable: decl.nullable ?? true,\n mutable: decl.mutable ?? false,\n role,\n refersTo,\n unique: decl.unique ?? false,\n default: cloneJson(defaultValue),\n fill,\n options,\n origin: resolveOrigin(decl.origin),\n dynamic: decl.dynamic ?? false,\n extra: Object.freeze(cloneJson({ ...extra })),\n });\n}\n\n/**\n * The declaration that reproduces a column's metadata, for patching an existing column's meta\n * (rename, move between tables, set() with a decl patch).\n * @param meta - the metadata to convert\n * @returns an equivalent declaration patch\n */\nexport function metaToDecl(meta: ColumnMeta): ColumnDeclPatch {\n return {\n name: meta.name,\n dtype: meta.dtype,\n components: meta.components,\n itemDtype: meta.itemDtype ?? undefined,\n itemComponents: meta.itemComponents ?? undefined,\n nullable: meta.nullable,\n mutable: meta.mutable,\n role: meta.role ?? undefined,\n refersTo: meta.refersTo ?? undefined,\n unique: meta.unique,\n default: meta.default,\n fill: meta.fill,\n options: meta.options ?? undefined,\n origin: meta.origin ?? undefined,\n dynamic: meta.dynamic,\n extra: meta.extra,\n };\n}\n\n// ============================================================ column base\n\n/**\n * Members shared by every column implementation (design sections 5.3, 5.7 and 5.8).\n */\nabstract class ColumnImpl<D extends Dtype> {\n readonly dtype: D;\n readonly meta: ColumnMeta;\n readonly length: number;\n readonly gpu: GpuEligibility;\n protected validityWords: U32 | null;\n protected nullCountValue: number;\n protected versionValue = 0;\n protected defaultCache: ColumnOf<D> | null = null;\n /** The column's own copy of the declared default, so a mutation of `meta.default` never reaches `value()`. */\n private readonly defaultValue: unknown;\n\n protected constructor(dtype: D, meta: ColumnMeta, length: number, validity: U32 | null, nullCount: number) {\n this.dtype = dtype;\n this.meta = meta;\n this.length = length;\n this.gpu = gpuEligibility(dtype);\n this.validityWords = validity;\n this.nullCountValue = nullCount;\n this.defaultValue = cloneJson(meta.default);\n }\n\n get validity(): U32 | null {\n return this.validityWords;\n }\n\n get nullCount(): number {\n return this.nullCountValue;\n }\n\n get version(): number {\n return this.versionValue;\n }\n\n abstract get byteLength(): number;\n\n get paddedByteLength(): number {\n return this.byteLength;\n }\n\n protected get validityByteLength(): number {\n return this.validityWords === null ? 0 : this.validityWords.byteLength;\n }\n\n /**\n * Whether the column's storage was transferred away (design sections 9.1 and 11.3): derived from\n * the array state, since a transferred ArrayBuffer leaves zero-length views behind.\n * @returns true when a typed array the column needs is empty although the column has rows\n */\n get detached(): boolean {\n if (this.length === 0) {\n return false;\n }\n const words = this.validityWords;\n return (words !== null && words.length === 0) || this.storageDetached();\n }\n\n isSet(row: number): boolean {\n if (!(row >= 0 && row < this.length)) {\n return false;\n }\n const words = this.validityWords;\n if (words === null) {\n return true;\n }\n if (words.length === 0) {\n throw this.detachedError();\n }\n return bitmapGet(words, row);\n }\n\n value(row: number): DtypeValue<D> | undefined {\n this.assertAttached();\n if (!(Number.isInteger(row) && row >= 0 && row < this.length)) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `row ${row} is out of range for a column of ${this.length} rows`,\n {\n row,\n length: this.length,\n column: this.meta.name,\n },\n );\n }\n const words = this.validityWords;\n if (words !== null && !bitmapGet(words, row)) {\n // an unset row reads the column's own copy of the declared default; a structured default is\n // handed out as a fresh copy so no caller can change what later reads see (design section 5.8)\n const { defaultValue } = this;\n return defaultValue === undefined ? undefined : (cloneJson(defaultValue) as DtypeValue<D>);\n }\n return this.readValue(row) as DtypeValue<D>;\n }\n\n materializeDefault(): ColumnOf<D> {\n this.assertAttached();\n if (this.meta.default === undefined) {\n throw new GraphFormatError(\"E_NO_DEFAULT\", `column \"${this.meta.name}\" declares no default`, {\n column: this.meta.name,\n });\n }\n if (this.nullCountValue === 0 || this.fillIsDefault()) {\n return this.self();\n }\n this.defaultCache ??= this.withDefaults();\n return this.defaultCache;\n }\n\n paddedU32View(): U32 {\n throw new GraphFormatError(\"E_GPU_INELIGIBLE\", `a ${this.dtype} column has no u32 view`, {\n column: this.meta.name,\n dtype: this.dtype,\n });\n }\n\n markDirty(): void {\n this.assertMutable(\"markDirty\");\n this.assertAttached();\n this.versionValue++;\n this.defaultCache = null;\n f32Cache.delete(this);\n const words = this.validityWords;\n if (words !== null) {\n this.nullCountValue = this.length - bitmapCount(words, this.length);\n }\n }\n\n mutableValidity(): U32 | null {\n this.assertMutable(\"mutableValidity\");\n return this.validityWords;\n }\n\n setAll(): void {\n this.assertMutable(\"setAll\");\n this.validityWords = null;\n this.nullCountValue = 0;\n this.versionValue++;\n this.defaultCache = null;\n }\n\n abstract slice(start: number, end: number): ColumnOf<D>;\n\n abstract clone(): ColumnOf<D>;\n\n /**\n * Whether the dtype-specific storage (data, codes, offsets) is a zero-length view although the\n * column has rows; the validity bitmap is checked by the base class.\n * @returns true when detached\n */\n protected abstract storageDetached(): boolean;\n\n protected abstract readValue(row: number): unknown;\n\n protected assertAttached(): void {\n if (this.detached) {\n throw this.detachedError();\n }\n }\n\n protected detachedError(): GraphFormatError {\n return new GraphFormatError(\"E_DETACHED\", `column \"${this.meta.name}\" was transferred away`, {\n column: this.meta.name,\n });\n }\n\n protected abstract self(): ColumnOf<D>;\n\n protected abstract fillIsDefault(): boolean;\n\n protected abstract withDefaults(): ColumnOf<D>;\n\n protected assertMutable(operation: string): void {\n if (!this.meta.mutable) {\n throw new GraphFormatError(\"E_COLUMN_IMMUTABLE\", `${operation}() on immutable column \"${this.meta.name}\"`, {\n column: this.meta.name,\n operation,\n });\n }\n }\n\n protected checkRange(start: number, end: number): void {\n this.assertAttached();\n if (!(Number.isInteger(start) && Number.isInteger(end) && start >= 0 && start <= end && end <= this.length)) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `row range [${start}, ${end}) is invalid for ${this.length} rows`,\n {\n start,\n end,\n length: this.length,\n column: this.meta.name,\n },\n );\n }\n }\n\n /**\n * The validity bitmap and null count of the row range [start, end); zero-copy at word boundaries.\n * @param start - first row\n * @param end - one past the last row\n * @returns the bitmap over the range (null when every row is set) and its null count\n */\n protected sliceValidity(start: number, end: number): { validity: U32 | null; nullCount: number } {\n const words = this.validityWords;\n if (words === null) {\n return { validity: null, nullCount: 0 };\n }\n const rows = end - start;\n const validity =\n start % 32 === 0\n ? shareView(words.subarray(start >>> 5, (start >>> 5) + bitmapWordCount(rows)))\n : bitmapSlice(words, start, end);\n return { validity, nullCount: rows - bitmapCount(validity, rows) };\n }\n\n protected cloneValidity(): U32 | null {\n this.assertAttached();\n return this.validityWords === null ? null : this.validityWords.slice();\n }\n}\n\n/**\n * Record that a zero-copy view aliases a buffer another column still holds (the owner count of\n * design section 9.1): a slice attached to a second snapshot must never let a transfer detach the\n * source, so the shared buffer is copied by `toWire({ transfer: true })` and `transferables()`.\n * @param view - a subarray of a column's storage\n * @returns the view\n */\nfunction shareView<T extends ArrayBufferView>(view: T): T {\n noteShared(view.buffer);\n return view;\n}\n\n// ============================================================ fixed-width numeric columns\n\nabstract class FixedColumnImpl<D extends NumericDtype, T extends TypedArrayData> extends ColumnImpl<D> {\n readonly data: T;\n\n protected constructor(\n dtype: D,\n meta: ColumnMeta,\n length: number,\n data: T,\n validity: U32 | null,\n nullCount: number,\n ) {\n super(dtype, meta, length, validity, nullCount);\n this.data = data;\n }\n\n override get byteLength(): number {\n return this.data.byteLength + this.validityByteLength;\n }\n\n mutableData(): T {\n this.assertMutable(\"mutableData\");\n this.assertAttached();\n return this.data;\n }\n\n protected override storageDetached(): boolean {\n return this.data.length === 0 && this.length * this.meta.components > 0;\n }\n\n override slice(start: number, end: number): ColumnOf<D> {\n this.checkRange(start, end);\n const { components } = this.meta;\n const data = this.sliceData(start * components, end * components);\n const { validity, nullCount } = this.sliceValidity(start, end);\n return this.wrap(this.meta, end - start, data, validity, nullCount);\n }\n\n override clone(): ColumnOf<D> {\n this.assertAttached();\n return this.wrap(this.meta, this.length, this.copyData(), this.cloneValidity(), this.nullCountValue);\n }\n\n protected override readValue(row: number): number | ArrayLike<number> {\n const { components } = this.meta;\n if (components === 1) {\n return this.data[row];\n }\n return this.data.subarray(row * components, (row + 1) * components);\n }\n\n protected override fillIsDefault(): boolean {\n const { fill, default: defaultValue, components } = this.meta;\n if (typeof fill !== \"number\") {\n return false;\n }\n return numericDefaultFill(this.dtype, components, defaultValue) === fill;\n }\n\n protected override withDefaults(): ColumnOf<D> {\n const { components, default: defaultValue } = this.meta;\n const data = this.copyData();\n const words = this.validityWords;\n if (words !== null) {\n for (let row = 0; row < this.length; row++) {\n if (!bitmapGet(words, row)) {\n writeNumeric(this.dtype, data, row * components, components, defaultValue, this.meta.name, row);\n }\n }\n }\n return this.wrap(this.meta, this.length, data, this.cloneValidity(), this.nullCountValue);\n }\n\n protected abstract wrap(\n meta: ColumnMeta,\n length: number,\n data: T,\n validity: U32 | null,\n nullCount: number,\n ): ColumnOf<D>;\n\n protected sliceData(start: number, end: number): T {\n return shareView(this.data.subarray(start, end) as T);\n }\n\n protected copyData(): T {\n return this.data.slice() as T;\n }\n}\n\n/**\n * Write one row's numeric value (a number, or an array of `components` numbers) into a typed array,\n * rejecting values the dtype cannot represent (a non-integer or out-of-range number for i32 / u32 /\n * u8) with E_COLUMN_TYPE instead of letting the typed array wrap them.\n * @param dtype - the numeric dtype\n * @param data - the destination\n * @param at - the element offset of the row\n * @param components - the stride\n * @param value - the value to write\n * @param column - the column name for error details\n * @param row - the row for error details\n */\nfunction writeNumeric(\n dtype: NumericDtype,\n data: TypedArrayData,\n at: number,\n components: number,\n value: unknown,\n column: string,\n row: number,\n): void {\n if (typeof value === \"number\") {\n assertRepresentable(dtype, value, column, row);\n if (components === 1) {\n data[at] = value;\n } else {\n data.fill(value, at, at + components);\n }\n return;\n }\n if (components === 1 || !isArrayLikeNumbers(value, components)) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `row ${row} of ${dtype} column \"${column}\" is not ${components} number(s)`,\n { column, row, components, found: typeof value },\n );\n }\n for (let k = 0; k < components; k++) {\n assertRepresentable(dtype, value[k], column, row);\n }\n for (let k = 0; k < components; k++) {\n data[at + k] = value[k];\n }\n}\n\nfunction assertRepresentable(dtype: NumericDtype, value: number, column: string, row: number): void {\n if (!representableNumber(dtype, value)) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `row ${row} of ${dtype} column \"${column}\": ${value} is not representable`,\n { column, row, value },\n );\n }\n}\n\n/**\n * Whether a value is an array-like of exactly `length` numbers (a multi-component cell).\n * @param value - the value\n * @param length - the required length\n * @returns true for a numeric vector of that length\n */\nexport function isArrayLikeNumbers(value: unknown, length: number): value is ArrayLike<number> {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n const arrayLike = value as ArrayLike<unknown>;\n if (arrayLike.length !== length) {\n return false;\n }\n for (let k = 0; k < length; k++) {\n if (typeof arrayLike[k] !== \"number\") {\n return false;\n }\n }\n return true;\n}\n\nclass F32ColumnImpl extends FixedColumnImpl<\"f32\", F32> implements F32Column {\n constructor(meta: ColumnMeta, length: number, data: F32, validity: U32 | null, nullCount: number) {\n super(\"f32\", meta, length, data, validity, nullCount);\n }\n\n protected override self(): F32Column {\n return this;\n }\n\n protected override wrap(\n meta: ColumnMeta,\n length: number,\n data: F32,\n validity: U32 | null,\n nullCount: number,\n ): F32Column {\n return new F32ColumnImpl(meta, length, data, validity, nullCount);\n }\n}\n\nclass F64ColumnImpl extends FixedColumnImpl<\"f64\", F64> implements F64Column {\n constructor(meta: ColumnMeta, length: number, data: F64, validity: U32 | null, nullCount: number) {\n super(\"f64\", meta, length, data, validity, nullCount);\n }\n\n protected override self(): F64Column {\n return this;\n }\n\n protected override wrap(\n meta: ColumnMeta,\n length: number,\n data: F64,\n validity: U32 | null,\n nullCount: number,\n ): F64Column {\n return new F64ColumnImpl(meta, length, data, validity, nullCount);\n }\n}\n\nclass I32ColumnImpl extends FixedColumnImpl<\"i32\", I32> implements I32Column {\n constructor(meta: ColumnMeta, length: number, data: I32, validity: U32 | null, nullCount: number) {\n super(\"i32\", meta, length, data, validity, nullCount);\n }\n\n protected override self(): I32Column {\n return this;\n }\n\n protected override wrap(\n meta: ColumnMeta,\n length: number,\n data: I32,\n validity: U32 | null,\n nullCount: number,\n ): I32Column {\n return new I32ColumnImpl(meta, length, data, validity, nullCount);\n }\n}\n\nclass U32ColumnImpl extends FixedColumnImpl<\"u32\", U32> implements U32Column {\n constructor(meta: ColumnMeta, length: number, data: U32, validity: U32 | null, nullCount: number) {\n super(\"u32\", meta, length, data, validity, nullCount);\n }\n\n override paddedU32View(): U32 {\n return this.data;\n }\n\n protected override self(): U32Column {\n return this;\n }\n\n protected override wrap(\n meta: ColumnMeta,\n length: number,\n data: U32,\n validity: U32 | null,\n nullCount: number,\n ): U32Column {\n return new U32ColumnImpl(meta, length, data, validity, nullCount);\n }\n}\n\nclass U8ColumnImpl extends FixedColumnImpl<\"u8\", U8> implements U8Column {\n constructor(meta: ColumnMeta, length: number, data: U8, validity: U32 | null, nullCount: number) {\n super(\"u8\", meta, length, data, validity, nullCount);\n }\n\n override get paddedByteLength(): number {\n return padTo4(this.data.byteLength) + this.validityByteLength;\n }\n\n override paddedU32View(): U32 {\n return paddedU32View(this.data);\n }\n\n protected override self(): U8Column {\n return this;\n }\n\n protected override wrap(\n meta: ColumnMeta,\n length: number,\n data: U8,\n validity: U32 | null,\n nullCount: number,\n ): U8Column {\n return new U8ColumnImpl(meta, length, data, validity, nullCount);\n }\n\n protected override sliceData(start: number, end: number): U8 {\n if (start % 4 === 0) {\n return shareView(this.data.subarray(start, end));\n }\n const out = allocU8(end - start);\n out.set(this.data.subarray(start, end));\n return out;\n }\n\n protected override copyData(): U8 {\n const out = allocU8(this.data.length);\n out.set(this.data);\n return out;\n }\n}\n\n// ============================================================ bool column\n\nclass BoolColumnImpl extends ColumnImpl<\"bool\"> implements BoolColumn {\n readonly data: U32;\n\n constructor(meta: ColumnMeta, length: number, data: U32, validity: U32 | null, nullCount: number) {\n super(\"bool\", meta, length, validity, nullCount);\n this.data = data;\n }\n\n override get byteLength(): number {\n return this.data.byteLength + this.validityByteLength;\n }\n\n mutableData(): U32 {\n this.assertMutable(\"mutableData\");\n this.assertAttached();\n return this.data;\n }\n\n override paddedU32View(): U32 {\n this.assertAttached();\n return this.data;\n }\n\n override slice(start: number, end: number): BoolColumn {\n this.checkRange(start, end);\n const rows = end - start;\n const data =\n start % 32 === 0\n ? shareView(this.data.subarray(start >>> 5, (start >>> 5) + bitmapWordCount(rows)))\n : bitmapSlice(this.data, start, end);\n const { validity, nullCount } = this.sliceValidity(start, end);\n return new BoolColumnImpl(this.meta, rows, data, validity, nullCount);\n }\n\n override clone(): BoolColumn {\n this.assertAttached();\n return new BoolColumnImpl(this.meta, this.length, this.data.slice(), this.cloneValidity(), this.nullCountValue);\n }\n\n protected override storageDetached(): boolean {\n return this.data.length === 0;\n }\n\n protected override self(): BoolColumn {\n return this;\n }\n\n protected override readValue(row: number): boolean {\n return bitmapGet(this.data, row);\n }\n\n protected override fillIsDefault(): boolean {\n return this.meta.fill === this.meta.default;\n }\n\n protected override withDefaults(): BoolColumn {\n const { default: defaultValue, name } = this.meta;\n if (typeof defaultValue !== \"boolean\") {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `default of bool column \"${name}\" is not a boolean`, {\n column: name,\n field: \"default\",\n });\n }\n const data = this.data.slice();\n const words = this.validityWords;\n if (words !== null) {\n for (let row = 0; row < this.length; row++) {\n if (!bitmapGet(words, row)) {\n if (defaultValue) {\n bitmapSet(data, row);\n } else {\n bitmapClear(data, row);\n }\n }\n }\n }\n return new BoolColumnImpl(this.meta, this.length, data, this.cloneValidity(), this.nullCountValue);\n }\n}\n\n// ============================================================ dict column\n\nclass DictColumnImpl extends ColumnImpl<\"dict\"> implements DictColumn {\n readonly codes: U32;\n readonly dictionary: readonly string[];\n private codeMap: Map<string, number> | null = null;\n\n constructor(\n meta: ColumnMeta,\n length: number,\n codes: U32,\n dictionary: readonly string[],\n validity: U32 | null,\n nullCount: number,\n ) {\n super(\"dict\", meta, length, validity, nullCount);\n this.codes = codes;\n this.dictionary = dictionary;\n }\n\n override get byteLength(): number {\n return this.codes.byteLength + this.validityByteLength;\n }\n\n codeOf(value: string): number {\n this.codeMap ??= buildCodeMap(this.dictionary);\n const code = this.codeMap.get(value);\n return code === undefined ? INVALID_INDEX : code;\n }\n\n mutableData(): U32 {\n this.assertMutable(\"mutableData\");\n this.assertAttached();\n return this.codes;\n }\n\n override paddedU32View(): U32 {\n this.assertAttached();\n return this.codes;\n }\n\n override slice(start: number, end: number): DictColumn {\n this.checkRange(start, end);\n const { validity, nullCount } = this.sliceValidity(start, end);\n return new DictColumnImpl(\n this.meta,\n end - start,\n shareView(this.codes.subarray(start, end)),\n this.dictionary,\n validity,\n nullCount,\n );\n }\n\n protected override storageDetached(): boolean {\n return this.codes.length === 0;\n }\n\n override clone(): DictColumn {\n this.assertAttached();\n return new DictColumnImpl(\n this.meta,\n this.length,\n this.codes.slice(),\n [...this.dictionary],\n this.cloneValidity(),\n this.nullCountValue,\n );\n }\n\n protected override self(): DictColumn {\n return this;\n }\n\n protected override readValue(row: number): string {\n return this.dictionary[this.codes[row]];\n }\n\n protected override fillIsDefault(): boolean {\n return this.meta.fill === this.meta.default;\n }\n\n protected override withDefaults(): DictColumn {\n const { default: defaultValue, name } = this.meta;\n if (typeof defaultValue !== \"string\") {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `default of dict column \"${name}\" is not a string`, {\n column: name,\n field: \"default\",\n });\n }\n let dict: readonly string[] = this.dictionary;\n let code = this.codeOf(defaultValue);\n if (code === INVALID_INDEX) {\n code = dict.length;\n dict = [...dict, defaultValue];\n }\n const codes = this.codes.slice();\n const words = this.validityWords;\n if (words !== null) {\n for (let row = 0; row < this.length; row++) {\n if (!bitmapGet(words, row)) {\n codes[row] = code;\n }\n }\n }\n return new DictColumnImpl(this.meta, this.length, codes, dict, this.cloneValidity(), this.nullCountValue);\n }\n}\n\n// ============================================================ string column\n\n/**\n * Encode strings into an Arrow Utf8 store: rows + 1 offsets and the concatenated bytes in a padded\n * u8 store.\n * @param strings - the rows\n * @returns the offsets and bytes\n */\nfunction encodeStrings(strings: readonly string[]): { offsets: U32; utf8: U8 } {\n const encoded = encodeUtf8Rows(strings, strings.length);\n const utf8 = allocU8(encoded.utf8.length);\n utf8.set(encoded.utf8);\n return { offsets: encoded.offsets, utf8 };\n}\n\nclass StringColumnImpl extends ColumnImpl<\"string\"> implements StringColumn {\n private offsetsStore: U32 | null;\n private utf8Store: U8 | null;\n private strings: (string | undefined)[] | null;\n\n constructor(\n meta: ColumnMeta,\n length: number,\n offsets: U32 | null,\n utf8: U8 | null,\n strings: (string | undefined)[] | null,\n validity: U32 | null,\n nullCount: number,\n ) {\n super(\"string\", meta, length, validity, nullCount);\n this.offsetsStore = offsets;\n this.utf8Store = utf8;\n this.strings = strings;\n }\n\n get offsets(): U32 {\n this.store();\n return this.offsetsStore as U32;\n }\n\n get utf8(): U8 {\n this.store();\n return this.utf8Store as U8;\n }\n\n override get byteLength(): number {\n this.store();\n return (this.offsetsStore as U32).byteLength + (this.utf8Store as U8).byteLength + this.validityByteLength;\n }\n\n valueAt(row: number): string {\n const cached = this.strings?.[row];\n if (cached !== undefined) {\n return cached;\n }\n this.assertAttached();\n this.store();\n const offsets = this.offsetsStore as U32;\n const utf8 = this.utf8Store as U8;\n const text = decoder.decode(utf8.subarray(offsets[row], offsets[row + 1]));\n this.strings ??= new Array<string | undefined>(this.length);\n this.strings[row] = text;\n return text;\n }\n\n decodeAll(): string[] {\n const out = new Array<string>(this.length);\n for (let row = 0; row < this.length; row++) {\n out[row] = this.valueAt(row);\n }\n return out;\n }\n\n override slice(start: number, end: number): StringColumn {\n this.checkRange(start, end);\n const rows = end - start;\n const { validity, nullCount } = this.sliceValidity(start, end);\n const strings = this.strings === null ? null : this.strings.slice(start, end);\n if (this.offsetsStore === null || this.utf8Store === null) {\n return new StringColumnImpl(this.meta, rows, null, null, strings, validity, nullCount);\n }\n const base = this.offsetsStore[start];\n const offsets = new Uint32Array(rows + 1);\n for (let i = 0; i <= rows; i++) {\n offsets[i] = this.offsetsStore[start + i] - base;\n }\n const utf8 = shareView(this.utf8Store.subarray(base, this.offsetsStore[end]));\n return new StringColumnImpl(this.meta, rows, offsets, utf8, strings, validity, nullCount);\n }\n\n override clone(): StringColumn {\n this.assertAttached();\n const strings = this.strings === null ? null : [...this.strings];\n if (this.offsetsStore === null || this.utf8Store === null) {\n return new StringColumnImpl(\n this.meta,\n this.length,\n null,\n null,\n strings,\n this.cloneValidity(),\n this.nullCountValue,\n );\n }\n const utf8 = allocU8(this.utf8Store.length);\n utf8.set(this.utf8Store);\n return new StringColumnImpl(\n this.meta,\n this.length,\n this.offsetsStore.slice(),\n utf8,\n strings,\n this.cloneValidity(),\n this.nullCountValue,\n );\n }\n\n /**\n * Whether the Utf8 store has been materialised (the wire writer asks before encoding).\n * @returns true when offsets and utf8 exist without being computed\n */\n hasStore(): boolean {\n return this.offsetsStore !== null;\n }\n\n /**\n * The decoded cache as it stands (sparse), for zero-copy re-wrapping.\n * @returns the cache, or null when no row has been decoded\n */\n decodedCache(): (string | undefined)[] | null {\n return this.strings;\n }\n\n protected override self(): StringColumn {\n return this;\n }\n\n protected override storageDetached(): boolean {\n // a materialised store is detached when its offsets vanished; undecoded rows then cannot be read\n return this.offsetsStore !== null && this.offsetsStore.length === 0;\n }\n\n protected override readValue(row: number): string {\n return this.valueAt(row);\n }\n\n protected override fillIsDefault(): boolean {\n return this.meta.fill === this.meta.default;\n }\n\n protected override withDefaults(): StringColumn {\n const { default: defaultValue, name } = this.meta;\n if (typeof defaultValue !== \"string\") {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `default of string column \"${name}\" is not a string`, {\n column: name,\n field: \"default\",\n });\n }\n const strings = this.decodeAll();\n const words = this.validityWords;\n if (words !== null) {\n for (let row = 0; row < this.length; row++) {\n if (!bitmapGet(words, row)) {\n strings[row] = defaultValue;\n }\n }\n }\n return new StringColumnImpl(\n this.meta,\n this.length,\n null,\n null,\n strings,\n this.cloneValidity(),\n this.nullCountValue,\n );\n }\n\n /**\n * Materialise the Utf8 store from the decoded strings on first need (design section 5.7); a\n * store that was transferred away is E_DETACHED.\n */\n private store(): void {\n if (this.offsetsStore !== null && this.utf8Store !== null) {\n this.assertAttached();\n return;\n }\n const strings = this.strings ?? [];\n const dense = new Array<string>(this.length);\n for (let row = 0; row < this.length; row++) {\n dense[row] = strings[row] ?? \"\";\n }\n const encoded = encodeStrings(dense);\n this.offsetsStore = encoded.offsets;\n this.utf8Store = encoded.utf8;\n // the column is the first holder of the store it materialises (design section 9.1)\n claimHolder(encoded.offsets.buffer);\n claimHolder(encoded.utf8.buffer);\n }\n}\n\n// ============================================================ list column\n\ntype ChildColumn = Exclude<Column, ListColumn>;\n\nclass ListColumnImpl extends ColumnImpl<\"list\"> implements ListColumn {\n readonly offsets: U32;\n readonly child: ChildColumn;\n\n constructor(\n meta: ColumnMeta,\n length: number,\n offsets: U32,\n child: ChildColumn,\n validity: U32 | null,\n nullCount: number,\n ) {\n super(\"list\", meta, length, validity, nullCount);\n this.offsets = offsets;\n this.child = child;\n }\n\n override get byteLength(): number {\n return this.offsets.byteLength + this.child.byteLength + this.validityByteLength;\n }\n\n sliceOf(row: number): readonly unknown[] {\n this.assertAttached();\n const start = this.offsets[row];\n const end = this.offsets[row + 1];\n const out = new Array<unknown>(end - start);\n for (let i = start; i < end; i++) {\n out[i - start] = this.child.value(i);\n }\n return out;\n }\n\n override slice(start: number, end: number): ListColumn {\n this.checkRange(start, end);\n const rows = end - start;\n const base = this.offsets[start];\n const offsets = new Uint32Array(rows + 1);\n for (let i = 0; i <= rows; i++) {\n offsets[i] = this.offsets[start + i] - base;\n }\n const { validity, nullCount } = this.sliceValidity(start, end);\n return new ListColumnImpl(\n this.meta,\n rows,\n offsets,\n this.child.slice(base, this.offsets[end]),\n validity,\n nullCount,\n );\n }\n\n override clone(): ListColumn {\n this.assertAttached();\n return new ListColumnImpl(\n this.meta,\n this.length,\n this.offsets.slice(),\n this.child.clone(),\n this.cloneValidity(),\n this.nullCountValue,\n );\n }\n\n protected override storageDetached(): boolean {\n return this.offsets.length === 0 || isColumnDetached(this.child);\n }\n\n protected override self(): ListColumn {\n return this;\n }\n\n protected override readValue(row: number): readonly unknown[] {\n return this.sliceOf(row);\n }\n\n protected override fillIsDefault(): boolean {\n return false;\n }\n\n protected override withDefaults(): ListColumn {\n const { default: defaultValue, name } = this.meta;\n if (!Array.isArray(defaultValue)) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `default of list column \"${name}\" is not an array`, {\n column: name,\n field: \"default\",\n });\n }\n const rows = new Array<readonly unknown[]>(this.length);\n const words = this.validityWords;\n for (let row = 0; row < this.length; row++) {\n rows[row] = words !== null && !bitmapGet(words, row) ? defaultValue : this.sliceOf(row);\n }\n const parts = listPartsFromValues(this.meta, rows);\n return new ListColumnImpl(\n this.meta,\n this.length,\n parts.offsets,\n parts.child,\n this.cloneValidity(),\n this.nullCountValue,\n );\n }\n}\n\n// ============================================================ json column\n\nclass JsonColumnImpl extends ColumnImpl<\"json\"> implements JsonColumn {\n readonly values: readonly unknown[];\n\n constructor(meta: ColumnMeta, length: number, values: readonly unknown[], validity: U32 | null, nullCount: number) {\n super(\"json\", meta, length, validity, nullCount);\n this.values = values;\n }\n\n override get byteLength(): number {\n return this.validityByteLength;\n }\n\n override slice(start: number, end: number): JsonColumn {\n this.checkRange(start, end);\n const { validity, nullCount } = this.sliceValidity(start, end);\n return new JsonColumnImpl(this.meta, end - start, this.values.slice(start, end), validity, nullCount);\n }\n\n override clone(): JsonColumn {\n this.assertAttached();\n return new JsonColumnImpl(this.meta, this.length, [...this.values], this.cloneValidity(), this.nullCountValue);\n }\n\n protected override storageDetached(): boolean {\n return false;\n }\n\n protected override self(): JsonColumn {\n return this;\n }\n\n protected override readValue(row: number): unknown {\n return this.values[row];\n }\n\n protected override fillIsDefault(): boolean {\n return false;\n }\n\n protected override withDefaults(): JsonColumn {\n const { default: defaultValue } = this.meta;\n const values = [...this.values];\n const words = this.validityWords;\n if (words !== null) {\n for (let row = 0; row < this.length; row++) {\n if (!bitmapGet(words, row)) {\n values[row] = defaultValue;\n }\n }\n }\n return new JsonColumnImpl(this.meta, this.length, values, this.cloneValidity(), this.nullCountValue);\n }\n}\n\n/**\n * Whether a value is a Column built by this package's factory (the structural Column type also\n * admits a foreign object with the right members, which the table refuses with E_COLUMN_TYPE).\n * @param value - the candidate\n * @returns true for an instance of a column implementation\n */\nexport function isPackageColumn(value: unknown): value is Column {\n return value instanceof ColumnImpl;\n}\n\n/**\n * Whether a column's storage was transferred away (design section 9.1): derived from the array\n * state. Every accessor of such a column throws E_DETACHED; the wire module and the checksum\n * comparison ask first.\n * @param column - any column\n * @returns true when detached\n */\nexport function isColumnDetached(column: Column): boolean {\n return (column as unknown as ColumnImpl<Dtype>).detached;\n}\n\n// ============================================================ factory\n\nfunction lengthError(meta: ColumnMeta, what: string, expected: number, found: number): GraphFormatError {\n return new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `column \"${meta.name}\": ${what} has length ${found}, expected ${expected}`,\n {\n column: meta.name,\n what,\n expected,\n found,\n },\n );\n}\n\nfunction slotError(meta: ColumnMeta, message: string): GraphFormatError {\n return new GraphFormatError(\"E_COLUMN_TYPE\", `column \"${meta.name}\": ${message}`, { column: meta.name });\n}\n\n/**\n * Wrap raw column storage into a Column of the dtype named by parts.meta (the column factory of\n * design section 5.7). Checks the slot use and the length rules of invariant I12 (E_COLUMN_LENGTH /\n * E_COLUMN_TYPE / E_COLUMN_ALIGNMENT), recomputes nullCount from the validity bitmap, and adopts\n * every buffer by reference.\n * @param parts - the storage slots; every slot the dtype does not use must be null\n * @returns the column\n */\nexport function createColumn(parts: MutableColumnParts): Column {\n const { meta, length } = parts;\n if (!(Number.isInteger(length) && length >= 0)) {\n throw new GraphFormatError(\"E_COLUMN_LENGTH\", `column \"${meta.name}\": invalid row count ${length}`, {\n column: meta.name,\n found: length,\n });\n }\n const { validity: given } = parts;\n let validity: U32 | null = null;\n if (given !== null) {\n if (!meta.nullable) {\n throw slotError(meta, \"a non-nullable column cannot carry a validity bitmap\");\n }\n if (!(given instanceof Uint32Array)) {\n throw slotError(meta, \"validity must be a Uint32Array\");\n }\n if (given.length !== bitmapWordCount(length)) {\n throw lengthError(meta, \"validity\", bitmapWordCount(length), given.length);\n }\n validity = given;\n }\n const nullCount = validity === null ? 0 : length - bitmapCount(validity, length);\n const { dtype } = meta;\n switch (dtype) {\n case \"f32\":\n return new F32ColumnImpl(meta, length, checkNumeric(parts, Float32Array), validity, nullCount);\n case \"f64\":\n return new F64ColumnImpl(meta, length, checkNumeric(parts, Float64Array), validity, nullCount);\n case \"i32\":\n return new I32ColumnImpl(meta, length, checkNumeric(parts, Int32Array), validity, nullCount);\n case \"u32\":\n return new U32ColumnImpl(meta, length, checkNumeric(parts, Uint32Array), validity, nullCount);\n case \"u8\": {\n const data = checkNumeric(parts, Uint8Array);\n if (!canViewAsPaddedU32(data)) {\n throw new GraphFormatError(\n \"E_COLUMN_ALIGNMENT\",\n `column \"${meta.name}\": no padded u32 view over the u8 data`,\n {\n column: meta.name,\n byteOffset: data.byteOffset,\n byteLength: data.byteLength,\n },\n );\n }\n return new U8ColumnImpl(meta, length, data, validity, nullCount);\n }\n case \"bool\": {\n if (!(parts.data instanceof Uint32Array)) {\n throw slotError(meta, \"bool data must be packed Uint32Array words\");\n }\n if (parts.data.length !== bitmapWordCount(length)) {\n throw lengthError(meta, \"data\", bitmapWordCount(length), parts.data.length);\n }\n return new BoolColumnImpl(meta, length, parts.data, validity, nullCount);\n }\n case \"dict\": {\n if (!(parts.data instanceof Uint32Array)) {\n throw slotError(meta, \"dict codes must be a Uint32Array\");\n }\n if (parts.data.length !== length) {\n throw lengthError(meta, \"codes\", length, parts.data.length);\n }\n if (parts.dictionary === null) {\n throw slotError(meta, \"dict column needs a dictionary\");\n }\n return new DictColumnImpl(meta, length, parts.data, parts.dictionary, validity, nullCount);\n }\n case \"string\": {\n if (parts.offsets === null || parts.utf8 === null) {\n const { strings } = parts;\n if (strings === null || strings.length !== length) {\n throw lengthError(meta, \"strings\", length, strings === null ? -1 : strings.length);\n }\n for (let row = 0; row < length; row++) {\n if (typeof strings[row] !== \"string\") {\n throw slotError(meta, `row ${row} is not a decoded string and no Utf8 store is present`);\n }\n }\n return new StringColumnImpl(meta, length, null, null, strings, validity, nullCount);\n }\n if (parts.offsets.length !== length + 1) {\n throw lengthError(meta, \"offsets\", length + 1, parts.offsets.length);\n }\n if (parts.offsets[length] !== parts.utf8.length) {\n throw lengthError(meta, \"utf8\", parts.offsets[length], parts.utf8.length);\n }\n return new StringColumnImpl(meta, length, parts.offsets, parts.utf8, parts.strings, validity, nullCount);\n }\n case \"list\": {\n if (parts.offsets === null || parts.offsets.length !== length + 1) {\n throw lengthError(meta, \"offsets\", length + 1, parts.offsets === null ? -1 : parts.offsets.length);\n }\n const { child } = parts;\n if (child === null || child.dtype === \"list\") {\n throw slotError(meta, \"list column needs a non-list child column\");\n }\n if (child.validity !== null || child.meta.nullable) {\n throw slotError(meta, \"list child must be non-nullable\");\n }\n if (child.dtype !== meta.itemDtype || child.meta.components !== meta.itemComponents) {\n throw slotError(\n meta,\n `list child is ${child.dtype} x${child.meta.components}, declared ${String(meta.itemDtype)} x${String(meta.itemComponents)}`,\n );\n }\n if (parts.offsets[length] !== child.length) {\n throw lengthError(meta, \"child\", parts.offsets[length], child.length);\n }\n return new ListColumnImpl(meta, length, parts.offsets, child, validity, nullCount);\n }\n case \"json\": {\n if (parts.values === null || parts.values.length !== length) {\n throw lengthError(meta, \"values\", length, parts.values === null ? -1 : parts.values.length);\n }\n return new JsonColumnImpl(meta, length, parts.values, validity, nullCount);\n }\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\nfunction checkNumeric<T extends TypedArrayData>(parts: MutableColumnParts, ctor: new (length: number) => T): T {\n const { meta, length } = parts;\n if (!(parts.data instanceof ctor)) {\n throw slotError(meta, `${meta.dtype} data must be a ${ctor.name}`);\n }\n const expected = length * meta.components;\n if (parts.data.length !== expected) {\n throw lengthError(meta, \"data\", expected, parts.data.length);\n }\n return parts.data;\n}\n\n/**\n * The raw storage of a column, sharing every buffer by reference (the inverse of createColumn): used\n * to re-wrap a column under new metadata and by the remap helpers.\n * @param column - the column to unwrap\n * @returns its storage slots\n */\nexport function partsOf(column: Column): MutableColumnParts {\n const base: MutableColumnParts = {\n meta: column.meta,\n length: column.length,\n data: null,\n validity: column.validity,\n nullCount: column.nullCount,\n dictionary: null,\n offsets: null,\n utf8: null,\n strings: null,\n child: null,\n values: null,\n };\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n case \"bool\":\n base.data = column.data;\n return base;\n case \"dict\":\n base.data = column.codes;\n base.dictionary = column.dictionary as string[];\n return base;\n case \"string\": {\n if (column instanceof StringColumnImpl) {\n base.strings = column.decodedCache();\n if (column.hasStore()) {\n base.offsets = column.offsets;\n base.utf8 = column.utf8;\n }\n return base;\n }\n base.offsets = column.offsets;\n base.utf8 = column.utf8;\n return base;\n }\n case \"list\":\n base.offsets = column.offsets;\n base.child = column.child;\n return base;\n case \"json\":\n base.values = column.values as unknown[];\n return base;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * The distinct backing buffers of a column's materialised typed storage (data or codes, validity,\n * a materialised Utf8 store, a list's offsets and child), for the owner count of design section\n * 9.1: a table claims them when it attaches the column, so a buffer viewed from two tables (a\n * zero-copy slice, a same-realm wire receiver) is recognised as shared. A string store that has not\n * been materialised is not encoded by asking.\n * @param column - the column\n * @returns the buffers, each once\n */\nexport function columnBuffers(column: Column): ArrayBuffer[] {\n const out = new Set<ArrayBuffer>();\n const add = (view: ArrayBufferView | null): void => {\n if (view !== null) {\n out.add(view.buffer as ArrayBuffer);\n }\n };\n add(column.validity);\n switch (column.dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n case \"bool\":\n add(column.data);\n break;\n case \"dict\":\n add(column.codes);\n break;\n case \"string\":\n if (!(column instanceof StringColumnImpl) || column.hasStore()) {\n add(column.offsets);\n add(column.utf8);\n }\n break;\n case \"list\":\n add(column.offsets);\n for (const buffer of columnBuffers(column.child)) {\n out.add(buffer);\n }\n break;\n case \"json\":\n break;\n default: {\n const unknown: never = column;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${(unknown as Column).dtype}`, {});\n }\n }\n return [...out];\n}\n\n/**\n * The same storage under different metadata (a rename, a move to another table, a declaration\n * patch); the buffers are shared, the Column object is new. The dtype, components and list child\n * shape must be unchanged (E_COLUMN_TYPE otherwise); the fill is kept because the unset rows\n * physically hold it; a nullable -> non-nullable change requires no unset rows.\n * @param column - the column to re-wrap\n * @param meta - the new metadata\n * @returns a new column sharing the storage\n */\nexport function rewrapColumn(column: Column, meta: ColumnMeta): Column {\n const old = column.meta;\n if (\n meta.dtype !== old.dtype ||\n meta.components !== old.components ||\n meta.itemDtype !== old.itemDtype ||\n meta.itemComponents !== old.itemComponents\n ) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${old.name}\" is ${old.dtype} x${old.components}; a patch cannot change its dtype`,\n {\n column: old.name,\n field: \"dtype\",\n },\n );\n }\n if (meta.fill !== old.fill) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `the fill of existing column \"${old.name}\" cannot change`, {\n column: old.name,\n field: \"fill\",\n });\n }\n const parts = partsOf(column);\n if (!meta.nullable && column.validity !== null) {\n if (column.nullCount > 0) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${old.name}\" has ${column.nullCount} unset rows and cannot become non-nullable`,\n {\n column: old.name,\n field: \"nullable\",\n nullCount: column.nullCount,\n },\n );\n }\n parts.validity = null;\n }\n parts.meta = meta;\n return createColumn(parts);\n}\n\n/**\n * Release the cached f32 copy a `gpuView()` of an f64 column keeps (design section 7.2:\n * `dropCaches()` releases every cached gpuView copy). A no-op for every other dtype.\n * @param column - the column\n */\nexport function dropGpuViewCache(column: Column): void {\n f32Cache.delete(column);\n}\n\n/**\n * The array a GPU binds for a column (design section 10.4): its own data for u32 / i32 / f32, the\n * padded view for u8, the packed words for bool, the codes for dict, and a cached f32 copy for f64\n * (dropped by markDirty() and by GraphSnapshot.dropCaches()).\n * @param column - the column\n * @returns the bindable array; E_GPU_INELIGIBLE for string / list / json\n */\nexport function gpuViewOf(column: Column): U32 | I32 | F32 {\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"i32\":\n case \"u32\":\n case \"bool\":\n return column.data;\n case \"u8\":\n return column.paddedU32View();\n case \"dict\":\n return column.codes;\n case \"f64\": {\n let cached = f32Cache.get(column);\n if (cached === undefined) {\n cached = new Float32Array(column.data);\n f32Cache.set(column, cached);\n }\n return cached;\n }\n case \"string\":\n case \"list\":\n case \"json\":\n throw new GraphFormatError(\"E_GPU_INELIGIBLE\", `a ${dtype} column cannot be bound by the GPU`, {\n column: column.meta.name,\n dtype,\n });\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n// ============================================================ construction from declarations and values\n\n/**\n * The physical dict code stored in rows that hold the fill: the code of the fill string, interned\n * on demand when those rows are SET (a non-nullable column), or 0 when the fill is not a member and\n * the rows are unset (their code is never read).\n * @param dictionary - the dictionary\n * @param fill - the column's fill\n * @param set - whether the rows holding the fill are set\n * @returns the code\n */\nfunction fillCode(dictionary: DictionaryBuilder, fill: number | string | boolean, set: boolean): number {\n const text = typeof fill === \"string\" ? fill : \"\";\n if (set) {\n // a SET row holding the fill (a non-nullable column) needs a code that names a member: the\n // nominal \"\" is interned on demand rather than borrowing code 0, which may belong to another\n // value or to nothing\n return dictionary.intern(text);\n }\n // an unset row's code is never read; 0 when the fill is not a member\n const code = dictionary.codeOf(text);\n return code === INVALID_INDEX ? 0 : code;\n}\n\n/**\n * The initial dictionary of a dict column: the declared options in order, then the fill when it is\n * a string not among them (so the fill code names a member).\n * @param meta - the column metadata\n * @returns the seeded dictionary builder\n */\nexport function seedDictionary(meta: ColumnMeta): DictionaryBuilder {\n const dictionary = new DictionaryBuilder(meta.options === null ? undefined : (meta.options as readonly string[]));\n if (typeof meta.fill === \"string\" && meta.fill !== \"\") {\n dictionary.intern(meta.fill);\n }\n return dictionary;\n}\n\n/**\n * A MutableColumnParts record with every storage slot null, for producers that fill one slot.\n * @param meta - the column metadata\n * @param length - the row count\n * @param validity - the validity bitmap, or null\n * @returns the parts\n */\nexport function emptyParts(meta: ColumnMeta, length: number, validity: U32 | null): MutableColumnParts {\n return {\n meta,\n length,\n data: null,\n validity,\n nullCount: validity === null ? 0 : length,\n dictionary: null,\n offsets: null,\n utf8: null,\n strings: null,\n child: null,\n values: null,\n };\n}\n\nfunction childMeta(meta: ColumnMeta): ColumnMeta {\n if (meta.itemDtype === null || meta.itemComponents === null) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `column \"${meta.name}\" is not a list`, {\n column: meta.name,\n field: \"itemDtype\",\n });\n }\n return resolveColumnMeta(`${meta.name}.item`, meta.domain, {\n dtype: meta.itemDtype,\n components: meta.itemComponents,\n nullable: false,\n refersTo: meta.refersTo ?? undefined,\n });\n}\n\n/**\n * A column of `length` rows with no value set: every row unset (when nullable) and the data holding\n * the fill (design section 5.3). This is what a declared column looks like before any value is\n * written, and what remap uses for rows no source row maps to.\n * @param domain - the table the column belongs to\n * @param length - the number of rows\n * @param decl - the declaration; dtype required\n * @returns the empty column\n */\nexport function createEmptyColumn(domain: ColumnDomain, length: number, decl: ColumnDeclPatch): Column {\n const name = decl.name ?? \"\";\n const meta = resolveColumnMeta(name, domain, decl);\n return emptyColumnOf(meta, length);\n}\n\n/**\n * An empty column from resolved metadata; see createEmptyColumn.\n * @param meta - the resolved metadata\n * @param length - the number of rows\n * @returns the empty column\n */\nfunction emptyColumnOf(meta: ColumnMeta, length: number): Column {\n const validity = meta.nullable ? new Uint32Array(bitmapWordCount(length)) : null;\n const parts = emptyParts(meta, length, validity);\n const { dtype, components, fill } = meta;\n switch (dtype) {\n case \"f32\":\n parts.data = new Float32Array(length * components).fill(fill as number);\n break;\n case \"f64\":\n parts.data = new Float64Array(length * components).fill(fill as number);\n break;\n case \"i32\":\n parts.data = new Int32Array(length * components).fill(fill as number);\n break;\n case \"u32\":\n parts.data = new Uint32Array(length * components).fill(fill as number);\n break;\n case \"u8\":\n parts.data = allocU8(length * components).fill(fill as number);\n break;\n case \"bool\":\n parts.data = makeBitmap(length, fill === true);\n break;\n case \"dict\": {\n const dictionary = seedDictionary(meta);\n parts.data = new Uint32Array(length).fill(fillCode(dictionary, fill, validity === null && length > 0));\n parts.dictionary = dictionary.values;\n break;\n }\n case \"string\": {\n const fillText = typeof fill === \"string\" ? fill : \"\";\n parts.strings = new Array<string>(length).fill(fillText);\n break;\n }\n case \"list\":\n parts.offsets = new Uint32Array(length + 1);\n parts.child = emptyColumnOf(childMeta(meta), 0);\n break;\n case \"json\":\n parts.values = new Array<unknown>(length).fill(undefined);\n break;\n default: {\n const dtypeName: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${dtypeName}`, { dtype: dtypeName });\n }\n }\n return createColumn(parts);\n}\n\n/**\n * Whether a JS array entry is an unset cell: undefined for every dtype, null too except for json,\n * where null is a value (design section 12.1).\n * @param value - the entry\n * @param dtype - the column dtype\n * @returns true when unset\n */\nfunction isUnsetEntry(value: unknown, dtype: Dtype): boolean {\n return value === undefined || (value === null && dtype !== \"json\");\n}\n\n/**\n * Build the offsets and child of a list column from an array of rows (each an array of items).\n * @param meta - the list column's metadata\n * @param rows - one array per row (an empty array for unset rows)\n * @returns the offsets and the wrapped child\n */\nfunction listPartsFromValues(\n meta: ColumnMeta,\n rows: readonly (readonly unknown[])[],\n): { offsets: U32; child: ChildColumn } {\n const offsets = new Uint32Array(rows.length + 1);\n const items: unknown[] = [];\n for (let row = 0; row < rows.length; row++) {\n for (const item of rows[row]) {\n items.push(item);\n }\n offsets[row + 1] = items.length;\n }\n const child = columnOfValues(childMeta(meta), items) as ChildColumn;\n return { offsets, child };\n}\n\n/**\n * A column from a JS array of values under resolved metadata (one entry per row; undefined, and null\n * except for json, is an unset row). Values are coerced per design section 5.1 (a boolean into a\n * number column becomes 1 / 0, a number or boolean into a string column its canonical text) and\n * rejected with E_COLUMN_TYPE otherwise.\n * @param meta - the resolved metadata\n * @param values - the entries, `length` of them\n * @returns the column\n */\nexport function columnOfValues(meta: ColumnMeta, values: readonly unknown[]): Column {\n const { length } = values;\n const { dtype, components, fill, name } = meta;\n let validity: U32 | null = null;\n let nullCount = 0;\n for (let row = 0; row < length; row++) {\n if (isUnsetEntry(values[row], dtype)) {\n if (!meta.nullable) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `row ${row} of non-nullable column \"${name}\" is unset`, {\n column: name,\n row,\n });\n }\n validity ??= makeBitmap(length, true);\n bitmapClear(validity, row);\n nullCount++;\n }\n }\n const parts = emptyParts(meta, length, validity);\n parts.nullCount = nullCount;\n const isSet = (row: number): boolean => validity === null || bitmapGet(validity, row);\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n const data = allocNumeric(dtype, length * components);\n if (fill !== 0) {\n data.fill(fill as number);\n }\n for (let row = 0; row < length; row++) {\n if (!isSet(row)) {\n continue;\n }\n const raw = values[row];\n const value = typeof raw === \"boolean\" ? Number(raw) : raw;\n writeNumeric(dtype, data, row * components, components, value, name, row);\n }\n parts.data = data;\n break;\n }\n case \"bool\": {\n const data = makeBitmap(length, fill === true);\n for (let row = 0; row < length; row++) {\n if (!isSet(row)) {\n continue;\n }\n const value = coerceValue(values[row], \"bool\");\n if (value === true) {\n bitmapSet(data, row);\n } else {\n bitmapClear(data, row);\n }\n }\n parts.data = data;\n break;\n }\n case \"dict\": {\n const dictionary = seedDictionary(meta);\n const codes = new Uint32Array(length);\n if (validity !== null) {\n codes.fill(fillCode(dictionary, fill, false));\n }\n for (let row = 0; row < length; row++) {\n if (!isSet(row)) {\n continue;\n }\n const value = coerceValue(values[row], \"string\");\n if (typeof value !== \"string\") {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `row ${row} of dict column \"${name}\" is not a string`, {\n column: name,\n row,\n });\n }\n codes[row] = dictionary.intern(value);\n }\n parts.data = codes;\n parts.dictionary = dictionary.values;\n break;\n }\n case \"string\": {\n const fillText = typeof fill === \"string\" ? fill : \"\";\n const strings = new Array<string>(length);\n for (let row = 0; row < length; row++) {\n if (!isSet(row)) {\n strings[row] = fillText;\n continue;\n }\n const value = coerceValue(values[row], \"string\");\n if (typeof value !== \"string\") {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `row ${row} of string column \"${name}\" is not a string`,\n { column: name, row },\n );\n }\n assertWellFormedString(value, { column: name, row });\n strings[row] = value;\n }\n parts.strings = strings;\n break;\n }\n case \"list\": {\n const rows = new Array<readonly unknown[]>(length);\n for (let row = 0; row < length; row++) {\n if (!isSet(row)) {\n rows[row] = [];\n continue;\n }\n const value = values[row];\n if (!Array.isArray(value)) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `row ${row} of list column \"${name}\" is not an array`, {\n column: name,\n row,\n });\n }\n rows[row] = value;\n }\n const listParts = listPartsFromValues(meta, rows);\n parts.offsets = listParts.offsets;\n parts.child = listParts.child;\n break;\n }\n case \"json\": {\n const out = new Array<unknown>(length);\n for (let row = 0; row < length; row++) {\n if (!isSet(row)) {\n out[row] = undefined;\n continue;\n }\n assertJsonValue(values[row], `row ${row}`);\n out[row] = values[row];\n }\n parts.values = out;\n break;\n }\n default: {\n const dtypeName: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${dtypeName}`, { dtype: dtypeName });\n }\n }\n return createColumn(parts);\n}\n\n/**\n * Allocate a numeric buffer of a dtype (a padded store for u8).\n * @param dtype - the numeric dtype\n * @param length - the element count\n * @returns the zeroed array\n */\nexport function allocNumeric(dtype: NumericDtype, length: number): TypedArrayData {\n switch (dtype) {\n case \"f32\":\n return new Float32Array(length);\n case \"f64\":\n return new Float64Array(length);\n case \"i32\":\n return new Int32Array(length);\n case \"u32\":\n return new Uint32Array(length);\n case \"u8\":\n return allocU8(length);\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Infer the declaration of a column from a JS array of values when the caller gave no dtype: the\n * widening rules of design section 5.1 over the entries (json when every entry is unset), and for a\n * list the same rules over the items.\n * @param values - the entries\n * @returns the dtype and, for a list, the item dtype\n */\nfunction inferDeclFromValues(values: readonly unknown[]): { dtype: Dtype; itemDtype: ScalarDtype | undefined } {\n let sawArray = false;\n let sawOther = false;\n for (const value of values) {\n if (value === undefined || value === null) {\n continue;\n }\n if (Array.isArray(value)) {\n sawArray = true;\n } else {\n sawOther = true;\n }\n }\n if (sawArray && !sawOther) {\n const items: unknown[] = [];\n for (const value of values) {\n if (Array.isArray(value)) {\n for (const item of value) {\n items.push(item);\n }\n }\n }\n return { dtype: \"list\", itemDtype: inferValuesDtype(items) ?? \"json\" };\n }\n return { dtype: inferValuesDtype(values) ?? \"json\", itemDtype: undefined };\n}\n\n/**\n * A column from a JS array of values with a declaration patch (the set() path for string / list /\n * json and for inferred dtypes). The dtype is inferred when the patch has none; nullable defaults to\n * true.\n * @param domain - the table the column belongs to\n * @param length - the table's row count; E_COLUMN_LENGTH when values.length differs\n * @param name - the column name\n * @param values - the entries, one per row\n * @param decl - the declaration patch\n * @returns the column\n */\nexport function columnFromValues(\n domain: ColumnDomain,\n length: number,\n name: string,\n values: readonly unknown[],\n decl: ColumnDeclPatch,\n): Column {\n if (values.length !== length) {\n throw new GraphFormatError(\"E_COLUMN_LENGTH\", `column \"${name}\": ${values.length} values for ${length} rows`, {\n column: name,\n expected: length,\n found: values.length,\n });\n }\n let patch: ColumnDeclPatch = { nullable: true, ...decl };\n if (patch.dtype === undefined) {\n const inferred = inferDeclFromValues(values);\n patch = { ...patch, dtype: inferred.dtype };\n if (inferred.dtype === \"list\" && patch.itemDtype === undefined) {\n patch = { ...patch, itemDtype: inferred.itemDtype };\n }\n }\n const meta = resolveColumnMeta(name, domain, patch);\n return columnOfValues(meta, values);\n}\n\n/**\n * The dtype a typed array class implies when the caller gave none.\n * @param data - the array\n * @returns f32 / f64 / i32 / u32 / u8\n */\nexport function dtypeOfArray(data: TypedArrayData): NumericDtype {\n if (data instanceof Float32Array) {\n return \"f32\";\n }\n if (data instanceof Float64Array) {\n return \"f64\";\n }\n if (data instanceof Int32Array) {\n return \"i32\";\n }\n if (data instanceof Uint32Array) {\n return \"u32\";\n }\n return \"u8\";\n}\n\n/**\n * A column adopting a typed array by reference (design section 5.7): the dtype comes from the array\n * class unless the patch names one (bool and dict over a Uint32Array); the length must be rowCount *\n * components (bool: ceil(rowCount / 32)) or E_COLUMN_LENGTH; a u8 array from which no padded u32 view\n * is constructible is copied, or refused with E_COLUMN_ALIGNMENT under adopt \"strict\". nullable\n * defaults to false (every row is set).\n * @param domain - the table the column belongs to\n * @param length - the table's row count\n * @param name - the column name\n * @param data - the typed array\n * @param decl - the declaration patch\n * @param adopt - \"copy\" (default) or \"strict\"\n * @returns the column (`column.data !== data` only when a u8 array was copied)\n */\nexport function columnFromTypedArray(\n domain: ColumnDomain,\n length: number,\n name: string,\n data: TypedArrayData,\n decl: ColumnDeclPatch,\n adopt: \"copy\" | \"strict\" = \"copy\",\n): Column {\n const arrayDtype = dtypeOfArray(data);\n const dtype = decl.dtype ?? arrayDtype;\n const compatible = dtype === arrayDtype || (arrayDtype === \"u32\" && (dtype === \"bool\" || dtype === \"dict\"));\n if (!compatible) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${name}\": a ${arrayDtype} array cannot back a ${dtype} column`,\n {\n column: name,\n field: \"dtype\",\n found: arrayDtype,\n expected: dtype,\n },\n );\n }\n const meta = resolveColumnMeta(name, domain, { nullable: false, ...decl, dtype });\n const parts = emptyParts(meta, length, null);\n let expected: number;\n switch (dtype) {\n case \"bool\":\n expected = bitmapWordCount(length);\n break;\n case \"dict\":\n expected = length;\n break;\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n expected = length * meta.components;\n break;\n default: {\n const dtypeName: string = dtype;\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${name}\": a ${dtypeName} column cannot adopt a typed array`,\n {\n column: name,\n field: \"dtype\",\n },\n );\n }\n }\n if (data.length !== expected) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `column \"${name}\": array length ${data.length}, expected ${expected}`,\n {\n column: name,\n expected,\n found: data.length,\n },\n );\n }\n if (!isOverPlainBuffer(data)) {\n // decision D-SAB: no SharedArrayBuffer in v1; a resizable buffer's view can change length (I17)\n const reason = data.buffer instanceof ArrayBuffer ? \"resizable ArrayBuffer\" : \"SharedArrayBuffer\";\n throw new GraphFormatError(\"E_UNSUPPORTED\", `column \"${name}\": a view over a ${reason} cannot be adopted`, {\n column: name,\n reason,\n });\n }\n let stored = data;\n if (data instanceof Uint8Array && !canViewAsPaddedU32(data)) {\n if (adopt === \"strict\") {\n throw new GraphFormatError(\n \"E_COLUMN_ALIGNMENT\",\n `column \"${name}\": no zero-copy padded u32 view over the u8 array`,\n {\n column: name,\n byteOffset: data.byteOffset,\n byteLength: data.byteLength,\n bufferByteLength: data.buffer.byteLength,\n },\n );\n }\n const copy = allocU8(data.length);\n copy.set(data);\n stored = copy;\n }\n parts.data = stored;\n if (dtype === \"dict\") {\n const dictionary = seedDictionary(meta);\n for (let row = 0; row < length; row++) {\n const code = data[row];\n if (code >= dictionary.size) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${name}\": code ${code} at row ${row} is outside the ${dictionary.size} declared options`,\n { column: name, row, code },\n );\n }\n }\n parts.dictionary = dictionary.values;\n }\n return createColumn(parts);\n}\n","/**\n * Enum-valued option checking (design section 11.1): a value outside its documented set is refused\n * with E_UNSUPPORTED (`details.field`, `details.found`, `details.reason` \"unsupported option\") at\n * the call, never taken as a default. Every public entry point that reads an enum option -- the\n * builder constructor and freeze overrides, the derived graphs, `degreeOrder`, `validate`,\n * `set`, `indicesOf`, `fromRecords`, `foldArcs` -- goes through here, so typed callers see no change\n * and an untyped caller's typo is an error rather than a silently different result.\n */\n\nimport { GraphFormatError } from \"../errors.js\";\n\n/**\n * Check that an option value is one of the allowed literals (undefined is accepted and returned so\n * the caller applies its default).\n * @param field - the option name for the error\n * @param value - the value\n * @param allowed - the documented literals\n * @returns the value, narrowed\n */\nexport function assertOneOf<T extends string>(field: string, value: unknown, allowed: readonly T[]): T | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\" || !(allowed as readonly string[]).includes(value)) {\n throw new GraphFormatError(\n \"E_UNSUPPORTED\",\n `option ${field} has an unsupported value ${describeOption(value)}`,\n {\n field,\n found: value,\n reason: \"unsupported option\",\n },\n );\n }\n return value as T;\n}\n\n/**\n * A plain-ASCII rendering of an option value for an error message.\n * @param value - the value\n * @returns the rendering\n */\nfunction describeOption(value: unknown): string {\n if (typeof value === \"string\") {\n return JSON.stringify(value.length > 40 ? `${value.slice(0, 37)}...` : value);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\" || value === null) {\n return String(value);\n }\n return `a ${typeof value}`;\n}\n\n/** The WeightReducer literals (design section 7.3). */\nexport const WEIGHT_REDUCERS = [\"first\", \"last\", \"sum\", \"min\", \"max\"] as const;\n\n/** The ColumnReducer literals (design section 7.3). */\nexport const COLUMN_REDUCERS = [...WEIGHT_REDUCERS, \"mean\", \"count\", \"drop\"] as const;\n","/**\n * The immutable id-to-index bijection of a snapshot (design section 4): five storage kinds chosen by\n * inspecting the ids once in O(n), SameValueZero equality, `INVALID_INDEX` on a miss, a dense-integer\n * fast path with no Map at all, lazily materialised typed / decoded representations in either\n * direction, and a reverse `Map` that is shared with the builder (guarded by `index < size`) or built\n * lazily on the first lookup.\n *\n * The class exposes exactly the public surface of design section 12.2. Everything the sibling\n * modules need beyond it (construction from ids, typed arrays or the wire; the typed form for the\n * wire; gather and remap for derived graphs and compaction) is a module-level function that reaches\n * the private storage through a module-private WeakMap, so nothing internal appears on the instance\n * type.\n */\n\nimport { INVALID_INDEX, MAX_COUNT } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport {\n type F64,\n type NodeId,\n type NodeIdMapContract,\n type NodeIdMapKind,\n type U8,\n type U32,\n type ValidationLevel,\n} from \"../types/index.js\";\nimport { assertOneOf } from \"../util/options.js\";\nimport { claimHolder } from \"../util/shared-buffers.js\";\nimport { checkUtf8Layout, encodeUtf8Rows, hasLoneSurrogate, resolveRange, Utf8Store } from \"./string-store.js\";\n\n// ============================================================ id validation\n\n/**\n * A short, plain-ASCII rendering of an id for error messages.\n * @param id - the value\n * @returns the number, a quoted (possibly truncated) string, or the type name\n */\nexport function describeId(id: unknown): string {\n if (typeof id === \"number\") {\n return String(id);\n }\n if (typeof id === \"string\") {\n const text = id.length > 40 ? `${id.slice(0, 37)}...` : id;\n return JSON.stringify(text);\n }\n if (id === null) {\n return \"null\";\n }\n if (typeof id === \"bigint\") {\n return `${String(id)}n`;\n }\n return `a value of type ${typeof id}`;\n}\n\n/**\n * Check a value as a node id and normalise it (design section 4.1): a finite number (`-0` becomes\n * `0`) or a string without a lone surrogate. NaN, non-finite numbers, bigints, objects, null and\n * undefined are E_INVALID_ID; a lone surrogate is E_INVALID_ID with details.reason \"lone surrogate\".\n * @param id - the value to check\n * @returns the id as stored\n */\nexport function validateNodeId(id: unknown): NodeId {\n if (typeof id === \"number\") {\n if (!Number.isFinite(id)) {\n throw new GraphFormatError(\"E_INVALID_ID\", `invalid node id ${String(id)}: not a finite number`, {\n id,\n reason: \"non-finite\",\n });\n }\n return id === 0 ? 0 : id;\n }\n if (typeof id === \"string\") {\n if (hasLoneSurrogate(id)) {\n throw new GraphFormatError(\"E_INVALID_ID\", `invalid node id ${describeId(id)}: lone surrogate`, {\n id,\n reason: \"lone surrogate\",\n });\n }\n return id;\n }\n throw new GraphFormatError(\"E_INVALID_ID\", `invalid node id: ${describeId(id)} is not a string or a number`, {\n reason: \"unsupported type\",\n type: typeof id,\n });\n}\n\n// ============================================================ storage\n\n/**\n * The private state of a NodeIdMap (design section 4.2). Which slots are non-null depends on the\n * kind and on which representations have been materialised so far:\n *\n * - identity: nothing;\n * - dense: denseValues (index -> id) and denseInverse (id -> index, INVALID_INDEX where absent);\n * - numeric: decoded (the builder's array, shared) and / or numbers (F64, the wire form); map;\n * - string: strings (a Utf8Store over the builder's array or over the wire buffers); map;\n * - mixed: decoded (shared) and / or tags + numbers + strings (the wire form); map.\n *\n * `map` is null until first needed for numeric / string / mixed and always null for identity / dense.\n * The object is mutable so that lazily materialised representations can be cached; the map instance\n * itself never changes. Exported only because the public constructor names it; never exported from\n * the package barrel.\n */\ninterface NodeIdMapStorage {\n /** The storage kind. */\n readonly kind: NodeIdMapKind;\n /** Number of ids. */\n readonly size: number;\n /** identity only: id === index + offset; 0 otherwise. */\n readonly offset: number;\n /** dense: the id of every index. */\n readonly denseValues: U32 | null;\n /** dense: index of every id in [0, maxId], INVALID_INDEX where absent. */\n readonly denseInverse: U32 | null;\n /** numeric / mixed: the decoded ids, shared by reference; entries at or beyond `size` are invisible. */\n readonly decoded: readonly NodeId[] | null;\n /** numeric: the ids as f64 (the wire form); mixed: the number rows, 0 where the row is a string. */\n numbers: F64 | null;\n /** mixed: 0 for a number row, 1 for a string row (the wire form). */\n tags: U8 | null;\n /** string / mixed: the Utf8 store (string: every row; mixed: string rows, number rows empty). */\n strings: Utf8Store | null;\n /** numeric / string / mixed: the reverse map; shared with the builder or built on first lookup. */\n map: Map<NodeId, number> | null;\n /** String(idOf(i)) -> i, built lazily by stringIndex(). */\n stringIndex: Map<string, number> | null;\n}\n\n/** The typed representation of an id map, one slot per wire member (design section 4.5). */\nexport interface NodeIdMapTypedParts {\n /** The storage kind. */\n readonly kind: NodeIdMapKind;\n /** Number of ids. */\n readonly size: number;\n /** identity only: id === index + offset; 0 otherwise. */\n readonly offset: number;\n /** dense: u32 ids per index; numeric: f64 ids per index; null otherwise. */\n readonly values: U32 | F64 | null;\n /** mixed: u8 tag per index (0 number, 1 string); null otherwise. */\n readonly tags: U8 | null;\n /** mixed: f64 per index (0 where string); null otherwise. */\n readonly numbers: F64 | null;\n /** string / mixed: rows + 1 offsets of the Utf8 store; null otherwise. */\n readonly offsets: U32 | null;\n /** string / mixed: the UTF-8 bytes; null otherwise. */\n readonly utf8: U8 | null;\n}\n\n/** Storage behind every instance, reachable by the module-level functions but not by consumers. */\nconst INTERNALS = new WeakMap<NodeIdMap, NodeIdMapStorage>();\n\n/**\n * The storage of an instance.\n * @param map - the id map\n * @returns its private storage\n */\nfunction storageOf(map: NodeIdMap): NodeIdMapStorage {\n const storage = INTERNALS.get(map);\n if (storage === undefined) {\n throw new GraphFormatError(\"E_UNSUPPORTED\", \"not a NodeIdMap of this package\", { reason: \"foreign id map\" });\n }\n return storage;\n}\n\n/**\n * A storage record with every slot null except the given ones.\n * @param kind - the storage kind\n * @param size - the id count\n * @param slots - the non-null slots\n * @returns the storage\n */\nfunction makeStorage(kind: NodeIdMapKind, size: number, slots: Partial<NodeIdMapStorage> = {}): NodeIdMapStorage {\n return {\n kind,\n size,\n offset: 0,\n denseValues: null,\n denseInverse: null,\n decoded: null,\n numbers: null,\n tags: null,\n strings: null,\n map: null,\n stringIndex: null,\n ...slots,\n };\n}\n\n/**\n * Whether a typed array the storage still reads from was transferred away.\n * @param storage - the storage\n * @returns true when detached\n */\nfunction storageDetached(storage: NodeIdMapStorage): boolean {\n if (storage.size === 0) {\n return false;\n }\n return (\n (storage.denseValues !== null && storage.denseValues.length === 0) ||\n (storage.decoded === null && storage.numbers !== null && storage.numbers.length === 0) ||\n (storage.decoded === null && storage.tags !== null && storage.tags.length === 0) ||\n (storage.decoded === null && storage.strings !== null && storage.strings.detached)\n );\n}\n\n/**\n * Whether an id map's typed storage was transferred away (design section 9.1), for validate().\n * @param map - the id map\n * @returns true when detached\n */\nexport function idMapDetached(map: NodeIdMap): boolean {\n const storage = INTERNALS.get(map);\n return storage !== undefined && storageDetached(storage);\n}\n\n/**\n * -0 is stored and reported as 0 (SameValueZero, design section 4.1).\n * @param value - a numeric id\n * @returns the id with -0 folded into 0\n */\nfunction normaliseZero(value: number): number {\n return value === 0 ? 0 : value;\n}\n\n/**\n * The E_DUPLICATE_ID error for two indices holding the same id.\n * @param id - the id\n * @param first - the lower index\n * @param second - the higher index\n * @returns the error\n */\nfunction duplicateIdError(id: NodeId, first: number, second: number): GraphFormatError {\n return new GraphFormatError(\n \"E_DUPLICATE_ID\",\n `duplicate node id ${describeId(id)} at indices ${first} and ${second}`,\n {\n id,\n indices: [first, second],\n },\n );\n}\n\n/**\n * The E_INVALID_SNAPSHOT error for an id bijection failure of untrusted typed input (invariant I11).\n * @param reason - what failed\n * @param details - extra context\n * @returns the error\n */\nfunction bijectionError(reason: string, details: Readonly<Record<string, unknown>>): GraphFormatError {\n return new GraphFormatError(\"E_INVALID_SNAPSHOT\", `id map violates invariant I11: ${reason}`, {\n invariant: \"I11\",\n reason,\n ...details,\n });\n}\n\n/**\n * The E_BAD_SERIALIZATION error for a malformed typed id map.\n * @param ref - the manifest member\n * @param reason - what is wrong\n * @param details - extra context\n * @returns the error\n */\nfunction layoutError(ref: string, reason: string, details: Readonly<Record<string, unknown>> = {}): GraphFormatError {\n return new GraphFormatError(\"E_BAD_SERIALIZATION\", `${ref}: ${reason}`, { ref, reason, ...details });\n}\n\n/**\n * Build the dense inverse array (id -> index) from the dense values, detecting duplicates.\n * @param values - the id of every index, integers in [0, MAX_COUNT)\n * @param maxId - the largest id\n * @param onDuplicate - builds the error thrown for a repeated id\n * @returns a fresh inverse of maxId + 1 entries filled with INVALID_INDEX where absent\n */\nfunction buildDenseInverse(\n values: U32,\n maxId: number,\n onDuplicate: (id: number, first: number, second: number) => GraphFormatError,\n): U32 {\n const inverse = new Uint32Array(maxId + 1).fill(INVALID_INDEX);\n for (let i = 0; i < values.length; i++) {\n const id = values[i];\n if (inverse[id] !== INVALID_INDEX) {\n throw onDuplicate(id, inverse[id], i);\n }\n inverse[id] = i;\n }\n return inverse;\n}\n\n/**\n * Build the reverse map of `size` decoded ids, detecting duplicates.\n * @param ids - the ids in index order\n * @param size - how many entries to index\n * @param onDuplicate - builds the error thrown for a repeated id\n * @returns a fresh Map from id to index\n */\nfunction buildReverseMap(\n ids: ArrayLike<NodeId>,\n size: number,\n onDuplicate: (id: NodeId, first: number, second: number) => GraphFormatError,\n): Map<NodeId, number> {\n const map = new Map<NodeId, number>();\n for (let i = 0; i < size; i++) {\n const id = ids[i];\n const seen = map.get(id);\n if (seen !== undefined) {\n throw onDuplicate(id, seen, i);\n }\n map.set(id, i);\n }\n return map;\n}\n\n// ============================================================ detection\n\n/** What one O(n) pass over the ids learns (design section 4.2). */\ninterface IdScan {\n /** Every id is a number. */\n readonly allNumbers: boolean;\n /** Every id is a string. */\n readonly allStrings: boolean;\n /** ids[i] === i + offset for every i, with an integer offset. */\n readonly identity: boolean;\n /** The identity offset (meaningful when identity). */\n readonly offset: number;\n /** Every id is an integer in [0, MAX_COUNT). */\n readonly allDenseIntegers: boolean;\n /** The largest id when allDenseIntegers, else -1. */\n readonly maxId: number;\n}\n\n/**\n * One pass over the first `size` ids that decides the storage kind. The ids are assumed valid\n * (finite numbers or strings).\n * @param ids - the ids in index order\n * @param size - how many to inspect\n * @returns the scan result\n */\nfunction scanIds(ids: ArrayLike<NodeId>, size: number): IdScan {\n let allNumbers = true;\n let allStrings = true;\n let allDenseIntegers = true;\n let maxId = -1;\n let offset = 0;\n let identity = true;\n if (size > 0) {\n const first = ids[0];\n if (typeof first === \"number\" && Number.isSafeInteger(first)) {\n offset = first;\n } else {\n identity = false;\n }\n }\n for (let i = 0; i < size; i++) {\n const id = ids[i];\n if (typeof id === \"number\") {\n allStrings = false;\n if (identity && id !== i + offset) {\n identity = false;\n }\n if (allDenseIntegers) {\n if (Number.isInteger(id) && id >= 0 && id < MAX_COUNT) {\n if (id > maxId) {\n maxId = id;\n }\n } else {\n allDenseIntegers = false;\n }\n }\n } else {\n allNumbers = false;\n identity = false;\n allDenseIntegers = false;\n }\n }\n if (!allNumbers) {\n maxId = -1;\n }\n return { allNumbers, allStrings, identity, offset, allDenseIntegers, maxId };\n}\n\n/**\n * The kind a scan selects (design section 4.2): identity, else dense when the inverse array would be\n * at most twice the node count, else numeric, string or mixed.\n * @param scan - the scan result\n * @param size - the id count\n * @returns the kind\n */\nfunction kindOf(scan: IdScan, size: number): NodeIdMapKind {\n if (size === 0 || scan.identity) {\n return \"identity\";\n }\n if (scan.allDenseIntegers && scan.maxId + 1 <= 2 * size) {\n return \"dense\";\n }\n if (scan.allNumbers) {\n return \"numeric\";\n }\n if (scan.allStrings) {\n return \"string\";\n }\n return \"mixed\";\n}\n\n/**\n * Copy the first `size` ids into a fresh U32 (dense values).\n * @param ids - the ids, all integers in [0, MAX_COUNT)\n * @param size - how many\n * @returns the values\n */\nfunction denseValuesOf(ids: ArrayLike<NodeId>, size: number): U32 {\n const values = new Uint32Array(size);\n for (let i = 0; i < size; i++) {\n const id = ids[i];\n values[i] = typeof id === \"number\" ? id : INVALID_INDEX;\n }\n return values;\n}\n\n// ============================================================ the class\n\n/**\n * Bijection between node ids and node indices for one snapshot (design section 4, invariant I11):\n * `indexOf(idOf(i)) === i` for every i, `size === nodeCount`, SameValueZero equality (so `1` and\n * `\"1\"` are distinct, `-0` is `0`, `1.5` is legal and `NaN` never occurs). Immutable. Lookups by id\n * are total and return `INVALID_INDEX` on a miss (decision C9); `requireIndex` is the checked form.\n *\n * Instances are created by the module-level factories (`nodeIdMapFromIds`, `nodeIdMapFromF64`,\n * `identityNodeIdMap`, `nodeIdMapFromTyped`) and by `gatherNodeIdMap` / `remapNodeIdMap`; the\n * constructor takes a prepared storage record and is not meant to be called by consumers.\n */\nexport class NodeIdMap implements NodeIdMapContract {\n /** The storage kind (design section 4.2). */\n readonly kind: NodeIdMapKind;\n\n /** Number of ids; equals nodeCount. */\n readonly size: number;\n\n /** identity only: id === index + offset (0 or 1 in practice); 0 for every other kind. */\n readonly offset: number;\n\n /** The private storage; also registered in INTERNALS for the module-level functions. */\n private readonly storage: NodeIdMapStorage;\n\n /**\n * Wrap a prepared storage record. Sibling modules use the factories of this module instead.\n * @param storage - the storage; the kind's slots must be filled as documented on NodeIdMapStorage\n * @internal\n */\n constructor(storage: NodeIdMapStorage) {\n this.kind = storage.kind;\n this.size = storage.size;\n this.offset = storage.kind === \"identity\" ? storage.offset : 0;\n this.storage = storage;\n INTERNALS.set(this, storage);\n Object.freeze(this);\n }\n\n /**\n * The id of a node index.\n * @param index - the node index\n * @returns the id; E_INDEX_RANGE when index is not an integer in [0, size)\n */\n idOf(index: number): NodeId {\n if (!(index >= 0 && index < this.size) || !Number.isInteger(index)) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `node index ${index} out of range (size ${this.size})`, {\n index,\n size: this.size,\n });\n }\n return this.idAt(index);\n }\n\n /**\n * Total lookup by id: SameValueZero, never coerces, so `indexOf(\"1\")` misses a map of numbers.\n * @param id - the node id\n * @returns the node index, or INVALID_INDEX when absent\n */\n indexOf(id: NodeId): number {\n const { storage } = this;\n switch (storage.kind) {\n case \"identity\": {\n if (typeof id !== \"number\") {\n return INVALID_INDEX;\n }\n const index = id - storage.offset;\n if (!Number.isInteger(index) || index < 0 || index >= storage.size) {\n return INVALID_INDEX;\n }\n return index === 0 ? 0 : index;\n }\n case \"dense\": {\n const inverse = storage.denseInverse as U32;\n if (typeof id !== \"number\" || !Number.isInteger(id) || id < 0 || id >= inverse.length) {\n return INVALID_INDEX;\n }\n return inverse[id];\n }\n case \"numeric\":\n case \"string\":\n case \"mixed\": {\n const index = this.reverseMap().get(id);\n return index === undefined || index >= storage.size ? INVALID_INDEX : index;\n }\n default:\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${String(storage.kind)}`, {\n kind: storage.kind,\n });\n }\n }\n\n /**\n * Whether an id is present.\n * @param id - the node id\n * @returns true when present\n */\n has(id: NodeId): boolean {\n return this.indexOf(id) !== INVALID_INDEX;\n }\n\n /**\n * Checked lookup by id, for algorithms that today throw \"node not found\".\n * @param id - the node id\n * @returns the node index; E_UNKNOWN_NODE when absent\n */\n requireIndex(id: NodeId): number {\n const index = this.indexOf(id);\n if (index === INVALID_INDEX) {\n throw new GraphFormatError(\"E_UNKNOWN_NODE\", `unknown node id ${describeId(id)}`, { id });\n }\n return index;\n }\n\n /**\n * Bulk lookup.\n * @param ids - the ids to resolve\n * @param onMissing - \"invalid\" (default) writes INVALID_INDEX for a miss; \"throw\" raises E_UNKNOWN_NODE\n * @returns a fresh U32 of indices in input order\n */\n indicesOf(ids: Iterable<NodeId>, onMissing: \"invalid\" | \"throw\" = \"invalid\"): U32 {\n assertOneOf(\"onMissing\", onMissing, [\"invalid\", \"throw\"] as const);\n const lookup =\n onMissing === \"throw\"\n ? (id: NodeId): number => this.requireIndex(id)\n : (id: NodeId): number => this.indexOf(id);\n if (Array.isArray(ids)) {\n const list = ids as readonly NodeId[];\n const out = new Uint32Array(list.length);\n for (let i = 0; i < list.length; i++) {\n out[i] = lookup(list[i]);\n }\n return out;\n }\n let out = new Uint32Array(16);\n let count = 0;\n for (const id of ids) {\n if (count === out.length) {\n const grown = new Uint32Array(out.length * 2);\n grown.set(out);\n out = grown;\n }\n out[count++] = lookup(id);\n }\n return out.slice(0, count);\n }\n\n /**\n * Bulk decode of a range of ids in one pass. Bounds follow Array.prototype.slice (negative values\n * count from the end, out-of-range values are clamped).\n * @param start - first index (default 0)\n * @param end - one past the last index (default size)\n * @returns a fresh array of the ids in index order\n */\n idsSlice(start = 0, end = this.size): NodeId[] {\n const [from, to] = resolveRange(start, end, this.size);\n const { storage } = this;\n this.assertAttached();\n switch (storage.kind) {\n case \"identity\": {\n const out = new Array<NodeId>(to - from);\n for (let i = from; i < to; i++) {\n out[i - from] = i + storage.offset;\n }\n return out;\n }\n case \"dense\":\n return Array.from((storage.denseValues as U32).subarray(from, to));\n case \"numeric\":\n if (storage.decoded !== null) {\n return storage.decoded.slice(from, to);\n }\n return Array.from((storage.numbers as F64).subarray(from, to), normaliseZero);\n case \"string\":\n return (storage.strings as Utf8Store).slice(from, to);\n case \"mixed\": {\n if (storage.decoded !== null) {\n return storage.decoded.slice(from, to);\n }\n const tags = storage.tags as U8;\n const numbers = storage.numbers as F64;\n const strings = storage.strings as Utf8Store;\n const out = new Array<NodeId>(to - from);\n for (let i = from; i < to; i++) {\n out[i - from] = tags[i] === 0 ? normaliseZero(numbers[i]) : strings.at(i);\n }\n return out;\n }\n default:\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${String(storage.kind)}`, {\n kind: storage.kind,\n });\n }\n }\n\n /**\n * Every id in index order.\n * @returns a fresh array\n */\n toArray(): NodeId[] {\n return this.idsSlice(0, this.size);\n }\n\n /**\n * Iterate the ids in index order.\n * @yields each id, decoding lazily\n */\n *[Symbol.iterator](): IterableIterator<NodeId> {\n for (let i = 0; i < this.size; i++) {\n yield this.idAt(i);\n }\n }\n\n /**\n * Key an index-aligned result vector by id (boundary helper, decision C11).\n * @param values - one value per node index\n * @returns a Map from id to value, in index order\n */\n toMap<T>(values: ArrayLike<T>): Map<NodeId, T> {\n const out = new Map<NodeId, T>();\n for (let i = 0; i < this.size; i++) {\n out.set(this.idAt(i), values[i]);\n }\n return out;\n }\n\n /**\n * Key an index-aligned result vector by String(id), for legacy Map<string, T> result shapes. When\n * two ids share a string form (1 and \"1\") the HIGHER index wins, exactly as the legacy\n * algorithms' assignment in node order does (design section 14.2).\n * @param values - one value per node index\n * @returns a Map from String(id) to value\n */\n toStringMap<T>(values: ArrayLike<T>): Map<string, T> {\n const out = new Map<string, T>();\n for (let i = 0; i < this.size; i++) {\n out.set(String(this.idAt(i)), values[i]);\n }\n return out;\n }\n\n /**\n * Key an index-aligned result vector by String(id), for legacy record result shapes only. The\n * record has a null prototype so ids such as \"__proto__\" are ordinary keys; when two ids share a\n * string form the HIGHER index wins (the legacy assignment order, design section 14.2).\n * @param values - one value per node index\n * @returns a record from String(id) to value\n */\n toRecord<T>(values: ArrayLike<T>): Record<string, T> {\n const out = Object.create(null) as Record<string, T>;\n for (let i = 0; i < this.size; i++) {\n out[String(this.idAt(i))] = values[i];\n }\n return out;\n }\n\n /**\n * Iterate [id, value] pairs of an index-aligned result vector.\n * @param values - one value per node index\n * @yields the pairs in index order\n */\n *entries<T>(values: ArrayLike<T>): IterableIterator<[NodeId, T]> {\n for (let i = 0; i < this.size; i++) {\n yield [this.idAt(i), values[i]];\n }\n }\n\n /**\n * String(idOf(i)) -> i, built lazily once, for legacy string-typed id parameters. When two ids\n * share a string form (always one number and one string, since ids are distinct) the STRING id\n * wins: a legacy string parameter \"1\" addressed the node whose id is the string \"1\".\n * @returns the read-only string index\n */\n stringIndex(): ReadonlyMap<string, number> {\n const { storage } = this;\n if (storage.stringIndex === null) {\n const index = new Map<string, number>();\n for (let i = 0; i < storage.size; i++) {\n const id = this.idAt(i);\n const key = String(id);\n if (typeof id === \"string\" || !index.has(key)) {\n index.set(key, i);\n }\n }\n storage.stringIndex = index;\n }\n return storage.stringIndex;\n }\n\n /**\n * Bytes of typed storage currently materialised; excludes the reverse Map and JS strings.\n * @returns the byte count\n */\n byteLength(): number {\n const { storage } = this;\n let bytes = 0;\n if (storage.denseValues !== null) {\n bytes += storage.denseValues.byteLength;\n }\n if (storage.denseInverse !== null) {\n bytes += storage.denseInverse.byteLength;\n }\n if (storage.numbers !== null) {\n bytes += storage.numbers.byteLength;\n }\n if (storage.tags !== null) {\n bytes += storage.tags.byteLength;\n }\n if (storage.strings !== null) {\n bytes += storage.strings.byteLength();\n }\n return bytes;\n }\n\n /**\n * Unchecked id of an in-range index.\n * @param index - a node index in [0, size)\n * @returns the id\n */\n private idAt(index: number): NodeId {\n const { storage } = this;\n this.assertAttached();\n switch (storage.kind) {\n case \"identity\":\n return index + storage.offset;\n case \"dense\":\n return (storage.denseValues as U32)[index];\n case \"numeric\":\n return storage.decoded !== null\n ? storage.decoded[index]\n : normaliseZero((storage.numbers as F64)[index]);\n case \"string\":\n return (storage.strings as Utf8Store).at(index);\n case \"mixed\":\n if (storage.decoded !== null) {\n return storage.decoded[index];\n }\n return (storage.tags as U8)[index] === 0\n ? normaliseZero((storage.numbers as F64)[index])\n : (storage.strings as Utf8Store).at(index);\n default:\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${String(storage.kind)}`, {\n kind: storage.kind,\n });\n }\n }\n\n /**\n * E_DETACHED when a typed array the map reads from was transferred away (design sections 9.1\n * and 11.3): derived from the array state (a transferred buffer leaves zero-length views).\n */\n private assertAttached(): void {\n if (storageDetached(this.storage)) {\n throw new GraphFormatError(\"E_DETACHED\", \"the id map's storage was transferred away\", {\n kind: this.storage.kind,\n });\n }\n }\n\n /**\n * The reverse map of a numeric / string / mixed map, built on first use (one pass over the ids,\n * after a bulk decode of a wire-decoded Utf8 store) when it was not shared by the builder.\n * @returns the map from id to index\n */\n private reverseMap(): Map<NodeId, number> {\n const { storage } = this;\n if (storage.map === null) {\n // the bulk decode below reads the Utf8 store: E_DETACHED, never a TypeError, after a transfer\n this.assertAttached();\n if (storage.decoded === null && storage.strings !== null) {\n storage.strings.materialiseDecoded();\n }\n const map = new Map<NodeId, number>();\n for (let i = 0; i < storage.size; i++) {\n map.set(this.idAt(i), i);\n }\n storage.map = map;\n }\n return storage.map;\n }\n}\n\n// ============================================================ factories\n\n/**\n * An identity map: id === index + offset, no storage at all (design section 4.2). What\n * `fromEdgeArrays` without ids and `contract()` produce; offset 1 covers 1-based files.\n * @param size - the node count\n * @param offset - the integer added to every index; default 0\n * @returns the map\n */\nexport function identityNodeIdMap(size: number, offset = 0): NodeIdMap {\n if (!Number.isInteger(size) || size < 0 || size > MAX_COUNT) {\n throw new GraphFormatError(\"E_TOO_LARGE\", `node count ${size} is not an integer in [0, MAX_COUNT]`, {\n count: size,\n max: MAX_COUNT,\n });\n }\n if (!Number.isSafeInteger(offset)) {\n throw new GraphFormatError(\"E_INVALID_ID\", `identity offset ${offset} is not a safe integer`, {\n offset,\n reason: \"non-integer offset\",\n });\n }\n return new NodeIdMap(makeStorage(\"identity\", size, { offset }));\n}\n\n/** Options of nodeIdMapFromIds. */\ninterface FromIdsOptions {\n /**\n * The builder's reverse map, shared by reference and guarded by `index < size` (decision C17). When\n * given, the ids are trusted (already validated and distinct) and `validate` is ignored.\n */\n readonly map?: Map<NodeId, number> | undefined;\n /**\n * Check every id (E_INVALID_ID) and their distinctness (E_DUPLICATE_ID), copying the array and\n * normalising -0; default true. false trusts the caller (derived graphs) and shares the array.\n */\n readonly validate?: boolean | undefined;\n}\n\n/**\n * Build a map from decoded ids in index order, choosing the kind in one O(n) pass (design section\n * 4.2, freeze step 9). With `options.map` (the builder's Map) the array and the Map are shared by\n * reference and nothing is validated; identity and dense maps drop the Map. Without it the ids are\n * validated and copied unless `validate` is false.\n * @param ids - the ids; only entries below `size` are read\n * @param size - the node count; default ids.length\n * @param options - the shared map and validation switch\n * @returns the map\n */\nexport function nodeIdMapFromIds(\n ids: readonly NodeId[],\n size: number = ids.length,\n options: FromIdsOptions = {},\n): NodeIdMap {\n if (!Number.isInteger(size) || size < 0 || size > MAX_COUNT) {\n throw new GraphFormatError(\"E_TOO_LARGE\", `node count ${size} is not an integer in [0, MAX_COUNT]`, {\n count: size,\n max: MAX_COUNT,\n });\n }\n const trusted = options.map !== undefined || options.validate === false;\n let source: readonly NodeId[] = ids;\n if (!trusted) {\n const copy = new Array<NodeId>(size);\n for (let i = 0; i < size; i++) {\n copy[i] = validateNodeId(ids[i]);\n }\n source = copy;\n }\n const scan = scanIds(source, size);\n const kind = kindOf(scan, size);\n switch (kind) {\n case \"identity\":\n return new NodeIdMap(makeStorage(\"identity\", size, { offset: size === 0 ? 0 : scan.offset }));\n case \"dense\": {\n const denseValues = denseValuesOf(source, size);\n const denseInverse = buildDenseInverse(denseValues, scan.maxId, duplicateIdError);\n return new NodeIdMap(makeStorage(\"dense\", size, { denseValues, denseInverse }));\n }\n case \"numeric\":\n case \"mixed\": {\n const map = options.map ?? (trusted ? null : buildReverseMap(source, size, duplicateIdError));\n return new NodeIdMap(makeStorage(kind, size, { decoded: source, map }));\n }\n case \"string\": {\n const map = options.map ?? (trusted ? null : buildReverseMap(source, size, duplicateIdError));\n const strings = Utf8Store.fromStrings(source as readonly string[], size);\n return new NodeIdMap(makeStorage(\"string\", size, { strings, map }));\n }\n default:\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${String(kind)}`, { kind });\n }\n}\n\n/** Options of nodeIdMapFromF64. */\ninterface FromF64Options {\n /**\n * Check that every value is finite (E_INVALID_ID) and that the values are distinct (E_DUPLICATE_ID);\n * default true. The array is adopted by reference either way; -0 entries are rewritten to 0 in a\n * copy when validating.\n */\n readonly validate?: boolean | undefined;\n}\n\n/**\n * Build a map from numeric ids in a Float64Array (the `ids: F64` form of `fromEdgeArrays` /\n * `fromCsr`), choosing identity, dense or numeric in one pass. A numeric map adopts the array as its\n * typed representation.\n * @param values - one id per index\n * @param options - the validation switch\n * @returns the map\n */\nexport function nodeIdMapFromF64(values: F64, options: FromF64Options = {}): NodeIdMap {\n const size = values.length;\n if (size > MAX_COUNT) {\n throw new GraphFormatError(\"E_TOO_LARGE\", `node count ${size} exceeds MAX_COUNT`, {\n count: size,\n max: MAX_COUNT,\n });\n }\n const validate = options.validate !== false;\n let numbers = values;\n if (validate) {\n let negativeZero = false;\n for (let i = 0; i < size; i++) {\n const v = values[i];\n if (!Number.isFinite(v)) {\n throw new GraphFormatError(\n \"E_INVALID_ID\",\n `invalid node id ${String(v)} at index ${i}: not a finite number`,\n {\n id: v,\n index: i,\n reason: \"non-finite\",\n },\n );\n }\n if (Object.is(v, -0)) {\n negativeZero = true;\n }\n }\n if (negativeZero) {\n numbers = values.slice();\n for (let i = 0; i < size; i++) {\n if (numbers[i] === 0) {\n numbers[i] = 0;\n }\n }\n }\n }\n const scan = scanIds(numbers, size);\n const kind = kindOf(scan, size);\n switch (kind) {\n case \"identity\":\n return new NodeIdMap(makeStorage(\"identity\", size, { offset: size === 0 ? 0 : scan.offset }));\n case \"dense\": {\n const denseValues = denseValuesOf(numbers, size);\n const denseInverse = buildDenseInverse(denseValues, scan.maxId, duplicateIdError);\n return new NodeIdMap(makeStorage(\"dense\", size, { denseValues, denseInverse }));\n }\n case \"numeric\": {\n const map = validate ? buildReverseMap(numbers, size, duplicateIdError) : null;\n return new NodeIdMap(makeStorage(\"numeric\", size, { numbers, map }));\n }\n default:\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unexpected id map kind ${kind} for numeric ids`, { kind });\n }\n}\n\n/**\n * The distinct backing buffers of an id map's materialised typed storage (dense values and inverse,\n * numbers, tags, an encoded Utf8 store), for the owner count of design section 9.1.\n * @param map - the id map\n * @returns the buffers, each once\n */\nexport function idMapBuffers(map: NodeIdMap): ArrayBuffer[] {\n const storage = INTERNALS.get(map);\n const out = new Set<ArrayBuffer>();\n if (storage === undefined) {\n // a foreign object standing in for a map (tests wrap one): nothing typed to claim\n return [];\n }\n for (const view of [storage.denseValues, storage.denseInverse, storage.numbers, storage.tags]) {\n if (view !== null) {\n out.add(view.buffer);\n }\n }\n if (storage.strings !== null && storage.strings.encoded) {\n out.add(storage.strings.offsets.buffer);\n out.add(storage.strings.utf8.buffer);\n }\n return [...out];\n}\n\n/**\n * Build a map from its typed (wire) representation (design sections 4.5 and 9.5), adopting the arrays\n * by reference. \"structure\" checks lengths, tag values, the dense bound and the Utf8 layout\n * (E_BAD_SERIALIZATION with details.ref); \"full\" additionally checks invariant I11: finite numbers,\n * well-formed UTF-8 (a fatal decode) and distinct ids (E_INVALID_SNAPSHOT with details.invariant\n * \"I11\"), building the reverse map eagerly. A dense duplicate is always detected because the inverse\n * array is rebuilt on load. An unknown kind is E_UNSUPPORTED with details.kind.\n * @param parts - the typed representation\n * @param validate - the validation level; default \"structure\"\n * @returns the map\n */\nexport function nodeIdMapFromTyped(parts: NodeIdMapTypedParts, validate: ValidationLevel = \"structure\"): NodeIdMap {\n const { kind, size } = parts;\n const structure = validate !== \"none\";\n const full = validate === \"full\";\n if (structure && (!Number.isInteger(size) || size < 0 || size > MAX_COUNT)) {\n throw layoutError(\"ids.size\", `size ${size} is not an integer in [0, MAX_COUNT]`, { found: size });\n }\n switch (kind) {\n case \"identity\": {\n // O(1) at every level: every id index + offset (the largest is offset + size - 1) must be a\n // safe integer (I11)\n if (!Number.isSafeInteger(parts.offset) || (size > 0 && !Number.isSafeInteger(parts.offset + size - 1))) {\n const reason = `offset ${parts.offset} with ${size} ids leaves the safe-integer range`;\n throw full\n ? bijectionError(reason, { found: parts.offset, size })\n : layoutError(\"ids.offset\", reason, { found: parts.offset, size });\n }\n return new NodeIdMap(makeStorage(\"identity\", size, { offset: normaliseZero(parts.offset) }));\n }\n case \"dense\": {\n const { values } = parts;\n if (!(values instanceof Uint32Array)) {\n throw layoutError(\"ids.values\", \"a dense id map needs u32 values\");\n }\n if (structure && values.length !== size) {\n throw layoutError(\"ids.values\", `expected ${size} values, found ${values.length}`, {\n expected: size,\n found: values.length,\n });\n }\n let maxId = -1;\n for (let i = 0; i < values.length; i++) {\n if (values[i] > maxId) {\n maxId = values[i];\n }\n }\n // the dense bounds are checked at every level: the scan is already paid, and the inverse\n // array below is allocated over [0, maxId], which an unchecked id could make enormous\n if (maxId >= MAX_COUNT) {\n throw layoutError(\"ids.values\", `dense id ${maxId} is not below MAX_COUNT`, { found: maxId });\n }\n if (maxId + 1 > 2 * Math.max(size, values.length)) {\n throw layoutError(\"ids.values\", `dense bound violated: max id ${maxId} with ${size} nodes`, {\n maxId,\n size,\n });\n }\n const denseInverse = buildDenseInverse(values, maxId, (id, first, second) =>\n bijectionError(`duplicate id ${id}`, { id, indices: [first, second] }),\n );\n return new NodeIdMap(makeStorage(\"dense\", size, { denseValues: values, denseInverse }));\n }\n case \"numeric\": {\n const numbers = parts.values;\n if (!(numbers instanceof Float64Array)) {\n throw layoutError(\"ids.values\", \"a numeric id map needs f64 values\");\n }\n if (structure && numbers.length !== size) {\n throw layoutError(\"ids.values\", `expected ${size} values, found ${numbers.length}`, {\n expected: size,\n found: numbers.length,\n });\n }\n let map: Map<NodeId, number> | null = null;\n if (full) {\n for (let i = 0; i < size; i++) {\n if (!Number.isFinite(numbers[i])) {\n throw bijectionError(`non-finite id at index ${i}`, { index: i, id: numbers[i] });\n }\n }\n map = buildReverseMap(numbers, size, (id, first, second) =>\n bijectionError(`duplicate id ${describeId(id)}`, { id, indices: [first, second] }),\n );\n }\n return new NodeIdMap(makeStorage(\"numeric\", size, { numbers, map }));\n }\n case \"string\": {\n const { offsets, utf8 } = parts;\n if (offsets === null || utf8 === null) {\n throw layoutError(\"ids.offsets\", \"a string id map needs offsets and utf8\");\n }\n if (structure) {\n checkUtf8Layout(offsets, utf8, size, \"ids.offsets\");\n }\n const strings = Utf8Store.fromEncoded(offsets, utf8);\n let map: Map<NodeId, number> | null = null;\n if (full) {\n const bad = strings.firstMalformedRow();\n if (bad !== -1) {\n throw bijectionError(`malformed UTF-8 in id at index ${bad}`, { index: bad });\n }\n map = buildReverseMap(strings.decodeAll(), size, (id, first, second) =>\n bijectionError(`duplicate id ${describeId(id)}`, { id, indices: [first, second] }),\n );\n }\n return new NodeIdMap(makeStorage(\"string\", size, { strings, map }));\n }\n case \"mixed\": {\n const { tags, numbers, offsets, utf8 } = parts;\n if (tags === null || numbers === null || offsets === null || utf8 === null) {\n throw layoutError(\"ids.tags\", \"a mixed id map needs tags, numbers, offsets and utf8\");\n }\n if (structure) {\n if (tags.length !== size) {\n throw layoutError(\"ids.tags\", `expected ${size} tags, found ${tags.length}`, {\n expected: size,\n found: tags.length,\n });\n }\n if (numbers.length !== size) {\n throw layoutError(\"ids.numbers\", `expected ${size} numbers, found ${numbers.length}`, {\n expected: size,\n found: numbers.length,\n });\n }\n for (let i = 0; i < size; i++) {\n if (tags[i] > 1) {\n throw layoutError(\"ids.tags\", `tag ${tags[i]} at index ${i} is not 0 or 1`, {\n index: i,\n found: tags[i],\n });\n }\n }\n checkUtf8Layout(offsets, utf8, size, \"ids.offsets\");\n }\n const strings = Utf8Store.fromEncoded(offsets, utf8);\n let map: Map<NodeId, number> | null = null;\n if (full) {\n const bad = strings.firstMalformedRow();\n if (bad !== -1) {\n throw bijectionError(`malformed UTF-8 in id at index ${bad}`, { index: bad });\n }\n const decoded = new Array<NodeId>(size);\n for (let i = 0; i < size; i++) {\n if (tags[i] === 0) {\n if (!Number.isFinite(numbers[i])) {\n throw bijectionError(`non-finite id at index ${i}`, { index: i, id: numbers[i] });\n }\n decoded[i] = numbers[i];\n } else {\n decoded[i] = strings.at(i);\n }\n }\n map = buildReverseMap(decoded, size, (id, first, second) =>\n bijectionError(`duplicate id ${describeId(id)}`, { id, indices: [first, second] }),\n );\n }\n return new NodeIdMap(makeStorage(\"mixed\", size, { tags, numbers, strings, map }));\n }\n default:\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${String(kind)}`, { kind });\n }\n}\n\n// ============================================================ typed form, gather, remap\n\n/**\n * The typed (wire) representation of a map (design section 4.5), materialising and caching whatever\n * the map only held in decoded form: the F64 of a numeric map, the Utf8 store of a string map, the\n * tags + numbers + Utf8 store of a mixed map. The dense inverse and the reverse Map are never part\n * of it. Repeated calls return the same arrays.\n * @param map - the id map\n * @returns the typed parts; every slot the kind does not use is null\n */\nexport function nodeIdMapToTyped(map: NodeIdMap): NodeIdMapTypedParts {\n const storage = storageOf(map);\n const { kind, size } = storage;\n switch (kind) {\n case \"identity\":\n return {\n kind,\n size,\n offset: storage.offset,\n values: null,\n tags: null,\n numbers: null,\n offsets: null,\n utf8: null,\n };\n case \"dense\":\n return {\n kind,\n size,\n offset: 0,\n values: storage.denseValues,\n tags: null,\n numbers: null,\n offsets: null,\n utf8: null,\n };\n case \"numeric\": {\n if (storage.numbers === null) {\n const decoded = storage.decoded as readonly NodeId[];\n const numbers = new Float64Array(size);\n for (let i = 0; i < size; i++) {\n const id = decoded[i];\n if (typeof id !== \"number\") {\n throw new GraphFormatError(\n \"E_INVALID_ID\",\n `numeric id map holds a ${typeof id} at index ${i}`,\n {\n index: i,\n found: typeof id,\n },\n );\n }\n numbers[i] = id;\n }\n storage.numbers = numbers;\n claimHolder(numbers.buffer);\n }\n return {\n kind,\n size,\n offset: 0,\n values: storage.numbers,\n tags: null,\n numbers: null,\n offsets: null,\n utf8: null,\n };\n }\n case \"string\": {\n const strings = storage.strings as Utf8Store;\n return {\n kind,\n size,\n offset: 0,\n values: null,\n tags: null,\n numbers: null,\n offsets: strings.offsets,\n utf8: strings.utf8,\n };\n }\n case \"mixed\": {\n if (storage.tags === null || storage.numbers === null || storage.strings === null) {\n const decoded = storage.decoded as readonly NodeId[];\n const tags = new Uint8Array(size);\n const numbers = new Float64Array(size);\n for (let i = 0; i < size; i++) {\n const id = decoded[i];\n if (typeof id === \"number\") {\n numbers[i] = id;\n } else {\n tags[i] = 1;\n }\n }\n const { offsets, utf8 } = encodeUtf8Rows(decoded, size);\n storage.tags = tags;\n storage.numbers = numbers;\n storage.strings = Utf8Store.fromEncoded(offsets, utf8);\n // the map is the first holder of the buffers it materialises (design section 9.1)\n for (const buffer of [tags.buffer, numbers.buffer, offsets.buffer, utf8.buffer]) {\n claimHolder(buffer);\n }\n }\n return {\n kind,\n size,\n offset: 0,\n values: null,\n tags: storage.tags,\n numbers: storage.numbers,\n offsets: storage.strings.offsets,\n utf8: storage.strings.utf8,\n };\n }\n default:\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${String(kind)}`, { kind });\n }\n}\n\n/**\n * The map of a gathered node space: `out.idOf(i) === map.idOf(indexMap[i])` (design section 7.3:\n * inducedSubgraph, relabel). The kind is re-detected from the gathered ids, so an identity map\n * gathered through a prefix stays identity and otherwise becomes dense or numeric per the rules of\n * design section 4.2. The caller guarantees indexMap has no repeats (a permutation or a selection),\n * so the result is a bijection without re-validation.\n * @param map - the source map\n * @param indexMap - new index -> source index; E_INDEX_RANGE when an entry is out of range\n * @returns the gathered map\n */\nexport function gatherNodeIdMap(map: NodeIdMap, indexMap: U32): NodeIdMap {\n const n = indexMap.length;\n const ids = new Array<NodeId>(n);\n for (let i = 0; i < n; i++) {\n ids[i] = map.idOf(indexMap[i]);\n }\n return nodeIdMapFromIds(ids, n, { validate: false });\n}\n\n/**\n * The map of a compacted node space: `out.idOf(remap[old]) === map.idOf(old)` for every old index\n * whose entry is not INVALID_INDEX (design sections 4.4 and 6.3 step 1). Every new index must be hit\n * exactly once.\n * @param map - the source map\n * @param remap - old index -> new index or INVALID_INDEX; length === map.size\n * @param newSize - the compacted node count\n * @returns the remapped map; E_INDEX_RANGE when remap is not a surjection onto [0, newSize)\n */\nexport function remapNodeIdMap(map: NodeIdMap, remap: U32, newSize: number): NodeIdMap {\n if (remap.length !== map.size) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `remap has ${remap.length} entries for ${map.size} ids`, {\n expected: map.size,\n found: remap.length,\n });\n }\n const ids = new Array<NodeId>(newSize);\n const seen = new Uint8Array(newSize);\n let filled = 0;\n for (let old = 0; old < remap.length; old++) {\n const target = remap[old];\n if (target === INVALID_INDEX) {\n continue;\n }\n if (target >= newSize || seen[target] === 1) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `remap entry ${target} at ${old} is out of range or repeated`, {\n index: target,\n size: newSize,\n });\n }\n seen[target] = 1;\n ids[target] = map.idOf(old);\n filled++;\n }\n if (filled !== newSize) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `remap fills ${filled} of ${newSize} new indices`, {\n filled,\n size: newSize,\n });\n }\n return nodeIdMapFromIds(ids, newSize, { validate: false });\n}\n","/**\n * The one resolver of graph-level metadata patches (design section 5.9), shared by the builder's\n * `setMeta` and by `fromCsr`: a GraphMetaPatch merged over the current metadata with the type rules\n * of every field -- strings, enums, a string list for keywords, a boolean or null for\n * declaredMultigraph, a ColumnOrigin for weightOrigin and a JSON object for extra. A field that is\n * `undefined` in the patch keeps the current value; `null` clears it. Every violation is\n * E_COLUMN_TYPE with `details.field`.\n */\n\nimport { resolveColumnMeta } from \"../columns/column.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type ColumnOrigin, type GraphMeta, type GraphMetaPatch } from \"../types/index.js\";\n\nconst ID_TYPES: ReadonlySet<\"string\" | \"integer\" | \"mixed\"> = new Set([\"string\", \"integer\", \"mixed\"] as const);\nconst TIME_FORMATS: ReadonlySet<\"integer\" | \"double\" | \"date\" | \"dateTime\"> = new Set([\n \"integer\",\n \"double\",\n \"date\",\n \"dateTime\",\n] as const);\nconst TIME_REPRESENTATIONS: ReadonlySet<\"interval\" | \"timestamp\"> = new Set([\"interval\", \"timestamp\"] as const);\nconst MODES: ReadonlySet<\"static\" | \"dynamic\" | \"slice\"> = new Set([\"static\", \"dynamic\", \"slice\"] as const);\n\n/**\n * A GraphMeta with every field null / empty (design section 5.9), for producers that have no\n * metadata and for tests.\n */\nexport const EMPTY_GRAPH_META: GraphMeta = Object.freeze({\n name: null,\n description: null,\n creator: null,\n created: null,\n modified: null,\n keywords: Object.freeze([]),\n sourceFormat: null,\n sourceVersion: null,\n idType: null,\n timeFormat: null,\n timeRepresentation: null,\n mode: null,\n declaredMultigraph: null,\n weightOrigin: null,\n extra: Object.freeze({}),\n});\n\n/**\n * The E_COLUMN_TYPE error for a metadata field of the wrong type.\n * @param field - the field\n * @param found - the value\n * @returns the error\n */\nfunction metaError(field: string, found: unknown): GraphFormatError {\n return new GraphFormatError(\"E_COLUMN_TYPE\", `meta.${field} has an unsupported value`, {\n field,\n found: typeof found,\n });\n}\n\n/**\n * An optional-string metadata field (the value is never undefined here).\n * @param field - the field name\n * @param value - the value\n * @returns the string or null\n */\nfunction metaString(field: string, value: unknown): string | null {\n if (value === null || typeof value === \"string\") {\n return value;\n }\n throw metaError(field, value);\n}\n\n/**\n * An enum-valued metadata field.\n * @param field - the field name\n * @param value - the value\n * @param allowed - the legal strings\n * @returns the value or null\n */\nfunction metaEnum<T extends string>(field: string, value: unknown, allowed: ReadonlySet<T>): T | null {\n if (value === null) {\n return null;\n }\n if (typeof value === \"string\" && allowed.has(value as T)) {\n return value as T;\n }\n throw metaError(field, value);\n}\n\n/**\n * The weightOrigin field as a complete ColumnOrigin.\n * @param value - the value\n * @returns the origin or null\n */\nfunction metaOrigin(value: unknown): ColumnOrigin | null {\n if (value === null) {\n return null;\n }\n if (typeof value !== \"object\") {\n throw metaError(\"weightOrigin\", value);\n }\n const input = value as Record<string, unknown>;\n const field = (name: string): string | null => {\n const v = input[name];\n if (v === undefined || v === null) {\n return null;\n }\n if (typeof v !== \"string\") {\n throw metaError(`weightOrigin.${name}`, v);\n }\n return v;\n };\n return Object.freeze({\n format: field(\"format\"),\n id: field(\"id\"),\n title: field(\"title\"),\n type: field(\"type\"),\n namespace: field(\"namespace\"),\n });\n}\n\n/**\n * Merge a metadata patch over the current metadata (design section 5.9): undefined fields keep the\n * current value, every other field is type-checked (E_COLUMN_TYPE with details.field).\n * @param current - the metadata before the patch\n * @param patch - the fields to set\n * @returns the merged metadata, frozen\n */\nexport function resolveGraphMeta(current: GraphMeta, patch: GraphMetaPatch): GraphMeta {\n const pick = <K extends keyof GraphMeta>(key: K, convert: (value: unknown) => GraphMeta[K]): GraphMeta[K] => {\n const value = patch[key];\n return value === undefined ? current[key] : convert(value);\n };\n return Object.freeze({\n name: pick(\"name\", (v) => metaString(\"name\", v)),\n description: pick(\"description\", (v) => metaString(\"description\", v)),\n creator: pick(\"creator\", (v) => metaString(\"creator\", v)),\n created: pick(\"created\", (v) => metaString(\"created\", v)),\n modified: pick(\"modified\", (v) => metaString(\"modified\", v)),\n keywords: pick(\"keywords\", (v) => {\n if (!Array.isArray(v) || v.some((k) => typeof k !== \"string\")) {\n throw metaError(\"keywords\", v);\n }\n return Object.freeze([...(v as string[])]);\n }),\n sourceFormat: pick(\"sourceFormat\", (v) => metaString(\"sourceFormat\", v)),\n sourceVersion: pick(\"sourceVersion\", (v) => metaString(\"sourceVersion\", v)),\n idType: pick(\"idType\", (v) => metaEnum(\"idType\", v, ID_TYPES)),\n timeFormat: pick(\"timeFormat\", (v) => metaEnum(\"timeFormat\", v, TIME_FORMATS)),\n timeRepresentation: pick(\"timeRepresentation\", (v) => metaEnum(\"timeRepresentation\", v, TIME_REPRESENTATIONS)),\n mode: pick(\"mode\", (v) => metaEnum(\"mode\", v, MODES)),\n declaredMultigraph: pick(\"declaredMultigraph\", (v) => {\n if (v === null || typeof v === \"boolean\") {\n return v;\n }\n throw metaError(\"declaredMultigraph\", v);\n }),\n weightOrigin: pick(\"weightOrigin\", (v) => metaOrigin(v)),\n extra: pick(\"extra\", (v) => {\n // the column resolver applies the JSON rules of design section 5.9 to `extra`\n const resolved = resolveColumnMeta(\"meta\", \"graph\", {\n dtype: \"json\",\n extra: v as Readonly<Record<string, unknown>>,\n });\n return resolved.extra;\n }),\n });\n}\n","/**\n * Growable typed staging for the builder (design section 6.2): structure-of-arrays typed arrays that\n * grow by doubling (capacity rounded up to 16 elements, backing buffers a multiple of 64 bytes) into\n * a resizable ArrayBuffer when the engine has one and by allocate-and-copy otherwise. The edge arrays\n * (src, dst, weight), the incidence lists, the per-declaration column data and the alive / weightSet /\n * validity bitmaps of the builder are all instances of the two classes here.\n *\n * Nothing a snapshot holds may alias staging (invariant I18): view() hands out a zero-copy window for\n * the freeze passes to read, and trim() produces the exact-length copy over a fresh fixed-length\n * buffer that a snapshot may keep.\n */\n\nimport { type TypedArrayData, type U32 } from \"../types/index.js\";\nimport {\n allocateStagingBuffer,\n growTypedArray,\n HAS_RESIZABLE_ARRAY_BUFFER,\n roundUp,\n STAGING_ELEMENT_GRANULE,\n stagingByteLength,\n type TypedArrayCtor,\n} from \"../util/typed-array.js\";\nimport { bitmapClearTrailing, bitmapCount, bitmapGet, bitmapSet, bitmapWordCount, bitmapWrite } from \"./bitmap.js\";\n\n/** Every bit set: the fill word of a range of whole words. */\nconst ALL_ONES = 0xffffffff;\n\n/** Construction options shared by GrowableTypedArray and GrowableBitmap. */\ninterface GrowableOptions {\n /** Initial capacity in elements (bits for a GrowableBitmap); defaults to 0, so the first push allocates. */\n readonly capacity?: number | undefined;\n /**\n * Whether backing buffers are resizable ArrayBuffers; defaults to the engine's HAS_RESIZABLE_ARRAY_BUFFER. Tests pass\n * false to exercise the allocate-and-copy path on an engine that has the feature.\n */\n readonly resizable?: boolean | undefined;\n}\n\n/**\n * A typed array that grows by doubling (design section 6.2). `length` is the number of elements in\n * use; `capacity` the allocated element count. Elements between length and capacity are unspecified\n * until written. Growth may replace the backing view object, so hot loops that cache `array` re-read\n * it after any call that can grow (push, pushAll, resize, ensureCapacity).\n */\nexport class GrowableTypedArray<T extends TypedArrayData> {\n private readonly ctor: TypedArrayCtor<T>;\n private readonly resizable: boolean;\n private backing: T;\n private used = 0;\n\n /**\n * Create an empty growable array.\n * @param ctor - the typed-array class of the elements (Uint32Array, Float32Array, ...)\n * @param options - initial capacity and buffer kind\n */\n constructor(ctor: TypedArrayCtor<T>, options?: GrowableOptions) {\n this.ctor = ctor;\n this.resizable = options?.resizable ?? HAS_RESIZABLE_ARRAY_BUFFER;\n this.backing = this.allocate(options?.capacity ?? 0);\n }\n\n /**\n * The number of elements in use.\n * @returns the length\n */\n get length(): number {\n return this.used;\n }\n\n /**\n * The allocated element count; growth happens when length would exceed it.\n * @returns the capacity\n */\n get capacity(): number {\n return this.backing.length;\n }\n\n /**\n * The backing view over the whole capacity, for hot loops that index it directly. Its identity\n * changes whenever the array grows.\n * @returns the backing typed array\n */\n get array(): T {\n return this.backing;\n }\n\n /**\n * Append one element.\n * @param value - the element\n * @returns the index it was written at (the old length)\n */\n push(value: number): number {\n const index = this.used;\n if (index >= this.backing.length) {\n this.backing = growTypedArray(this.backing, this.ctor, index + 1, this.resizable);\n }\n this.backing[index] = value;\n this.used = index + 1;\n return index;\n }\n\n /**\n * Append many elements at once (bulk addEdges input).\n * @param values - the elements, in order\n * @returns the index the first one was written at (the old length)\n */\n pushAll(values: ArrayLike<number>): number {\n const index = this.used;\n const end = index + values.length;\n this.ensureCapacity(end);\n this.backing.set(values, index);\n this.used = end;\n return index;\n }\n\n /**\n * Read element i.\n * @param i - the index, below length\n * @returns the element\n */\n get(i: number): number {\n return this.backing[i];\n }\n\n /**\n * Write element i.\n * @param i - the index, below length\n * @param value - the element\n */\n set(i: number, value: number): void {\n this.backing[i] = value;\n }\n\n /**\n * Make sure at least `n` elements fit without a further reallocation.\n * @param n - the capacity to guarantee\n */\n ensureCapacity(n: number): void {\n if (n > this.backing.length) {\n this.backing = growTypedArray(this.backing, this.ctor, n, this.resizable);\n }\n }\n\n /**\n * Set the length: growing fills the new elements with `fill` (the incidence lists grow with\n * INVALID_INDEX), shrinking drops the tail without releasing capacity.\n * @param length - the new length\n * @param fill - the value written into elements [old length, length); defaults to 0\n */\n resize(length: number, fill = 0): void {\n if (length > this.used) {\n this.ensureCapacity(length);\n this.backing.fill(fill, this.used, length);\n }\n this.used = length;\n }\n\n /**\n * A zero-copy window over the elements in use. It aliases staging, so it is for the freeze passes\n * to read from and never for a snapshot to keep (invariant I18); it is invalidated by growth.\n * @returns a view of exactly `length` elements\n */\n view(): T {\n return new this.ctor(this.backing.buffer, 0, this.used);\n }\n\n /**\n * An exact-length copy over a fresh fixed-length ArrayBuffer: what a snapshot may keep, and what a\n * compaction writes back through.\n * @returns a new typed array of `length` elements\n */\n trim(): T {\n const out = new this.ctor(new ArrayBuffer(this.used * this.ctor.BYTES_PER_ELEMENT), 0, this.used);\n out.set(this.view());\n return out;\n }\n\n /**\n * Drop every element but keep the capacity (a builder reused after a merging freeze).\n */\n clear(): void {\n this.used = 0;\n }\n\n /**\n * Drop the elements and the backing storage (freeze({ release: true }) and dispose(), design\n * section 6.1). The array is usable again afterwards; the next push allocates.\n */\n release(): void {\n this.used = 0;\n this.backing = this.allocate(0);\n }\n\n /**\n * Allocate a backing view of at least `capacity` elements over a fresh staging buffer.\n * @param capacity - the element count wanted; 0 allocates an empty view over an empty buffer\n * @returns the view\n */\n private allocate(capacity: number): T {\n const bytesPerElement = this.ctor.BYTES_PER_ELEMENT;\n const byteLength =\n capacity === 0 ? 0 : stagingByteLength(roundUp(capacity, STAGING_ELEMENT_GRANULE), bytesPerElement);\n return new this.ctor(allocateStagingBuffer(byteLength, this.resizable), 0, byteLength / bytesPerElement);\n }\n}\n\n/**\n * A growable packed bitmap (design section 6.2: nodeAlive, edgeAlive, weightSet and the validity of\n * every staging column), in the one LSB-first u32 layout of design section 5.3. `length` is in bits;\n * every bit at or above it is kept clear so view() and trim() are exact bitmaps over `length` bits.\n */\nexport class GrowableBitmap {\n private readonly words: GrowableTypedArray<U32>;\n private bits = 0;\n\n /**\n * Create an empty bitmap.\n * @param options - initial capacity in bits and buffer kind\n */\n constructor(options?: GrowableOptions) {\n this.words = new GrowableTypedArray<U32>(Uint32Array, {\n capacity: bitmapWordCount(options?.capacity ?? 0),\n resizable: options?.resizable,\n });\n }\n\n /**\n * The number of bits in use.\n * @returns the length in bits\n */\n get length(): number {\n return this.bits;\n }\n\n /**\n * Append one bit.\n * @param value - the bit\n * @returns the index it was written at (the old length)\n */\n push(value: boolean): number {\n const index = this.bits;\n if (index % 32 === 0) {\n this.words.push(0);\n }\n if (value) {\n bitmapWrite(this.words.array, index, true);\n }\n this.bits = index + 1;\n return index;\n }\n\n /**\n * Read bit i.\n * @param i - the bit index, below length\n * @returns true when set\n */\n get(i: number): boolean {\n return bitmapGet(this.words.array, i);\n }\n\n /**\n * Write bit i.\n * @param i - the bit index, below length\n * @param value - the bit\n */\n set(i: number, value: boolean): void {\n bitmapWrite(this.words.array, i, value);\n }\n\n /**\n * The number of set bits below length.\n * @returns the count\n */\n count(): number {\n return bitmapCount(this.words.array, this.bits);\n }\n\n /**\n * Set the length in bits: growing writes `fill` into the new bits, shrinking clears the dropped\n * bits so the trailing-bits-clear convention holds.\n * @param length - the new length in bits\n * @param fill - the value of bits [old length, length); defaults to false\n */\n resize(length: number, fill = false): void {\n const oldBits = this.bits;\n this.words.resize(bitmapWordCount(length), 0);\n if (length < oldBits) {\n bitmapClearTrailing(this.words.array, length);\n } else if (fill && length > oldBits) {\n this.setRange(oldBits, length);\n }\n this.bits = length;\n }\n\n /**\n * Set every bit in [from, to): the ragged head and tail bit by bit, the whole words in between\n * with one fill.\n * @param from - the first bit to set\n * @param to - one past the last bit to set\n */\n private setRange(from: number, to: number): void {\n const { array } = this.words;\n let i = from;\n while (i < to && i % 32 !== 0) {\n bitmapSet(array, i++);\n }\n const fullEnd = to - (to % 32);\n if (i < fullEnd) {\n array.fill(ALL_ONES, i / 32, fullEnd / 32);\n i = fullEnd;\n }\n while (i < to) {\n bitmapSet(array, i++);\n }\n }\n\n /**\n * A zero-copy window over the ceil(length / 32) words in use; aliases staging (invariant I18) and\n * is invalidated by growth.\n * @returns the words\n */\n view(): U32 {\n return this.words.view();\n }\n\n /**\n * An exact copy of the words in use over a fresh fixed-length ArrayBuffer: a validity bitmap or a\n * bool column's data a snapshot may keep.\n * @returns a new U32 of ceil(length / 32) words\n */\n trim(): U32 {\n return this.words.trim();\n }\n\n /**\n * Drop every bit but keep the capacity.\n */\n clear(): void {\n this.bits = 0;\n this.words.clear();\n }\n\n /**\n * Drop the bits and the backing storage.\n */\n release(): void {\n this.bits = 0;\n this.words.release();\n }\n}\n","/**\n * The builder's staging representation and its compaction (design sections 6.2 and 6.3 step 1).\n *\n * Staging is structure-of-arrays typed storage that grows by doubling: the node side (`ids`,\n * `idToIndex`, `nodeAlive`, the incidence-list heads `firstOut` / `firstIn`), the edge side (`src`,\n * `dst`, `weight`, `weightSet`, `edgeAlive`, the incidence-list links `nextOut` / `nextIn`), the live\n * counts, and one `StagingColumn` per declared node / edge / extension column (a growable typed array,\n * packed bitmap or JS array plus an optional validity bitmap and, for dict columns, an interning\n * dictionary). No per-node or per-edge object is ever allocated.\n *\n * Compaction (`compactStaging`) gathers a NEW staging object through node and edge remaps assigned in\n * index order (invariant I14): tombstoned nodes and edges disappear, `refersTo` column values are\n * rewritten (dangling references become INVALID_INDEX with the row unset), fresh `ids` / `idToIndex`\n * objects are built so the previous snapshot keeps the ones it shares (design section 4.2), and the\n * incidence lists are rebuilt. The source staging is never modified, so a freeze that throws after\n * compacting leaves the builder exactly as it was (design section 11.1); the builder commits the new\n * staging only when the freeze succeeds.\n */\n\nimport { bitmapClear, bitmapGet, bitmapWordCount, makeBitmap } from \"../columns/bitmap.js\";\nimport {\n allocNumeric,\n assertJsonValue,\n columnOfValues,\n createColumn,\n isArrayLikeNumbers,\n metaToDecl,\n representableNumber,\n resolveColumnMeta,\n seedDictionary,\n} from \"../columns/column.js\";\nimport { assertWellFormedString, DictionaryBuilder } from \"../columns/dictionary.js\";\nimport { GrowableBitmap, GrowableTypedArray } from \"../columns/growable.js\";\nimport { coerceValue, DtypeInferrer, type InferredDtype, inferValueDtype } from \"../columns/infer.js\";\nimport { INVALID_INDEX } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { detachString } from \"../ids/string-store.js\";\nimport {\n type Column,\n type ColumnDeclPatch,\n type ColumnDomain,\n type ColumnMeta,\n type Dtype,\n type NodeId,\n type ScalarDtype,\n type TypedArrayData,\n type U32,\n} from \"../types/index.js\";\nimport { type MutableColumnParts } from \"../types/internal.js\";\n\n// ============================================================ small helpers\n\n/** The shared, frozen empty list every unset / unwritten list row points at. */\nconst EMPTY_LIST: readonly unknown[] = Object.freeze([]);\n\n/**\n * The E_COLUMN_TYPE error for a value a column cannot hold.\n * @param meta - the column\n * @param row - the row\n * @param message - what is wrong\n * @param found - the offending value's type or shape\n * @returns the error\n */\nfunction cellError(meta: ColumnMeta, row: number, message: string, found: unknown): GraphFormatError {\n return new GraphFormatError(\"E_COLUMN_TYPE\", `row ${row} of ${meta.dtype} column \"${meta.name}\": ${message}`, {\n column: meta.name,\n domain: meta.domain,\n row,\n found,\n });\n}\n\n/**\n * The dtype an inferred (auto-declared) column starts with for a value (design section 5.1).\n * @param value - the first set value\n * @returns the inferred dtype; E_COLUMN_TYPE for a value no column can hold\n */\nexport function inferInitialDtype(value: unknown): InferredDtype {\n const dtype = inferValueDtype(value);\n if (dtype === null) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", \"an unset value cannot start an inferred column\", {\n reason: \"unset\",\n });\n }\n return dtype;\n}\n\n/**\n * The position of a dtype in the widening order of design section 5.1, for the union rule of\n * `addGraph()` (design section 6.6): the dtypes outside the inference order map to the narrowest\n * inferred dtype that can hold every value of theirs.\n * @param dtype - any dtype\n * @returns the inferred dtype the column widens to when it must hold values of `dtype`\n */\nexport function inferredEquivalent(dtype: Dtype): InferredDtype {\n switch (dtype) {\n case \"bool\":\n return \"bool\";\n case \"i32\":\n case \"u8\":\n return \"i32\";\n case \"u32\":\n case \"f32\":\n case \"f64\":\n return \"f64\";\n case \"dict\":\n case \"string\":\n return \"string\";\n case \"list\":\n case \"json\":\n return \"json\";\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Check one list item against the child dtype of a list column at write time, so a bad item fails\n * at the call that supplied it rather than at freeze.\n * @param meta - the list column\n * @param row - the row\n * @param item - the item\n */\nfunction checkListItem(meta: ColumnMeta, row: number, item: unknown): void {\n const itemDtype = meta.itemDtype as ScalarDtype;\n const components = meta.itemComponents ?? 1;\n switch (itemDtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n if (components === 1) {\n if (typeof item !== \"number\" || !representableNumber(itemDtype, item)) {\n throw cellError(meta, row, `list item is not a representable ${itemDtype}`, typeof item);\n }\n return;\n }\n if (!Array.isArray(item) || item.length !== components) {\n throw cellError(meta, row, `list item is not ${components} numbers`, typeof item);\n }\n for (const k of item as unknown[]) {\n if (typeof k !== \"number\" || !representableNumber(itemDtype, k)) {\n throw cellError(meta, row, `list item component is not a representable ${itemDtype}`, typeof k);\n }\n }\n return;\n }\n case \"bool\":\n if (typeof item !== \"boolean\") {\n throw cellError(meta, row, \"list item is not a boolean\", typeof item);\n }\n return;\n case \"dict\":\n case \"string\":\n if (typeof item !== \"string\") {\n throw cellError(meta, row, \"list item is not a string\", typeof item);\n }\n assertWellFormedString(item, { column: meta.name, row });\n return;\n case \"json\":\n assertJsonValue(item, meta.name);\n return;\n default: {\n const name: string = itemDtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n// ============================================================ staging columns\n\n/** The widening a write caused on an inferred column. */\ninterface WideningStep {\n /** The dtype before. */\n readonly from: Dtype;\n /** The dtype after. */\n readonly to: Dtype;\n}\n\n/**\n * One growable column of the builder (design section 6.2).\n *\n * A DECLARED column stores values in the storage of its dtype (a growable typed array for the numeric\n * dtypes and dict codes, a growable bitmap for bool, a JS array for string / list / json) plus an\n * optional validity bitmap and, for dict columns, the interning dictionary; rows are materialised\n * lazily up to `length` and unset rows physically hold the fill (design section 5.3). It never widens\n * and rejects values it cannot hold with E_COLUMN_TYPE at the write.\n *\n * An INFERRED column (auto-declared by a string column name in `setNodeValue` / `addNodeRecord`, or\n * a declared column widened by the union rule of `addGraph`) keeps the values exactly as written in a\n * JS array and widens its dtype monotonically per design section 5.1 as wider values arrive; the\n * values are coerced ONCE, at freeze, to the final dtype (bool -> 1 / 0 in a number column, number or\n * boolean -> its canonical text in a string column), exactly as `fromRecords` would.\n */\nexport class StagingColumn {\n /** The resolved metadata; replaced when an inferred column widens. */\n meta: ColumnMeta;\n\n /** Rows materialised so far. */\n length = 0;\n\n /** Declared numeric data (rows * components) or dict codes. */\n typed: GrowableTypedArray<TypedArrayData> | null = null;\n\n /** Declared bool data. */\n bits: GrowableBitmap | null = null;\n\n /** Declared string / list / json rows, or the raw values of an inferred column. */\n values: unknown[] | null = null;\n\n /** dict only: the interning dictionary. */\n dictionary: DictionaryBuilder | null = null;\n\n /** The validity bitmap; null for a non-nullable column. */\n validity: GrowableBitmap | null = null;\n\n private inferrer: DtypeInferrer | null;\n\n private readonly resizable: boolean | undefined;\n\n /**\n * Create an empty column.\n * @param meta - the resolved metadata\n * @param inferred - whether the column stages raw values and may widen\n * @param resizable - the staging buffer kind (tests pass false); undefined = engine default\n * @param dictionary - an existing dictionary to share (compaction); a fresh one when omitted\n */\n constructor(meta: ColumnMeta, inferred: boolean, resizable?: boolean, dictionary?: DictionaryBuilder) {\n this.meta = meta;\n this.resizable = resizable;\n if (inferred) {\n this.inferrer = new DtypeInferrer();\n this.inferrer.widenTo(inferredEquivalent(meta.dtype));\n } else {\n this.inferrer = null;\n }\n this.allocate(dictionary);\n }\n\n /**\n * Whether the column stages raw values and may widen.\n * @returns true for an inferred column\n */\n get inferred(): boolean {\n return this.inferrer !== null;\n }\n\n /**\n * The inferred dtype of an inferred column, or null.\n * @returns the current inferred dtype\n */\n get inferredDtype(): InferredDtype | null {\n return this.inferrer === null ? null : this.inferrer.dtype;\n }\n\n /**\n * Make at least `rows` rows exist, unset (when nullable) and holding the fill.\n * @param rows - the row count to reach\n */\n ensureLength(rows: number): void {\n if (rows <= this.length) {\n return;\n }\n const { meta } = this;\n if (this.typed !== null) {\n this.typed.resize(rows * meta.components, this.fillNumber());\n } else if (this.bits !== null) {\n this.bits.resize(rows, meta.fill === true);\n } else if (this.values !== null) {\n const fill = this.fillValue();\n for (let row = this.length; row < rows; row++) {\n this.values.push(fill);\n }\n }\n if (this.validity !== null) {\n this.validity.resize(rows, false);\n }\n this.length = rows;\n }\n\n /**\n * Whether a row holds a value.\n * @param row - the row\n * @returns true when set (non-nullable columns: when materialised)\n */\n isSet(row: number): boolean {\n if (row >= this.length) {\n return false;\n }\n return this.validity === null || this.validity.get(row);\n }\n\n /**\n * Set one cell (design sections 5.1 and 6.6). `undefined` unsets the row, and so does `null`\n * except on a declared json column (JSON null imports as unset, design section 5.3). An inferred\n * column widens when the value is wider than its dtype; the widening is returned so the builder\n * can report it.\n * @param row - the row; rows below it are materialised\n * @param value - the value\n * @returns the widening that took place, or null\n */\n write(row: number, value: unknown): WideningStep | null {\n this.ensureLength(row + 1);\n if (value === undefined || (value === null && (this.inferrer !== null || this.meta.dtype !== \"json\"))) {\n this.unset(row);\n return null;\n }\n let widened: WideningStep | null = null;\n if (this.inferrer !== null) {\n const before = this.meta.dtype;\n if (this.inferrer.observeValue(value)) {\n const next = this.inferrer.dtype as InferredDtype;\n this.widenTo(next);\n widened = { from: before, to: next };\n }\n this.storeRaw(row, value);\n } else {\n this.store(row, value);\n }\n if (this.validity !== null) {\n this.validity.set(row, true);\n }\n return widened;\n }\n\n /**\n * Validate a value exactly as `write` would, without writing anything: the same E_COLUMN_TYPE\n * errors for a value the column cannot hold (a non-representable number, a lone surrogate, a\n * non-JSON object, an unset value on a non-nullable column). The record methods of the builder\n * validate every attribute before they apply anything (design section 11.1).\n * @param row - the row the value is meant for (error details only)\n * @param value - the value\n */\n checkValue(row: number, value: unknown): void {\n if (value === undefined || (value === null && (this.inferrer !== null || this.meta.dtype !== \"json\"))) {\n if (this.validity === null) {\n throw this.unsetError(row);\n }\n return;\n }\n if (this.inferrer !== null) {\n inferValueDtype(value);\n this.checkRaw(row, value);\n return;\n }\n this.coerce(row, value);\n }\n\n /**\n * Unset one cell: the validity bit is cleared and the fill is written back (design section 5.3).\n * @param row - the row; E_COLUMN_TYPE on a non-nullable column\n */\n unset(row: number): void {\n this.ensureLength(row + 1);\n if (this.validity === null) {\n throw this.unsetError(row);\n }\n this.validity.set(row, false);\n this.writeFill(row);\n }\n\n /**\n * The E_COLUMN_TYPE error for unsetting a row of a non-nullable column.\n * @param row - the row\n * @returns the error\n */\n private unsetError(row: number): GraphFormatError {\n return new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `row ${row} of non-nullable column \"${this.meta.name}\" cannot be unset`,\n { column: this.meta.name, row, field: \"nullable\" },\n );\n }\n\n /**\n * The JS value of one cell as the frozen column would hold it: a number (or an array of\n * `components` numbers), a boolean, a string, a list or a json value; undefined for an unset or\n * unmaterialised row. An inferred column's raw value is coerced to its current dtype.\n * @param row - the row\n * @returns the value\n */\n read(row: number): unknown {\n if (!this.isSet(row)) {\n return undefined;\n }\n if (this.inferrer !== null) {\n return coerceValue((this.values as unknown[])[row], this.inferrer.dtype as InferredDtype);\n }\n const { meta } = this;\n const { dtype, components } = meta;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n const typed = this.typed as GrowableTypedArray<TypedArrayData>;\n if (components === 1) {\n return typed.get(row);\n }\n const out = new Array<number>(components);\n for (let k = 0; k < components; k++) {\n out[k] = typed.get(row * components + k);\n }\n return out;\n }\n case \"bool\":\n return (this.bits as GrowableBitmap).get(row);\n case \"dict\": {\n const code = (this.typed as GrowableTypedArray<TypedArrayData>).get(row);\n return (this.dictionary as DictionaryBuilder).values[code];\n }\n case \"string\":\n case \"list\":\n case \"json\":\n return (this.values as unknown[])[row];\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n }\n\n /**\n * Widen the column to a wider dtype of the design section 5.1 order. An inferred column only\n * changes its dtype (its raw values are coerced at freeze); a declared column becomes inferred:\n * its current values are read out and kept as raw values from then on.\n * @param next - the dtype to widen to\n */\n widenTo(next: InferredDtype): void {\n const { meta } = this;\n const nextMeta = resolveColumnMeta(meta.name, meta.domain, {\n dtype: next,\n nullable: true,\n role: meta.role ?? undefined,\n extra: meta.extra,\n });\n if (this.inferrer !== null) {\n this.inferrer.widenTo(next);\n this.meta = nextMeta;\n return;\n }\n const rows = this.length;\n const raw = new Array<unknown>(rows);\n const validity = new GrowableBitmap({ capacity: rows, resizable: this.resizable });\n validity.resize(rows, false);\n for (let row = 0; row < rows; row++) {\n if (this.isSet(row)) {\n raw[row] = this.read(row);\n validity.set(row, true);\n }\n }\n this.meta = nextMeta;\n this.inferrer = new DtypeInferrer();\n this.inferrer.widenTo(next);\n this.typed = null;\n this.bits = null;\n this.dictionary = null;\n this.values = raw;\n this.validity = validity;\n }\n\n /**\n * A new column of the same shape holding the rows `indexMap` selects (`out[i] = this[indexMap[i]]`),\n * or every row in order when `indexMap` is null, with `refersTo` values rewritten through\n * `valueRemap` when given: an in-range value maps to its new index and a dangling reference\n * becomes INVALID_INDEX with the row unset (for a list, dangling items are dropped and a row whose\n * every item dangled becomes unset and empty). The dictionary of a dict column is shared.\n * @param indexMap - new row -> old row, or null to keep every row\n * @param valueRemap - the remap of the space the values reference, or null\n * @returns the gathered column\n */\n gather(indexMap: U32 | null, valueRemap: U32 | null): StagingColumn {\n const rows = indexMap === null ? this.length : indexMap.length;\n const out = new StagingColumn(this.meta, this.inferred, this.resizable, this.dictionary ?? undefined);\n out.ensureLength(rows);\n const { components } = this.meta;\n const rewrite = valueRemap !== null && this.meta.refersTo !== null;\n for (let i = 0; i < rows; i++) {\n const old = indexMap === null ? i : indexMap[i];\n if (!this.isSet(old)) {\n continue;\n }\n if (out.typed !== null && this.typed !== null) {\n if (rewrite) {\n const mapped = remapIndex(this.typed.get(old), valueRemap);\n if (mapped === INVALID_INDEX) {\n // dangling reference: INVALID_INDEX (the fill of a refersTo column) with the row unset\n out.unsetDangling(i);\n continue;\n }\n out.typed.set(i, mapped);\n } else {\n for (let k = 0; k < components; k++) {\n out.typed.set(i * components + k, this.typed.get(old * components + k));\n }\n }\n } else if (out.bits !== null && this.bits !== null) {\n out.bits.set(i, this.bits.get(old));\n } else if (out.values !== null && this.values !== null) {\n let value = this.values[old];\n if (rewrite) {\n const items = value as readonly number[];\n const kept: number[] = [];\n for (const item of items) {\n const mapped = remapIndex(item, valueRemap);\n if (mapped !== INVALID_INDEX) {\n kept.push(mapped);\n }\n }\n if (kept.length === 0 && items.length > 0) {\n out.unsetDangling(i);\n continue;\n }\n value = kept;\n }\n out.values[i] = value;\n }\n if (out.validity !== null) {\n out.validity.set(i, true);\n }\n }\n return out;\n }\n\n /**\n * Leave row `i` of a gathered column unset because its reference dangled (design section 5.11).\n * A non-nullable column gains a validity bitmap and becomes nullable (invariant I12 forbids a set\n * row holding INVALID_INDEX; `remapColumn` flips `nullable` the same way): every earlier row is\n * marked set except a scalar reference row still holding the INVALID_INDEX fill.\n * @param i - the row being gathered; rows below it are already gathered\n */\n private unsetDangling(i: number): void {\n if (this.validity !== null) {\n return;\n }\n const { meta } = this;\n this.meta = resolveColumnMeta(meta.name, meta.domain, { ...metaToDecl(meta), nullable: true });\n const validity = new GrowableBitmap({ capacity: this.length, resizable: this.resizable });\n validity.resize(this.length, false);\n const { typed } = this;\n for (let row = 0; row < i; row++) {\n if (typed === null || typed.get(row) !== INVALID_INDEX) {\n validity.set(row, true);\n }\n }\n this.validity = validity;\n }\n\n /**\n * Freeze the column into `rows` rows (design section 6.3 step 10): typed data is copied out of\n * staging into exact-length buffers (invariant I18), the validity bitmap is copied (and dropped when\n * every row is set), a dict dictionary is copied so the snapshot's column never changes (I17), and\n * string / list / json rows and the raw values of an inferred column go through the column factory,\n * which coerces them to the final dtype.\n * @param rows - the row count of the table\n * @returns the frozen column\n */\n toColumn(rows: number): Column {\n this.ensureLength(rows);\n const { meta } = this;\n const { dtype, components } = meta;\n if (this.inferrer !== null) {\n const source = this.values as unknown[];\n const entries = new Array<unknown>(rows);\n for (let row = 0; row < rows; row++) {\n entries[row] = this.isSet(row) ? source[row] : undefined;\n }\n return columnOfValues(meta, entries);\n }\n let validity: U32 | null = null;\n if (this.validity !== null && this.validity.count() !== rows) {\n validity = this.validity.trim();\n }\n const parts: MutableColumnParts = {\n meta,\n length: rows,\n data: null,\n validity,\n nullCount: validity === null ? 0 : rows - (this.validity as GrowableBitmap).count(),\n dictionary: null,\n offsets: null,\n utf8: null,\n strings: null,\n child: null,\n values: null,\n };\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n const data = allocNumeric(dtype, rows * components);\n data.set((this.typed as GrowableTypedArray<TypedArrayData>).view().subarray(0, rows * components));\n parts.data = data;\n if (meta.refersTo !== null && this.validity === null) {\n unsetFillReferences(parts, data as U32, rows);\n }\n return createColumn(parts);\n }\n case \"bool\":\n parts.data = (this.bits as GrowableBitmap).trim();\n return createColumn(parts);\n case \"dict\": {\n const codes = new Uint32Array(rows);\n codes.set((this.typed as GrowableTypedArray<TypedArrayData>).view().subarray(0, rows));\n parts.data = codes;\n parts.dictionary = [...(this.dictionary as DictionaryBuilder).values];\n return createColumn(parts);\n }\n case \"string\":\n case \"list\":\n case \"json\": {\n const source = this.values as unknown[];\n const entries = new Array<unknown>(rows);\n for (let row = 0; row < rows; row++) {\n const value = this.isSet(row) ? source[row] : undefined;\n entries[row] = value === undefined ? this.unsetEntry() : value;\n }\n return columnOfValues(meta, entries);\n }\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n }\n\n /**\n * Bytes of typed staging held by the column (JS arrays are not counted).\n * @returns the byte count\n */\n byteLength(): number {\n let bytes = 0;\n if (this.typed !== null) {\n bytes += this.typed.array.byteLength;\n }\n if (this.bits !== null) {\n bytes += bitmapWordCount(this.bits.length) * 4;\n }\n if (this.validity !== null) {\n bytes += bitmapWordCount(this.validity.length) * 4;\n }\n return bytes;\n }\n\n /**\n * Allocate the storage of the current dtype (raw values for an inferred column).\n * @param dictionary - a dictionary to share, or undefined for a fresh seeded one\n */\n private allocate(dictionary: DictionaryBuilder | undefined): void {\n const { meta } = this;\n const { dtype } = meta;\n const options = { resizable: this.resizable };\n if (this.inferrer !== null) {\n this.values = [];\n this.validity = new GrowableBitmap(options);\n return;\n }\n switch (dtype) {\n case \"f32\":\n this.typed = new GrowableTypedArray(Float32Array, options);\n break;\n case \"f64\":\n this.typed = new GrowableTypedArray(Float64Array, options);\n break;\n case \"i32\":\n this.typed = new GrowableTypedArray(Int32Array, options);\n break;\n case \"u32\":\n this.typed = new GrowableTypedArray(Uint32Array, options);\n break;\n case \"u8\":\n this.typed = new GrowableTypedArray(Uint8Array, options);\n break;\n case \"bool\":\n this.bits = new GrowableBitmap(options);\n break;\n case \"dict\": {\n this.typed = new GrowableTypedArray(Uint32Array, options);\n this.dictionary = dictionary ?? seedDictionary(meta);\n break;\n }\n case \"string\":\n case \"list\":\n case \"json\":\n this.values = [];\n break;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n this.validity = meta.nullable ? new GrowableBitmap(options) : null;\n }\n\n /**\n * The number written into unset numeric rows (the dict fill code for dict columns).\n * @returns the fill\n */\n private fillNumber(): number {\n const { meta } = this;\n if (meta.dtype === \"dict\") {\n const dictionary = this.dictionary as DictionaryBuilder;\n const text = typeof meta.fill === \"string\" ? meta.fill : \"\";\n if (this.validity === null) {\n // a set row holding the fill needs a member's code: the nominal \"\" is interned on demand\n return dictionary.intern(text);\n }\n const code = dictionary.codeOf(text);\n return code === INVALID_INDEX ? 0 : code;\n }\n return typeof meta.fill === \"number\" ? meta.fill : 0;\n }\n\n /**\n * The JS value stored in unset rows of a JS-array column (undefined for an inferred column).\n * @returns the fill\n */\n private fillValue(): unknown {\n if (this.inferrer !== null) {\n return undefined;\n }\n switch (this.meta.dtype) {\n case \"string\":\n return typeof this.meta.fill === \"string\" ? this.meta.fill : \"\";\n case \"list\":\n return EMPTY_LIST;\n default:\n return undefined;\n }\n }\n\n /**\n * The entry handed to the column factory for an unset row of a declared JS-array column:\n * undefined for a nullable column, the fill for a non-nullable one (json: null, the one JSON value\n * that means \"nothing\").\n * @returns the entry\n */\n private unsetEntry(): unknown {\n if (this.meta.nullable) {\n return undefined;\n }\n return this.meta.dtype === \"json\" ? null : this.fillValue();\n }\n\n private writeFill(row: number): void {\n const { components } = this.meta;\n if (this.typed !== null) {\n const fill = this.fillNumber();\n for (let k = 0; k < components; k++) {\n this.typed.set(row * components + k, fill);\n }\n } else if (this.bits !== null) {\n this.bits.set(row, this.meta.fill === true);\n } else if (this.values !== null) {\n this.values[row] = this.fillValue();\n }\n }\n\n /**\n * Keep a raw value on an inferred column after checking it is storable at all (a json value must\n * be JSON; a string must be well-formed).\n * @param row - the row\n * @param value - the value as written\n */\n private storeRaw(row: number, value: unknown): void {\n this.checkRaw(row, value);\n (this.values as unknown[])[row] = typeof value === \"string\" ? detachString(value) : value;\n }\n\n /**\n * The checks of storeRaw: a string must be well-formed, an object must be JSON.\n * @param row - the row\n * @param value - the value as written\n */\n private checkRaw(row: number, value: unknown): void {\n const { meta } = this;\n if (typeof value === \"string\") {\n assertWellFormedString(value, { column: meta.name, row });\n } else if (typeof value === \"object\") {\n assertJsonValue(value, `${meta.name}[${row}]`);\n }\n }\n\n /**\n * Store a value on a declared column: validate and normalise it (E_COLUMN_TYPE when the column\n * cannot hold it), then write the normalised form.\n * @param row - the row\n * @param value - the value\n */\n private store(row: number, value: unknown): void {\n this.put(row, this.coerce(row, value));\n }\n\n /**\n * Validate a value against a declared column's dtype and return the form `put` writes: a number\n * or an array of `components` numbers, a boolean, a string, a copied list, or a JSON value.\n * @param row - the row (error details only)\n * @param value - the value\n * @returns the normalised value\n */\n private coerce(row: number, value: unknown): unknown {\n const { meta } = this;\n const { dtype, components } = meta;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n const scalar = typeof value === \"boolean\" ? Number(value) : value;\n if (typeof scalar === \"number\") {\n if (!representableNumber(dtype, scalar)) {\n throw cellError(meta, row, `${scalar} is not representable`, scalar);\n }\n return scalar;\n }\n if (components === 1 || !isArrayLikeNumbers(scalar, components)) {\n throw cellError(meta, row, `not ${components} number(s)`, typeof scalar);\n }\n for (let k = 0; k < components; k++) {\n if (!representableNumber(dtype, scalar[k])) {\n throw cellError(meta, row, `${scalar[k]} is not representable`, scalar[k]);\n }\n }\n return scalar;\n }\n case \"bool\":\n return coerceValue(value, \"bool\") === true;\n case \"dict\":\n case \"string\": {\n const text = coerceValue(value, \"string\");\n if (typeof text !== \"string\") {\n throw cellError(meta, row, \"not a string\", typeof value);\n }\n assertWellFormedString(text, { column: meta.name, row });\n return detachString(text);\n }\n case \"list\": {\n if (!Array.isArray(value)) {\n throw cellError(meta, row, \"not an array\", typeof value);\n }\n for (const item of value as unknown[]) {\n checkListItem(meta, row, item);\n }\n return (value as unknown[]).map((item) => (typeof item === \"string\" ? detachString(item) : item));\n }\n case \"json\":\n assertJsonValue(value, `${meta.name}[${row}]`);\n return value;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n }\n\n /**\n * Write a value `coerce` returned.\n * @param row - the row\n * @param value - the normalised value\n */\n private put(row: number, value: unknown): void {\n const { dtype, components } = this.meta;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n const typed = this.typed as GrowableTypedArray<TypedArrayData>;\n if (typeof value === \"number\") {\n if (components === 1) {\n typed.set(row, value);\n } else {\n for (let k = 0; k < components; k++) {\n typed.set(row * components + k, value);\n }\n }\n return;\n }\n const vector = value as ArrayLike<number>;\n for (let k = 0; k < components; k++) {\n typed.set(row * components + k, vector[k]);\n }\n return;\n }\n case \"bool\":\n (this.bits as GrowableBitmap).set(row, value === true);\n return;\n case \"dict\":\n (this.typed as GrowableTypedArray<TypedArrayData>).set(\n row,\n (this.dictionary as DictionaryBuilder).intern(value as string),\n );\n return;\n case \"string\":\n case \"list\":\n case \"json\":\n (this.values as unknown[])[row] = value;\n return;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n }\n}\n\n/**\n * Map an index-valued cell through a remap: in range and alive -> the new index; otherwise INVALID_INDEX.\n * @param value - the old index\n * @param remap - old -> new or INVALID_INDEX\n * @returns the new index or INVALID_INDEX\n */\nfunction remapIndex(value: number, remap: U32): number {\n return value < remap.length ? remap[value] : INVALID_INDEX;\n}\n\n/**\n * The frozen form of a non-nullable scalar `refersTo` column whose rows were never all written: the\n * unwritten rows still hold the INVALID_INDEX fill, and a SET row holding INVALID_INDEX violates\n * invariant I12, so the frozen column becomes nullable with exactly those rows unset (the rule of\n * `gather` for a dangling reference and of `remapColumn`; design sections 5.11 and 6.3, the builder\n * establishes I1-I13 by construction). The builder's own declaration is left alone. A column whose\n * every row holds an index is returned as declared.\n * @param parts - the parts being assembled; `meta`, `validity` and `nullCount` are replaced when needed\n * @param data - the frozen u32 data (stride 1: refersTo requires a scalar u32)\n * @param rows - the row count\n */\nfunction unsetFillReferences(parts: MutableColumnParts, data: U32, rows: number): void {\n let validity: U32 | null = null;\n for (let row = 0; row < rows; row++) {\n if (data[row] === INVALID_INDEX) {\n validity ??= makeBitmap(rows, true);\n bitmapClear(validity, row);\n parts.nullCount++;\n }\n }\n if (validity !== null) {\n const { meta } = parts;\n parts.meta = resolveColumnMeta(meta.name, meta.domain, { ...metaToDecl(meta), nullable: true });\n parts.validity = validity;\n }\n}\n\n/**\n * Create a staging column from a declaration patch.\n * @param name - the column name\n * @param domain - the table\n * @param decl - the declaration; dtype required\n * @param inferred - whether the column may widen\n * @param resizable - the staging buffer kind\n * @returns the column\n */\nexport function createStagingColumn(\n name: string,\n domain: ColumnDomain,\n decl: ColumnDeclPatch,\n inferred: boolean,\n resizable?: boolean,\n): StagingColumn {\n return new StagingColumn(resolveColumnMeta(name, domain, decl), inferred, resizable);\n}\n\n// ============================================================ extension tables\n\n/** One extension table under construction (design section 5.10). */\nexport interface ExtensionStaging {\n /** The table name. */\n readonly name: string;\n /** Its columns in declaration order. */\n readonly columns: StagingColumn[];\n /** Rows appended so far. */\n rowCount: number;\n}\n\n// ============================================================ staging\n\n/** Construction options of a Staging. */\ninterface StagingOptions {\n /** Staging weight precision (design section 3.7). */\n readonly weightDtype: \"f32\" | \"f64\";\n /** Allocate the weight array up front (`weighted: true`). */\n readonly weighted: boolean;\n /** Node capacity hint. */\n readonly expectedNodes: number | null;\n /** Edge capacity hint. */\n readonly expectedEdges: number | null;\n /** The staging buffer kind; undefined = engine default. */\n readonly resizable: boolean | undefined;\n}\n\n/**\n * Whether every edge so far agreed on supplying or omitting its weight (design section 3.7): the\n * `weightSet` bitmap is only allocated once they disagree (\"mixed\").\n */\ntype WeightMode = \"none\" | \"explicit\" | \"omitted\" | \"mixed\";\n\n/**\n * The staging of one builder (design section 6.2). Plain growable storage plus the push and link\n * primitives; every rule (id validation, policies, error codes) lives in the builder.\n */\nexport class Staging {\n /** The staging options. */\n readonly options: StagingOptions;\n\n /** The ids in index order, or null while every node is anonymous (id === index). */\n ids: NodeId[] | null = null;\n\n /** id -> index, shared by reference with frozen snapshots; null while every node is anonymous. */\n idToIndex: Map<NodeId, number> | null = null;\n\n /** Bit i set: node i is live. */\n readonly nodeAlive: GrowableBitmap;\n\n /** Head of the out-list of every node (an edge index), INVALID_INDEX = empty. */\n readonly firstOut: GrowableTypedArray<U32>;\n\n /** Head of the in-list of every node. */\n readonly firstIn: GrowableTypedArray<U32>;\n\n /** Declared source of every edge. */\n readonly src: GrowableTypedArray<U32>;\n\n /** Declared target of every edge. */\n readonly dst: GrowableTypedArray<U32>;\n\n /** Per-edge weights (f32 or f64 per weightDtype), or null while unweighted. */\n weight: GrowableTypedArray<TypedArrayData> | null = null;\n\n /** Bit e set: edge e's weight was supplied explicitly; null while every edge agrees. */\n weightSet: GrowableBitmap | null = null;\n\n /** Whether edges so far supplied, omitted, or disagreed about their weight. */\n weightMode: WeightMode = \"none\";\n\n /** Bit e set: edge e is live. */\n readonly edgeAlive: GrowableBitmap;\n\n /** Next edge in the out-list of the source of every edge. */\n readonly nextOut: GrowableTypedArray<U32>;\n\n /** Next edge in the in-list of the target of every edge. */\n readonly nextIn: GrowableTypedArray<U32>;\n\n /** Live node count. */\n liveNodeCount = 0;\n\n /** Live edge count. */\n liveEdgeCount = 0;\n\n /** Live self-loop count. */\n selfLoopCount = 0;\n\n /** Node columns in handle order. */\n nodeColumns: StagingColumn[] = [];\n\n /** Edge columns in handle order. */\n edgeColumns: StagingColumn[] = [];\n\n /** Extension tables in handle order. */\n extensions: ExtensionStaging[] = [];\n\n /**\n * Create empty staging.\n * @param options - precision, capacity hints and buffer kind\n */\n constructor(options: StagingOptions) {\n this.options = options;\n const { resizable } = options;\n const nodes = options.expectedNodes ?? 0;\n const edges = options.expectedEdges ?? 0;\n this.nodeAlive = new GrowableBitmap({ capacity: nodes, resizable });\n this.firstOut = new GrowableTypedArray<U32>(Uint32Array, { capacity: nodes, resizable });\n this.firstIn = new GrowableTypedArray<U32>(Uint32Array, { capacity: nodes, resizable });\n this.src = new GrowableTypedArray<U32>(Uint32Array, { capacity: edges, resizable });\n this.dst = new GrowableTypedArray<U32>(Uint32Array, { capacity: edges, resizable });\n this.edgeAlive = new GrowableBitmap({ capacity: edges, resizable });\n this.nextOut = new GrowableTypedArray<U32>(Uint32Array, { capacity: edges, resizable });\n this.nextIn = new GrowableTypedArray<U32>(Uint32Array, { capacity: edges, resizable });\n if (options.weighted) {\n this.weight = this.allocateWeights(edges);\n }\n }\n\n /**\n * The next node index to be assigned.\n * @returns the node bound\n */\n get nodeBound(): number {\n return this.nodeAlive.length;\n }\n\n /**\n * The next edge index to be assigned.\n * @returns the edge bound\n */\n get edgeBound(): number {\n return this.edgeAlive.length;\n }\n\n /**\n * Whether tombstoned nodes or edges exist.\n * @returns true when compaction is needed\n */\n get hasTombstones(): boolean {\n return this.liveNodeCount < this.nodeBound || this.liveEdgeCount < this.edgeBound;\n }\n\n /**\n * Grow capacity ahead of a bulk push.\n * @param nodes - the node count to fit\n * @param edges - the edge count to fit\n */\n reserve(nodes: number, edges: number): void {\n if (nodes > 0) {\n this.firstOut.ensureCapacity(nodes);\n this.firstIn.ensureCapacity(nodes);\n }\n if (edges > 0) {\n this.src.ensureCapacity(edges);\n this.dst.ensureCapacity(edges);\n this.nextOut.ensureCapacity(edges);\n this.nextIn.ensureCapacity(edges);\n if (this.weight !== null) {\n this.weight.ensureCapacity(edges);\n }\n }\n }\n\n /**\n * Materialise `ids` and `idToIndex` from the anonymous prefix (every node so far has id === index).\n */\n materialiseIds(): void {\n if (this.ids !== null && this.idToIndex !== null) {\n return;\n }\n const bound = this.nodeBound;\n const ids = new Array<NodeId>(bound);\n const map = new Map<NodeId, number>();\n for (let i = 0; i < bound; i++) {\n ids[i] = i;\n map.set(i, i);\n }\n this.ids = ids;\n this.idToIndex = map;\n }\n\n /**\n * Append a live node; the id is recorded only when the id structures exist.\n * @param id - the id, or null for an anonymous node (id === index)\n * @returns the new index\n */\n pushNode(id: NodeId | null): number {\n const index = this.nodeAlive.push(true);\n this.firstOut.push(INVALID_INDEX);\n this.firstIn.push(INVALID_INDEX);\n if (this.ids !== null && this.idToIndex !== null) {\n const stored = id ?? index;\n this.ids.push(stored);\n this.idToIndex.set(stored, index);\n }\n this.liveNodeCount++;\n return index;\n }\n\n /**\n * The weight array, allocated on first use and back-filled with 1 for existing edges.\n * @returns the growable weight array\n */\n ensureWeights(): GrowableTypedArray<TypedArrayData> {\n if (this.weight === null) {\n this.weight = this.allocateWeights(this.edgeBound);\n this.weight.resize(this.edgeBound, 1);\n }\n return this.weight;\n }\n\n /**\n * Record whether an edge's weight was explicit (design section 3.7): the `weightSet` bitmap is\n * allocated on the first edge that disagrees with every earlier one.\n * @param edge - the edge index (=== edgeBound - 1 when appending)\n * @param explicit - whether the weight was supplied\n */\n trackWeight(edge: number, explicit: boolean): void {\n if (this.weightSet !== null) {\n if (edge >= this.weightSet.length) {\n this.weightSet.resize(edge + 1, false);\n }\n this.weightSet.set(edge, explicit);\n return;\n }\n switch (this.weightMode) {\n case \"none\":\n this.weightMode = explicit ? \"explicit\" : \"omitted\";\n return;\n case \"explicit\":\n if (!explicit) {\n this.allocateWeightSet(true, edge);\n }\n return;\n case \"omitted\":\n if (explicit) {\n this.allocateWeightSet(false, edge);\n }\n return;\n case \"mixed\":\n return;\n default: {\n const mode: string = this.weightMode;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown weight mode ${mode}`, { mode });\n }\n }\n }\n\n /**\n * Whether an edge's weight was supplied explicitly (design section 3.7).\n * @param e - the edge index\n * @returns true when explicit\n */\n weightExplicit(e: number): boolean {\n if (this.weightSet === null) {\n return this.weightMode === \"explicit\";\n }\n return e < this.weightSet.length && this.weightSet.get(e);\n }\n\n /**\n * Append a live edge and link it into both incidence lists. The caller has validated the\n * endpoints and the weight.\n * @param u - source index\n * @param v - target index\n * @param weight - the weight, or undefined when omitted (stored as 1 when the array exists)\n * @returns the new edge index\n */\n pushEdge(u: number, v: number, weight: number | undefined): number {\n const e = this.src.push(u);\n this.dst.push(v);\n if (weight !== undefined) {\n this.ensureWeights().push(weight);\n } else if (this.weight !== null) {\n this.weight.push(1);\n }\n this.trackWeight(e, weight !== undefined);\n this.edgeAlive.push(true);\n this.nextOut.push(this.firstOut.get(u));\n this.firstOut.set(u, e);\n this.nextIn.push(this.firstIn.get(v));\n this.firstIn.set(v, e);\n this.liveEdgeCount++;\n if (u === v) {\n this.selfLoopCount++;\n }\n return e;\n }\n\n /**\n * Append `src.length` live edges at once (the bulk `addEdges` path): the same storage, weight\n * tracking and incidence-list linking as one pushEdge per edge in order, done as typed-array\n * passes. The caller has validated the endpoints and the weights.\n * @param src - source indices\n * @param dst - target indices, as many as `src`\n * @param weights - the explicit weight of every edge, or null when every weight is omitted\n * @returns the first new edge index\n */\n pushEdges(src: U32, dst: U32, weights: TypedArrayData | null): number {\n const count = src.length;\n const first = this.edgeBound;\n const end = first + count;\n if (count === 0) {\n return first;\n }\n this.src.pushAll(src);\n this.dst.pushAll(dst);\n if (weights !== null) {\n this.ensureWeights().pushAll(weights);\n } else if (this.weight !== null) {\n this.weight.resize(end, 1);\n }\n this.trackWeights(first, count, weights !== null);\n this.edgeAlive.resize(end, true);\n this.nextOut.resize(end);\n this.nextIn.resize(end);\n this.selfLoopCount += linkEdgeRange(\n this.src.array,\n this.dst.array,\n first,\n end,\n this.firstOut.array,\n this.firstIn.array,\n this.nextOut.array,\n this.nextIn.array,\n );\n this.liveEdgeCount += count;\n return first;\n }\n\n /**\n * trackWeight for a batch of `count` edges from `first` that all supplied or all omitted their\n * weight: the same mode transitions and bitmap contents as `count` calls in order.\n * @param first - the first edge of the batch\n * @param count - the batch size, at least 1\n * @param explicit - whether the batch supplied its weights\n */\n private trackWeights(first: number, count: number, explicit: boolean): void {\n const end = first + count;\n let bitmap = this.weightSet;\n if (bitmap === null) {\n switch (this.weightMode) {\n case \"none\":\n this.weightMode = explicit ? \"explicit\" : \"omitted\";\n return;\n case \"explicit\":\n if (explicit) {\n return;\n }\n bitmap = this.allocateWeightSet(true, first);\n break;\n case \"omitted\":\n if (!explicit) {\n return;\n }\n bitmap = this.allocateWeightSet(false, first);\n break;\n case \"mixed\":\n return;\n default: {\n const mode: string = this.weightMode;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown weight mode ${mode}`, { mode });\n }\n }\n }\n if (bitmap.length < first) {\n bitmap.resize(first, false);\n }\n bitmap.resize(end, explicit);\n }\n\n /**\n * Tombstone a live edge (O(1)).\n * @param e - a live edge index\n */\n killEdge(e: number): void {\n this.edgeAlive.set(e, false);\n this.liveEdgeCount--;\n if (this.src.get(e) === this.dst.get(e)) {\n this.selfLoopCount--;\n }\n }\n\n /**\n * Live edges leaving a node, walked from the out-list (O(degree)).\n * @param u - the node index\n * @returns the live edge indices in ascending order\n */\n outEdges(u: number): U32 {\n const out: number[] = [];\n for (let e = this.firstOut.get(u); e !== INVALID_INDEX; e = this.nextOut.get(e)) {\n if (this.edgeAlive.get(e)) {\n out.push(e);\n }\n }\n return Uint32Array.from(out).sort();\n }\n\n /**\n * Live edges entering a node, walked from the in-list (O(degree)).\n * @param v - the node index\n * @returns the live edge indices in ascending order\n */\n inEdges(v: number): U32 {\n const out: number[] = [];\n for (let e = this.firstIn.get(v); e !== INVALID_INDEX; e = this.nextIn.get(e)) {\n if (this.edgeAlive.get(e)) {\n out.push(e);\n }\n }\n return Uint32Array.from(out).sort();\n }\n\n /**\n * Live edges incident to a node in either orientation (the undirected outEdgesOf / inEdgesOf,\n * design section 6.6 and invariant I7): both lists walked, a self-loop listed once (O(degree)).\n * @param u - the node index\n * @returns the live edge indices in ascending order\n */\n incidentEdges(u: number): U32 {\n const out: number[] = [];\n for (let e = this.firstOut.get(u); e !== INVALID_INDEX; e = this.nextOut.get(e)) {\n if (this.edgeAlive.get(e)) {\n out.push(e);\n }\n }\n for (let e = this.firstIn.get(u); e !== INVALID_INDEX; e = this.nextIn.get(e)) {\n if (this.edgeAlive.get(e) && this.src.get(e) !== u) {\n out.push(e);\n }\n }\n return Uint32Array.from(out).sort();\n }\n\n /**\n * Bytes of typed staging held (capacity, not length), for `byteLength()`.\n * @returns the byte count\n */\n byteLength(): number {\n let bytes =\n this.firstOut.array.byteLength +\n this.firstIn.array.byteLength +\n this.src.array.byteLength +\n this.dst.array.byteLength +\n this.nextOut.array.byteLength +\n this.nextIn.array.byteLength +\n bitmapWordCount(this.nodeAlive.length) * 4 +\n bitmapWordCount(this.edgeAlive.length) * 4;\n if (this.weight !== null) {\n bytes += this.weight.array.byteLength;\n }\n if (this.weightSet !== null) {\n bytes += bitmapWordCount(this.weightSet.length) * 4;\n }\n for (const column of this.nodeColumns) {\n bytes += column.byteLength();\n }\n for (const column of this.edgeColumns) {\n bytes += column.byteLength();\n }\n for (const table of this.extensions) {\n for (const column of table.columns) {\n bytes += column.byteLength();\n }\n }\n return bytes;\n }\n\n private allocateWeights(capacity: number): GrowableTypedArray<TypedArrayData> {\n const { resizable } = this.options;\n return this.options.weightDtype === \"f64\"\n ? new GrowableTypedArray<TypedArrayData>(Float64Array, { capacity, resizable })\n : new GrowableTypedArray<TypedArrayData>(Float32Array, { capacity, resizable });\n }\n\n /**\n * Allocate the weightSet bitmap over `edge + 1` bits: every earlier edge gets `earlier`, `edge`\n * itself the opposite.\n * @param earlier - the value of every edge before `edge`\n * @param edge - the first disagreeing edge\n * @returns the new bitmap\n */\n private allocateWeightSet(earlier: boolean, edge: number): GrowableBitmap {\n const bitmap = new GrowableBitmap({ capacity: edge + 1, resizable: this.options.resizable });\n bitmap.resize(edge, earlier);\n bitmap.push(!earlier);\n this.weightSet = bitmap;\n this.weightMode = \"mixed\";\n return bitmap;\n }\n}\n\n// ============================================================ compaction\n\n/** The maps of the two index spaces a `refersTo` column's values may live in (old -> new, or source -> builder). */\nexport interface IndexMaps {\n /** Node index map. */\n readonly node: U32;\n /** Edge index map. */\n readonly edge: U32;\n}\n\n/** An old -> new index remap with its inverse and the new count. */\nexport interface IndexRemap {\n /** old index -> new index or INVALID_INDEX. */\n readonly remap: U32;\n /** new index -> old index. */\n readonly origin: U32;\n /** The new count. */\n readonly count: number;\n}\n\n/**\n * The remap that drops every index whose `keep(i)` is false, assigning new indices in index order\n * (invariant I14).\n * @param bound - the old index space size\n * @param keep - whether an old index survives\n * @returns the remap, its inverse and the new count\n */\nexport function remapDropping(bound: number, keep: (i: number) => boolean): IndexRemap {\n const remap = new Uint32Array(bound);\n let count = 0;\n for (let i = 0; i < bound; i++) {\n remap[i] = keep(i) ? count++ : INVALID_INDEX;\n }\n const origin = new Uint32Array(count);\n for (let i = 0; i < bound; i++) {\n if (remap[i] !== INVALID_INDEX) {\n origin[remap[i]] = i;\n }\n }\n return { remap, origin, count };\n}\n\n/**\n * The remap that keeps exactly the indices whose bit is set in `keep` (a bitmap over `bound` bits),\n * assigning new indices in index order (invariant I14): `remapDropping` over the builder's alive\n * bitmaps without a call per index.\n * @param bound - the old index space size\n * @param keep - a bitmap of at least `bound` bits; bit i set = old index i survives\n * @returns the remap, its inverse and the new count\n */\nexport function remapKeepingBits(bound: number, keep: U32): IndexRemap {\n const remap = new Uint32Array(bound);\n let count = 0;\n for (let i = 0; i < bound; i++) {\n if (((keep[i >>> 5] >>> (i & 31)) & 1) === 1) {\n remap[i] = count++;\n } else {\n remap[i] = INVALID_INDEX;\n }\n }\n const origin = new Uint32Array(count);\n for (let i = 0; i < bound; i++) {\n const mapped = remap[i];\n if (mapped !== INVALID_INDEX) {\n origin[mapped] = i;\n }\n }\n return { remap, origin, count };\n}\n\n/**\n * The remap that keeps exactly the survivors of a merge walk (the indices with `survivorOf[e] === e`),\n * assigning new indices in index order (invariant I14): `remapDropping` for design section 6.5's\n * step-7 repeat without a call per edge.\n * @param survivorOf - old edge -> its survivor (itself for a survivor)\n * @returns the remap, its inverse and the new count\n */\nexport function remapSurvivors(survivorOf: U32): IndexRemap {\n const bound = survivorOf.length;\n const remap = new Uint32Array(bound);\n let count = 0;\n for (let e = 0; e < bound; e++) {\n if (survivorOf[e] === e) {\n remap[e] = count++;\n } else {\n remap[e] = INVALID_INDEX;\n }\n }\n const origin = new Uint32Array(count);\n for (let e = 0; e < bound; e++) {\n const mapped = remap[e];\n if (mapped !== INVALID_INDEX) {\n origin[mapped] = e;\n }\n }\n return { remap, origin, count };\n}\n\n/** What a compaction gathers: the node and edge remaps plus optional merged-weight overrides. */\ninterface CompactionPlan {\n /** The node remap (old -> new). */\n readonly nodes: IndexRemap;\n /** The edge remap (old -> new) of the ROWS; merged edges map to INVALID_INDEX here (their survivor carries them). */\n readonly edges: IndexRemap;\n /**\n * The remap `refersTo: \"edge\"` VALUES are rewritten through when it differs from the row remap: a\n * merged edge maps to its survivor's new index (design sections 5.11 and 7.3), never to\n * INVALID_INDEX. Null when the row remap applies to values too.\n */\n readonly edgeValues: U32 | null;\n /** Per NEW edge: the reduced weight to store where `mergedWeightStored` is set; null when no merge happened. */\n readonly mergedWeights: Float64Array | null;\n /** Per NEW edge: bit set when `mergedWeights` holds a value to store; null when no merge happened. */\n readonly mergedWeightStored: U32 | null;\n /** Per NEW edge: bit set when the merged group's weight is explicit after the merge; null when no merge happened. */\n readonly mergedWeightSet: U32 | null;\n}\n\n/**\n * Link the edges [first, end) into both incidence lists in index order, exactly as pushEdge does one\n * at a time (every list head becomes the highest linked index).\n * @param src - sources (backing view)\n * @param dst - targets (backing view)\n * @param first - the first edge to link\n * @param end - one past the last edge to link\n * @param firstOut - out-list heads\n * @param firstIn - in-list heads\n * @param nextOut - receives the out-list links\n * @param nextIn - receives the in-list links\n * @returns the number of self-loops among the linked edges\n */\nfunction linkEdgeRange(\n src: U32,\n dst: U32,\n first: number,\n end: number,\n firstOut: U32,\n firstIn: U32,\n nextOut: U32,\n nextIn: U32,\n): number {\n let loops = 0;\n for (let e = first; e < end; e++) {\n const u = src[e];\n const v = dst[e];\n nextOut[e] = firstOut[u];\n firstOut[u] = e;\n nextIn[e] = firstIn[v];\n firstIn[v] = e;\n if (u === v) {\n loops++;\n }\n }\n return loops;\n}\n\n/**\n * The edge gather of a compaction: endpoints through the node remap, in new-index order, with both\n * incidence lists rebuilt (every list head is the highest edge index, as after pushEdge in order).\n * @param src - the source staging's sources (backing view)\n * @param dst - the source staging's targets (backing view)\n * @param origin - new edge index -> old edge index\n * @param nodeRemap - old node index -> new node index\n * @param outSrc - receives the remapped sources\n * @param outDst - receives the remapped targets\n * @param firstOut - out-list heads, INVALID_INDEX on entry\n * @param firstIn - in-list heads, INVALID_INDEX on entry\n * @param nextOut - receives the out-list links\n * @param nextIn - receives the in-list links\n * @returns the self-loop count\n */\nfunction gatherEdges(\n src: U32,\n dst: U32,\n origin: U32,\n nodeRemap: U32,\n outSrc: U32,\n outDst: U32,\n firstOut: U32,\n firstIn: U32,\n nextOut: U32,\n nextIn: U32,\n): number {\n const edgeCount = origin.length;\n let loops = 0;\n for (let e = 0; e < edgeCount; e++) {\n const old = origin[e];\n const u = nodeRemap[src[old]];\n const v = nodeRemap[dst[old]];\n outSrc[e] = u;\n outDst[e] = v;\n nextOut[e] = firstOut[u];\n firstOut[u] = e;\n nextIn[e] = firstIn[v];\n firstIn[v] = e;\n if (u === v) {\n loops++;\n }\n }\n return loops;\n}\n\n/**\n * `out[i] = values[origin[i]]` for every new index; the element conversion is the target array's\n * (an f64 source into f32 staging rounds exactly as a push would).\n * @param values - the old values (backing view)\n * @param origin - new index -> old index\n * @param out - receives the gathered values\n */\nfunction gatherValues(values: TypedArrayData, origin: U32, out: TypedArrayData): void {\n const count = origin.length;\n for (let i = 0; i < count; i++) {\n out[i] = values[origin[i]];\n }\n}\n\n/**\n * Store the reduced weight of every merged group on its survivor (design section 6.5).\n * @param merged - per new edge, the reduced weight where `stored` is set\n * @param stored - per new edge, bit set when a reduced weight is to be stored\n * @param weights - the new staging weights\n * @param edgeCount - the new edge count\n */\nfunction applyMergedWeights(merged: Float64Array, stored: U32, weights: TypedArrayData, edgeCount: number): void {\n for (let e = 0; e < edgeCount; e++) {\n if (bitmapGet(stored, e)) {\n weights[e] = merged[e];\n }\n }\n}\n\n/**\n * Gather a new staging through a compaction plan (design section 6.3 step 1). The source is left\n * untouched; the result has no tombstones, fresh `ids` / `idToIndex` objects (or none when every node\n * is anonymous), rebuilt incidence lists, gathered columns with `refersTo` values rewritten, and\n * extension tables with their `refersTo` values rewritten.\n * @param source - the staging to compact\n * @param plan - the remaps and merge overrides\n * @returns the compacted staging\n */\nexport function compactStaging(source: Staging, plan: CompactionPlan): Staging {\n const { nodes, edges } = plan;\n const out = new Staging({\n ...source.options,\n weighted: source.weight !== null || plan.mergedWeights !== null,\n expectedNodes: nodes.count,\n expectedEdges: edges.count,\n });\n // nodes: every new node is live with empty incidence lists (what pushNode(null) does, in bulk); ids\n // and map are fresh objects; anonymous nodes stay anonymous (their ids are their new indices)\n out.nodeAlive.resize(nodes.count, true);\n out.firstOut.resize(nodes.count, INVALID_INDEX);\n out.firstIn.resize(nodes.count, INVALID_INDEX);\n out.liveNodeCount = nodes.count;\n if (source.ids !== null) {\n const ids = new Array<NodeId>(nodes.count);\n const map = new Map<NodeId, number>();\n for (let i = 0; i < nodes.count; i++) {\n const id = source.ids[nodes.origin[i]];\n ids[i] = id;\n map.set(id, i);\n }\n out.ids = ids;\n out.idToIndex = map;\n }\n // edges: gathered in new-index order through the backing views (one typed-array pass, design\n // section 6.3 step 1), weights and explicit-weight bits carried, lists rebuilt by pushing every\n // edge in index order exactly as pushEdge does (head of each list = highest index)\n const { remap: nodeRemap } = nodes;\n const edgeCount = edges.count;\n const { origin } = edges;\n out.weightMode = source.weightMode;\n if (source.weightSet !== null || plan.mergedWeightSet !== null) {\n out.weightSet = new GrowableBitmap({ capacity: edgeCount, resizable: source.options.resizable });\n out.weightMode = \"mixed\";\n }\n out.src.resize(edgeCount);\n out.dst.resize(edgeCount);\n out.nextOut.resize(edgeCount);\n out.nextIn.resize(edgeCount);\n out.edgeAlive.resize(edgeCount, true);\n out.liveEdgeCount = edgeCount;\n out.selfLoopCount = gatherEdges(\n source.src.array,\n source.dst.array,\n origin,\n nodeRemap,\n out.src.array,\n out.dst.array,\n out.firstOut.array,\n out.firstIn.array,\n out.nextOut.array,\n out.nextIn.array,\n );\n if (out.weight !== null) {\n out.weight.resize(edgeCount);\n const weights = out.weight.array;\n if (source.weight === null) {\n weights.fill(1, 0, edgeCount);\n } else {\n gatherValues(source.weight.array, origin, weights);\n }\n if (plan.mergedWeights !== null && plan.mergedWeightStored !== null) {\n applyMergedWeights(plan.mergedWeights, plan.mergedWeightStored, weights, edgeCount);\n }\n }\n if (out.weightSet !== null) {\n out.weightSet.resize(edgeCount, false);\n for (let e = 0; e < edgeCount; e++) {\n let explicit = source.weightExplicit(origin[e]);\n if (plan.mergedWeightSet !== null && bitmapGet(plan.mergedWeightSet, e)) {\n explicit = true;\n }\n if (explicit) {\n out.weightSet.set(e, true);\n }\n }\n }\n // columns\n const refs: IndexMaps = { node: nodeRemap, edge: plan.edgeValues ?? edges.remap };\n out.nodeColumns = source.nodeColumns.map((column) => column.gather(nodes.origin, valueRemapFor(column, refs)));\n out.edgeColumns = source.edgeColumns.map((column) => column.gather(edges.origin, valueRemapFor(column, refs)));\n out.extensions = source.extensions.map((table) => ({\n name: table.name,\n rowCount: table.rowCount,\n columns: table.columns.map((column) => column.gather(null, valueRemapFor(column, refs))),\n }));\n return out;\n}\n\n/**\n * The value remap that applies to a column's `refersTo`, if any.\n * @param column - the column\n * @param refs - the node and edge remaps\n * @returns the remap of the referenced space, or null\n */\nfunction valueRemapFor(column: StagingColumn, refs: IndexMaps): U32 | null {\n switch (column.meta.refersTo) {\n case \"node\":\n return refs.node;\n case \"edge\":\n return refs.edge;\n default:\n return null;\n }\n}\n","/**\n * AttributeTable: a set of index-aligned columns with a fixed row count (design section 5.7). The\n * column SET is a mutable side table of the snapshot (set / remove / rename at any time, by the\n * snapshot owner); the row count is fixed for the life of the table (invariant I17) and column\n * contents are frozen unless the column was declared mutable (design section 5.8). \"Absent\" is\n * always null on this surface; undefined only ever means \"unset row\" from value(). Iteration yields\n * columns in declaration order. At most one column per role (E_DUPLICATE_ROLE).\n *\n * The exported helper functions (tableWithColumns, verifyUniqueColumns, declareColumn) are for the\n * snapshot, builder and freeze modules; they are not part of the public surface.\n */\n\nimport { GraphFormatError } from \"../errors.js\";\nimport {\n type AttributeTableContract,\n type Column,\n type ColumnDeclPatch,\n type ColumnDomain,\n type ColumnInput,\n type ColumnOf,\n type ColumnRole,\n type Dtype,\n type F32,\n type I32,\n type SetOptions,\n type TypedArrayData,\n type U32,\n} from \"../types/index.js\";\nimport { type TableParts } from \"../types/internal.js\";\nimport { assertOneOf } from \"../util/options.js\";\nimport { claimHolder, holderCount, isShared, noteShared } from \"../util/shared-buffers.js\";\nimport { bitmapGet } from \"./bitmap.js\";\nimport {\n columnBuffers,\n columnFromTypedArray,\n columnFromValues,\n gpuViewOf,\n isPackageColumn,\n metaToDecl,\n resolveColumnMeta,\n rewrapColumn,\n} from \"./column.js\";\n\n/**\n * Whether a set() payload is a typed array (as opposed to a Column object or a JS array).\n * @param data - the payload\n * @returns true for one of the five typed-array classes\n */\nfunction isTypedArrayData(data: unknown): data is TypedArrayData {\n return (\n data instanceof Uint32Array ||\n data instanceof Int32Array ||\n data instanceof Float32Array ||\n data instanceof Float64Array ||\n data instanceof Uint8Array\n );\n}\n\n/**\n * Whether a set() payload is a Column object (duck-typed on the members every column has).\n * @param data - the payload\n * @returns true for a Column\n */\nfunction isColumn(data: unknown): data is Column {\n if (typeof data !== \"object\" || data === null || Array.isArray(data) || isTypedArrayData(data)) {\n return false;\n }\n const candidate = data as { dtype?: unknown; meta?: unknown; length?: unknown };\n return (\n typeof candidate.dtype === \"string\" &&\n typeof candidate.meta === \"object\" &&\n typeof candidate.length === \"number\"\n );\n}\n\n/**\n * The number of column-set changes a table has seen (set / remove / rename), so a cached role or name\n * lookup can be reused while the set is unchanged.\n * @param table - the table\n * @returns the change count\n */\nexport function columnSetVersion(table: AttributeTable): number {\n return (table as unknown as { mutations: number }).mutations;\n}\n\n/**\n * Record a table as a holder of a column and of every buffer the column views (design section 9.1).\n * @param column - the column being attached\n */\nfunction claimColumn(column: Column): void {\n claimHolder(column);\n for (const buffer of columnBuffers(column)) {\n claimHolder(buffer);\n }\n}\n\n/**\n * A set of columns with a fixed row count (design sections 5.7 and 12.2): `nodes` (nodeCount rows),\n * `edges` (edgeCount rows), `graph` (1 row) and extension tables. The column set is a mutable side\n * table; the row count is fixed; iteration is in declaration order.\n */\nexport class AttributeTable implements AttributeTableContract {\n /** The table the columns belong to. */\n readonly domain: ColumnDomain;\n\n /** Number of rows of every column; fixed for the life of the table. */\n readonly rowCount: number;\n\n private readonly columns: Map<string, Column>;\n\n /** Bumped on every change of the column set (set / remove / rename), for callers that cache a lookup. */\n private mutations = 0;\n\n /**\n * Create a table from wrapped columns (the constructor the freeze pipeline, fromCsr and the wire\n * reader use). Every column must have the table's row count and domain, names must be unique and\n * at most one column may hold each role.\n * @param parts - the domain, the row count and the columns in declaration order\n * @internal\n */\n constructor(parts: TableParts) {\n const { domain, rowCount } = parts;\n if (!(Number.isInteger(rowCount) && rowCount >= 0)) {\n throw new GraphFormatError(\"E_COLUMN_LENGTH\", `invalid row count ${rowCount} for a ${domain} table`, {\n domain,\n found: rowCount,\n });\n }\n this.domain = domain;\n this.rowCount = rowCount;\n this.columns = new Map();\n for (const column of parts.columns) {\n const { name } = column.meta;\n if (this.columns.has(name)) {\n throw new GraphFormatError(\"E_COLUMN_EXISTS\", `column \"${name}\" is declared twice`, { column: name });\n }\n this.checkColumn(name, column);\n this.checkRole(name, column.meta.role, false);\n this.columns.set(name, column);\n claimColumn(column);\n }\n }\n\n /**\n * Column names in declaration order.\n * @returns a fresh array of the names\n */\n names(): readonly string[] {\n return [...this.columns.keys()];\n }\n\n /**\n * Whether a column exists.\n * @param name - the column name\n * @returns true when present\n */\n has(name: string): boolean {\n return this.columns.has(name);\n }\n\n /**\n * Total lookup by name.\n * @param name - the column name\n * @returns the column, or null when absent\n */\n get(name: string): Column | null {\n return this.columns.get(name) ?? null;\n }\n\n /**\n * Checked lookup by name.\n * @param name - the column name\n * @returns the column; E_UNKNOWN_COLUMN when absent\n */\n require(name: string): Column {\n const column = this.columns.get(name);\n if (column === undefined) {\n throw new GraphFormatError(\"E_UNKNOWN_COLUMN\", `no ${this.domain} column named \"${name}\"`, {\n column: name,\n domain: this.domain,\n });\n }\n return column;\n }\n\n /**\n * Total lookup by name and dtype.\n * @param name - the column name\n * @param dtype - the expected dtype\n * @returns the column, or null when absent or of another dtype\n */\n typed<D extends Dtype>(name: string, dtype: D): ColumnOf<D> | null {\n const column = this.columns.get(name);\n if (column === undefined || column.dtype !== dtype) {\n return null;\n }\n return column as ColumnOf<D>;\n }\n\n /**\n * Checked lookup by name and dtype.\n * @param name - the column name\n * @param dtype - the expected dtype\n * @returns the column; E_UNKNOWN_COLUMN when absent, E_COLUMN_TYPE when of another dtype\n */\n requireTyped<D extends Dtype>(name: string, dtype: D): ColumnOf<D> {\n const column = this.require(name);\n if (column.dtype !== dtype) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `column \"${name}\" is ${column.dtype}, expected ${dtype}`, {\n column: name,\n expected: dtype,\n found: column.dtype,\n });\n }\n return column as ColumnOf<D>;\n }\n\n /**\n * The column holding a role (at most one per table).\n * @param role - the role\n * @returns the column, or null when no column has the role\n */\n byRole(role: ColumnRole): Column | null {\n for (const column of this.columns.values()) {\n if (column.meta.role === role) {\n return column;\n }\n }\n return null;\n }\n\n /**\n * Typed read of one cell honouring the column's declared default.\n * @param name - the column name; E_UNKNOWN_COLUMN when absent\n * @param row - the row index; E_INDEX_RANGE when out of range\n * @returns the value, the default for an unset row, or undefined for an unset row without a default\n */\n value(name: string, row: number): unknown {\n return this.require(name).value(row);\n }\n\n /**\n * Whether one cell holds a value.\n * @param name - the column name; E_UNKNOWN_COLUMN when absent\n * @param row - the row index (false when out of range)\n * @returns true when set\n */\n isSet(name: string, row: number): boolean {\n return this.require(name).isSet(row);\n }\n\n /**\n * Attach a column (design section 5.7). A typed array is adopted by reference after its length is\n * checked (E_COLUMN_LENGTH); a u8 array from which no padded u32 view is constructible is copied\n * unless opts.adopt is \"strict\" (E_COLUMN_ALIGNMENT); a view over a SharedArrayBuffer or a\n * resizable buffer is E_UNSUPPORTED (decision D-SAB, invariant I10); a JS array builds a column of\n * the declared dtype, or of the dtype inferred from the values (design section 5.1) when the\n * patch names none; a Column object is moved in when its row count matches. Replaces a column of\n * the same name. E_DUPLICATE_ROLE when the declared role is held by another column and\n * opts.replaceRole is not set; with replaceRole the previous holder is removed.\n * @param name - the column name\n * @param data - a Column, a typed array, or a JS array of values\n * @param decl - declaration fields to apply (dtype is inferred from a typed array when omitted)\n * @param opts - role replacement and u8 adoption options\n * @returns the attached column (`column.data !== data` only when a u8 array was copied)\n */\n set(\n name: string,\n data: Column | TypedArrayData | readonly unknown[],\n decl?: ColumnDeclPatch,\n opts?: SetOptions,\n ): Column {\n const patch = decl ?? {};\n let column: Column;\n if (isTypedArrayData(data)) {\n const adopt = assertOneOf(\"adopt\", opts?.adopt, [\"copy\", \"strict\"] as const) ?? \"copy\";\n column = columnFromTypedArray(this.domain, this.rowCount, name, data, patch, adopt);\n } else if (Array.isArray(data)) {\n column = columnFromValues(this.domain, this.rowCount, name, data, patch);\n } else if (isColumn(data)) {\n if (!isPackageColumn(data)) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `column \"${name}\": not a Column of this package`, {\n column: name,\n reason: \"foreign column\",\n });\n }\n column = this.adoptColumn(name, data, decl);\n if (column !== data && holderCount(data) > 0) {\n // a re-wrapped column shares every buffer with `data`, which another table still holds\n noteShared(column);\n }\n } else {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `column \"${name}\": unsupported data (${typeof data})`, {\n column: name,\n found: typeof data,\n });\n }\n this.checkRole(name, column.meta.role, opts?.replaceRole ?? false);\n const previous = this.columns.get(name);\n if (previous !== column) {\n // a Column object moved in from another table gains a second holder, and so does every\n // buffer it views (a zero-copy slice of another table's column, design section 9.1);\n // re-wrapping this table's own column under a patch adds no holder of its buffers\n claimHolder(column);\n if (previous !== data) {\n for (const buffer of columnBuffers(column)) {\n claimHolder(buffer);\n }\n }\n }\n // Map.set on an existing key keeps its position, so a replacement keeps the declaration order\n this.columns.set(name, column);\n this.mutations++;\n return column;\n }\n\n /**\n * Remove a column.\n * @param name - the column name\n * @returns true when a column was removed\n */\n remove(name: string): boolean {\n const removed = this.columns.delete(name);\n if (removed) {\n this.mutations++;\n }\n return removed;\n }\n\n /**\n * Rename a column in place (declaration order kept). The Column object is re-wrapped under the new\n * name; its storage is shared with the previous object.\n * @param from - the current name; E_UNKNOWN_COLUMN when absent\n * @param to - the new name; E_COLUMN_EXISTS when another column has it\n */\n rename(from: string, to: string): void {\n const column = this.require(from);\n if (from === to) {\n return;\n }\n if (this.columns.has(to)) {\n throw new GraphFormatError(\"E_COLUMN_EXISTS\", `cannot rename \"${from}\": a column named \"${to}\" exists`, {\n column: to,\n });\n }\n const renamed = rewrapColumn(column, resolveColumnMeta(to, this.domain, metaToDecl(column.meta)));\n // the same table keeps holding the same buffers: only the new Column object is claimed\n claimHolder(renamed);\n if (isShared(column)) {\n noteShared(renamed);\n }\n const entries = [...this.columns.entries()];\n this.columns.clear();\n for (const [name, existing] of entries) {\n if (name === from) {\n this.columns.set(to, renamed);\n } else {\n this.columns.set(name, existing);\n }\n }\n this.mutations++;\n }\n\n /**\n * The array a GPU binds for a column (design section 10.4): its own data for the direct dtypes,\n * the padded u32 view for u8, the packed words for bool, the codes for dict, and a cached f32 copy\n * for f64.\n * @param name - the column name; E_UNKNOWN_COLUMN when absent\n * @returns the bindable array; E_GPU_INELIGIBLE for string / list / json\n */\n gpuView(name: string): U32 | I32 | F32 {\n return gpuViewOf(this.require(name));\n }\n\n /**\n * A new table with the same columns: the Column objects are shared, the set is independent.\n * @returns the cloned table\n */\n clone(): AttributeTable {\n return new AttributeTable({\n domain: this.domain,\n rowCount: this.rowCount,\n columns: [...this.columns.values()],\n });\n }\n\n /**\n * Iterate the columns in declaration order.\n * @returns an iterator over the columns\n */\n [Symbol.iterator](): IterableIterator<Column> {\n return this.columns.values();\n }\n\n /**\n * Move a Column object in: checked for row count and re-wrapped when its name, domain or\n * declaration differ from the target slot.\n * @param name - the target name\n * @param column - the column\n * @param decl - an optional declaration patch\n * @returns the column to store (the same object when nothing changes)\n */\n private adoptColumn(name: string, column: Column, decl: ColumnDeclPatch | undefined): Column {\n this.checkColumn(name, column);\n const { meta } = column;\n const unchanged = decl === undefined && meta.name === name && meta.domain === this.domain;\n if (unchanged) {\n return column;\n }\n const merged: ColumnDeclPatch = { ...metaToDecl(meta), ...decl };\n if (decl?.fill === undefined) {\n merged.fill = meta.fill;\n }\n return rewrapColumn(column, resolveColumnMeta(name, this.domain, merged));\n }\n\n private checkColumn(name: string, column: Column): void {\n if (column.length !== this.rowCount) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `column \"${name}\" has ${column.length} rows; the ${this.domain} table has ${this.rowCount}`,\n { column: name, expected: this.rowCount, found: column.length },\n );\n }\n }\n\n /**\n * Enforce \"at most one column per role\": E_DUPLICATE_ROLE when another column holds the role,\n * unless replaceRole, in which case that column is removed.\n * @param name - the column being attached (a column may keep its own role)\n * @param role - the role being attached, or null\n * @param replaceRole - whether to evict the previous holder\n */\n private checkRole(name: string, role: ColumnRole | null, replaceRole: boolean): void {\n if (role === null) {\n return;\n }\n for (const [otherName, other] of this.columns) {\n if (otherName !== name && other.meta.role === role) {\n if (!replaceRole) {\n throw new GraphFormatError(\n \"E_DUPLICATE_ROLE\",\n `role \"${role}\" is already held by column \"${otherName}\" in the ${this.domain} table`,\n { role, column: name, holder: otherName },\n );\n }\n this.columns.delete(otherName);\n return;\n }\n }\n }\n}\n\n/**\n * Create an empty table.\n * @param domain - the table's domain\n * @param rowCount - the fixed row count\n * @returns a table with no columns\n */\nexport function createTable(domain: ColumnDomain, rowCount: number): AttributeTable {\n return new AttributeTable({ domain, rowCount, columns: [] });\n}\n\n/**\n * A cloned table plus the given columns (the column half of snapshot.withColumns(), design section\n * 7.3): the Column objects of the source are shared, the set is new, and each entry of `columns` is\n * attached through set() (a typed array, or a ColumnInput carrying data and a declaration patch).\n * @param table - the source table\n * @param columns - the columns to add or replace, keyed by name\n * @returns the new table\n */\nexport function tableWithColumns(\n table: AttributeTable,\n columns: Readonly<Record<string, TypedArrayData | ColumnInput>>,\n): AttributeTable {\n const out = table.clone();\n for (const name of Object.keys(columns)) {\n const input = columns[name];\n if (isTypedArrayData(input)) {\n out.set(name, input);\n } else {\n out.set(name, input.data, input.decl);\n }\n }\n return out;\n}\n\n/**\n * The comparable key of one set cell for uniqueness checks: the number, string, boolean or\n * dictionary value; json values are compared by their JSON text.\n * @param column - the column\n * @param row - a set row\n * @returns the key\n */\nfunction uniqueKey(column: Column, row: number): unknown {\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n if (column.meta.components === 1) {\n return column.data[row];\n }\n return Array.from(\n column.data.subarray(row * column.meta.components, (row + 1) * column.meta.components),\n ).join(\",\");\n case \"bool\":\n return bitmapGet(column.data, row);\n case \"dict\":\n return column.codes[row];\n case \"string\":\n return column.valueAt(row);\n case \"list\":\n return JSON.stringify(column.sliceOf(row));\n case \"json\":\n return JSON.stringify(column.values[row]);\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Enforce a unique column over its set rows (design section 5.5; the freeze step 10 hook):\n * E_DUPLICATE_EDGE_ID for an edge column and E_DUPLICATE_ID for every other domain, with the\n * duplicated value and both rows in details.\n * @param column - a column declared unique\n */\nexport function verifyUniqueColumn(column: Column): void {\n if (!column.meta.unique) {\n return;\n }\n const seen = new Map<unknown, number>();\n for (let row = 0; row < column.length; row++) {\n if (!column.isSet(row)) {\n continue;\n }\n const key = uniqueKey(column, row);\n const first = seen.get(key);\n if (first !== undefined) {\n const code = column.meta.domain === \"edge\" ? \"E_DUPLICATE_EDGE_ID\" : \"E_DUPLICATE_ID\";\n throw new GraphFormatError(\n code,\n `column \"${column.meta.name}\" is unique but rows ${first} and ${row} hold the same value`,\n {\n column: column.meta.name,\n domain: column.meta.domain,\n rows: [first, row],\n value: column.value(row),\n },\n );\n }\n seen.set(key, row);\n }\n}\n\n/**\n * Enforce every unique column of a table (freeze step 10).\n * @param table - the table to check\n */\nexport function verifyUniqueColumns(table: AttributeTable): void {\n for (const column of table) {\n verifyUniqueColumn(column);\n }\n}\n","/**\n * Edge ids are optional data, not structure (design section 4.6): an edge column with role \"id\"\n * (dtype string, dict, u32 or f64 in practice; any scalar numeric dtype is read the same way) holds\n * them, importers declare it `unique: true`, and `snapshot.edgeIndexOf(id)` resolves an id through\n * a Map built lazily on the first call. This module owns that lazy index and the uniqueness check\n * freeze runs over the SET rows of a unique id column (E_DUPLICATE_EDGE_ID with both edge indices).\n * Equality is SameValueZero (a JS Map key), the same rule as node ids.\n */\n\nimport { INVALID_INDEX } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type Column, type EdgeId } from \"../types/index.js\";\n\n/**\n * The E_COLUMN_TYPE error for a column whose dtype cannot hold edge ids.\n * @param column - the column\n * @returns the error\n */\nfunction unsupportedDtype(column: Column): GraphFormatError {\n return new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column ${JSON.stringify(column.meta.name)} of dtype ${column.dtype} cannot hold edge ids`,\n { column: column.meta.name, dtype: column.dtype, reason: \"edge id dtype\" },\n );\n}\n\n/**\n * The id stored in one SET row of an edge id column: the decoded string of a string column, the\n * dictionary value of a dict column, or the (first component of the) number of a numeric column.\n * The caller has checked `column.isSet(row)`.\n * @param column - the id column\n * @param row - a set row\n * @returns the id\n */\nexport function edgeIdOfRow(column: Column, row: number): EdgeId {\n switch (column.dtype) {\n case \"string\":\n return column.valueAt(row);\n case \"dict\":\n return column.dictionary[column.codes[row]];\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n return column.data[row * column.meta.components];\n case \"bool\":\n case \"list\":\n case \"json\":\n throw unsupportedDtype(column);\n default:\n throw unsupportedDtype(column);\n }\n}\n\n/**\n * Whether a column's dtype can hold edge ids (string, dict or a scalar numeric dtype).\n * @param column - the column\n * @returns true when edgeIdOfRow can read it\n */\nexport function canHoldEdgeIds(column: Column): boolean {\n switch (column.dtype) {\n case \"string\":\n case \"dict\":\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n return true;\n case \"bool\":\n case \"list\":\n case \"json\":\n return false;\n default:\n return false;\n }\n}\n\n/**\n * Build the id -> edge index map of an id column over its SET rows in one pass. When an id repeats\n * the lowest edge index wins (a unique column never repeats; `findDuplicateEdgeId` reports it).\n * @param column - the edge id column\n * @returns a fresh Map from id to logical edge index\n */\nexport function buildEdgeIdMap(column: Column): Map<EdgeId, number> {\n if (!canHoldEdgeIds(column)) {\n throw unsupportedDtype(column);\n }\n const map = new Map<EdgeId, number>();\n const rows = column.length;\n for (let e = 0; e < rows; e++) {\n if (!column.isSet(e)) {\n continue;\n }\n const id = edgeIdOfRow(column, e);\n if (!map.has(id)) {\n map.set(id, e);\n }\n }\n return map;\n}\n\n/**\n * The lazily built index behind `snapshot.edgeIndexOf(id)` (design section 4.6): a Map from id to\n * logical edge index over the set rows of the role \"id\" edge column, built on the first lookup and\n * rebuilt when a mutable column's `version` has changed since.\n */\nexport class EdgeIdIndex {\n /** The edge id column. */\n private readonly column: Column;\n\n /** The map, or null before the first lookup. */\n private map: Map<EdgeId, number> | null;\n\n /** column.version when the map was built. */\n private builtVersion: number;\n\n /**\n * Wrap an edge id column; nothing is built until the first lookup.\n * @param column - the edge column with role \"id\"; E_COLUMN_TYPE when its dtype cannot hold ids\n */\n constructor(column: Column) {\n if (!canHoldEdgeIds(column)) {\n throw unsupportedDtype(column);\n }\n this.column = column;\n this.map = null;\n this.builtVersion = -1;\n }\n\n /**\n * Whether the map has been built (and is current).\n * @returns true when the next lookup will not build\n */\n get built(): boolean {\n return this.map !== null && this.builtVersion === this.column.version;\n }\n\n /**\n * Number of distinct ids over the set rows; builds the map.\n * @returns the id count\n */\n get size(): number {\n return this.ensure().size;\n }\n\n /**\n * The logical edge index of an id.\n * @param id - the edge id\n * @returns the edge index, or INVALID_INDEX on a miss\n */\n indexOf(id: EdgeId): number {\n const index = this.ensure().get(id);\n return index === undefined ? INVALID_INDEX : index;\n }\n\n /**\n * Whether an id is present.\n * @param id - the edge id\n * @returns true when some set row holds it\n */\n has(id: EdgeId): boolean {\n return this.ensure().has(id);\n }\n\n /**\n * The map, built on first use and rebuilt after the column's version changed.\n * @returns the id -> edge index map\n */\n private ensure(): Map<EdgeId, number> {\n const { version } = this.column;\n if (this.map === null || this.builtVersion !== version) {\n this.map = buildEdgeIdMap(this.column);\n this.builtVersion = version;\n }\n return this.map;\n }\n}\n","/**\n * Core-array allocation for the freeze pipeline (design sections 6.3 step 11 and 10.3): the five core\n * arrays of a snapshot laid out hot to cold (rowPtr, colIdx, weights, arcToEdge, edgeToArc) inside ONE\n * ArrayBuffer at 256-byte-aligned offsets, or -- for the transient pass of a non-\"keep\" duplicate\n * policy and for `freeze({ arena: false })` -- as separate fresh buffers. Either way every array is\n * 4-byte aligned over a plain ArrayBuffer (invariant I10). A zero-length array, an absent weights\n * array and an identity permutation have a null segment and occupy nothing in the arena.\n *\n * The counting-sort scatter of counting-sort.ts writes straight into the arrays returned here, so a\n * \"keep\"-policy freeze touches the arena exactly once (design section 6.3 step 6).\n */\n\nimport { ALIGNMENT } from \"../constants.js\";\nimport { type ArenaLayout, type ArenaSegment, type CoreArrayName, type F32, type U32 } from \"../types/index.js\";\nimport { layoutSegments } from \"../util/typed-array.js\";\n\n/** The shape of a core to allocate: the counts and which optional arrays exist. */\ninterface CoreShape {\n /** The node count n. */\n readonly nodeCount: number;\n /** The arc count A. */\n readonly arcCount: number;\n /** The logical edge count E. */\n readonly edgeCount: number;\n /** Whether the weights array exists. */\n readonly weighted: boolean;\n /** Whether the permutation is the identity, in which case arcToEdge / edgeToArc are not allocated. */\n readonly identity: boolean;\n}\n\n/** The five core arrays plus the arena they live in (null for separate buffers). */\nexport interface CoreArrays {\n /** nodeCount + 1 row offsets. */\n readonly rowPtr: U32;\n /** arcCount targets. */\n readonly colIdx: U32;\n /** arcCount f32 weights, or null when unweighted. */\n readonly weights: F32 | null;\n /** arcCount entries, or null when the permutation is the identity. */\n readonly arcToEdge: U32 | null;\n /** edgeCount entries, or null when the permutation is the identity. */\n readonly edgeToArc: U32 | null;\n /** The arena, or null when the arrays are separate buffers. */\n readonly arena: ArenaLayout | null;\n}\n\n/** The order of the core arrays inside the arena: hot to cold (design section 10.3). */\n/** The core arrays in arena order, hot to cold (design section 10.3); the wire and fromCsr use the same order. */\nexport const CORE_ORDER: readonly CoreArrayName[] = [\"rowPtr\", \"colIdx\", \"weights\", \"arcToEdge\", \"edgeToArc\"];\n\n/**\n * The unpadded byte length of every core array in arena order for a shape.\n * @param shape - the core shape\n * @returns five byte lengths; 0 for an absent array\n */\nfunction byteLengthsOf(shape: CoreShape): number[] {\n const permArcs = shape.identity ? 0 : shape.arcCount;\n const permEdges = shape.identity ? 0 : shape.edgeCount;\n return [\n 4 * (shape.nodeCount + 1),\n 4 * shape.arcCount,\n shape.weighted ? 4 * shape.arcCount : 0,\n 4 * permArcs,\n 4 * permEdges,\n ];\n}\n\n/**\n * Allocate the core arrays as separate fresh buffers (design section 6.3 step 11 with `arena: false`,\n * and the transient target of a non-\"keep\" duplicate policy). Every array is a fresh typed array, so\n * I10 holds by the constructor guarantee.\n * @param shape - the core shape\n * @returns the arrays with `arena: null`\n */\nexport function allocateSeparateCore(shape: CoreShape): CoreArrays {\n return {\n rowPtr: new Uint32Array(shape.nodeCount + 1),\n colIdx: new Uint32Array(shape.arcCount),\n weights: shape.weighted ? new Float32Array(shape.arcCount) : null,\n arcToEdge: shape.identity ? null : new Uint32Array(shape.arcCount),\n edgeToArc: shape.identity ? null : new Uint32Array(shape.edgeCount),\n arena: null,\n };\n}\n\n/**\n * Allocate the core arrays inside one arena (design section 10.3): one ArrayBuffer of the total padded\n * size, every non-empty segment starting at a multiple of 256 bytes, ordered rowPtr, colIdx, weights,\n * arcToEdge, edgeToArc. `hotByteLength` is the end of the weights segment (or of colIdx when\n * unweighted). For the worked example of section 10.3 (n = 100,000, A = 2,000,000, E = 1,000,000,\n * weighted, permutations materialised) the segments start at 0 / 400,128 / 8,400,128 / 16,400,128 /\n * 24,400,128 and the arena is 28,400,128 bytes.\n * @param shape - the core shape\n * @returns the arrays as views into the arena, plus its layout\n */\nexport function allocateArenaCore(shape: CoreShape): CoreArrays {\n const byteLengths = byteLengthsOf(shape);\n const layout = layoutSegments(byteLengths, ALIGNMENT);\n const buffer = new ArrayBuffer(layout.byteLength);\n const segments: Record<CoreArrayName, ArenaSegment | null> = {\n rowPtr: null,\n colIdx: null,\n weights: null,\n arcToEdge: null,\n edgeToArc: null,\n };\n let hotByteLength = 0;\n for (let i = 0; i < CORE_ORDER.length; i++) {\n const offset = layout.offsets[i];\n if (offset === null) {\n continue;\n }\n const segment: ArenaSegment = Object.freeze({ byteOffset: offset, byteLength: byteLengths[i] });\n segments[CORE_ORDER[i]] = segment;\n if (i <= 2) {\n hotByteLength = offset + byteLengths[i];\n }\n }\n const u32 = (name: CoreArrayName, length: number): U32 => {\n const segment = segments[name];\n return segment === null ? new Uint32Array(0) : new Uint32Array(buffer, segment.byteOffset, length);\n };\n let weights: F32 | null = null;\n if (shape.weighted) {\n const segment = segments.weights;\n weights = segment === null ? new Float32Array(0) : new Float32Array(buffer, segment.byteOffset, shape.arcCount);\n }\n const arena: ArenaLayout = Object.freeze({\n buffer,\n byteOffset: 0,\n byteLength: layout.byteLength,\n alignment: ALIGNMENT,\n segments: Object.freeze(segments),\n hotByteLength,\n });\n return {\n rowPtr: u32(\"rowPtr\", shape.nodeCount + 1),\n colIdx: u32(\"colIdx\", shape.arcCount),\n weights,\n arcToEdge: shape.identity ? null : u32(\"arcToEdge\", shape.arcCount),\n edgeToArc: shape.identity ? null : u32(\"edgeToArc\", shape.edgeCount),\n arena,\n };\n}\n\n/**\n * Allocate the core arrays for a shape, in one arena or as separate buffers.\n * @param shape - the core shape\n * @param useArena - true for one 256-aligned arena (the freeze default), false for separate buffers\n * @returns the arrays\n */\nexport function allocateCoreArrays(shape: CoreShape, useArena: boolean): CoreArrays {\n return useArena ? allocateArenaCore(shape) : allocateSeparateCore(shape);\n}\n\n/**\n * The shape of an already built core.\n * @param core - the core arrays\n * @returns the shape\n */\nexport function shapeOfCore(core: CoreArrays): CoreShape {\n return {\n nodeCount: core.rowPtr.length - 1,\n arcCount: core.colIdx.length,\n edgeCount: core.edgeToArc === null ? core.colIdx.length : core.edgeToArc.length,\n weighted: core.weights !== null,\n identity: core.arcToEdge === null,\n };\n}\n\n/**\n * Copy a core built in separate buffers into a fresh arena of the same shape (the non-\"keep\" duplicate\n * policy path of design section 6.3 step 7 when nothing was merged: the transient arrays are final,\n * only their home changes). The source arrays are not modified.\n * @param core - the core in separate buffers\n * @returns the same contents as views into a new arena\n */\nexport function copyCoreIntoArena(core: CoreArrays): CoreArrays {\n const out = allocateArenaCore(shapeOfCore(core));\n out.rowPtr.set(core.rowPtr);\n out.colIdx.set(core.colIdx);\n if (out.weights !== null && core.weights !== null) {\n out.weights.set(core.weights);\n }\n if (out.arcToEdge !== null && core.arcToEdge !== null) {\n out.arcToEdge.set(core.arcToEdge);\n }\n if (out.edgeToArc !== null && core.edgeToArc !== null) {\n out.edgeToArc.set(core.edgeToArc);\n }\n return out;\n}\n","/**\n * The row-ordering queries of design section 3.9 as pure functions over the core arrays: binary\n * searches over sorted rows (invariant I4) for `findArc` / `hasArc` / `arcsBetween` /\n * `multiplicity` / `selfLoopsAt`, and the binary search over `rowPtr` behind `arcSource`. Every\n * function is total for in-range arguments and unchecked for out-of-range ones (design section\n * 11.1: typed-array semantics, no bounds checks in hot paths). GraphSnapshot's methods of the same\n * names delegate here; the views and the derived graphs reuse the searches directly.\n *\n * Multigraph semantics (design section 3.5): parallel arcs are adjacent and ordered by logical edge\n * index, so the first arc of `[lo, hi)` is the lowest logical edge index among the parallels.\n */\n\nimport { INVALID_INDEX } from \"../constants.js\";\nimport { type U32 } from \"../types/index.js\";\n\n/**\n * The first index in [lo, hi) whose value is >= v, or hi when none is (the sorted-row lower bound).\n * @param colIdx - the sorted targets\n * @param lo - the start of the row\n * @param hi - one past the end of the row\n * @param v - the target to search for\n * @returns the lower bound\n */\nexport function lowerBound(colIdx: U32, lo: number, hi: number, v: number): number {\n let low = lo;\n let high = hi;\n while (low < high) {\n const mid = low + Math.floor((high - low) / 2);\n if (colIdx[mid] < v) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n}\n\n/**\n * The first index in [lo, hi) whose value is > v, or hi when none is (the sorted-row upper bound).\n * @param colIdx - the sorted targets\n * @param lo - the start of the row\n * @param hi - one past the end of the row\n * @param v - the target to search for\n * @returns the upper bound\n */\nexport function upperBound(colIdx: U32, lo: number, hi: number, v: number): number {\n let low = lo;\n let high = hi;\n while (low < high) {\n const mid = low + Math.floor((high - low) / 2);\n if (colIdx[mid] <= v) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low;\n}\n\n/**\n * The first arc u -> v (the lowest logical edge index among parallels), or INVALID_INDEX.\n * @param rowPtr - the row offsets\n * @param colIdx - the sorted targets\n * @param u - the source node index\n * @param v - the target node index\n * @returns the arc index or INVALID_INDEX\n */\nexport function findArcIn(rowPtr: U32, colIdx: U32, u: number, v: number): number {\n const hi = rowPtr[u + 1];\n const at = lowerBound(colIdx, rowPtr[u], hi, v);\n return at < hi && colIdx[at] === v ? at : INVALID_INDEX;\n}\n\n/**\n * The half-open arc range [lo, hi) of every arc u -> v; empty (lo === hi) when there is none.\n * @param rowPtr - the row offsets\n * @param colIdx - the sorted targets\n * @param u - the source node index\n * @param v - the target node index\n * @returns the range as a fresh two-element tuple\n */\nexport function arcRangeIn(rowPtr: U32, colIdx: U32, u: number, v: number): [lo: number, hi: number] {\n const start = rowPtr[u];\n const end = rowPtr[u + 1];\n const lo = lowerBound(colIdx, start, end, v);\n const hi = upperBound(colIdx, lo, end, v);\n return [lo, hi];\n}\n\n/**\n * The number of parallel arcs u -> v.\n * @param rowPtr - the row offsets\n * @param colIdx - the sorted targets\n * @param u - the source node index\n * @param v - the target node index\n * @returns hi - lo of the arc range\n */\nexport function multiplicityIn(rowPtr: U32, colIdx: U32, u: number, v: number): number {\n const start = rowPtr[u];\n const end = rowPtr[u + 1];\n const lo = lowerBound(colIdx, start, end, v);\n return upperBound(colIdx, lo, end, v) - lo;\n}\n\n/**\n * The row containing an arc: the largest u with rowPtr[u] <= a < rowPtr[u + 1], found by binary\n * search over rowPtr (empty rows are skipped because their two offsets are equal).\n * @param rowPtr - the row offsets, nodeCount + 1 entries\n * @param a - the arc index, below rowPtr[nodeCount]\n * @returns the source node index\n */\nexport function arcSourceIn(rowPtr: U32, a: number): number {\n // first index i with rowPtr[i] > a; the row is i - 1\n let low = 0;\n let high = rowPtr.length;\n while (low < high) {\n const mid = low + Math.floor((high - low) / 2);\n if (rowPtr[mid] <= a) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return low - 1;\n}\n\n/**\n * The number of self-loop arcs at a node: the multiplicity of u -> u.\n * @param rowPtr - the row offsets\n * @param colIdx - the sorted targets\n * @param u - the node index\n * @returns the loop count\n */\nexport function selfLoopsAtIn(rowPtr: U32, colIdx: U32, u: number): number {\n return multiplicityIn(rowPtr, colIdx, u, u);\n}\n","/**\n * The cached views of design section 7.2 as pure functions of a snapshot's core arrays, plus the\n * per-arc / per-edge boundary helpers `foldArcs` and `expandEdges` of design section 7.5.\n *\n * Every function here computes one view from the public core (rowPtr, colIdx, weights, arcToEdge,\n * edgeToArc, flags, counts) in O(n + m) or O(n log d) and returns a fresh object; GraphSnapshot owns\n * the per-instance cache (invariant I17: computed once, never invalidated, SHARED -- a caller that\n * needs scratch calls `.slice()`). Aliasing is deliberate and documented per view: `coo().dst` is\n * `colIdx`, `reverse()` of an undirected snapshot is the forward arrays, an identity permutation\n * lets `edgeList().weights` alias `weights`, and so on, so `viewByteLength()` counts only the bytes a\n * view owns.\n *\n * Nothing here allocates an identity permutation that the snapshot has not materialised: view objects\n * reach `arcToEdge` / `edgeToArc` through getters, so touching `coo()` on a directed identity\n * snapshot costs one `src` array and nothing else until `coo().arcToEdge` is read.\n */\n\nimport { GraphFormatError } from \"../errors.js\";\nimport {\n type CooView,\n type DegreeOrderView,\n type EdgeListView,\n type F32,\n type F64,\n type GraphSnapshot,\n type NumericVector,\n type ReverseView,\n type U32,\n type ViewName,\n} from \"../types/index.js\";\nimport { assertOneOf } from \"../util/options.js\";\nimport { arcRangeIn } from \"./queries.js\";\n\n// ============================================================ reverse\n\n/**\n * The cuGraph degree tiers of `degreeOrder()`: a node with at least DEGREE_TIER_HIGH arcs is scheduled\n * per workgroup, at least DEGREE_TIER_MID per subgroup, at least DEGREE_TIER_LOW per thread; degree 0\n * nodes form the trailing segment (design section 7.2).\n */\nexport const DEGREE_TIER_HIGH = 1024;\n/** Lower bound of the middle degree tier. */\nexport const DEGREE_TIER_MID = 32;\n/** Lower bound of the low degree tier. */\nconst DEGREE_TIER_LOW = 1;\n\n/**\n * The identity permutation of `length` entries as a fresh 4-byte-aligned array (invariant I10).\n * @param length - the entry count\n * @returns 0..length-1\n */\nexport function identityPermutation(length: number): U32 {\n const out = new Uint32Array(length);\n for (let i = 0; i < length; i++) {\n out[i] = i;\n }\n return out;\n}\n\n/**\n * The in-adjacency of a snapshot (design section 7.2): `ReverseView` with `fwdArc` (reverse arc k ->\n * forward arc) and `arcToEdge` (`arcToEdge[fwdArc[k]]`) materialised lazily. For an undirected\n * snapshot the forward arrays are shared (invariant I7), `fwdArc` is the identity (allocated on first\n * read) and `arcToEdge` is the snapshot's own array. For a directed snapshot whose permutation is the\n * identity, the reverse `arcToEdge` IS `fwdArc` (aliased, zero bytes).\n */\nexport class ReverseAdjacency implements ReverseView {\n /** Whether the source snapshot is directed. */\n readonly directed: boolean;\n /** Number of nodes. */\n readonly nodeCount: number;\n /** Number of arcs. */\n readonly arcCount: number;\n /** Row offsets of the reverse adjacency (the forward rowPtr when undirected). */\n readonly rowPtr: U32;\n /** Source node of every forward arc, sorted within each reverse row (the forward colIdx when undirected). */\n readonly colIdx: U32;\n /** Per-reverse-arc weights, gathered from the forward weights (the forward array when undirected). */\n readonly weights: F32 | null;\n\n private readonly source: GraphSnapshot;\n private fwdArcCache: U32 | null;\n private arcToEdgeCache: U32 | null;\n private arcToEdgeOwned: boolean;\n private readonly fwdArcIsIdentity: boolean;\n\n /**\n * Wrap the reverse arrays. Used by `computeReverse()`; not meant to be constructed elsewhere.\n * @param source - the snapshot the view belongs to\n * @param rowPtr - the reverse row offsets\n * @param colIdx - the reverse targets (forward sources)\n * @param weights - the gathered weights, or null when unweighted\n * @param fwdArc - the reverse arc -> forward arc map, or null when it is the identity (undirected)\n */\n constructor(source: GraphSnapshot, rowPtr: U32, colIdx: U32, weights: F32 | null, fwdArc: U32 | null) {\n this.source = source;\n this.directed = source.directed;\n this.nodeCount = source.nodeCount;\n this.arcCount = source.arcCount;\n this.rowPtr = rowPtr;\n this.colIdx = colIdx;\n this.weights = weights;\n this.fwdArcCache = fwdArc;\n this.fwdArcIsIdentity = fwdArc === null;\n this.arcToEdgeCache = null;\n this.arcToEdgeOwned = false;\n }\n\n /**\n * Reverse arc k -> forward arc index; the identity for an undirected snapshot, materialised on first\n * read outside any arena.\n * @returns the map, arcCount entries\n */\n get fwdArc(): U32 {\n this.fwdArcCache ??= identityPermutation(this.arcCount);\n return this.fwdArcCache;\n }\n\n /**\n * Logical edge of every reverse arc: `source.arcToEdge[fwdArc[k]]`, materialised on first read.\n * Aliases `source.arcToEdge` when undirected and `fwdArc` when the forward permutation is the\n * identity.\n * @returns the map, arcCount entries\n */\n get arcToEdge(): U32 {\n if (this.arcToEdgeCache === null) {\n if (this.fwdArcIsIdentity) {\n this.arcToEdgeCache = this.source.arcToEdge;\n } else if (this.source.flags.arcToEdgeIsIdentity) {\n this.arcToEdgeCache = this.fwdArc;\n } else {\n const { fwdArc } = this;\n const forward = this.source.arcToEdge;\n const out = new Uint32Array(this.arcCount);\n for (let k = 0; k < out.length; k++) {\n out[k] = forward[fwdArc[k]];\n }\n this.arcToEdgeCache = out;\n this.arcToEdgeOwned = true;\n }\n }\n return this.arcToEdgeCache;\n }\n\n /**\n * Bytes owned by this view (not shared with the snapshot's core): the reverse arrays when directed,\n * a materialised identity `fwdArc`, and a gathered `arcToEdge`.\n * @returns the byte count\n */\n get ownedByteLength(): number {\n let bytes = 0;\n if (this.directed) {\n bytes += this.rowPtr.byteLength + this.colIdx.byteLength;\n if (this.weights !== null) {\n bytes += this.weights.byteLength;\n }\n }\n if (this.fwdArcCache !== null) {\n bytes += this.fwdArcCache.byteLength;\n }\n if (this.arcToEdgeOwned && this.arcToEdgeCache !== null) {\n bytes += this.arcToEdgeCache.byteLength;\n }\n return bytes;\n }\n\n /**\n * The arrays this view has materialised so far, for checksums and byte accounting.\n * @returns the arrays, keyed by member name\n */\n materialised(): Readonly<Record<string, Uint32Array | Float32Array>> {\n const out: Record<string, Uint32Array | Float32Array> = {\n rowPtr: this.rowPtr,\n colIdx: this.colIdx,\n };\n if (this.weights !== null) {\n out.weights = this.weights;\n }\n if (this.fwdArcCache !== null) {\n out.fwdArc = this.fwdArcCache;\n }\n if (this.arcToEdgeCache !== null) {\n out.arcToEdge = this.arcToEdgeCache;\n }\n return out;\n }\n}\n\n/**\n * Compute the reverse view (design section 7.2): a stable counting sort of the forward arcs by target\n * (O(n + m)) so that every reverse row is sorted by source with parallels in ascending edge order\n * (invariant I4 for the reverse), weights gathered when weighted (Q37). Undirected: the forward\n * arrays themselves (invariant I7).\n * @param snapshot - the snapshot\n * @returns the reverse view\n */\nexport function computeReverse(snapshot: GraphSnapshot): ReverseAdjacency {\n const { nodeCount, arcCount, rowPtr, colIdx, weights } = snapshot;\n if (!snapshot.directed) {\n return new ReverseAdjacency(snapshot, rowPtr, colIdx, weights, null);\n }\n const revPtr = new Uint32Array(nodeCount + 1);\n for (let a = 0; a < arcCount; a++) {\n revPtr[colIdx[a] + 1]++;\n }\n for (let v = 0; v < nodeCount; v++) {\n revPtr[v + 1] += revPtr[v];\n }\n const revIdx = new Uint32Array(arcCount);\n const fwdArc = new Uint32Array(arcCount);\n const revWeights = weights === null ? null : new Float32Array(arcCount);\n const cursor = revPtr.slice(0, nodeCount);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u]; a < end; a++) {\n const v = colIdx[a];\n const k = cursor[v]++;\n revIdx[k] = u;\n fwdArc[k] = a;\n if (revWeights !== null && weights !== null) {\n revWeights[k] = weights[a];\n }\n }\n }\n return new ReverseAdjacency(snapshot, revPtr, revIdx, revWeights, fwdArc);\n}\n\n// ============================================================ coo and edge list\n\n/**\n * The source node of every arc: `rowPtr` expanded to arc length.\n * @param rowPtr - the row offsets\n * @param nodeCount - the node count\n * @param arcCount - the arc count\n * @returns a fresh Uint32Array(arcCount)\n */\nfunction expandRowPtr(rowPtr: U32, nodeCount: number, arcCount: number): U32 {\n const src = new Uint32Array(arcCount);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u]; a < end; a++) {\n src[a] = u;\n }\n }\n return src;\n}\n\n/**\n * Compute the per-arc COO view (design section 7.2): `src` is the only new array; `dst` aliases\n * `colIdx`, `weights` aliases `weights`, and `arcToEdge` reaches the snapshot's array through a\n * getter (so an identity permutation is not materialised by building the view).\n * @param snapshot - the snapshot\n * @returns the COO view\n */\nexport function computeCoo(snapshot: GraphSnapshot): CooView {\n return cooViewOf(snapshot, expandRowPtr(snapshot.rowPtr, snapshot.nodeCount, snapshot.arcCount));\n}\n\n/**\n * Wrap a per-arc source array as the COO view of a snapshot (the shape `computeCoo()` returns; also\n * used to install a carried `src` from the wire).\n * @param snapshot - the snapshot\n * @param src - source node of every arc, arcCount entries\n * @returns the COO view\n */\nexport function cooViewOf(snapshot: GraphSnapshot, src: U32): CooView {\n return Object.freeze({\n src,\n dst: snapshot.colIdx,\n weights: snapshot.weights,\n get arcToEdge(): U32 {\n return snapshot.arcToEdge;\n },\n });\n}\n\n/**\n * Compute the edge list view (design section 7.2): every logical edge once in declared orientation.\n * `src[e]` is the row holding `edgeToArc[e]`, `dst[e] === colIdx[edgeToArc[e]]`, `arc` aliases\n * `edgeToArc` through a getter, `weights` is gathered through `edgeToArc` (aliased when the\n * permutation is the identity, in which case `dst` aliases `colIdx` too).\n * @param snapshot - the snapshot\n * @returns the edge list view\n */\nexport function computeEdgeList(snapshot: GraphSnapshot): EdgeListView {\n const { nodeCount, edgeCount, arcCount, rowPtr, colIdx, weights } = snapshot;\n if (snapshot.flags.arcToEdgeIsIdentity) {\n return edgeListViewOf(snapshot, expandRowPtr(rowPtr, nodeCount, arcCount), colIdx, weights);\n }\n const { arcToEdge, edgeToArc } = snapshot;\n const src = new Uint32Array(edgeCount);\n const dst = new Uint32Array(edgeCount);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u]; a < end; a++) {\n const e = arcToEdge[a];\n if (edgeToArc[e] === a) {\n src[e] = u;\n dst[e] = colIdx[a];\n }\n }\n }\n let edgeWeights: F32 | null = null;\n if (weights !== null) {\n edgeWeights = new Float32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n edgeWeights[e] = weights[edgeToArc[e]];\n }\n }\n return edgeListViewOf(snapshot, src, dst, edgeWeights);\n}\n\n/**\n * Wrap per-edge arrays as the edge list view of a snapshot (the shape `computeEdgeList()` returns;\n * also used to install carried arrays from the wire). `arc` reaches `edgeToArc` through a getter so\n * an identity permutation is not materialised by building the view.\n * @param snapshot - the snapshot\n * @param src - declared source of every edge, edgeCount entries\n * @param dst - declared target of every edge, edgeCount entries (colIdx itself when the permutation is the identity)\n * @param weights - per-edge weights, or null when unweighted\n * @returns the edge list view\n */\nexport function edgeListViewOf(snapshot: GraphSnapshot, src: U32, dst: U32, weights: F32 | null): EdgeListView {\n return Object.freeze({\n src,\n dst,\n weights,\n get arc(): U32 {\n return snapshot.edgeToArc;\n },\n });\n}\n\n// ============================================================ degrees\n\n/**\n * Out-arc counts: `rowPtr[u + 1] - rowPtr[u]` (a self-loop counted once, design section 3.4).\n * @param rowPtr - the row offsets\n * @param nodeCount - the node count\n * @returns a fresh Uint32Array(nodeCount)\n */\nexport function rowLengths(rowPtr: U32, nodeCount: number): U32 {\n const out = new Uint32Array(nodeCount);\n for (let u = 0; u < nodeCount; u++) {\n out[u] = rowPtr[u + 1] - rowPtr[u];\n }\n return out;\n}\n\n/**\n * The graph-theoretic degree (design section 3.4): in + out when directed, out + self-loops when\n * undirected (a loop counts twice, the NetworkX convention).\n * @param outDegree - the out-degree view\n * @param inOrLoops - inDegree() when directed, selfLoopsPerNode() when undirected\n * @returns a fresh Uint32Array(n)\n */\nexport function sumDegrees(outDegree: U32, inOrLoops: U32): U32 {\n const out = new Uint32Array(outDegree.length);\n for (let u = 0; u < out.length; u++) {\n out[u] = outDegree[u] + inOrLoops[u];\n }\n return out;\n}\n\n/**\n * Row sums of an arc-aligned weight array as f64 (design section 7.2): a self-loop arc counted once;\n * a row may sum to 0 because zero weights are legal.\n * @param rowPtr - the row offsets of the adjacency being summed (forward or reverse)\n * @param weights - the arc-aligned weights of that adjacency\n * @param nodeCount - the node count\n * @returns a fresh Float64Array(nodeCount)\n */\nexport function rowWeightSums(rowPtr: U32, weights: F32, nodeCount: number): F64 {\n const out = new Float64Array(nodeCount);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n let sum = 0;\n for (let a = rowPtr[u]; a < end; a++) {\n sum += weights[a];\n }\n out[u] = sum;\n }\n return out;\n}\n\n/**\n * A u32 count vector widened to f64 (the unweighted case of the weighted-degree views).\n * @param counts - the counts\n * @returns a fresh Float64Array of the same length\n */\nexport function widenToF64(counts: U32): F64 {\n return new Float64Array(counts);\n}\n\n/**\n * Element-wise sum of two f64 vectors of equal length.\n * @param a - the first vector\n * @param b - the second vector\n * @returns a fresh Float64Array\n */\nexport function sumF64(a: F64, b: F64): F64 {\n const out = new Float64Array(a.length);\n for (let i = 0; i < out.length; i++) {\n out[i] = a[i] + b[i];\n }\n return out;\n}\n\n/**\n * The sum of weights over logical edges, each undirected edge once (design section 7.2), accumulated\n * in f64. `edgeCount` when unweighted.\n * @param snapshot - the snapshot\n * @returns the total weight\n */\nexport function computeTotalWeight(snapshot: GraphSnapshot): number {\n const { weights, edgeCount } = snapshot;\n if (weights === null) {\n return edgeCount;\n }\n let sum = 0;\n if (snapshot.flags.arcToEdgeIsIdentity) {\n for (let a = 0; a < weights.length; a++) {\n sum += weights[a];\n }\n return sum;\n }\n const { edgeToArc } = snapshot;\n for (let e = 0; e < edgeCount; e++) {\n sum += weights[edgeToArc[e]];\n }\n return sum;\n}\n\n// ============================================================ self-loops\n\n/** The two self-loop views, computed together in one O(n log d) pass. */\ninterface SelfLoopViews {\n /** Arcs a with colIdx[a] === row(a), ascending. */\n readonly selfLoopArcs: U32;\n /** Loop arcs per node. */\n readonly selfLoopsPerNode: U32;\n}\n\n/**\n * Find every self-loop arc by a binary search per row (design section 7.2).\n * @param snapshot - the snapshot\n * @returns the loop arcs (length selfLoopCount) and the per-node counts\n */\nexport function computeSelfLoops(snapshot: GraphSnapshot): SelfLoopViews {\n const { nodeCount, rowPtr, colIdx, selfLoopCount } = snapshot;\n const perNode = new Uint32Array(nodeCount);\n const arcs = new Uint32Array(selfLoopCount);\n let at = 0;\n for (let u = 0; u < nodeCount; u++) {\n const [lo, hi] = arcRangeIn(rowPtr, colIdx, u, u);\n perNode[u] = hi - lo;\n for (let a = lo; a < hi && at < selfLoopCount; a++) {\n arcs[at++] = a;\n }\n }\n return { selfLoopArcs: arcs, selfLoopsPerNode: perNode };\n}\n\n/**\n * Sum of weights over each node's self-loop arcs as f64; the loop counts widened when unweighted.\n * @param snapshot - the snapshot\n * @param loops - the self-loop views\n * @returns a fresh Float64Array(n)\n */\nexport function computeSelfLoopWeight(snapshot: GraphSnapshot, loops: SelfLoopViews): F64 {\n const { weights, nodeCount, rowPtr, colIdx } = snapshot;\n if (weights === null) {\n return widenToF64(loops.selfLoopsPerNode);\n }\n const out = new Float64Array(nodeCount);\n for (let u = 0; u < nodeCount; u++) {\n if (loops.selfLoopsPerNode[u] === 0) {\n continue;\n }\n const [lo, hi] = arcRangeIn(rowPtr, colIdx, u, u);\n let sum = 0;\n for (let a = lo; a < hi; a++) {\n sum += weights[a];\n }\n out[u] = sum;\n }\n return out;\n}\n\n// ============================================================ mate\n\n/**\n * The E_INVALID_SNAPSHOT error the mate walk raises when the doubled storage of invariant I7 does not\n * hold (the row of the mate does not hold the expected source at the cursor).\n * @param u - the row being walked\n * @param v - the target whose mate group was expected\n * @param arc - the arc where the walk failed\n * @returns the error\n */\nfunction pairingError(u: number, v: number, arc: number): GraphFormatError {\n return new GraphFormatError(\n \"E_INVALID_SNAPSHOT\",\n `invariant I7 violated: arc ${arc} in row ${u} targeting ${v} has no mate in row ${v}`,\n { invariant: \"I7\", row: u, arc, target: v },\n );\n}\n\n/**\n * For every arc of an undirected snapshot, the arc storing the opposite orientation of the same edge\n * (a self-loop maps to itself), by the O(m) lockstep walk of design section 6.4: rows are visited in\n * ascending order, every group of k parallel arcs u -> v (v > u) is paired k-th to k-th with the group\n * v -> u at row v's cursor, and the cursor advances so that by the time row v is visited every\n * target below v has been consumed. Throws E_DIRECTED on a directed snapshot.\n * @param snapshot - an undirected snapshot\n * @returns a fresh Uint32Array(arcCount)\n */\nexport function computeMate(snapshot: GraphSnapshot): U32 {\n if (snapshot.directed) {\n throw new GraphFormatError(\"E_DIRECTED\", \"mate() is defined for undirected snapshots only\", {\n directed: true,\n });\n }\n const { nodeCount, arcCount, rowPtr, colIdx } = snapshot;\n const mate = new Uint32Array(arcCount);\n const cursor = rowPtr.slice(0, nodeCount);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n let a = cursor[u];\n while (a < end) {\n const v = colIdx[a];\n let g = a + 1;\n while (g < end && colIdx[g] === v) {\n g++;\n }\n const k = g - a;\n if (v === u) {\n for (let i = 0; i < k; i++) {\n mate[a + i] = a + i;\n }\n } else {\n const b = cursor[v];\n if (v < u || b + k > rowPtr[v + 1] || colIdx[b] !== u || colIdx[b + k - 1] !== u) {\n throw pairingError(u, v, a);\n }\n for (let i = 0; i < k; i++) {\n mate[a + i] = b + i;\n mate[b + i] = a + i;\n }\n cursor[v] = b + k;\n }\n a = g;\n }\n cursor[u] = end;\n }\n return mate;\n}\n\n// ============================================================ degree order\n\n/**\n * Nodes permuted by descending out-degree of an adjacency (counting sort, ties in ascending node\n * index) with the cuGraph tier boundaries (design section 7.2): `segmentOffsets = [0, hiEnd,\n * midEnd, lowEnd, n]` for the thresholds 1024 / 32 / 1.\n * @param rowPtr - the row offsets of the adjacency to order by (forward, or reverse for the in-degree)\n * @param nodeCount - the node count\n * @returns the permutation and its tier offsets\n */\nexport function computeDegreeOrder(rowPtr: U32, nodeCount: number): DegreeOrderView {\n const degree = rowLengths(rowPtr, nodeCount);\n let maxDegree = 0;\n for (let u = 0; u < nodeCount; u++) {\n if (degree[u] > maxDegree) {\n maxDegree = degree[u];\n }\n }\n const start = new Uint32Array(maxDegree + 1);\n for (let u = 0; u < nodeCount; u++) {\n start[degree[u]]++;\n }\n // descending: the start of degree d is the number of nodes with a larger degree\n let run = 0;\n for (let d = maxDegree; d >= 0; d--) {\n const count = start[d];\n start[d] = run;\n run += count;\n }\n const perm = new Uint32Array(nodeCount);\n let hi = 0;\n let mid = 0;\n let low = 0;\n for (let u = 0; u < nodeCount; u++) {\n const d = degree[u];\n perm[start[d]++] = u;\n if (d >= DEGREE_TIER_HIGH) {\n hi++;\n } else if (d >= DEGREE_TIER_MID) {\n mid++;\n } else if (d >= DEGREE_TIER_LOW) {\n low++;\n }\n }\n const segmentOffsets = new Uint32Array([0, hi, hi + mid, hi + mid + low, nodeCount]);\n return Object.freeze({ perm, segmentOffsets });\n}\n\n// ============================================================ symmetry\n\n/**\n * Whether a directed snapshot's arc set is closed under reversal with equal weights (design sections\n * 3.6 and 7.2): forward row v and reverse row v hold the same targets (versus sources; both sorted,\n * so one lockstep walk), and within each run of parallel arcs to one target the same multiset of\n * weights. Parallel arcs are ordered by edge index in both rows, so their weights can arrive in a\n * different order (an expanded undirected multigraph with unequal parallel weights, design section\n * 6.6); each run is compared as a sorted multiset, which is positional for simple graphs. Undirected\n * snapshots are symmetric by construction.\n * @param snapshot - the snapshot\n * @param reverse - its reverse view\n * @returns true when symmetric\n */\nexport function computeSymmetric(snapshot: GraphSnapshot, reverse: ReverseView): boolean {\n if (!snapshot.directed) {\n return true;\n }\n const { nodeCount, arcCount, rowPtr, colIdx, weights } = snapshot;\n for (let v = 0; v <= nodeCount; v++) {\n if (rowPtr[v] !== reverse.rowPtr[v]) {\n return false;\n }\n }\n const revIdx = reverse.colIdx;\n for (let a = 0; a < arcCount; a++) {\n if (colIdx[a] !== revIdx[a]) {\n return false;\n }\n }\n const revWeights = reverse.weights;\n if (weights === null || revWeights === null) {\n return true;\n }\n if (!snapshot.flags.multigraph) {\n for (let a = 0; a < arcCount; a++) {\n if (weights[a] !== revWeights[a]) {\n return false;\n }\n }\n return true;\n }\n // multigraph: compare each parallel run (adjacent by I4, equal targets in both rows) as a multiset\n let a = 0;\n while (a < arcCount) {\n let b = a + 1;\n while (b < arcCount && colIdx[b] === colIdx[a] && b < rowPtr[rowOf(rowPtr, nodeCount, a) + 1]) {\n b++;\n }\n if (b - a === 1) {\n if (weights[a] !== revWeights[a]) {\n return false;\n }\n } else if (!sameWeightMultiset(weights, revWeights, a, b)) {\n return false;\n }\n a = b;\n }\n return true;\n}\n\n/**\n * The row holding arc `a` (binary search on rowPtr).\n * @param rowPtr - the row offsets\n * @param nodeCount - the node count\n * @param a - the arc\n * @returns the row\n */\nfunction rowOf(rowPtr: U32, nodeCount: number, a: number): number {\n let lo = 0;\n let hi = nodeCount;\n while (hi - lo > 1) {\n const mid = (lo + hi) >>> 1;\n if (rowPtr[mid] <= a) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n return lo;\n}\n\n/**\n * Whether two weight runs hold the same multiset (sorted scratch copies compared position by position).\n * @param x - one weight array\n * @param y - the other\n * @param start - the first arc of the run\n * @param end - one past the last arc of the run\n * @returns true when the multisets agree\n */\nfunction sameWeightMultiset(x: F32, y: F32, start: number, end: number): boolean {\n const p = x.slice(start, end).sort();\n const q = y.slice(start, end).sort();\n for (let i = 0; i < p.length; i++) {\n if (p[i] !== q[i] && !(Number.isNaN(p[i]) && Number.isNaN(q[i]))) {\n return false;\n }\n }\n return true;\n}\n\n// ============================================================ byte accounting\n\n/**\n * The bytes a cached view owns beyond the snapshot's core (aliased arrays count zero), for\n * `byteLength({ views: true })` (design section 7.2).\n * @param snapshot - the snapshot\n * @param name - the view name\n * @param value - the cached value\n * @returns the byte count\n */\nexport function viewByteLength(snapshot: GraphSnapshot, name: ViewName, value: unknown): number {\n switch (name) {\n case \"reverse\":\n return value instanceof ReverseAdjacency ? value.ownedByteLength : 0;\n case \"coo\": {\n const coo = value as CooView;\n return coo.src.byteLength;\n }\n case \"edgeList\": {\n const list = value as EdgeListView;\n let bytes = list.src.byteLength;\n if (list.dst !== snapshot.colIdx) {\n bytes += list.dst.byteLength;\n }\n if (list.weights !== null && list.weights !== snapshot.weights) {\n bytes += list.weights.byteLength;\n }\n return bytes;\n }\n case \"outDegree\":\n case \"inDegree\":\n case \"degree\":\n case \"weightedOutDegree\":\n case \"weightedInDegree\":\n case \"weightedDegree\":\n case \"selfLoopWeight\":\n case \"selfLoopArcs\":\n case \"selfLoopsPerNode\":\n case \"mate\":\n return (value as ArrayBufferView).byteLength;\n case \"degreeOrder\":\n case \"reverseDegreeOrder\": {\n const order = value as DegreeOrderView;\n return order.perm.byteLength + order.segmentOffsets.byteLength;\n }\n case \"totalWeight\":\n case \"symmetric\":\n return 0;\n default: {\n const unknown: never = name;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown view ${String(unknown)}`, { view: unknown });\n }\n }\n}\n\n/**\n * The typed arrays a cached view currently holds, keyed by member name, for the checksum records of\n * design section 5.8 (aliased core arrays are included: a write through the alias is a violation\n * too). Scalar views hold nothing.\n * @param snapshot - the snapshot\n * @param name - the view name\n * @param value - the cached value\n * @returns the arrays by member name\n */\nexport function viewArrays(\n snapshot: GraphSnapshot,\n name: ViewName,\n value: unknown,\n): Readonly<Record<string, ArrayBufferView>> {\n switch (name) {\n case \"reverse\":\n return value instanceof ReverseAdjacency ? value.materialised() : {};\n case \"coo\": {\n const coo = value as CooView;\n return { src: coo.src };\n }\n case \"edgeList\": {\n const list = value as EdgeListView;\n const out: Record<string, ArrayBufferView> = { src: list.src };\n if (list.dst !== snapshot.colIdx) {\n out.dst = list.dst;\n }\n if (list.weights !== null && list.weights !== snapshot.weights) {\n out.weights = list.weights;\n }\n return out;\n }\n case \"outDegree\":\n case \"inDegree\":\n case \"degree\":\n case \"weightedOutDegree\":\n case \"weightedInDegree\":\n case \"weightedDegree\":\n case \"selfLoopWeight\":\n case \"selfLoopArcs\":\n case \"selfLoopsPerNode\":\n case \"mate\":\n return { data: value as ArrayBufferView };\n case \"degreeOrder\":\n case \"reverseDegreeOrder\": {\n const order = value as DegreeOrderView;\n return { perm: order.perm, segmentOffsets: order.segmentOffsets };\n }\n case \"totalWeight\":\n case \"symmetric\":\n return {};\n default: {\n const unknown: never = name;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown view ${String(unknown)}`, { view: unknown });\n }\n }\n}\n\n// ============================================================ boundary helpers (7.5)\n\n/**\n * A zeroed vector of the same class as `like`.\n * @param like - the vector whose class to match\n * @param length - the element count\n * @returns the new vector\n */\nfunction allocVector<T extends NumericVector>(like: T, length: number): T {\n if (like instanceof Float64Array) {\n return new Float64Array(length) as T;\n }\n if (like instanceof Float32Array) {\n return new Float32Array(length) as T;\n }\n if (like instanceof Int32Array) {\n return new Int32Array(length) as T;\n }\n return new Uint32Array(length) as T;\n}\n\n/**\n * Reduce a per-arc vector (arcCount entries) to a per-edge vector (edgeCount entries) through\n * `arcToEdge` (design section 7.5): `\"first\"` takes the value of the arc holding the declared\n * orientation (`edgeToArc[e]`), `\"sum\"` / `\"max\"` / `\"min\"` combine both arcs of an undirected edge.\n * Returns `perArc` itself when the permutation is the identity and no `out` is given.\n * @param snapshot - the snapshot the vector is aligned to\n * @param perArc - the per-arc values, arcCount entries\n * @param reducer - how the arcs of one edge combine\n * @param out - an optional destination of edgeCount entries\n * @returns the per-edge vector\n */\nexport function foldArcs<T extends NumericVector>(\n snapshot: GraphSnapshot,\n perArc: T,\n reducer: \"first\" | \"sum\" | \"max\" | \"min\",\n out?: T,\n): T {\n const { edgeCount, arcCount } = snapshot;\n assertOneOf(\"reducer\", reducer, [\"first\", \"sum\", \"max\", \"min\"] as const);\n if (perArc.length !== arcCount) {\n throw new GraphFormatError(\"E_COLUMN_LENGTH\", `perArc has ${perArc.length} entries, expected ${arcCount}`, {\n expected: arcCount,\n found: perArc.length,\n });\n }\n if (snapshot.flags.arcToEdgeIsIdentity) {\n if (out === undefined) {\n return perArc;\n }\n out.set(perArc);\n return out;\n }\n const result = out ?? allocVector(perArc, edgeCount);\n const { edgeToArc, arcToEdge } = snapshot;\n for (let e = 0; e < edgeCount; e++) {\n result[e] = perArc[edgeToArc[e]];\n }\n switch (reducer) {\n case \"first\":\n break;\n case \"sum\":\n for (let a = 0; a < arcCount; a++) {\n const e = arcToEdge[a];\n if (edgeToArc[e] !== a) {\n result[e] += perArc[a];\n }\n }\n break;\n case \"max\":\n for (let a = 0; a < arcCount; a++) {\n const e = arcToEdge[a];\n if (perArc[a] > result[e]) {\n result[e] = perArc[a];\n }\n }\n break;\n case \"min\":\n for (let a = 0; a < arcCount; a++) {\n const e = arcToEdge[a];\n if (perArc[a] < result[e]) {\n result[e] = perArc[a];\n }\n }\n break;\n default: {\n const unknown: never = reducer;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown reducer ${String(unknown)}`, { reducer: unknown });\n }\n }\n return result;\n}\n\n/**\n * Expand a per-edge vector (edgeCount entries) to a per-arc vector (arcCount entries) through\n * `arcToEdge` (design section 7.5). Returns `perEdge` itself when the permutation is the identity and\n * no `out` is given.\n * @param snapshot - the snapshot the vector is aligned to\n * @param perEdge - the per-edge values, edgeCount entries\n * @param out - an optional destination of arcCount entries\n * @returns the per-arc vector\n */\nexport function expandEdges<T extends NumericVector>(snapshot: GraphSnapshot, perEdge: T, out?: T): T {\n const { edgeCount, arcCount } = snapshot;\n if (perEdge.length !== edgeCount) {\n throw new GraphFormatError(\"E_COLUMN_LENGTH\", `perEdge has ${perEdge.length} entries, expected ${edgeCount}`, {\n expected: edgeCount,\n found: perEdge.length,\n });\n }\n if (snapshot.flags.arcToEdgeIsIdentity) {\n if (out === undefined) {\n return perEdge;\n }\n out.set(perEdge);\n return out;\n }\n const result = out ?? allocVector(perEdge, arcCount);\n const { arcToEdge } = snapshot;\n for (let a = 0; a < arcCount; a++) {\n result[a] = perEdge[arcToEdge[a]];\n }\n return result;\n}\n","/**\n * `validate()` (design sections 3.2, 9.5 and 11.4): the invariants I1-I13 as one function each, the\n * two levels \"structure\" (O(n + m + columns): lengths, ranges, counts, alignment, column length\n * rules) and \"full\" (O(m log d): sortedness, orientation, pairing, NaN, flag recomputation, id\n * bijection, unique columns), and the flag predicates of design section 3.8 shared with the derived\n * graph core builder so that every flag has exactly one definition.\n *\n * Every check throws `E_INVALID_SNAPSHOT` on the first violation with `details.invariant` naming the\n * number (\"I4\") and the location (`row`, `arc`, `edge`, `column`, `table`, `flag`, `reason`). The\n * functions take the public `GraphSnapshot` contract, so test/invariants.test.ts runs the same\n * helpers over hand-written fixtures. Checksum comparison needs the snapshot's private records and\n * lives in graph-snapshot.ts.\n */\n\nimport { bitmapCount, bitmapGet } from \"../columns/bitmap.js\";\nimport { verifyUniqueColumn } from \"../columns/table.js\";\nimport { ALIGNMENT, INVALID_INDEX, MAX_COUNT } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport {\n type ArenaLayout,\n type AttributeTable,\n type Column,\n type CoreArrayName,\n type F32,\n type GraphSnapshot,\n type SnapshotFlags,\n type U32,\n} from \"../types/index.js\";\nimport { isFourByteAligned, isOverPlainBuffer } from \"../util/typed-array.js\";\n\n// ============================================================ errors\n\n/**\n * Build the E_INVALID_SNAPSHOT error of one violated invariant.\n * @param invariant - the invariant number, e.g. \"I4\"\n * @param message - a plain-ASCII description naming the location\n * @param details - the location (row, arc, edge, column, ...); `invariant` is added\n * @returns the error\n */\nexport function invariantViolation(\n invariant: string,\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n): GraphFormatError {\n return new GraphFormatError(\"E_INVALID_SNAPSHOT\", `invariant ${invariant} violated: ${message}`, {\n invariant,\n ...details,\n });\n}\n\n// ============================================================ flags (3.8)\n\n/** The arrays the flag predicates read; a subset of the core so the builder can call it before the snapshot exists. */\ninterface FlagSource {\n /** Whether the graph is directed. */\n readonly directed: boolean;\n /** The node count. */\n readonly nodeCount: number;\n /** The row offsets. */\n readonly rowPtr: U32;\n /** The sorted targets. */\n readonly colIdx: U32;\n /** The per-arc weights, or null. */\n readonly weights: F32 | null;\n /** The arc -> edge permutation, or null when it is known to be the identity. */\n readonly arcToEdge: U32 | null;\n /** The number of self-loop logical edges. */\n readonly selfLoopCount: number;\n}\n\n/**\n * Whether some row holds two arcs with equal colIdx (parallel edges); adjacent by invariant I4.\n * @param rowPtr - the row offsets\n * @param colIdx - the sorted targets\n * @param nodeCount - the node count\n * @returns true for a multigraph\n */\nfunction hasParallelArcs(rowPtr: U32, colIdx: U32, nodeCount: number): boolean {\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u] + 1; a < end; a++) {\n if (colIdx[a] === colIdx[a - 1]) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * The number of arcs a with colIdx[a] === row(a).\n * @param rowPtr - the row offsets\n * @param colIdx - the sorted targets\n * @param nodeCount - the node count\n * @returns the loop arc count\n */\nexport function countLoopArcs(rowPtr: U32, colIdx: U32, nodeCount: number): number {\n let loops = 0;\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u]; a < end; a++) {\n if (colIdx[a] === u) {\n loops++;\n }\n }\n }\n return loops;\n}\n\n/**\n * Whether a permutation array is the identity.\n * @param perm - the array\n * @returns true when perm[i] === i for every i\n */\nexport function isIdentity(perm: U32): boolean {\n for (let i = 0; i < perm.length; i++) {\n if (perm[i] !== i) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compute every flag of design section 3.8 from the arrays (invariant I9: never guessed).\n * @param core - the arrays and counts the predicates read\n * @returns the truthful flags\n */\nexport function computeFlags(core: FlagSource): SnapshotFlags {\n const { directed, nodeCount, rowPtr, colIdx, weights, arcToEdge } = core;\n let allWeightsOne = true;\n let nonNegativeWeights = true;\n let finiteWeights = true;\n if (weights !== null) {\n for (let a = 0; a < weights.length; a++) {\n const w = weights[a];\n if (w !== 1) {\n allWeightsOne = false;\n }\n if (!(w >= 0)) {\n nonNegativeWeights = false;\n }\n if (!Number.isFinite(w)) {\n finiteWeights = false;\n }\n }\n }\n return {\n multigraph: hasParallelArcs(rowPtr, colIdx, nodeCount),\n hasSelfLoops: core.selfLoopCount > 0,\n arcToEdgeIsIdentity: directed && (arcToEdge === null || isIdentity(arcToEdge)),\n weighted: weights !== null,\n allWeightsOne,\n nonNegativeWeights,\n finiteWeights,\n };\n}\n\n// ============================================================ I1 - I3: structure\n\n/**\n * I1: rowPtr has nodeCount + 1 entries, starts at 0, is non-decreasing and ends at arcCount ===\n * colIdx.length.\n * @param s - the snapshot\n */\nexport function checkI1(s: GraphSnapshot): void {\n const { rowPtr, colIdx, nodeCount, arcCount } = s;\n if (rowPtr.length !== nodeCount + 1) {\n throw invariantViolation(\"I1\", `rowPtr has ${rowPtr.length} entries, expected ${nodeCount + 1}`, {\n expected: nodeCount + 1,\n found: rowPtr.length,\n });\n }\n if (rowPtr[0] !== 0) {\n throw invariantViolation(\"I1\", `rowPtr[0] is ${rowPtr[0]}, expected 0`, { row: 0, found: rowPtr[0] });\n }\n for (let u = 0; u < nodeCount; u++) {\n if (rowPtr[u + 1] < rowPtr[u]) {\n throw invariantViolation(\"I1\", `rowPtr decreases at row ${u}: ${rowPtr[u]} -> ${rowPtr[u + 1]}`, {\n row: u,\n });\n }\n }\n if (rowPtr[nodeCount] !== arcCount || colIdx.length !== arcCount) {\n throw invariantViolation(\n \"I1\",\n `rowPtr[${nodeCount}] = ${rowPtr[nodeCount]}, colIdx.length = ${colIdx.length}, arcCount = ${arcCount}`,\n { row: nodeCount, found: rowPtr[nodeCount], expected: arcCount, colIdxLength: colIdx.length },\n );\n }\n}\n\n/**\n * I2: every colIdx entry is below nodeCount (so INVALID_INDEX never appears).\n * @param s - the snapshot\n */\nexport function checkI2(s: GraphSnapshot): void {\n const { colIdx, nodeCount } = s;\n for (let a = 0; a < colIdx.length; a++) {\n if (colIdx[a] >= nodeCount) {\n throw invariantViolation(\"I2\", `colIdx[${a}] = ${colIdx[a]} is not below nodeCount ${nodeCount}`, {\n arc: a,\n found: colIdx[a],\n });\n }\n }\n}\n\n/**\n * I3: the counts are non-negative integers at most MAX_COUNT, edgeCount <= arcCount and selfLoopCount\n * <= edgeCount.\n * @param s - the snapshot\n */\nexport function checkI3(s: GraphSnapshot): void {\n const counts: readonly [string, number][] = [\n [\"nodeCount\", s.nodeCount],\n [\"edgeCount\", s.edgeCount],\n [\"arcCount\", s.arcCount],\n [\"selfLoopCount\", s.selfLoopCount],\n ];\n for (const [name, value] of counts) {\n if (!Number.isInteger(value) || value < 0 || value > MAX_COUNT) {\n throw invariantViolation(\"I3\", `${name} = ${value} is not an integer in [0, MAX_COUNT]`, {\n count: name,\n found: value,\n });\n }\n }\n if (s.edgeCount > s.arcCount) {\n throw invariantViolation(\"I3\", `edgeCount ${s.edgeCount} exceeds arcCount ${s.arcCount}`, {\n edgeCount: s.edgeCount,\n arcCount: s.arcCount,\n });\n }\n if (s.selfLoopCount > s.edgeCount) {\n throw invariantViolation(\"I3\", `selfLoopCount ${s.selfLoopCount} exceeds edgeCount ${s.edgeCount}`, {\n selfLoopCount: s.selfLoopCount,\n edgeCount: s.edgeCount,\n });\n }\n}\n\n// ============================================================ I4 - I8: rows, permutations, pairing, weights\n\n/**\n * I4: within every row colIdx is non-decreasing and arcs with equal colIdx are ordered by ascending\n * arcToEdge. Full level.\n * @param s - the snapshot\n */\nexport function checkI4(s: GraphSnapshot): void {\n const { rowPtr, colIdx, nodeCount } = s;\n const identity = s.flags.arcToEdgeIsIdentity;\n const arcToEdge = identity ? null : s.arcToEdge;\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u] + 1; a < end; a++) {\n if (colIdx[a] < colIdx[a - 1]) {\n throw invariantViolation(\"I4\", `row ${u} is not sorted at arc ${a}`, { row: u, arc: a });\n }\n if (colIdx[a] === colIdx[a - 1] && arcToEdge !== null && arcToEdge[a] <= arcToEdge[a - 1]) {\n throw invariantViolation(\"I4\", `parallel arcs ${a - 1} and ${a} in row ${u} are not in edge order`, {\n row: u,\n arc: a,\n });\n }\n }\n }\n}\n\n/**\n * I5 (structure part): arcToEdge has arcCount entries below edgeCount and edgeToArc has edgeCount\n * entries below arcCount; an identity flag requires arcCount === edgeCount and a directed snapshot.\n * @param s - the snapshot\n */\nexport function checkI5Ranges(s: GraphSnapshot): void {\n const { arcCount, edgeCount } = s;\n if (s.flags.arcToEdgeIsIdentity) {\n if (!s.directed || arcCount !== edgeCount) {\n throw invariantViolation(\"I5\", \"identity permutation claimed on a snapshot where it cannot hold\", {\n directed: s.directed,\n arcCount,\n edgeCount,\n });\n }\n return;\n }\n const { arcToEdge, edgeToArc } = s;\n if (arcToEdge.length !== arcCount) {\n throw invariantViolation(\"I5\", `arcToEdge has ${arcToEdge.length} entries, expected ${arcCount}`, {\n expected: arcCount,\n found: arcToEdge.length,\n });\n }\n if (edgeToArc.length !== edgeCount) {\n throw invariantViolation(\"I5\", `edgeToArc has ${edgeToArc.length} entries, expected ${edgeCount}`, {\n expected: edgeCount,\n found: edgeToArc.length,\n });\n }\n for (let a = 0; a < arcCount; a++) {\n if (arcToEdge[a] >= edgeCount) {\n throw invariantViolation(\"I5\", `arcToEdge[${a}] = ${arcToEdge[a]} is not below edgeCount ${edgeCount}`, {\n arc: a,\n found: arcToEdge[a],\n });\n }\n }\n for (let e = 0; e < edgeCount; e++) {\n if (edgeToArc[e] >= arcCount) {\n throw invariantViolation(\"I5\", `edgeToArc[${e}] = ${edgeToArc[e]} is not below arcCount ${arcCount}`, {\n edge: e,\n found: edgeToArc[e],\n });\n }\n }\n}\n\n/**\n * I5 (orientation part): arcToEdge[edgeToArc[e]] === e for every edge. Full level.\n * @param s - the snapshot\n */\nexport function checkI5Orientation(s: GraphSnapshot): void {\n if (s.flags.arcToEdgeIsIdentity) {\n return;\n }\n const { arcToEdge, edgeToArc, edgeCount } = s;\n for (let e = 0; e < edgeCount; e++) {\n if (arcToEdge[edgeToArc[e]] !== e) {\n throw invariantViolation(\"I5\", `arcToEdge[edgeToArc[${e}]] = ${arcToEdge[edgeToArc[e]]}, expected ${e}`, {\n edge: e,\n arc: edgeToArc[e],\n });\n }\n }\n}\n\n/**\n * I6: a directed snapshot has arcCount === edgeCount (structure) and arcToEdge is a permutation of\n * 0..edgeCount-1 (full: every edge exactly once).\n * @param s - the snapshot\n * @param full - whether to run the permutation check\n */\nexport function checkI6(s: GraphSnapshot, full: boolean): void {\n if (!s.directed) {\n return;\n }\n const { arcCount, edgeCount } = s;\n if (arcCount !== edgeCount) {\n throw invariantViolation(\"I6\", `directed snapshot has arcCount ${arcCount} but edgeCount ${edgeCount}`, {\n arcCount,\n edgeCount,\n });\n }\n if (!full || s.flags.arcToEdgeIsIdentity) {\n return;\n }\n const { arcToEdge } = s;\n const seen = new Uint8Array(edgeCount);\n for (let a = 0; a < arcCount; a++) {\n const e = arcToEdge[a];\n if (e >= edgeCount || seen[e] === 1) {\n throw invariantViolation(\"I6\", `edge ${e} appears more than once in arcToEdge (arc ${a})`, {\n arc: a,\n edge: e,\n });\n }\n seen[e] = 1;\n }\n}\n\n/**\n * I7 (structure part): an undirected snapshot has arcCount === 2 * edgeCount - selfLoopCount.\n * @param s - the snapshot\n */\nexport function checkI7Counts(s: GraphSnapshot): void {\n if (s.directed) {\n return;\n }\n const expected = 2 * s.edgeCount - s.selfLoopCount;\n if (s.arcCount !== expected) {\n throw invariantViolation(\n \"I7\",\n `undirected snapshot has arcCount ${s.arcCount}, expected 2 * ${s.edgeCount} - ${s.selfLoopCount} = ${expected}`,\n { arcCount: s.arcCount, expected },\n );\n }\n}\n\n/**\n * I7 (pairing part): every arc u -> v with u !== v has exactly one mate v -> u with the same logical\n * edge and weight, a self-loop edge has exactly one arc, and every edge appears once (loop) or twice\n * (mates). The lockstep walk of design section 6.4. Full level.\n * @param s - the snapshot\n */\nexport function checkI7Pairing(s: GraphSnapshot): void {\n if (s.directed) {\n return;\n }\n const { nodeCount, arcCount, edgeCount, rowPtr, colIdx, weights, arcToEdge } = s;\n const occurrences = new Uint8Array(edgeCount);\n for (let a = 0; a < arcCount; a++) {\n const e = arcToEdge[a];\n if (occurrences[e] === 2) {\n throw invariantViolation(\"I7\", `edge ${e} appears more than twice in arcToEdge (arc ${a})`, {\n arc: a,\n edge: e,\n });\n }\n occurrences[e]++;\n }\n const cursor = rowPtr.slice(0, nodeCount);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n let a = cursor[u];\n if (a < rowPtr[u] || a > end) {\n throw invariantViolation(\"I7\", `row ${u} was over-consumed by mates from earlier rows`, { row: u });\n }\n while (a < end) {\n const v = colIdx[a];\n let g = a + 1;\n while (g < end && colIdx[g] === v) {\n g++;\n }\n const k = g - a;\n if (v === u) {\n for (let i = a; i < g; i++) {\n if (occurrences[arcToEdge[i]] !== 1) {\n throw invariantViolation(\"I7\", `self-loop edge ${arcToEdge[i]} has more than one arc`, {\n row: u,\n arc: i,\n edge: arcToEdge[i],\n });\n }\n }\n } else {\n if (v < u) {\n throw invariantViolation(\"I7\", `arc ${a} in row ${u} targets ${v} but row ${v} holds no mate`, {\n row: u,\n arc: a,\n target: v,\n });\n }\n const b = cursor[v];\n const rowEnd = rowPtr[v + 1];\n for (let i = 0; i < k; i++) {\n const arc = a + i;\n const mate = b + i;\n if (mate >= rowEnd || colIdx[mate] !== u) {\n throw invariantViolation(\n \"I7\",\n `arc ${arc} in row ${u} targeting ${v} has no mate in row ${v}`,\n {\n row: u,\n arc,\n target: v,\n },\n );\n }\n if (arcToEdge[mate] !== arcToEdge[arc]) {\n throw invariantViolation(\n \"I7\",\n `arcs ${arc} and ${mate} should share a logical edge but hold ${arcToEdge[arc]} and ${arcToEdge[mate]}`,\n { row: u, arc, mate },\n );\n }\n if (occurrences[arcToEdge[arc]] !== 2) {\n throw invariantViolation(\"I7\", `edge ${arcToEdge[arc]} of arc ${arc} does not have two arcs`, {\n row: u,\n arc,\n edge: arcToEdge[arc],\n });\n }\n if (weights !== null && weights[arc] !== weights[mate]) {\n throw invariantViolation(\n \"I7\",\n `arcs ${arc} and ${mate} carry different weights ${weights[arc]} and ${weights[mate]}`,\n { row: u, arc, mate },\n );\n }\n }\n if (b + k < rowEnd && colIdx[b + k] === u) {\n throw invariantViolation(\"I7\", `row ${v} holds more arcs to ${u} than row ${u} holds to ${v}`, {\n row: v,\n arc: b + k,\n target: u,\n });\n }\n cursor[v] = b + k;\n }\n a = g;\n }\n cursor[u] = end;\n }\n}\n\n/**\n * I8 (length part): weights is null or has arcCount entries.\n * @param s - the snapshot\n */\nexport function checkI8Length(s: GraphSnapshot): void {\n const { weights, arcCount } = s;\n if (weights !== null && weights.length !== arcCount) {\n throw invariantViolation(\"I8\", `weights has ${weights.length} entries, expected ${arcCount}`, {\n expected: arcCount,\n found: weights.length,\n });\n }\n}\n\n/**\n * I8 (value part): no weight is NaN. Full level.\n * @param s - the snapshot\n */\nexport function checkI8NaN(s: GraphSnapshot): void {\n const { weights } = s;\n if (weights === null) {\n return;\n }\n for (let a = 0; a < weights.length; a++) {\n if (Number.isNaN(weights[a])) {\n throw invariantViolation(\"I8\", `weights[${a}] is NaN`, { arc: a });\n }\n }\n}\n\n// ============================================================ I9 - I13: flags, alignment, ids, columns\n\n/**\n * I9: every flag equals its predicate over the arrays, and selfLoopCount equals the number of loop\n * arcs. Full level.\n * @param s - the snapshot\n */\nexport function checkI9(s: GraphSnapshot): void {\n const loopArcs = countLoopArcs(s.rowPtr, s.colIdx, s.nodeCount);\n if (loopArcs !== s.selfLoopCount) {\n throw invariantViolation(\"I9\", `selfLoopCount is ${s.selfLoopCount} but ${loopArcs} loop arcs exist`, {\n reason: \"selfLoopCount\",\n expected: loopArcs,\n found: s.selfLoopCount,\n });\n }\n const recomputed = computeFlags({\n directed: s.directed,\n nodeCount: s.nodeCount,\n rowPtr: s.rowPtr,\n colIdx: s.colIdx,\n weights: s.weights,\n arcToEdge: s.flags.arcToEdgeIsIdentity ? null : s.arcToEdge,\n selfLoopCount: s.selfLoopCount,\n });\n const names: readonly (keyof SnapshotFlags)[] = [\n \"multigraph\",\n \"hasSelfLoops\",\n \"arcToEdgeIsIdentity\",\n \"weighted\",\n \"allWeightsOne\",\n \"nonNegativeWeights\",\n \"finiteWeights\",\n ];\n for (const name of names) {\n if (s.flags[name] !== recomputed[name]) {\n throw invariantViolation(\"I9\", `flag ${name} is ${s.flags[name]} but the arrays say ${recomputed[name]}`, {\n flag: name,\n found: s.flags[name],\n expected: recomputed[name],\n });\n }\n }\n}\n\n/**\n * Check one core array against its arena segment (design section 10.3).\n * @param arena - the arena\n * @param name - the core array name\n * @param array - the array, or null when absent\n */\nfunction checkSegment(arena: ArenaLayout, name: CoreArrayName, array: ArrayBufferView | null): void {\n const segment = arena.segments[name];\n if (segment === null) {\n return;\n }\n if (array === null) {\n throw invariantViolation(\"I10\", `arena names a segment for absent core array ${name}`, { array: name });\n }\n const relative = segment.byteOffset - arena.byteOffset;\n if (relative < 0 || relative % ALIGNMENT !== 0 || relative + segment.byteLength > arena.byteLength) {\n throw invariantViolation(\n \"I10\",\n `arena segment ${name} at ${segment.byteOffset} is not 256-aligned inside the arena`,\n {\n array: name,\n byteOffset: segment.byteOffset,\n },\n );\n }\n if (\n array.buffer !== arena.buffer ||\n array.byteOffset !== segment.byteOffset ||\n array.byteLength !== segment.byteLength\n ) {\n throw invariantViolation(\"I10\", `core array ${name} is not the view its arena segment describes`, {\n array: name,\n byteOffset: array.byteOffset,\n byteLength: array.byteLength,\n });\n }\n}\n\n/**\n * I10: every core array is 4-byte aligned over a plain ArrayBuffer and, when an arena exists, every\n * array with a non-null segment is the 256-aligned view the segment describes and hotByteLength is the\n * end of the weights (or colIdx, or rowPtr) segment.\n * @param s - the snapshot\n */\nexport function checkI10(s: GraphSnapshot): void {\n const identity = s.flags.arcToEdgeIsIdentity;\n const arrays: readonly [CoreArrayName, ArrayBufferView | null][] = [\n [\"rowPtr\", s.rowPtr],\n [\"colIdx\", s.colIdx],\n [\"weights\", s.weights],\n [\"arcToEdge\", identity ? null : s.arcToEdge],\n [\"edgeToArc\", identity ? null : s.edgeToArc],\n ];\n for (const [name, array] of arrays) {\n if (array === null) {\n continue;\n }\n if (!isFourByteAligned(array)) {\n throw invariantViolation(\"I10\", `core array ${name} is not 4-byte aligned`, {\n array: name,\n byteOffset: array.byteOffset,\n byteLength: array.byteLength,\n });\n }\n if (!isOverPlainBuffer(array)) {\n throw invariantViolation(\"I10\", `core array ${name} is not a view over a plain ArrayBuffer`, {\n array: name,\n reason: \"buffer\",\n });\n }\n }\n const { arena } = s;\n if (arena === null) {\n return;\n }\n const { alignment }: { alignment: number } = arena;\n if (alignment !== ALIGNMENT) {\n throw invariantViolation(\"I10\", `arena alignment is ${alignment}, expected ${ALIGNMENT}`, {\n found: alignment,\n });\n }\n for (const [name, array] of arrays) {\n checkSegment(arena, name, array);\n }\n let hotEnd = 0;\n for (const name of [\"rowPtr\", \"colIdx\", \"weights\"] as const) {\n const segment = arena.segments[name];\n if (segment !== null) {\n hotEnd = segment.byteOffset + segment.byteLength - arena.byteOffset;\n }\n }\n if (arena.hotByteLength !== hotEnd) {\n throw invariantViolation(\"I10\", `arena.hotByteLength is ${arena.hotByteLength}, expected ${hotEnd}`, {\n reason: \"hotByteLength\",\n found: arena.hotByteLength,\n expected: hotEnd,\n });\n }\n}\n\n/**\n * I11 (size part): the id map has nodeCount ids.\n * @param s - the snapshot\n */\nexport function checkI11Size(s: GraphSnapshot): void {\n if (s.ids.size !== s.nodeCount) {\n throw invariantViolation(\"I11\", `ids.size is ${s.ids.size}, expected nodeCount ${s.nodeCount}`, {\n expected: s.nodeCount,\n found: s.ids.size,\n });\n }\n}\n\n/**\n * I11 (bijection part): ids.indexOf(ids.idOf(i)) === i for every i and no id is NaN. Full level.\n * @param s - the snapshot\n */\nexport function checkI11Bijection(s: GraphSnapshot): void {\n const { ids, nodeCount } = s;\n for (let i = 0; i < nodeCount; i++) {\n const id = ids.idOf(i);\n if (typeof id === \"number\" && Number.isNaN(id)) {\n throw invariantViolation(\"I11\", `id of node ${i} is NaN`, { index: i });\n }\n const back = ids.indexOf(id);\n if (back !== i) {\n throw invariantViolation(\"I11\", `ids.indexOf(ids.idOf(${i})) is ${back}`, { index: i, found: back });\n }\n }\n}\n\n/**\n * The E_INVALID_SNAPSHOT error of one column length-rule violation (I12).\n * @param table - the table name for the message\n * @param column - the column\n * @param message - what is wrong\n * @param details - extra location details\n * @returns the error\n */\nfunction columnViolation(\n table: string,\n column: Column,\n message: string,\n details: Readonly<Record<string, unknown>> = {},\n): GraphFormatError {\n return invariantViolation(\"I12\", `column \"${column.meta.name}\" of table ${table}: ${message}`, {\n table,\n column: column.meta.name,\n ...details,\n });\n}\n\n/**\n * Check that offsets are rows + 1 long, non-decreasing and end at `end`.\n * @param table - the table name for the message\n * @param column - the column\n * @param offsets - the offsets\n * @param rows - the row count\n * @param end - the expected last offset\n */\nfunction checkOffsets(table: string, column: Column, offsets: U32, rows: number, end: number): void {\n if (offsets.length !== rows + 1) {\n throw columnViolation(table, column, `offsets has ${offsets.length} entries, expected ${rows + 1}`, {\n expected: rows + 1,\n found: offsets.length,\n });\n }\n if (offsets[0] !== 0) {\n throw columnViolation(table, column, `offsets[0] is ${offsets[0]}`, { row: 0 });\n }\n for (let r = 0; r < rows; r++) {\n if (offsets[r + 1] < offsets[r]) {\n throw columnViolation(table, column, `offsets decrease at row ${r}`, { row: r });\n }\n }\n if (offsets[rows] !== end) {\n throw columnViolation(table, column, `offsets[${rows}] is ${offsets[rows]}, expected ${end}`, {\n row: rows,\n found: offsets[rows],\n expected: end,\n });\n }\n}\n\n/**\n * Check the values of a refersTo u32 array: every entry below `bound` or INVALID_INDEX; when\n * `rowValidity` is given an INVALID_INDEX entry requires its row to be unset.\n * @param table - the table name for the message\n * @param column - the column\n * @param values - the u32 values\n * @param components - values per row\n * @param bound - the referenced space's row count\n * @param rowValidity - the validity bitmap of the rows (null = all set), or undefined to skip the unset rule\n */\nfunction checkReferences(\n table: string,\n column: Column,\n values: U32,\n components: number,\n bound: number,\n rowValidity: U32 | null | undefined,\n): void {\n for (let i = 0; i < values.length; i++) {\n const value = values[i];\n if (value === INVALID_INDEX) {\n const row = Math.floor(i / components);\n if (rowValidity !== undefined && (rowValidity === null || bitmapGet(rowValidity, row))) {\n throw columnViolation(table, column, `row ${row} is set but holds INVALID_INDEX`, { row });\n }\n continue;\n }\n if (value >= bound) {\n throw columnViolation(table, column, `value ${value} at ${i} is not below ${bound}`, {\n row: Math.floor(i / components),\n found: value,\n expected: bound,\n });\n }\n }\n}\n\n/**\n * The refersTo rules of invariant I12 for one column: a u32 column's values (or a list column's u32\n * child items) are below `bound` or INVALID_INDEX, and a scalar INVALID_INDEX sits in an unset row.\n * @param table - the table name for the message\n * @param column - a column whose meta.refersTo is set\n * @param bound - the referenced space's row count\n */\nfunction checkColumnReferences(table: string, column: Column, bound: number): void {\n switch (column.dtype) {\n case \"u32\":\n checkReferences(table, column, column.data, column.meta.components, bound, column.validity);\n return;\n case \"list\": {\n const { child } = column;\n if (child.dtype !== \"u32\") {\n throw columnViolation(table, column, `refersTo list requires a u32 child, found ${child.dtype}`);\n }\n checkReferences(table, column, child.data, 1, bound, undefined);\n return;\n }\n default:\n throw columnViolation(table, column, `refersTo requires dtype u32, found ${column.dtype}`);\n }\n}\n\n/**\n * The typed arrays a column exposes to a GPU consumer (data, validity, codes, list child data): each\n * must be a view over a plain ArrayBuffer (I10, decision D-SAB).\n * @param column - the column\n * @returns the arrays with their names\n */\nfunction columnArrays(column: Column): readonly [string, ArrayBufferView | null][] {\n switch (column.dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n case \"bool\":\n return [\n [\"data\", column.data],\n [\"validity\", column.validity],\n ];\n case \"dict\":\n return [\n [\"codes\", column.codes],\n [\"validity\", column.validity],\n ];\n case \"string\":\n return [\n [\"offsets\", column.offsets],\n [\"utf8\", column.utf8],\n [\"validity\", column.validity],\n ];\n case \"list\":\n return [\n [\"offsets\", column.offsets],\n [\"validity\", column.validity],\n ...columnArrays(column.child).map(([name, array]): [string, ArrayBufferView | null] => [\n `child.${name}`,\n array,\n ]),\n ];\n case \"json\":\n return [[\"validity\", column.validity]];\n default: {\n const unknown: never = column;\n throw invariantViolation(\"I12\", `unknown dtype ${(unknown as Column).dtype}`);\n }\n }\n}\n\n/**\n * The length rules of design section 5.7 for one column, plus dictionary code ranges, refersTo\n * ranges, the recorded nullCount (recomputed from the bitmap, design section 9.5) and the plain\n * ArrayBuffer rule of I10 for every typed array the column exposes (I12).\n * @param table - the table name for the message\n * @param column - the column\n * @param rows - the table's row count\n * @param s - the snapshot (for the referenced row counts)\n */\nexport function checkColumnRules(table: string, column: Column, rows: number, s: GraphSnapshot): void {\n if (column.length !== rows) {\n throw columnViolation(table, column, `has ${column.length} rows, expected ${rows}`, {\n expected: rows,\n found: column.length,\n });\n }\n const { validity, meta } = column;\n const validityWords = Math.ceil(rows / 32);\n if (validity !== null && validity.length !== validityWords) {\n throw columnViolation(table, column, `validity has ${validity.length} words, expected ${validityWords}`, {\n expected: validityWords,\n found: validity.length,\n });\n }\n const nullCount = validity === null ? 0 : rows - bitmapCount(validity, rows);\n if (column.nullCount !== nullCount) {\n throw columnViolation(\n table,\n column,\n `nullCount is ${column.nullCount}, the validity bitmap says ${nullCount}`,\n {\n expected: nullCount,\n found: column.nullCount,\n reason: \"nullCount\",\n },\n );\n }\n for (const [name, array] of columnArrays(column)) {\n if (array !== null && !isOverPlainBuffer(array)) {\n throw columnViolation(table, column, `${name} is not a view over a plain ArrayBuffer`, {\n array: name,\n reason: \"buffer\",\n });\n }\n }\n const refBound = meta.refersTo === \"node\" ? s.nodeCount : s.edgeCount;\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n const expected = rows * meta.components;\n if (column.data.length !== expected) {\n throw columnViolation(table, column, `data has ${column.data.length} values, expected ${expected}`, {\n expected,\n found: column.data.length,\n });\n }\n if (meta.refersTo !== null) {\n checkColumnReferences(table, column, refBound);\n }\n break;\n }\n case \"bool\":\n if (column.data.length !== validityWords) {\n throw columnViolation(\n table,\n column,\n `bool data has ${column.data.length} words, expected ${validityWords}`,\n {\n expected: validityWords,\n found: column.data.length,\n },\n );\n }\n break;\n case \"dict\": {\n if (column.codes.length !== rows) {\n throw columnViolation(table, column, `codes has ${column.codes.length} entries, expected ${rows}`, {\n expected: rows,\n found: column.codes.length,\n });\n }\n const size = column.dictionary.length;\n for (let r = 0; r < rows; r++) {\n if (column.codes[r] >= size && (validity === null || bitmapGet(validity, r))) {\n throw columnViolation(table, column, `code ${column.codes[r]} at row ${r} is not below ${size}`, {\n row: r,\n found: column.codes[r],\n });\n }\n }\n break;\n }\n case \"string\":\n checkOffsets(table, column, column.offsets, rows, column.utf8.length);\n break;\n case \"list\": {\n const { child } = column;\n checkOffsets(table, column, column.offsets, rows, child.length);\n if (child.validity !== null) {\n throw columnViolation(table, column, \"list child column has a validity bitmap\");\n }\n if (meta.refersTo !== null) {\n checkColumnReferences(table, column, refBound);\n }\n break;\n }\n case \"json\":\n if (column.values.length !== rows) {\n throw columnViolation(table, column, `values has ${column.values.length} entries, expected ${rows}`, {\n expected: rows,\n found: column.values.length,\n });\n }\n break;\n default: {\n const unknown: never = dtype;\n throw columnViolation(table, column, `unknown dtype ${String(unknown)}`);\n }\n }\n}\n\n/**\n * Check every column of a table against its row count.\n * @param name - the table name for the message\n * @param table - the table\n * @param rows - the expected row count\n * @param s - the snapshot\n */\nfunction checkTable(name: string, table: AttributeTable, rows: number, s: GraphSnapshot): void {\n for (const column of table) {\n checkColumnRules(name, column, rows, s);\n }\n}\n\n/**\n * I12: the node, edge and graph tables have nodeCount, edgeCount and 1 rows, every column (extension\n * tables included) obeys its length rules, dictionary codes are in range and refersTo values are in\n * range or INVALID_INDEX with the row unset.\n * @param s - the snapshot\n */\nexport function checkI12(s: GraphSnapshot): void {\n const tables: readonly [string, AttributeTable, number][] = [\n [\"nodes\", s.nodes, s.nodeCount],\n [\"edges\", s.edges, s.edgeCount],\n [\"graph\", s.graph, 1],\n ];\n for (const [name, table, rows] of tables) {\n if (table.rowCount !== rows) {\n throw invariantViolation(\"I12\", `table ${name} has ${table.rowCount} rows, expected ${rows}`, {\n table: name,\n expected: rows,\n found: table.rowCount,\n });\n }\n checkTable(name, table, rows, s);\n }\n for (const [name, table] of s.extensions) {\n checkTable(`extensions[${name}]`, table, table.rowCount, s);\n }\n}\n\n/**\n * I13: edge attribute columns are indexed by logical edge: the edge table has edgeCount rows.\n * @param s - the snapshot\n */\nexport function checkI13(s: GraphSnapshot): void {\n if (s.edges.rowCount !== s.edgeCount) {\n throw invariantViolation(\"I13\", `edge table has ${s.edges.rowCount} rows, expected edgeCount ${s.edgeCount}`, {\n expected: s.edgeCount,\n found: s.edges.rowCount,\n });\n }\n}\n\n// ============================================================ levels\n\n/**\n * The \"structure\" level of design section 9.5: I1-I3, I5 lengths and ranges, I6 / I7 counts, I8\n * length, I10, I11 size, I12 lengths and ranges, I13. O(n + m + columns).\n * @param s - the snapshot\n */\nexport function validateStructure(s: GraphSnapshot): void {\n checkI3(s);\n checkI1(s);\n checkI2(s);\n checkI5Ranges(s);\n checkI6(s, false);\n checkI7Counts(s);\n checkI8Length(s);\n checkI10(s);\n checkI11Size(s);\n checkI13(s);\n checkI12(s);\n}\n\n/**\n * The \"full\" level of design section 9.5: structure plus I4, I5 orientation, I6 permutation, I8 NaN\n * (before the pairing walk, so a NaN weight is reported as I8 rather than as an unequal mate), I7\n * pairing, I9 flags, I11 bijection and unique columns. O(m log d).\n * @param s - the snapshot\n */\nexport function validateFull(s: GraphSnapshot): void {\n validateStructure(s);\n checkI4(s);\n checkI5Orientation(s);\n checkI6(s, true);\n checkI8NaN(s);\n checkI7Pairing(s);\n checkI9(s);\n checkI11Bijection(s);\n const tables: readonly [string, AttributeTable][] = [\n [\"nodes\", s.nodes],\n [\"edges\", s.edges],\n [\"graph\", s.graph],\n ...[...s.extensions].map(([name, table]): [string, AttributeTable] => [`extensions[${name}]`, table]),\n ];\n for (const [name, table] of tables) {\n for (const column of table) {\n checkUniqueColumn(name, column);\n }\n }\n}\n\n/**\n * The `unique` rule of a column as a validation failure (design sections 9.5 and 11.4): the\n * freeze-time codes E_DUPLICATE_ID / E_DUPLICATE_EDGE_ID of `verifyUniqueColumn` become\n * E_INVALID_SNAPSHOT with `details.invariant` \"I12\", `details.reason` \"unique\" and the original\n * code in `details.cause`, so a reader of untrusted input sees one error family.\n * @param table - the table name for the message\n * @param column - the column\n */\nexport function checkUniqueColumn(table: string, column: Column): void {\n try {\n verifyUniqueColumn(column);\n } catch (err) {\n if (err instanceof GraphFormatError && (err.code === \"E_DUPLICATE_ID\" || err.code === \"E_DUPLICATE_EDGE_ID\")) {\n throw columnViolation(table, column, err.message, { ...err.details, reason: \"unique\", cause: err.code });\n }\n throw err;\n }\n}\n","/**\n * Content checks of the views a wire manifest carries (`includeViews`, design sections 9.1 and 9.5),\n * run at the \"structure\" level before a carried view is installed on the receiver. Every view is a\n * pure function of the core (design section 7.2), so each check is exact: the index views are\n * compared with what the core says arc by arc in O(n + m) without allocating a second copy, and the\n * four f64 views are compared with the snapshot's own computation. A view that disagrees is\n * E_INVALID_SNAPSHOT with `details.invariant` \"I2\" (a corrupt index array) or \"I17\" (a corrupt\n * value array) and `details.view` naming it. At \"none\" nothing is checked (the manifest is trusted,\n * design section 9.5); at \"full\" carried views are never installed.\n */\n\nimport { type GraphFormatError } from \"../errors.js\";\nimport { type GraphSnapshot } from \"../snapshot/graph-snapshot.js\";\nimport { invariantViolation } from \"../snapshot/validate.js\";\nimport { DEGREE_TIER_HIGH, DEGREE_TIER_MID, rowLengths } from \"../snapshot/views.js\";\nimport { type F32, type F64, type ReverseView, type U32 } from \"../types/index.js\";\n\n/** The per-arc facts every index-view check reads, computed once per manifest. */\nexport class CoreFacts {\n /** The row (source) of every arc. */\n readonly arcRow: U32;\n /** Loop arcs per node. */\n readonly loops: U32;\n /** In-arcs per node (directed only; the out-degree when undirected). */\n readonly inDegree: U32;\n\n /**\n * Expand the core once.\n * @param snapshot - the snapshot\n */\n constructor(snapshot: GraphSnapshot) {\n const { nodeCount, arcCount, rowPtr, colIdx, directed } = snapshot;\n const arcRow = new Uint32Array(arcCount);\n const loops = new Uint32Array(nodeCount);\n const inDegree = directed ? new Uint32Array(nodeCount) : rowLengths(rowPtr, nodeCount);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u]; a < end; a++) {\n arcRow[a] = u;\n const v = colIdx[a];\n if (v === u) {\n loops[u]++;\n }\n if (directed) {\n inDegree[v]++;\n }\n }\n }\n this.arcRow = arcRow;\n this.loops = loops;\n this.inDegree = inDegree;\n }\n\n /**\n * The exclusive prefix sum of the in-degrees (the reverse rowPtr).\n * @returns nodeCount + 1 offsets\n */\n inDegreePrefix(): U32 {\n const n = this.inDegree.length;\n const out = new Uint32Array(n + 1);\n for (let u = 0; u < n; u++) {\n out[u + 1] = out[u] + this.inDegree[u];\n }\n return out;\n }\n}\n\n/**\n * The error for a carried view that disagrees with the core.\n * @param view - the view name\n * @param member - the member array\n * @param index - the offending index\n * @param invariant - \"I2\" for an index array, \"I17\" for a value array\n * @returns the error\n */\nfunction viewError(view: string, member: string, index: number, invariant: \"I2\" | \"I17\"): GraphFormatError {\n return invariantViolation(invariant, `carried view ${view}.${member} disagrees with the core at ${index}`, {\n view,\n member,\n index,\n reason: \"view\",\n });\n}\n\n/**\n * Compare two arrays element by element (NaN equal to NaN).\n * @param view - the view name\n * @param member - the member name\n * @param found - the carried array\n * @param expected - the truth\n * @param invariant - the invariant to report\n */\nfunction expectSame(\n view: string,\n member: string,\n found: ArrayLike<number>,\n expected: ArrayLike<number>,\n invariant: \"I2\" | \"I17\",\n): void {\n for (let i = 0; i < expected.length; i++) {\n if (!Object.is(found[i], expected[i]) && found[i] !== expected[i]) {\n throw viewError(view, member, i, invariant);\n }\n }\n}\n\n/**\n * Check that an array is a permutation of 0..length-1.\n * @param view - the view name\n * @param member - the member name\n * @param perm - the array\n */\nfunction expectPermutation(view: string, member: string, perm: U32): void {\n const seen = new Uint8Array(perm.length);\n for (let i = 0; i < perm.length; i++) {\n const p = perm[i];\n if (p >= perm.length || seen[p] === 1) {\n throw viewError(view, member, i, \"I2\");\n }\n seen[p] = 1;\n }\n}\n\n/**\n * outDegree: the row lengths.\n * @param snapshot - the snapshot\n * @param data - the carried array\n */\nexport function checkOutDegree(snapshot: GraphSnapshot, data: U32): void {\n expectSame(\"outDegree\", \"data\", data, rowLengths(snapshot.rowPtr, snapshot.nodeCount), \"I2\");\n}\n\n/**\n * inDegree (directed): the in-arc counts.\n * @param facts - the core facts\n * @param data - the carried array\n */\nexport function checkInDegree(facts: CoreFacts, data: U32): void {\n expectSame(\"inDegree\", \"data\", data, facts.inDegree, \"I2\");\n}\n\n/**\n * degree: outDegree + inDegree (directed) or outDegree + loops (undirected), design section 3.4.\n * @param snapshot - the snapshot\n * @param facts - the core facts\n * @param data - the carried array\n */\nexport function checkDegree(snapshot: GraphSnapshot, facts: CoreFacts, data: U32): void {\n const out = rowLengths(snapshot.rowPtr, snapshot.nodeCount);\n const add = snapshot.directed ? facts.inDegree : facts.loops;\n for (let u = 0; u < out.length; u++) {\n if (data[u] !== out[u] + add[u]) {\n throw viewError(\"degree\", \"data\", u, \"I2\");\n }\n }\n}\n\n/**\n * selfLoopsPerNode: the loop arcs per row.\n * @param facts - the core facts\n * @param data - the carried array\n */\nexport function checkSelfLoopsPerNode(facts: CoreFacts, data: U32): void {\n expectSame(\"selfLoopsPerNode\", \"data\", data, facts.loops, \"I2\");\n}\n\n/**\n * selfLoopArcs: ascending arcs, each a loop; with the length fixed to selfLoopCount that is exact.\n * @param snapshot - the snapshot\n * @param facts - the core facts\n * @param data - the carried array\n */\nexport function checkSelfLoopArcs(snapshot: GraphSnapshot, facts: CoreFacts, data: U32): void {\n const { colIdx, arcCount } = snapshot;\n for (let i = 0; i < data.length; i++) {\n const a = data[i];\n if (a >= arcCount || colIdx[a] !== facts.arcRow[a] || (i > 0 && a <= data[i - 1])) {\n throw viewError(\"selfLoopArcs\", \"data\", i, \"I2\");\n }\n }\n}\n\n/**\n * coo.src: the row of every arc.\n * @param facts - the core facts\n * @param src - the carried array\n */\nexport function checkCooSrc(facts: CoreFacts, src: U32): void {\n expectSame(\"coo\", \"src\", src, facts.arcRow, \"I2\");\n}\n\n/**\n * edgeList: `src[e]` is the row of `edgeToArc[e]`, `dst[e]` its target, `weights[e]` its weight.\n * @param snapshot - the snapshot\n * @param facts - the core facts\n * @param src - the carried sources\n * @param dst - the carried targets, or null when colIdx is aliased\n * @param weights - the carried weights, or null when aliased or unweighted\n */\nexport function checkEdgeList(\n snapshot: GraphSnapshot,\n facts: CoreFacts,\n src: U32,\n dst: U32 | null,\n weights: F32 | null,\n): void {\n const { edgeCount, edgeToArc, colIdx, arcCount } = snapshot;\n const forward = snapshot.weights;\n for (let e = 0; e < edgeCount; e++) {\n const a = edgeToArc[e];\n if (a >= arcCount || src[e] !== facts.arcRow[a]) {\n throw viewError(\"edgeList\", \"src\", e, \"I2\");\n }\n if (dst !== null && dst[e] !== colIdx[a]) {\n throw viewError(\"edgeList\", \"dst\", e, \"I2\");\n }\n if (weights !== null && forward !== null && !Object.is(weights[e], forward[a])) {\n throw viewError(\"edgeList\", \"weights\", e, \"I17\");\n }\n }\n}\n\n/**\n * mate (undirected): an involution pairing the two arcs of every non-loop edge (invariant I7) and\n * fixing every loop arc.\n * @param snapshot - the snapshot\n * @param facts - the core facts\n * @param mate - the carried array\n */\nexport function checkMate(snapshot: GraphSnapshot, facts: CoreFacts, mate: U32): void {\n const { arcCount, arcToEdge, colIdx } = snapshot;\n for (let a = 0; a < arcCount; a++) {\n const m = mate[a];\n const loop = colIdx[a] === facts.arcRow[a];\n if (m >= arcCount || mate[m] !== a || arcToEdge[m] !== arcToEdge[a] || (m === a) !== loop) {\n throw viewError(\"mate\", \"data\", a, \"I2\");\n }\n }\n}\n\n/**\n * degreeOrder / reverseDegreeOrder: a permutation ordered by non-increasing degree with ties in\n * ascending node index, and the cuGraph tier offsets of design section 7.2.\n * @param name - the view name\n * @param degree - the degree of every node the order sorts by\n * @param perm - the carried permutation\n * @param segmentOffsets - the carried tier offsets\n */\nexport function checkDegreeOrder(\n name: \"degreeOrder\" | \"reverseDegreeOrder\",\n degree: U32,\n perm: U32,\n segmentOffsets: U32,\n): void {\n expectPermutation(name, \"perm\", perm);\n let hi = 0;\n let mid = 0;\n let low = 0;\n for (let i = 0; i < perm.length; i++) {\n const d = degree[perm[i]];\n if (i > 0) {\n const previous = degree[perm[i - 1]];\n if (d > previous || (d === previous && perm[i] < perm[i - 1])) {\n throw viewError(name, \"perm\", i, \"I2\");\n }\n }\n if (d >= DEGREE_TIER_HIGH) {\n hi++;\n } else if (d >= DEGREE_TIER_MID) {\n mid++;\n } else if (d >= 1) {\n low++;\n }\n }\n const expected = [0, hi, hi + mid, hi + mid + low, perm.length];\n expectSame(name, \"segmentOffsets\", segmentOffsets, expected, \"I2\");\n}\n\n/**\n * reverse (directed): the in-adjacency with rows sorted by source and ties by forward arc, `fwdArc`\n * a permutation of the arcs, `colIdx` the sources, `weights` the forward weights gathered.\n * @param snapshot - the snapshot\n * @param facts - the core facts\n * @param reverse - the carried view\n */\nexport function checkReverse(snapshot: GraphSnapshot, facts: CoreFacts, reverse: ReverseView): void {\n const { nodeCount, arcCount, colIdx } = snapshot;\n const forward = snapshot.weights;\n const { rowPtr, fwdArc } = reverse;\n const revIdx = reverse.colIdx;\n const revWeights = reverse.weights;\n if (rowPtr[0] !== 0 || rowPtr[nodeCount] !== arcCount) {\n throw viewError(\"reverse\", \"rowPtr\", 0, \"I2\");\n }\n expectSame(\"reverse\", \"rowPtr\", rowPtr, facts.inDegreePrefix(), \"I2\");\n expectPermutation(\"reverse\", \"fwdArc\", fwdArc);\n for (let v = 0; v < nodeCount; v++) {\n const end = rowPtr[v + 1];\n for (let k = rowPtr[v]; k < end; k++) {\n const a = fwdArc[k];\n const source = facts.arcRow[a];\n if (colIdx[a] !== v || revIdx[k] !== source) {\n throw viewError(\"reverse\", \"colIdx\", k, \"I2\");\n }\n if (k > rowPtr[v]) {\n const previous = fwdArc[k - 1];\n const previousSource = facts.arcRow[previous];\n if (source < previousSource || (source === previousSource && a <= previous)) {\n throw viewError(\"reverse\", \"fwdArc\", k, \"I2\");\n }\n }\n if (revWeights !== null && forward !== null && !Object.is(revWeights[k], forward[a])) {\n throw viewError(\"reverse\", \"weights\", k, \"I17\");\n }\n }\n }\n}\n\n/**\n * An f64 view: compared with the snapshot's own computation.\n * @param name - the view name\n * @param found - the carried array\n * @param expected - the computed truth\n */\nexport function checkF64View(name: string, found: F64, expected: F64): void {\n expectSame(name, \"data\", found, expected, \"I17\");\n}\n","/**\n * The wire encoder (design sections 4.5, 5.9, 9.1 and 12.2): `toWire()` turns a snapshot into a\n * JSON-serialisable manifest plus a list of ArrayBuffers, `transferables()` lists the exclusively\n * owned buffers a worker hand-off may transfer, and the segment collector shared with the GSNP\n * container writer of bytes.ts lays every typed array out as a WireBufferRef.\n *\n * Two layouts exist. In REFERENCE mode (toWire) every distinct backing ArrayBuffer becomes one entry\n * of `buffers` and a reference carries the array's own byteOffset, so the core stays views over the\n * arena (one buffer) and nothing is copied unless `transfer: true` meets a shared buffer. In\n * CONTAINER mode (toBytes / toByteChunks) every array is placed at a 256-byte-aligned offset of one\n * buffer region in manifest order, core arrays first so the region's prefix is the arena.\n *\n * toWire allocates nothing for typed data except the first materialisation of a lazily kept\n * representation: the Utf8 store of string ids and string columns and the f64 / tag arrays of a\n * numeric or mixed id map are cached by their owners, the encoded dictionaries and the JSON text of\n * json columns are cached here. Non-finite numbers and -0 inside metadata are carried as the tagged\n * strings of design section 5.9 so the manifest survives JSON.stringify unchanged.\n */\n\nimport { CORE_ORDER } from \"../builder/arena.js\";\nimport { isPlainObject } from \"../columns/column.js\";\nimport { ALIGNMENT, FORMAT_VERSION, IS_LITTLE_ENDIAN, WIRE_FORMAT, WIRE_MAJOR, WIRE_MINOR } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { NodeIdMap, nodeIdMapToTyped } from \"../ids/node-id-map.js\";\nimport { type EncodedUtf8, encodeUtf8Rows } from \"../ids/string-store.js\";\nimport { type GraphSnapshot, peekView } from \"../snapshot/graph-snapshot.js\";\nimport { viewArrays } from \"../snapshot/views.js\";\nimport {\n type AttributeTable,\n type Column,\n type ColumnMeta,\n type CoreArrayName,\n type GraphMeta,\n type JsonColumn,\n type ToWireOptions,\n type TypedArrayData,\n type ViewName,\n type WireArena,\n type WireBufferRef,\n type WireColumn,\n type WireDtype,\n type WireIdMap,\n type WireManifest,\n type WireSnapshot,\n type WireUtf8,\n} from \"../types/index.js\";\nimport { isShared, noteShared } from \"../util/shared-buffers.js\";\nimport { alignUp } from \"../util/typed-array.js\";\n\n// ============================================================ constants\n\n/**\n * The `producer` string written into every manifest (design section 9.1): the package name and its\n * npm version. Golden fixtures mask it when compared. Bumped together with package.json.\n */\nexport const WIRE_PRODUCER = \"@graphty/graph-format@0.1.0\";\n\n/** The views the wire carries when named by includeViews; the scalar views are never carried. */\nconst SCALAR_VIEWS: ReadonlySet<ViewName> = new Set<ViewName>([\"totalWeight\", \"symmetric\"]);\n\n/** The core arrays in arena order (design section 10.3). */\n\nconst encoder = new TextEncoder();\n\n// ============================================================ host endianness\n\n/**\n * Refuse to emit wire data on a big-endian host (design section 9.2): every supported platform is\n * little-endian and there is no byte-swapping reader, so a big-endian host must never produce a file\n * other hosts reject. The parameter exists so the refusal path is testable on a little-endian host.\n * @param littleEndian - whether the host is little-endian; defaults to the detected value\n */\nexport function assertLittleEndianHost(littleEndian: boolean = IS_LITTLE_ENDIAN): void {\n if (!littleEndian) {\n throw new GraphFormatError(\"E_UNSUPPORTED\", \"the wire format cannot be written on a big-endian host\", {\n reason: \"big-endian host\",\n });\n }\n}\n\n// ============================================================ shared-buffer bookkeeping (9.1)\n\n// ============================================================ JSON tagging (5.9)\n\n/** The tag key of a non-finite or negative-zero number on the wire. */\nconst NUM_TAG = \"$num\";\nconst ESC_TAG = \"$esc\";\n\n/**\n * Encode a JSON value for the manifest (design section 5.9): `Infinity`, `-Infinity`, `NaN` and `-0`\n * become `{ \"$num\": \"...\" }`, arrays and plain objects are copied recursively, everything else is\n * returned as is. A user object whose ONLY key is `$num` or `$esc` would collide with the tags, so\n * it is wrapped as `{ \"$esc\": { ...the object... } }` and unwrapped by the reader.\n * The input has already passed assertJsonValue (design section 5.9), so no other shape can occur.\n * @param value - the JSON value\n * @returns the tagged copy\n */\nexport function encodeJsonValue(value: unknown): unknown {\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) {\n return { [NUM_TAG]: \"NaN\" };\n }\n if (value === Infinity) {\n return { [NUM_TAG]: \"Infinity\" };\n }\n if (value === -Infinity) {\n return { [NUM_TAG]: \"-Infinity\" };\n }\n if (Object.is(value, -0)) {\n return { [NUM_TAG]: \"-0\" };\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((item: unknown) => encodeJsonValue(item));\n }\n if (isPlainObject(value)) {\n const keys = Object.keys(value);\n const out: Record<string, unknown> = {};\n for (const key of keys) {\n defineJsonKey(out, key, encodeJsonValue(value[key]));\n }\n if (keys.length === 1 && (keys[0] === NUM_TAG || keys[0] === ESC_TAG)) {\n return { [ESC_TAG]: out };\n }\n return out;\n }\n return value;\n}\n\n/**\n * Add an own enumerable property to a plain object without going through a setter, so a key such as\n * \"__proto__\" stays a data property (the manifest reader rejects it anyway).\n * @param target - the object\n * @param key - the property name\n * @param value - the value\n */\nexport function defineJsonKey(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n// ============================================================ the segment collector\n\n/** How references are laid out. */\ntype WireMode = \"reference\" | \"container\";\n\n/** One typed array placed in the container region: the source view and where it goes. */\nexport interface ContainerSegment {\n /** The source array. */\n readonly view: TypedArrayData;\n /** Its reference (buffer 0, region-relative byteOffset). */\n readonly ref: WireBufferRef;\n}\n\n/**\n * Collects typed arrays into WireBufferRefs (design sections 9.1 and 9.2). In reference mode\n * `buffers` is the list of distinct backing buffers (a shared buffer copied under `transfer`, its\n * index recorded in `copied`); in container mode `segments` is the placement of every distinct array\n * at a 256-aligned offset and `regionLength` the padded length of the region.\n */\nexport class WireLayout {\n /** The layout mode. */\n readonly mode: WireMode;\n /** Reference mode: whether shared buffers are copied so the rest can be transferred. */\n readonly transfer: boolean;\n /** Reference mode: the distinct buffers, or their copies. */\n readonly buffers: ArrayBuffer[] = [];\n /** Reference mode: the indices of `buffers` holding copies of shared buffers. */\n readonly copied: number[] = [];\n /** Container mode: every placed array in region order. */\n readonly segments: ContainerSegment[] = [];\n\n private readonly bufferIndex = new Map<ArrayBuffer, number>();\n private readonly placed = new Map<string, WireBufferRef>();\n private cursor = 0;\n\n /**\n * Create a collector.\n * @param mode - reference (toWire) or container (toBytes)\n * @param transfer - reference mode only: copy shared buffers so the others can be transferred\n */\n constructor(mode: WireMode, transfer = false) {\n this.mode = mode;\n this.transfer = transfer;\n }\n\n /**\n * Container mode: the padded byte length of the region (every segment padded to 256 bytes).\n * @returns the region length\n */\n get regionLength(): number {\n return alignUp(this.cursor, ALIGNMENT);\n }\n\n /**\n * Reference mode: the index a buffer was assigned, or null when no array over it was placed.\n * @param buffer - the buffer\n * @returns the index into `buffers`, or null\n */\n indexOf(buffer: ArrayBuffer): number | null {\n return this.bufferIndex.get(buffer) ?? null;\n }\n\n /**\n * Place a typed array and return its reference. The same byte range is placed once. When the\n * holder of the array (its column, table or id map) is shared, the buffer is recorded as shared\n * so `finalise()` copies it under `transfer` (design section 9.1).\n * @param view - the array\n * @param dtype - its wire dtype (\"utf8\" for byte stores, \"u8\" for u8 columns and tags)\n * @param sharedHolder - whether the object holding the array is held by more than one snapshot or table\n * @returns the reference\n */\n ref(view: TypedArrayData, dtype: WireDtype, sharedHolder = false): WireBufferRef {\n if (sharedHolder) {\n noteShared(view.buffer);\n }\n if (this.mode === \"reference\") {\n return {\n buffer: this.bufferIndexOf(view.buffer),\n byteOffset: view.byteOffset,\n byteLength: view.byteLength,\n dtype,\n length: view.length,\n };\n }\n const key = `${this.bufferIndexOf(view.buffer)}:${view.byteOffset}:${view.byteLength}:${dtype}`;\n const existing = this.placed.get(key);\n if (existing !== undefined) {\n return existing;\n }\n const byteOffset = alignUp(this.cursor, ALIGNMENT);\n this.cursor = byteOffset + view.byteLength;\n const ref: WireBufferRef = { buffer: 0, byteOffset, byteLength: view.byteLength, dtype, length: view.length };\n this.placed.set(key, ref);\n this.segments.push({ view, ref });\n return ref;\n }\n\n /**\n * Reference mode with `transfer`: replace every buffer recorded as shared by a copy and list its\n * index in `copied` (design section 9.1). Called once after every array was placed, so the\n * decision does not depend on the order in which shared holders were met.\n */\n finalise(): void {\n if (this.mode !== \"reference\" || !this.transfer) {\n return;\n }\n for (let i = 0; i < this.buffers.length; i++) {\n const buffer = this.buffers[i];\n if (isShared(buffer)) {\n this.buffers[i] = buffer.slice(0);\n this.copied.push(i);\n }\n }\n }\n\n /**\n * The index of a backing buffer, assigning the next one on first sight.\n * @param buffer - the buffer\n * @returns the index\n */\n private bufferIndexOf(buffer: ArrayBuffer): number {\n const known = this.bufferIndex.get(buffer);\n if (known !== undefined) {\n return known;\n }\n const index = this.buffers.length;\n this.bufferIndex.set(buffer, index);\n this.buffers.push(buffer);\n return index;\n }\n}\n\n// ============================================================ dtype helpers\n\n/**\n * The wire dtype of a typed array by its class.\n * @param view - the array\n * @returns the dtype (\"u8\" for a Uint8Array; byte stores pass \"utf8\" explicitly)\n */\nfunction wireDtypeOf(view: TypedArrayData): WireDtype {\n if (view instanceof Uint32Array) {\n return \"u32\";\n }\n if (view instanceof Int32Array) {\n return \"i32\";\n }\n if (view instanceof Float32Array) {\n return \"f32\";\n }\n if (view instanceof Float64Array) {\n return \"f64\";\n }\n return \"u8\";\n}\n\n// ============================================================ caches of lazily kept representations\n\n/** Encoded dictionaries, keyed by the dictionary array (shared between a static column and its temporal table). */\nconst DICTIONARY_CACHE = new WeakMap<readonly string[], EncodedUtf8>();\n\n/** JSON text of json columns, keyed by the column, with the column version it was built from. */\nconst JSON_TEXT_CACHE = new WeakMap<Column, { readonly version: number; readonly encoded: EncodedUtf8 }>();\n\n/**\n * Whether a cached Utf8 store is still usable: the same row count and not detached by a transfer.\n * @param encoded - the cached store\n * @param rows - the expected row count\n * @returns true when the cache can be reused\n */\nfunction cacheUsable(encoded: EncodedUtf8, rows: number): boolean {\n return encoded.offsets.length === rows + 1;\n}\n\n/**\n * The encoded form of a dictionary, built once per dictionary array.\n * @param dictionary - the strings in code order\n * @returns the offsets and bytes\n */\nfunction encodedDictionary(dictionary: readonly string[]): EncodedUtf8 {\n const cached = DICTIONARY_CACHE.get(dictionary);\n if (cached !== undefined && cacheUsable(cached, dictionary.length)) {\n return cached;\n }\n const encoded = encodeUtf8Rows(dictionary, dictionary.length);\n DICTIONARY_CACHE.set(dictionary, encoded);\n return encoded;\n}\n\n/**\n * The JSON text of every row of a json column as a Utf8 store (an unset row is empty text), built\n * once per column version.\n * @param column - the json column\n * @returns the offsets and bytes\n */\nfunction encodedJsonText(column: JsonColumn): EncodedUtf8 {\n const cached = JSON_TEXT_CACHE.get(column);\n if (cached !== undefined && cached.version === column.version && cacheUsable(cached.encoded, column.length)) {\n return cached.encoded;\n }\n const texts = new Array<string>(column.length);\n for (let row = 0; row < column.length; row++) {\n const value = column.values[row];\n texts[row] = value === undefined || !column.isSet(row) ? \"\" : JSON.stringify(encodeJsonValue(value));\n }\n const encoded = encodeUtf8Rows(texts, texts.length);\n JSON_TEXT_CACHE.set(column, { version: column.version, encoded });\n return encoded;\n}\n\n// ============================================================ column encoding\n\n/**\n * A Utf8 store as two references.\n * @param layout - the collector\n * @param encoded - the offsets and bytes\n * @param shared - whether the holder of the store is shared\n * @returns the wire store\n */\nfunction utf8Ref(layout: WireLayout, encoded: EncodedUtf8, shared: boolean): WireUtf8 {\n return { offsets: layout.ref(encoded.offsets, \"u32\", shared), utf8: layout.ref(encoded.utf8, \"utf8\", shared) };\n}\n\n/**\n * The manifest copy of a column's metadata: the JSON fields tagged per design section 5.9, the rest\n * copied as is. The tagged fields no longer match ColumnMeta's static types when a value was\n * non-finite; the reader decodes them before resolving the metadata again.\n * @param meta - the resolved metadata\n * @returns the manifest form\n */\nfunction encodeColumnMeta(meta: ColumnMeta): ColumnMeta {\n return {\n name: meta.name,\n domain: meta.domain,\n dtype: meta.dtype,\n components: meta.components,\n itemDtype: meta.itemDtype,\n itemComponents: meta.itemComponents,\n nullable: meta.nullable,\n mutable: meta.mutable,\n role: meta.role,\n refersTo: meta.refersTo,\n unique: meta.unique,\n default: encodeJsonValue(meta.default),\n fill: encodeJsonValue(meta.fill) as number | string | boolean,\n options: meta.options === null ? null : (encodeJsonValue(meta.options) as readonly unknown[]),\n origin: meta.origin === null ? null : { ...meta.origin },\n dynamic: meta.dynamic,\n extra: encodeJsonValue(meta.extra) as Readonly<Record<string, unknown>>,\n };\n}\n\n/**\n * Encode one column (design section 9.1): the buffers its dtype uses, null for the rest. A column\n * held by more than one table (or belonging to a table held by more than one snapshot) has every\n * buffer recorded as shared, including the ones it materialises lazily while being encoded.\n * @param layout - the collector\n * @param column - the column\n * @param tableShared - whether the table holding the column is shared\n * @returns the wire column\n */\nfunction encodeColumn(layout: WireLayout, column: Column, tableShared: boolean): WireColumn {\n const shared = tableShared || isShared(column);\n const base = {\n meta: encodeColumnMeta(column.meta),\n data: null as WireBufferRef | null,\n validity: column.validity === null ? null : layout.ref(column.validity, \"u32\", shared),\n nullCount: column.nullCount,\n dictionary: null as WireUtf8 | null,\n strings: null as WireUtf8 | null,\n offsets: null as WireBufferRef | null,\n child: null as WireColumn | null,\n jsonText: null as WireUtf8 | null,\n };\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n base.data = layout.ref(column.data, dtype, shared);\n break;\n case \"bool\":\n base.data = layout.ref(column.data, \"u32\", shared);\n break;\n case \"dict\":\n base.data = layout.ref(column.codes, \"u32\", shared);\n base.dictionary = utf8Ref(layout, encodedDictionary(column.dictionary), shared);\n break;\n case \"string\":\n base.strings = {\n offsets: layout.ref(column.offsets, \"u32\", shared),\n utf8: layout.ref(column.utf8, \"utf8\", shared),\n };\n break;\n case \"list\":\n base.offsets = layout.ref(column.offsets, \"u32\", shared);\n base.child = encodeColumn(layout, column.child, shared);\n break;\n case \"json\":\n base.jsonText = utf8Ref(layout, encodedJsonText(column), shared);\n break;\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n return base;\n}\n\n/**\n * Encode every column of a table in declaration order.\n * @param layout - the collector\n * @param table - the table\n * @returns the wire columns\n */\nfunction encodeTable(layout: WireLayout, table: AttributeTable): WireColumn[] {\n const out: WireColumn[] = [];\n const tableShared = isShared(table);\n for (const column of table) {\n out.push(encodeColumn(layout, column, tableShared));\n }\n return out;\n}\n\n// ============================================================ id map, meta, views\n\n/**\n * Encode the id map (design section 4.5), materialising its typed form on first use.\n * @param layout - the collector\n * @param snapshot - the snapshot\n * @returns the wire id map\n */\nfunction encodeIds(layout: WireLayout, snapshot: GraphSnapshot): WireIdMap {\n const { ids } = snapshot;\n if (!(ids instanceof NodeIdMap)) {\n throw new GraphFormatError(\"E_UNSUPPORTED\", \"the snapshot's id map is not a NodeIdMap of this package\", {\n reason: \"foreign id map\",\n });\n }\n const typed = nodeIdMapToTyped(ids);\n const shared = isShared(ids);\n return {\n kind: typed.kind,\n size: typed.size,\n offset: typed.offset,\n values: typed.values === null ? null : layout.ref(typed.values, wireDtypeOf(typed.values), shared),\n tags: typed.tags === null ? null : layout.ref(typed.tags, \"u8\", shared),\n numbers: typed.numbers === null ? null : layout.ref(typed.numbers, \"f64\", shared),\n offsets: typed.offsets === null ? null : layout.ref(typed.offsets, \"u32\", shared),\n utf8: typed.utf8 === null ? null : layout.ref(typed.utf8, \"utf8\", shared),\n };\n}\n\n/**\n * The manifest copy of the graph metadata with `extra` tagged per design section 5.9.\n * @param meta - the metadata\n * @returns the manifest form\n */\nfunction encodeGraphMeta(meta: GraphMeta): GraphMeta {\n return {\n name: meta.name,\n description: meta.description,\n creator: meta.creator,\n created: meta.created,\n modified: meta.modified,\n keywords: [...meta.keywords],\n sourceFormat: meta.sourceFormat,\n sourceVersion: meta.sourceVersion,\n idType: meta.idType,\n timeFormat: meta.timeFormat,\n timeRepresentation: meta.timeRepresentation,\n mode: meta.mode,\n declaredMultigraph: meta.declaredMultigraph,\n weightOrigin: meta.weightOrigin === null ? null : { ...meta.weightOrigin },\n extra: encodeJsonValue(meta.extra) as Readonly<Record<string, unknown>>,\n };\n}\n\n/**\n * The cached, non-scalar views named by includeViews, each as its materialised member arrays\n * (design section 9.1). A view that is not resident is skipped: the receiver recomputes it.\n * @param layout - the collector\n * @param snapshot - the snapshot\n * @param names - the requested views\n * @returns the wire views, or null when none was carried\n */\nfunction encodeViews(\n layout: WireLayout,\n snapshot: GraphSnapshot,\n names: readonly ViewName[] | undefined,\n): Record<string, Record<string, WireBufferRef>> | null {\n if (names === undefined || names.length === 0) {\n return null;\n }\n const out: Record<string, Record<string, WireBufferRef>> = {};\n let count = 0;\n for (const name of new Set(names)) {\n if (SCALAR_VIEWS.has(name)) {\n continue;\n }\n const value: unknown = peekView(snapshot, name);\n if (value === null) {\n continue;\n }\n const members: Record<string, WireBufferRef> = {};\n let any = false;\n for (const [member, array] of Object.entries(viewArrays(snapshot, name, value))) {\n const view = array as TypedArrayData;\n members[member] = layout.ref(view, wireDtypeOf(view));\n any = true;\n }\n if (any) {\n out[name] = members;\n count++;\n }\n }\n return count === 0 ? null : out;\n}\n\n// ============================================================ the manifest\n\n/** The result of collecting a snapshot: the manifest and the layout that placed its arrays. */\ninterface CollectedWire {\n /** The manifest. */\n readonly manifest: WireManifest;\n /** The collector holding the buffers (reference mode) or the segments (container mode). */\n readonly layout: WireLayout;\n}\n\n/**\n * Build the manifest of a snapshot over a collector (design section 9.1): core arrays first (an\n * identity permutation, an absent weights array and a zero-length array are null), then the id map,\n * the tables, the extension tables, the metadata and the requested views.\n * @param snapshot - the snapshot\n * @param layout - the collector\n * @param includeViews - the views to carry\n * @param includeColumns - whether attribute and extension tables are carried (default true)\n * @returns the manifest and the collector\n */\nexport function collectWire(\n snapshot: GraphSnapshot,\n layout: WireLayout,\n includeViews: readonly ViewName[] | undefined,\n includeColumns = true,\n): CollectedWire {\n assertLittleEndianHost();\n const identity = snapshot.flags.arcToEdgeIsIdentity;\n const coreArrays: Record<CoreArrayName, TypedArrayData | null> = {\n rowPtr: snapshot.rowPtr,\n colIdx: snapshot.colIdx,\n weights: snapshot.weights,\n arcToEdge: identity ? null : snapshot.arcToEdge,\n edgeToArc: identity ? null : snapshot.edgeToArc,\n };\n const coreRefs: Record<CoreArrayName, WireBufferRef | null> = {\n rowPtr: null,\n colIdx: null,\n weights: null,\n arcToEdge: null,\n edgeToArc: null,\n };\n const rowPtrRef = layout.ref(snapshot.rowPtr, \"u32\");\n coreRefs.rowPtr = rowPtrRef;\n for (const name of CORE_ORDER) {\n const array = coreArrays[name];\n if (name !== \"rowPtr\" && array !== null && array.length > 0) {\n coreRefs[name] = layout.ref(array, wireDtypeOf(array));\n }\n }\n const arena = encodeArena(snapshot, layout, coreRefs);\n const ids = encodeIds(layout, snapshot);\n const nodeColumns = includeColumns ? encodeTable(layout, snapshot.nodes) : [];\n const edgeColumns = includeColumns ? encodeTable(layout, snapshot.edges) : [];\n const graphColumns = includeColumns ? encodeTable(layout, snapshot.graph) : [];\n const extensions: { name: string; rowCount: number; columns: WireColumn[] }[] = [];\n if (includeColumns) {\n for (const [name, table] of snapshot.extensions) {\n extensions.push({ name, rowCount: table.rowCount, columns: encodeTable(layout, table) });\n }\n }\n const views = encodeViews(layout, snapshot, includeViews);\n layout.finalise();\n const manifest: WireManifest = {\n format: WIRE_FORMAT,\n wire: [WIRE_MAJOR, WIRE_MINOR],\n producer: WIRE_PRODUCER,\n formatVersion: FORMAT_VERSION,\n directed: snapshot.directed,\n counts: {\n nodes: snapshot.nodeCount,\n edges: snapshot.edgeCount,\n arcs: snapshot.arcCount,\n selfLoops: snapshot.selfLoopCount,\n },\n flags: { ...snapshot.flags },\n core: {\n rowPtr: rowPtrRef,\n colIdx: coreRefs.colIdx,\n weights: coreRefs.weights,\n arcToEdge: coreRefs.arcToEdge,\n edgeToArc: coreRefs.edgeToArc,\n },\n arena,\n ids,\n nodeColumns,\n edgeColumns,\n graphColumns,\n extensions,\n meta: encodeGraphMeta(snapshot.meta),\n views,\n copied: layout.copied,\n label: snapshot.label,\n };\n return { manifest, layout };\n}\n\n/**\n * The arena descriptor: in container mode the prefix of the region holding the core arrays (always\n * present); in reference mode the snapshot's own arena when it has one.\n * @param snapshot - the snapshot\n * @param layout - the collector, after the core arrays were placed\n * @param coreRefs - the core references\n * @returns the descriptor, or null\n */\nfunction encodeArena(\n snapshot: GraphSnapshot,\n layout: WireLayout,\n coreRefs: Readonly<Record<CoreArrayName, WireBufferRef | null>>,\n): WireArena | null {\n if (layout.mode === \"container\") {\n let end = 0;\n let hotByteLength = 0;\n for (const name of CORE_ORDER) {\n const ref = coreRefs[name];\n if (ref === null) {\n continue;\n }\n end = ref.byteOffset + ref.byteLength;\n if (name === \"rowPtr\" || name === \"colIdx\" || name === \"weights\") {\n hotByteLength = end;\n }\n }\n return { buffer: 0, byteOffset: 0, byteLength: end, hotByteLength };\n }\n const { arena } = snapshot;\n if (arena === null) {\n return null;\n }\n const buffer = layout.indexOf(arena.buffer);\n if (buffer === null) {\n return null;\n }\n return { buffer, byteOffset: arena.byteOffset, byteLength: arena.byteLength, hotByteLength: arena.hotByteLength };\n}\n\n// ============================================================ public entry points\n\n/**\n * The plain-object wire form of a snapshot (design section 9.1): a JSON-serialisable manifest plus\n * the distinct backing ArrayBuffers of the core, the id map, the columns and the extension tables.\n * Without `transfer` every buffer is a plain reference and postMessage clones; with `transfer: true`\n * every buffer held by more than one snapshot, table or column (design section 9.1, tracked by\n * src/util/shared-buffers.ts) is copied (its index listed in `manifest.copied`) so the remaining\n * buffers can be transferred with `transferables()`.\n * @param snapshot - the snapshot\n * @param options - transfer mode, the cached views to carry and whether columns are carried\n * @returns the wire snapshot; E_UNSUPPORTED on a big-endian host\n */\nexport function toWire(snapshot: GraphSnapshot, options: ToWireOptions = {}): WireSnapshot {\n const transfer = options.transfer === true;\n const layout = new WireLayout(\"reference\", transfer);\n const { manifest } = collectWire(snapshot, layout, options.includeViews, options.includeColumns !== false);\n if (transfer) {\n // the transfer list of THIS wire: exclusive originals plus the fresh copies of shared buffers\n TRANSFER_LISTS.set(snapshot, [...layout.buffers]);\n }\n return { manifest, buffers: layout.buffers };\n}\n\n/** Per snapshot, the buffers its most recent `toWire({ transfer: true })` put into `wire.buffers`. */\nconst TRANSFER_LISTS = new WeakMap<GraphSnapshot, ArrayBuffer[]>();\n\n/**\n * The postMessage transfer list of design section 9.1: the same set `toWire({ transfer: true })`\n * put into `wire.buffers` -- exclusively owned originals plus the fresh copies made for shared\n * buffers -- so `postMessage(wire, snapshot.transferables())` transfers exactly the buffers the\n * wire carries, whatever `includeColumns` / `includeViews` selected (a buffer the wire does not\n * reference is never listed, so no column is lost on either side). Before any transfer-mode toWire()\n * call the list is computed for the default wire shape: the distinct exclusively owned buffers of\n * the core, the id map, the typed columns, the string stores and the extension tables; a buffer\n * held by more than one snapshot, table or column is excluded and an identity permutation is never\n * included.\n * @param snapshot - the snapshot\n * @returns the buffers, in manifest order\n */\nexport function transferables(snapshot: GraphSnapshot): ArrayBuffer[] {\n const recorded = TRANSFER_LISTS.get(snapshot);\n if (recorded !== undefined) {\n return [...recorded];\n }\n const layout = new WireLayout(\"reference\", false);\n collectWire(snapshot, layout, undefined, true);\n return layout.buffers.filter((buffer) => !isShared(buffer));\n}\n\n/**\n * The UTF-8 bytes of a manifest as the container stores them (design section 9.2).\n * @param manifest - the manifest\n * @returns the encoded JSON text\n */\nexport function encodeManifest(manifest: WireManifest): Uint8Array {\n return encoder.encode(JSON.stringify(manifest));\n}\n","/**\n * The wire decoder (design sections 4.5, 5.9, 9.1, 9.5 and 11.3): `fromWire()` rebuilds a snapshot\n * from a WireSnapshot, and `decodeManifest()` is the shared reader the GSNP container functions of\n * bytes.ts drive with their own buffer regions.\n *\n * Rules (design section 9.1): a manifest whose `formatVersion` is not the reader's or whose wire\n * major is unknown is refused with E_UNSUPPORTED_VERSION; a newer wire minor is read by ignoring\n * unknown manifest fields; an unknown column dtype is E_UNSUPPORTED unless `unknownColumns: \"skip\"`\n * drops the column and names it in `meta.extra[\"graphty.skippedColumns\"]`; an unknown id-map kind\n * is always E_UNSUPPORTED; unknown view entries are ignored and recomputed. Every WireBufferRef is\n * checked against its buffer before a typed array is built over it (E_BAD_SERIALIZATION with\n * details.ref), whatever the validation level, because a RangeError from a typed-array constructor\n * is never an acceptable failure mode; the \"structure\" and \"full\" levels add the checks of design\n * section 9.5 and then run the snapshot's own validate().\n *\n * Buffers are adopted by reference by default: the arrays are views into the caller's buffers and\n * the arena descriptor is honoured. A SharedArrayBuffer is copied (decision D-SAB), and `copy: true`\n * copies every buffer before adoption.\n */\n\nimport { CORE_ORDER } from \"../builder/arena.js\";\nimport { createColumn, emptyParts, isPlainObject, resolveColumnMeta } from \"../columns/column.js\";\nimport { AttributeTable } from \"../columns/table.js\";\nimport { ALIGNMENT, FORMAT_VERSION, MAX_COUNT, WIRE_FORMAT, WIRE_MAJOR } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type NodeIdMap, nodeIdMapFromTyped, type NodeIdMapTypedParts } from \"../ids/node-id-map.js\";\nimport { checkUtf8Layout, decodeUtf8Rows, Utf8Store } from \"../ids/string-store.js\";\nimport { createSnapshot, type GraphSnapshot, seedView } from \"../snapshot/graph-snapshot.js\";\nimport { cooViewOf, edgeListViewOf, ReverseAdjacency, rowLengths } from \"../snapshot/views.js\";\nimport {\n type ArenaLayout,\n type ArenaSegment,\n type Column,\n type ColumnDeclPatch,\n type ColumnDomain,\n type ColumnMeta,\n type ColumnOrigin,\n type ColumnOriginInput,\n type CoreArrayName,\n type Dtype,\n type F32,\n type F64,\n type FromWireOptions,\n type GraphMeta,\n type NodeIdMapKind,\n type ScalarDtype,\n type SnapshotFlags,\n type TypedArrayData,\n type U8,\n type U32,\n type ValidationLevel,\n type WireBufferRef,\n type WireDtype,\n type WireSnapshot,\n} from \"../types/index.js\";\nimport { type MutableColumnParts, type SnapshotParts } from \"../types/internal.js\";\nimport { canViewAsPaddedU32, copyToPaddedStore, padTo4 } from \"../util/typed-array.js\";\nimport {\n checkCooSrc,\n checkDegree,\n checkDegreeOrder,\n checkEdgeList,\n checkF64View,\n checkInDegree,\n checkMate,\n checkOutDegree,\n checkReverse,\n checkSelfLoopArcs,\n checkSelfLoopsPerNode,\n CoreFacts,\n} from \"./carried-views.js\";\nimport { defineJsonKey } from \"./to-wire.js\";\n\n// ============================================================ vocabularies\n\nconst WIRE_DTYPES: ReadonlySet<string> = new Set([\"u32\", \"i32\", \"f32\", \"f64\", \"u8\", \"utf8\"]);\nconst COLUMN_DTYPES: ReadonlySet<string> = new Set([\n \"f32\",\n \"f64\",\n \"i32\",\n \"u32\",\n \"u8\",\n \"bool\",\n \"dict\",\n \"string\",\n \"list\",\n \"json\",\n]);\nconst ID_MAP_KINDS: ReadonlySet<string> = new Set([\"identity\", \"dense\", \"numeric\", \"string\", \"mixed\"]);\nconst ID_TYPES: ReadonlySet<GraphMeta[\"idType\"] & string> = new Set([\"string\", \"integer\", \"mixed\"] as const);\nconst TIME_FORMATS: ReadonlySet<GraphMeta[\"timeFormat\"] & string> = new Set([\n \"integer\",\n \"double\",\n \"date\",\n \"dateTime\",\n] as const);\nconst TIME_REPRESENTATIONS: ReadonlySet<GraphMeta[\"timeRepresentation\"] & string> = new Set([\n \"interval\",\n \"timestamp\",\n] as const);\nconst MODES: ReadonlySet<GraphMeta[\"mode\"] & string> = new Set([\"static\", \"dynamic\", \"slice\"] as const);\nconst FORBIDDEN_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nconst NUM_TAG = \"$num\";\nconst ESC_TAG = \"$esc\";\n/** The deepest JSON nesting a manifest value may have; deeper input is refused instead of overflowing the stack. */\nconst MAX_JSON_DEPTH = 256;\n\n/**\n * A short plain-ASCII rendering of an untrusted manifest value for an error message: strings are\n * quoted, everything else is named by type (a bigint or a null-prototype object cannot be\n * stringified, and a structuredClone-delivered manifest can carry both).\n * @param value - the value\n * @returns the rendering\n */\nfunction describe(value: unknown): string {\n if (typeof value === \"string\") {\n return JSON.stringify(value.length > 40 ? `${value.slice(0, 37)}...` : value);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\" || value === null) {\n return String(value);\n }\n return value === undefined ? \"undefined\" : `a ${typeof value}`;\n}\n\n/** The meta.extra key naming the columns dropped under unknownColumns: \"skip\" (design section 9.1). */\nexport const SKIPPED_COLUMNS_KEY = \"graphty.skippedColumns\";\n\n// ============================================================ errors and shape readers\n\n/**\n * The E_BAD_SERIALIZATION error of a malformed manifest member or buffer reference.\n * @param ref - the manifest path, e.g. \"nodeColumns[2].data\"\n * @param reason - what is wrong\n * @param details - extra context\n * @returns the error\n */\nexport function badWire(\n ref: string,\n reason: string,\n details: Readonly<Record<string, unknown>> = {},\n): GraphFormatError {\n return new GraphFormatError(\"E_BAD_SERIALIZATION\", `${ref}: ${reason}`, { ref, reason, ...details });\n}\n\nfunction asObject(value: unknown, path: string): Record<string, unknown> {\n if (!isPlainObject(value)) {\n throw badWire(path, \"expected an object\");\n }\n return value;\n}\n\nfunction asArray(value: unknown, path: string): readonly unknown[] {\n if (!Array.isArray(value)) {\n throw badWire(path, \"expected an array\");\n }\n return value as readonly unknown[];\n}\n\nfunction asString(value: unknown, path: string): string {\n if (typeof value !== \"string\") {\n throw badWire(path, \"expected a string\");\n }\n return value;\n}\n\nfunction asStringOrNull(value: unknown, path: string): string | null {\n if (value === undefined || value === null) {\n return null;\n }\n return asString(value, path);\n}\n\nfunction asBoolean(value: unknown, path: string): boolean {\n if (typeof value !== \"boolean\") {\n throw badWire(path, \"expected a boolean\");\n }\n return value;\n}\n\nfunction asBooleanOrNull(value: unknown, path: string): boolean | null {\n if (value === undefined || value === null) {\n return null;\n }\n return asBoolean(value, path);\n}\n\nfunction asCount(value: unknown, path: string): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0 || value > MAX_COUNT) {\n throw badWire(path, `expected an integer in [0, ${MAX_COUNT}]`, { found: value });\n }\n // JSON.parse(\"-0\") is -0; a count is stored as 0 (design section 4.1)\n return value === 0 ? 0 : value;\n}\n\nfunction asEnum<T extends string>(value: unknown, path: string, allowed: ReadonlySet<T>): T | null {\n if (value === undefined || value === null) {\n return null;\n }\n if (typeof value !== \"string\" || !(allowed as ReadonlySet<string>).has(value)) {\n throw badWire(path, `unexpected value ${describe(value)}`, { found: value });\n }\n return value as T;\n}\n\n/**\n * Whether a string names a column dtype this reader knows.\n * @param value - the dtype text\n * @returns true for one of the ten dtypes\n */\nfunction isKnownDtype(value: unknown): value is Dtype {\n return typeof value === \"string\" && COLUMN_DTYPES.has(value);\n}\n\n// ============================================================ JSON values (5.9)\n\n/**\n * Decode a manifest JSON value (design section 5.9): `{ \"$num\": \"Infinity\" | \"-Infinity\" | \"NaN\" |\n * \"-0\" }` becomes the number, `{ \"$esc\": { ... } }` unwraps a user object whose only key collided\n * with a tag (the writer's escape), arrays and plain objects are rebuilt recursively (a key named\n * `__proto__`, `constructor` or `prototype` is refused), everything else is returned as is. Nesting\n * deeper than MAX_JSON_DEPTH is E_BAD_SERIALIZATION rather than a stack overflow.\n * @param value - the value from the manifest\n * @param path - the manifest path for error messages\n * @param depth - the current nesting depth\n * @returns the decoded value\n */\nexport function decodeJsonValue(value: unknown, path: string, depth = 0): unknown {\n if (depth > MAX_JSON_DEPTH) {\n throw badWire(path, `JSON nesting deeper than ${MAX_JSON_DEPTH}`, { reason: \"nesting\" });\n }\n if (Array.isArray(value)) {\n return value.map((item: unknown, i) => decodeJsonValue(item, `${path}[${i}]`, depth + 1));\n }\n if (!isPlainObject(value)) {\n return value;\n }\n const keys = Object.keys(value);\n if (keys.length === 1 && keys[0] === NUM_TAG) {\n const tag: unknown = value[NUM_TAG];\n switch (tag) {\n case \"NaN\":\n return Number.NaN;\n case \"Infinity\":\n return Infinity;\n case \"-Infinity\":\n return -Infinity;\n case \"-0\":\n return -0;\n default:\n throw badWire(path, `unknown number tag ${describe(tag)}`, { found: tag });\n }\n }\n if (keys.length === 1 && keys[0] === ESC_TAG) {\n const inner: unknown = value[ESC_TAG];\n if (!isPlainObject(inner)) {\n throw badWire(path, \"an escaped object must hold a plain object\", { found: typeof inner });\n }\n return decodeJsonObject(inner, path, depth);\n }\n return decodeJsonObject(value, path, depth);\n}\n\n/**\n * Rebuild a plain object's members (no tag interpretation of the object itself).\n * @param value - the plain object\n * @param path - the manifest path\n * @param depth - the nesting depth of the object\n * @returns the rebuilt object\n */\nfunction decodeJsonObject(value: Record<string, unknown>, path: string, depth: number): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n if (FORBIDDEN_KEYS.has(key)) {\n throw badWire(path, `forbidden key \"${key}\"`, { key });\n }\n defineJsonKey(out, key, decodeJsonValue(value[key], `${path}.${key}`, depth + 1));\n }\n return out;\n}\n\n/**\n * The JSON.parse reviver of design section 9.5: refuses the prototype-pollution keys.\n * @param key - the property name being revived\n * @param value - the revived value\n * @returns the value unchanged\n */\nfunction guardReviver(this: unknown, key: string, value: unknown): unknown {\n if (FORBIDDEN_KEYS.has(key)) {\n throw badWire(\"manifest\", `forbidden key \"${key}\"`, { key });\n }\n return value;\n}\n\n/**\n * Parse JSON text from a container (the manifest or one json column row) with the guarding\n * reviver. A syntax error is E_BAD_SERIALIZATION.\n * @param text - the JSON text\n * @param path - the manifest path for error messages\n * @returns the parsed value\n */\nexport function parseGuardedJson(text: string, path: string): unknown {\n try {\n return JSON.parse(text, guardReviver) as unknown;\n } catch (err) {\n if (err instanceof GraphFormatError) {\n throw err;\n }\n throw badWire(path, `not valid JSON (${err instanceof Error ? err.message : String(err)})`);\n }\n}\n\n// ============================================================ options and regions\n\n/** The options of fromWire / fromBytes after defaults were applied. */\ninterface ResolvedFromWireOptions {\n /** The validation level. */\n readonly level: ValidationLevel;\n /** Whether buffers are copied before adoption. */\n readonly copy: boolean;\n /** What to do with an unknown column dtype. */\n readonly unknownColumns: \"error\" | \"skip\";\n}\n\n/**\n * Apply defaults to FromWireOptions and reject values outside their documented sets (E_UNSUPPORTED).\n * @param options - the caller's options\n * @param defaultLevel - \"structure\" for fromWire, \"full\" for fromBytes\n * @returns the resolved options\n */\nexport function resolveFromWireOptions(\n options: FromWireOptions | undefined,\n defaultLevel: ValidationLevel,\n): ResolvedFromWireOptions {\n const level = options?.validate ?? defaultLevel;\n if (level !== \"none\" && level !== \"structure\" && level !== \"full\") {\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown validation level ${String(level)}`, {\n option: \"validate\",\n found: level,\n });\n }\n const unknownColumns = options?.unknownColumns ?? \"error\";\n if (unknownColumns !== \"error\" && unknownColumns !== \"skip\") {\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown unknownColumns policy ${String(unknownColumns)}`, {\n option: \"unknownColumns\",\n found: unknownColumns,\n });\n }\n const copy = options?.copy ?? false;\n if (typeof copy !== \"boolean\") {\n throw new GraphFormatError(\"E_UNSUPPORTED\", \"copy must be a boolean\", { option: \"copy\", found: copy });\n }\n return { level, copy, unknownColumns };\n}\n\n/** Where a located byte range lives. */\nexport interface LocatedRange {\n /** The plain ArrayBuffer holding the bytes. */\n readonly buffer: ArrayBuffer;\n /** The absolute byte offset of the range inside `buffer`. */\n readonly byteOffset: number;\n}\n\n/**\n * One buffer index of a manifest as the decoder sees it: a byte length for range checks, a locator\n * that finds a range contiguously in one plain buffer (null when it spans chunks or lives in a\n * SharedArrayBuffer) and a reader that copies a range out.\n */\nexport interface WireRegion {\n /** The byte length every reference is checked against. */\n readonly byteLength: number;\n /**\n * Find a byte range in one plain buffer.\n * @param byteOffset - region-relative start\n * @param byteLength - length\n * @returns the buffer and absolute offset, or null when the range cannot be adopted\n */\n locate(byteOffset: number, byteLength: number): LocatedRange | null;\n /**\n * Copy a byte range into a fresh buffer.\n * @param byteOffset - region-relative start\n * @param byteLength - length\n * @returns a Uint8Array at offset 0 of a fresh ArrayBuffer of at least byteLength bytes\n */\n read(byteOffset: number, byteLength: number): U8;\n}\n\n/**\n * A region over one plain ArrayBuffer.\n * @param buffer - the buffer\n * @param base - the absolute byte offset of the region's start inside the buffer\n * @param byteLength - the region's byte length\n * @returns the region\n */\nexport function bufferRegion(buffer: ArrayBuffer, base: number, byteLength: number): WireRegion {\n return {\n byteLength,\n locate(byteOffset: number): LocatedRange {\n return { buffer, byteOffset: base + byteOffset };\n },\n read(byteOffset: number, length: number): U8 {\n const out = new Uint8Array(new ArrayBuffer(padTo4(length)), 0, length);\n out.set(new Uint8Array(buffer, base + byteOffset, length));\n return out;\n },\n };\n}\n\n/**\n * Copy an ArrayBuffer or SharedArrayBuffer into a fresh ArrayBuffer.\n * @param buffer - the source\n * @returns the copy\n */\nfunction copyBuffer(buffer: ArrayBufferLike): ArrayBuffer {\n const out = new ArrayBuffer(buffer.byteLength);\n new Uint8Array(out).set(new Uint8Array(buffer));\n return out;\n}\n\n/**\n * Whether a value is a SharedArrayBuffer (never adopted, decision D-SAB).\n * @param value - the value\n * @returns true for a SharedArrayBuffer\n */\nexport function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer {\n return typeof SharedArrayBuffer !== \"undefined\" && value instanceof SharedArrayBuffer;\n}\n\n// ============================================================ the decoder\n\n/** Who a placed byte range belongs to, for the overlap rule of design section 9.5. */\ntype RangeKind = \"core\" | \"immutable\" | \"mutable\" | \"view\";\n\n/** An adopted byte range, keyed by the ArrayBuffer it lives in (absolute offsets), for the overlap rule. */\ninterface PlacedRange {\n readonly buffer: ArrayBuffer;\n readonly start: number;\n readonly end: number;\n readonly kind: RangeKind;\n readonly path: string;\n}\n\ninterface SkippedColumn {\n readonly domain: ColumnDomain;\n readonly table: string | null;\n readonly name: string;\n readonly dtype: string;\n}\n\n/**\n * Bytes per element and constructor of a wire dtype.\n * @param dtype - the wire dtype\n * @returns the element size\n */\nfunction wireElementSize(dtype: WireDtype): number {\n switch (dtype) {\n case \"u32\":\n case \"i32\":\n case \"f32\":\n return 4;\n case \"f64\":\n return 8;\n case \"u8\":\n case \"utf8\":\n return 1;\n default: {\n const name: string = dtype;\n throw badWire(\"dtype\", `unknown wire dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Build the typed array of a wire dtype over a buffer.\n * @param dtype - the wire dtype\n * @param buffer - the buffer\n * @param byteOffset - the absolute start\n * @param length - the element count\n * @returns the array\n */\nfunction buildArray(dtype: WireDtype, buffer: ArrayBuffer, byteOffset: number, length: number): TypedArrayData {\n switch (dtype) {\n case \"u32\":\n return new Uint32Array(buffer, byteOffset, length);\n case \"i32\":\n return new Int32Array(buffer, byteOffset, length);\n case \"f32\":\n return new Float32Array(buffer, byteOffset, length);\n case \"f64\":\n return new Float64Array(buffer, byteOffset, length);\n case \"u8\":\n case \"utf8\":\n return new Uint8Array(buffer, byteOffset, length);\n default: {\n const name: string = dtype;\n throw badWire(\"dtype\", `unknown wire dtype ${name}`, { dtype: name });\n }\n }\n}\n\n/**\n * Read a WireBufferRef's shape from an untrusted manifest member.\n * @param value - the member\n * @param path - its manifest path\n * @returns the reference\n */\nfunction readRef(value: unknown, path: string): WireBufferRef {\n const o = asObject(value, path);\n const { dtype } = o;\n if (typeof dtype !== \"string\" || !WIRE_DTYPES.has(dtype)) {\n throw badWire(path, `unknown wire dtype ${describe(dtype)}`, { found: dtype });\n }\n const fields = [\"buffer\", \"byteOffset\", \"byteLength\", \"length\"] as const;\n for (const field of fields) {\n const v = o[field];\n if (typeof v !== \"number\" || !Number.isInteger(v) || v < 0) {\n throw badWire(`${path}.${field}`, \"expected a non-negative integer\", { found: v });\n }\n }\n return {\n buffer: o.buffer as number,\n byteOffset: o.byteOffset as number,\n byteLength: o.byteLength as number,\n dtype: dtype as WireDtype,\n length: o.length as number,\n };\n}\n\n/**\n * The error to throw for a failure while building a column or table from untrusted input: a\n * column-construction error (E_COLUMN_*, and E_DUPLICATE_ROLE from the table constructor) becomes\n * E_BAD_SERIALIZATION naming the manifest path, every other Error passes through, and a non-Error\n * value is wrapped.\n * @param err - the caught value\n * @param path - the manifest path of the column or table\n * @returns the error to throw\n */\nfunction asWireError(err: unknown, path: string): Error {\n if (err instanceof GraphFormatError && (err.code.startsWith(\"E_COLUMN\") || err.code === \"E_DUPLICATE_ROLE\")) {\n return new GraphFormatError(\"E_BAD_SERIALIZATION\", `${path}: ${err.message}`, {\n ref: path,\n reason: err.message,\n cause: err.code,\n ...err.details,\n });\n }\n if (err instanceof Error) {\n return err;\n }\n return badWire(path, String(err));\n}\n\n/**\n * The stateful reader of one manifest: resolves references against the regions, records placed\n * ranges for the overlap rule and the columns skipped under unknownColumns: \"skip\".\n */\nclass WireDecoder {\n private readonly regions: readonly WireRegion[];\n private readonly options: ResolvedFromWireOptions;\n private readonly ranges: PlacedRange[] = [];\n readonly skipped: SkippedColumn[] = [];\n\n /**\n * Create a decoder.\n * @param regions - one region per buffer index\n * @param options - the resolved options\n */\n constructor(regions: readonly WireRegion[], options: ResolvedFromWireOptions) {\n this.regions = regions;\n this.options = options;\n }\n\n /**\n * Whether the level includes the structure checks.\n * @returns true for \"structure\" and \"full\"\n */\n get structure(): boolean {\n return this.options.level !== \"none\";\n }\n\n /**\n * Whether the level is \"full\".\n * @returns true for \"full\"\n */\n get full(): boolean {\n return this.options.level === \"full\";\n }\n\n /**\n * Check a reference against its region (design section 9.5) and build the typed array over the\n * referenced bytes, adopting them when they are contiguous and aligned and copying otherwise.\n * @param value - the manifest member holding the reference\n * @param path - its manifest path\n * @param expected - the wire dtype the slot requires\n * @param kind - who the range belongs to\n * @returns the typed array\n */\n array(value: unknown, path: string, expected: WireDtype, kind: RangeKind): TypedArrayData {\n const ref = readRef(value, path);\n if (ref.dtype !== expected) {\n throw badWire(path, `expected dtype ${expected}, found ${ref.dtype}`, {\n expected,\n found: ref.dtype,\n });\n }\n const region = this.regions[ref.buffer] as WireRegion | undefined;\n if (region === undefined) {\n throw badWire(path, `buffer index ${ref.buffer} is out of range (${this.regions.length} buffers)`, {\n found: ref.buffer,\n buffers: this.regions.length,\n });\n }\n const elementSize = wireElementSize(ref.dtype);\n if (ref.byteOffset % elementSize !== 0) {\n throw badWire(path, `byteOffset ${ref.byteOffset} is not a multiple of ${elementSize}`, {\n byteOffset: ref.byteOffset,\n elementSize,\n });\n }\n if (ref.byteLength !== ref.length * elementSize) {\n throw badWire(path, `byteLength ${ref.byteLength} is not length ${ref.length} * ${elementSize}`, {\n byteLength: ref.byteLength,\n length: ref.length,\n elementSize,\n });\n }\n if (ref.byteOffset + ref.byteLength > region.byteLength) {\n throw badWire(path, `range [${ref.byteOffset}, ${ref.byteOffset + ref.byteLength}) exceeds the buffer`, {\n byteOffset: ref.byteOffset,\n byteLength: ref.byteLength,\n bufferByteLength: region.byteLength,\n });\n }\n const located = region.locate(ref.byteOffset, ref.byteLength);\n if (located !== null && located.byteOffset % elementSize === 0) {\n // adopted: the overlap rule is checked on the ArrayBuffer itself, so listing one buffer\n // twice in wire.buffers cannot hide an alias\n this.ranges.push({\n buffer: located.buffer,\n start: located.byteOffset,\n end: located.byteOffset + ref.byteLength,\n kind,\n path,\n });\n return buildArray(ref.dtype, located.buffer, located.byteOffset, ref.length);\n }\n // copied: a private buffer, nothing to overlap\n const copy = region.read(ref.byteOffset, ref.byteLength);\n return buildArray(ref.dtype, copy.buffer, 0, ref.length);\n }\n\n /**\n * A u32 array slot.\n * @param value - the manifest member\n * @param path - its path\n * @param kind - the range owner\n * @returns the array\n */\n u32(value: unknown, path: string, kind: RangeKind): U32 {\n return this.array(value, path, \"u32\", kind) as U32;\n }\n\n /**\n * A Utf8 store slot (offsets + utf8), its layout checked at the structure level and its bytes at\n * the full level.\n * @param value - the manifest member (a WireUtf8)\n * @param path - its path\n * @param rows - the row count the store must have, or null to take it from the offsets (a dictionary)\n * @param kind - the range owner\n * @param always - check the layout at every level (stores decoded eagerly)\n * @returns the offsets and bytes\n */\n utf8(\n value: unknown,\n path: string,\n rows: number | null,\n kind: RangeKind,\n always = false,\n ): { offsets: U32; utf8: U8 } {\n const o = asObject(value, path);\n const offsets = this.u32(o.offsets, `${path}.offsets`, kind);\n const utf8 = this.array(o.utf8, `${path}.utf8`, \"utf8\", kind) as U8;\n if (offsets.length === 0) {\n throw badWire(`${path}.offsets`, \"a Utf8 store needs at least one offset\");\n }\n if (this.structure || always) {\n checkUtf8Layout(offsets, utf8, rows ?? offsets.length - 1, path);\n }\n if (this.full) {\n const bad = Utf8Store.fromEncoded(offsets, utf8).firstMalformedRow();\n if (bad !== -1) {\n throw badWire(path, `malformed UTF-8 in row ${bad}`, { row: bad });\n }\n }\n return { offsets, utf8 };\n }\n\n /**\n * Enforce the overlap rule of design section 9.5: no byte overlap between a mutable column and\n * any core or immutable segment.\n */\n checkOverlaps(): void {\n const fixed = this.ranges.filter((r) => (r.kind === \"core\" || r.kind === \"immutable\") && r.end > r.start);\n for (const range of this.ranges) {\n if (range.kind !== \"mutable\" || range.end === range.start) {\n continue;\n }\n for (const other of fixed) {\n if (other.buffer === range.buffer && range.start < other.end && other.start < range.end) {\n throw badWire(range.path, `mutable column overlaps ${other.path}`, { overlaps: other.path });\n }\n }\n }\n }\n\n // ---------------------------------------------------------------- columns\n\n /**\n * Decode one column (design section 9.1), or drop it under unknownColumns: \"skip\".\n * @param value - the WireColumn\n * @param domain - the table's domain\n * @param table - the extension table name, or null\n * @param rows - the row count\n * @param path - the manifest path\n * @returns the column, or null when skipped\n */\n column(value: unknown, domain: ColumnDomain, table: string | null, rows: number, path: string): Column | null {\n const w = asObject(value, path);\n const metaRaw = asObject(w.meta, `${path}.meta`);\n const name = asString(metaRaw.name, `${path}.meta.name`);\n const { dtype, itemDtype } = metaRaw;\n const unknown = !isKnownDtype(dtype) || (dtype === \"list\" && !isKnownDtype(itemDtype));\n if (unknown) {\n const found = dtype === \"list\" ? itemDtype : dtype;\n if (this.options.unknownColumns === \"skip\") {\n this.skipped.push({ domain, table, name, dtype: String(found) });\n return null;\n }\n throw new GraphFormatError(\"E_UNSUPPORTED\", `column \"${name}\" has unknown dtype ${String(found)}`, {\n dtype: found,\n column: name,\n ref: path,\n });\n }\n const meta = this.columnMeta(metaRaw, name, domain, path);\n const kind: RangeKind = meta.mutable ? \"mutable\" : \"immutable\";\n const parts: MutableColumnParts = emptyParts(\n meta,\n rows,\n w.validity === null || w.validity === undefined ? null : this.u32(w.validity, `${path}.validity`, kind),\n );\n const declaredNullCount = w.nullCount;\n switch (meta.dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n parts.data = this.array(w.data, `${path}.data`, meta.dtype, kind);\n break;\n case \"u8\": {\n const data = this.array(w.data, `${path}.data`, \"u8\", kind) as U8;\n parts.data = canViewAsPaddedU32(data) ? data : copyToPaddedStore(data);\n break;\n }\n case \"bool\":\n parts.data = this.u32(w.data, `${path}.data`, kind);\n break;\n case \"dict\": {\n parts.data = this.u32(w.data, `${path}.data`, kind);\n const dict = this.utf8(w.dictionary, `${path}.dictionary`, null, kind, true);\n parts.dictionary = decodeUtf8Rows(dict.utf8, dict.offsets, 0, dict.offsets.length - 1);\n break;\n }\n case \"string\": {\n const store = this.utf8(w.strings, `${path}.strings`, rows, kind);\n parts.offsets = store.offsets;\n parts.utf8 = store.utf8;\n break;\n }\n case \"list\": {\n const offsets = this.u32(w.offsets, `${path}.offsets`, kind);\n if (offsets.length !== rows + 1) {\n throw badWire(`${path}.offsets`, `expected ${rows + 1} offsets, found ${offsets.length}`, {\n expected: rows + 1,\n found: offsets.length,\n });\n }\n parts.offsets = offsets;\n const child = this.column(w.child, domain, table, offsets[rows], `${path}.child`);\n if (child === null || child.dtype === \"list\") {\n throw badWire(`${path}.child`, \"a list column needs a non-list child column\");\n }\n parts.child = child;\n break;\n }\n case \"json\":\n parts.values = this.jsonRows(w.jsonText, rows, `${path}.jsonText`, kind);\n break;\n default: {\n const dtypeName: string = meta.dtype;\n throw badWire(`${path}.meta.dtype`, `unknown dtype ${dtypeName}`, { dtype: dtypeName });\n }\n }\n let column: Column;\n try {\n column = createColumn(parts);\n } catch (err) {\n throw asWireError(err, path);\n }\n if (this.structure && column.nullCount !== declaredNullCount) {\n throw badWire(\n `${path}.nullCount`,\n `manifest says ${String(declaredNullCount)}, the bitmap says ${column.nullCount}`,\n {\n expected: column.nullCount,\n found: declaredNullCount,\n },\n );\n }\n return column;\n }\n\n /**\n * Resolve a column's metadata from its manifest form: the tagged JSON fields decoded, then the\n * declaration resolver of the column module applied so every rule of design section 5.5 holds.\n * @param raw - the manifest meta\n * @param name - the column name\n * @param domain - the table's domain\n * @param path - the column's manifest path\n * @returns the resolved metadata\n */\n private columnMeta(raw: Record<string, unknown>, name: string, domain: ColumnDomain, path: string): ColumnMeta {\n const metaPath = `${path}.meta`;\n const optional = <T>(key: string, check: (v: unknown, p: string) => T): T | undefined => {\n const v = raw[key];\n return v === undefined || v === null ? undefined : check(v, `${metaPath}.${key}`);\n };\n const numberOf = (v: unknown, p: string): number => {\n if (typeof v !== \"number\") {\n throw badWire(p, \"expected a number\", { found: v });\n }\n return v;\n };\n const decl: ColumnDeclPatch = {\n name,\n dtype: raw.dtype as Dtype,\n components: optional(\"components\", numberOf),\n itemDtype: optional(\"itemDtype\", (v) => v as ScalarDtype),\n itemComponents: optional(\"itemComponents\", numberOf),\n nullable: optional(\"nullable\", asBoolean),\n mutable: optional(\"mutable\", asBoolean),\n role: optional(\"role\", asString),\n refersTo: optional(\"refersTo\", (v) => v as \"node\" | \"edge\"),\n unique: optional(\"unique\", asBoolean),\n default: decodeJsonValue(raw.default, `${metaPath}.default`),\n fill: decodeJsonValue(raw.fill, `${metaPath}.fill`) as number | string | boolean | undefined,\n options: optional(\"options\", (v, p) => decodeJsonValue(v, p) as readonly unknown[]),\n origin: optional(\"origin\", (v) => v as ColumnOriginInput),\n dynamic: optional(\"dynamic\", asBoolean),\n extra: optional(\"extra\", (v, p) => decodeJsonValue(v, p) as Readonly<Record<string, unknown>>),\n };\n try {\n return resolveColumnMeta(name, domain, decl);\n } catch (err) {\n throw asWireError(err, path);\n }\n }\n\n /**\n * The values of a json column from its JSON text store: empty text is an unset row (undefined),\n * every other row is parsed with the guarding reviver and untagged.\n * @param value - the WireUtf8\n * @param rows - the row count\n * @param path - the manifest path\n * @param kind - the range owner\n * @returns one value per row\n */\n private jsonRows(value: unknown, rows: number, path: string, kind: RangeKind): unknown[] {\n const store = this.utf8(value, path, rows, kind, true);\n const texts = decodeUtf8Rows(store.utf8, store.offsets, 0, rows);\n const values = new Array<unknown>(rows);\n for (let row = 0; row < rows; row++) {\n const text = texts[row];\n values[row] =\n text === \"\" ? undefined : decodeJsonValue(parseGuardedJson(text, `${path}[${row}]`), `${path}[${row}]`);\n }\n return values;\n }\n\n /**\n * Decode a table's columns in declaration order.\n * @param value - the WireColumn array\n * @param domain - the domain\n * @param table - the extension table name, or null\n * @param rows - the row count\n * @param path - the manifest path\n * @returns the table\n */\n table(value: unknown, domain: ColumnDomain, table: string | null, rows: number, path: string): AttributeTable {\n const list = asArray(value, path);\n const columns: Column[] = [];\n const names = new Set<string>();\n for (let i = 0; i < list.length; i++) {\n const column = this.column(list[i], domain, table, rows, `${path}[${i}]`);\n if (column === null) {\n continue;\n }\n if (names.has(column.meta.name)) {\n throw badWire(`${path}[${i}].meta.name`, `column \"${column.meta.name}\" is declared twice`, {\n column: column.meta.name,\n });\n }\n names.add(column.meta.name);\n columns.push(column);\n }\n try {\n return new AttributeTable({ domain, rowCount: rows, columns });\n } catch (err) {\n throw asWireError(err, path);\n }\n }\n\n // ---------------------------------------------------------------- id map\n\n /**\n * Decode the id map (design section 4.5). An unknown kind is E_UNSUPPORTED with details.kind.\n * @param value - the WireIdMap\n * @returns the map\n */\n ids(value: unknown): NodeIdMap {\n const o = asObject(value, \"ids\");\n const kindRaw = o.kind;\n if (typeof kindRaw !== \"string\" || !ID_MAP_KINDS.has(kindRaw)) {\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${describe(kindRaw)}`, {\n kind: kindRaw,\n ref: \"ids.kind\",\n });\n }\n const kind = kindRaw as NodeIdMapKind;\n const size = asCount(o.size, \"ids.size\");\n const offsetRaw = o.offset ?? 0;\n if (typeof offsetRaw !== \"number\") {\n throw badWire(\"ids.offset\", \"expected a number\", { found: offsetRaw });\n }\n const parts: NodeIdMapTypedParts = {\n kind,\n size,\n offset: kind === \"identity\" ? offsetRaw : 0,\n values: null,\n tags: null,\n numbers: null,\n offsets: null,\n utf8: null,\n };\n const typed = parts as { -readonly [K in keyof NodeIdMapTypedParts]: NodeIdMapTypedParts[K] };\n switch (kind) {\n case \"identity\":\n break;\n case \"dense\":\n typed.values = this.u32(o.values, \"ids.values\", \"immutable\");\n break;\n case \"numeric\":\n typed.values = this.array(o.values, \"ids.values\", \"f64\", \"immutable\") as F64;\n break;\n case \"string\": {\n typed.offsets = this.u32(o.offsets, \"ids.offsets\", \"immutable\");\n typed.utf8 = this.array(o.utf8, \"ids.utf8\", \"utf8\", \"immutable\") as U8;\n break;\n }\n case \"mixed\": {\n typed.tags = this.array(o.tags, \"ids.tags\", \"u8\", \"immutable\") as U8;\n typed.numbers = this.array(o.numbers, \"ids.numbers\", \"f64\", \"immutable\") as F64;\n typed.offsets = this.u32(o.offsets, \"ids.offsets\", \"immutable\");\n typed.utf8 = this.array(o.utf8, \"ids.utf8\", \"utf8\", \"immutable\") as U8;\n break;\n }\n default: {\n const name: string = kind;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id map kind ${name}`, { kind: name });\n }\n }\n return nodeIdMapFromTyped(typed, this.options.level);\n }\n\n // ---------------------------------------------------------------- views\n\n /**\n * Resolve the member arrays of the carried views (design section 9.1): every reference is\n * checked like any other, and the arrays are installed on the snapshot by `installViews()`.\n * @param value - the manifest views member\n * @returns the member arrays per view name (unknown names included; they are ignored later)\n */\n views(value: unknown): CarriedViews {\n const out: CarriedViews = new Map();\n if (value === null || value === undefined) {\n return out;\n }\n const views = asObject(value, \"views\");\n for (const name of Object.keys(views)) {\n const members = asObject(views[name], `views.${name}`);\n const arrays = new Map<string, TypedArrayData>();\n for (const member of Object.keys(members)) {\n const path = `views.${name}.${member}`;\n const ref = readRef(members[member], path);\n arrays.set(member, this.array(ref, path, ref.dtype, \"view\"));\n }\n out.set(name, arrays);\n }\n return out;\n }\n}\n\n// ============================================================ carried views\n\n/** The member arrays of the views a manifest carried, keyed by view name then member name. */\ntype CarriedViews = Map<string, Map<string, TypedArrayData>>;\n\n/**\n * One member array of a carried view, checked for class and length.\n * @param members - the view's member arrays\n * @param view - the view name (for the error path)\n * @param member - the member name\n * @param ctor - the required typed-array class\n * @param length - the required length\n * @param required - whether an absent member is an error\n * @returns the array, or null when absent and not required\n */\nfunction viewMember<T extends TypedArrayData>(\n members: ReadonlyMap<string, TypedArrayData>,\n view: string,\n member: string,\n ctor: new (length: number) => T,\n length: number,\n required: boolean,\n): T | null {\n const path = `views.${view}.${member}`;\n const array = members.get(member);\n if (array === undefined) {\n if (required) {\n throw badWire(path, \"the carried view is missing this member\");\n }\n return null;\n }\n if (!(array instanceof ctor)) {\n throw badWire(path, `expected ${ctor.name}, found ${array.constructor.name}`, {\n expected: ctor.name,\n found: array.constructor.name,\n });\n }\n if (array.length !== length) {\n throw badWire(path, `expected ${length} entries, found ${array.length}`, {\n expected: length,\n found: array.length,\n });\n }\n return array;\n}\n\n/**\n * The per-node or per-arc array of a single-member view.\n * @param members - the view's member arrays\n * @param view - the view name\n * @param ctor - the required typed-array class\n * @param length - the required length\n * @returns the array\n */\nfunction dataMember<T extends TypedArrayData>(\n members: ReadonlyMap<string, TypedArrayData>,\n view: string,\n ctor: new (length: number) => T,\n length: number,\n): T {\n return viewMember(members, view, \"data\", ctor, length, true) as T;\n}\n\n/**\n * Install the views a manifest carried into the snapshot's cache (design section 9.1), so the\n * receiver does not recompute them. Views that alias another view on an undirected snapshot\n * (`reverse`, `inDegree`, `weightedInDegree`, `reverseDegreeOrder`) are left to the snapshot, which\n * produces the alias itself; `mate` on a directed snapshot and unknown view names are ignored.\n * Every installed member must have the class and length of the view it claims to be\n * (E_BAD_SERIALIZATION otherwise); at the \"structure\" level (`verify`) every carried view is also\n * checked against the core before it is installed (src/wire/carried-views.ts), so a corrupt or\n * forged view never enters the cache below \"full\".\n * @param snapshot - the freshly built snapshot\n * @param carried - the carried member arrays\n * @param verify - whether to check the contents (the \"structure\" level)\n */\nfunction installViews(snapshot: GraphSnapshot, carried: CarriedViews, verify: boolean): void {\n const { directed, nodeCount, edgeCount, arcCount, selfLoopCount } = snapshot;\n let facts: CoreFacts | null = null;\n const factsOf = (): CoreFacts => {\n facts ??= new CoreFacts(snapshot);\n return facts;\n };\n /**\n * Install an f64 view; under `verify` it is compared with the snapshot's own computation instead\n * (which then stays cached), so a corrupt value array never enters the cache.\n * @param name - the view\n */\n const seedF64 = (name: \"weightedOutDegree\" | \"weightedInDegree\" | \"weightedDegree\" | \"selfLoopWeight\"): void => {\n const data = dataMember(\n carried.get(name) as ReadonlyMap<string, TypedArrayData>,\n name,\n Float64Array,\n nodeCount,\n );\n if (verify) {\n checkF64View(name, data, snapshot[name]());\n return;\n }\n seedView(snapshot, name, data);\n };\n for (const [name, members] of carried) {\n switch (name) {\n case \"reverse\": {\n if (!directed) {\n break;\n }\n const rowPtr = viewMember(members, name, \"rowPtr\", Uint32Array, nodeCount + 1, true) as U32;\n const colIdx = viewMember(members, name, \"colIdx\", Uint32Array, arcCount, true) as U32;\n const fwdArc = viewMember(members, name, \"fwdArc\", Uint32Array, arcCount, true) as U32;\n const weights = viewMember(members, name, \"weights\", Float32Array, arcCount, snapshot.weights !== null);\n if (weights !== null && snapshot.weights === null) {\n throw badWire(`views.${name}.weights`, \"weights carried for an unweighted snapshot\");\n }\n const reverse = new ReverseAdjacency(snapshot, rowPtr, colIdx, weights, fwdArc);\n if (verify) {\n checkReverse(snapshot, factsOf(), reverse);\n }\n seedView(snapshot, \"reverse\", reverse);\n break;\n }\n case \"coo\": {\n const src = viewMember(members, name, \"src\", Uint32Array, arcCount, true) as U32;\n if (verify) {\n checkCooSrc(factsOf(), src);\n }\n seedView(snapshot, \"coo\", cooViewOf(snapshot, src));\n break;\n }\n case \"edgeList\": {\n const identity = snapshot.flags.arcToEdgeIsIdentity;\n const src = viewMember(members, name, \"src\", Uint32Array, edgeCount, true) as U32;\n const dst = viewMember(members, name, \"dst\", Uint32Array, edgeCount, !identity);\n const weights = viewMember(\n members,\n name,\n \"weights\",\n Float32Array,\n edgeCount,\n snapshot.weights !== null && !identity,\n );\n if (weights !== null && snapshot.weights === null) {\n throw badWire(`views.${name}.weights`, \"weights carried for an unweighted snapshot\");\n }\n if (verify) {\n checkEdgeList(snapshot, factsOf(), src, dst, weights);\n }\n seedView(\n snapshot,\n \"edgeList\",\n edgeListViewOf(snapshot, src, dst ?? snapshot.colIdx, weights ?? snapshot.weights),\n );\n break;\n }\n case \"outDegree\": {\n const data = dataMember(members, name, Uint32Array, nodeCount);\n if (verify) {\n checkOutDegree(snapshot, data);\n }\n seedView(snapshot, name, data);\n break;\n }\n case \"degree\": {\n const data = dataMember(members, name, Uint32Array, nodeCount);\n if (verify) {\n checkDegree(snapshot, factsOf(), data);\n }\n seedView(snapshot, name, data);\n break;\n }\n case \"selfLoopsPerNode\": {\n const data = dataMember(members, name, Uint32Array, nodeCount);\n if (verify) {\n checkSelfLoopsPerNode(factsOf(), data);\n }\n seedView(snapshot, name, data);\n break;\n }\n case \"inDegree\":\n if (directed) {\n const data = dataMember(members, name, Uint32Array, nodeCount);\n if (verify) {\n checkInDegree(factsOf(), data);\n }\n seedView(snapshot, name, data);\n }\n break;\n case \"weightedOutDegree\":\n case \"weightedDegree\":\n case \"selfLoopWeight\":\n seedF64(name);\n break;\n case \"weightedInDegree\":\n if (directed) {\n seedF64(name);\n }\n break;\n case \"selfLoopArcs\": {\n const data = dataMember(members, name, Uint32Array, selfLoopCount);\n if (verify) {\n checkSelfLoopArcs(snapshot, factsOf(), data);\n }\n seedView(snapshot, name, data);\n break;\n }\n case \"mate\":\n if (!directed) {\n const data = dataMember(members, name, Uint32Array, arcCount);\n if (verify) {\n checkMate(snapshot, factsOf(), data);\n }\n seedView(snapshot, name, data);\n }\n break;\n case \"degreeOrder\":\n case \"reverseDegreeOrder\": {\n if (name === \"reverseDegreeOrder\" && !directed) {\n break;\n }\n const perm = viewMember(members, name, \"perm\", Uint32Array, nodeCount, true) as U32;\n const segmentOffsets = viewMember(members, name, \"segmentOffsets\", Uint32Array, 5, true) as U32;\n if (verify) {\n const degree = name === \"degreeOrder\" ? rowLengths(snapshot.rowPtr, nodeCount) : factsOf().inDegree;\n checkDegreeOrder(name, degree, perm, segmentOffsets);\n }\n seedView(snapshot, name, Object.freeze({ perm, segmentOffsets }));\n break;\n }\n default:\n // An unknown view name (a newer minor) or a scalar view: ignored and recomputed.\n break;\n }\n }\n}\n\n// ============================================================ core, arena, meta\n\ninterface CoreRefs {\n readonly rowPtr: WireBufferRef;\n readonly colIdx: WireBufferRef | null;\n readonly weights: WireBufferRef | null;\n readonly arcToEdge: WireBufferRef | null;\n readonly edgeToArc: WireBufferRef | null;\n}\n\n/** The counts a manifest declares. */\ninterface WireCounts {\n readonly nodes: number;\n readonly edges: number;\n readonly arcs: number;\n readonly selfLoops: number;\n}\n\ninterface CoreArrays {\n readonly rowPtr: U32;\n readonly colIdx: U32;\n readonly weights: F32 | null;\n readonly arcToEdge: U32 | null;\n readonly edgeToArc: U32 | null;\n}\n\n/**\n * Read the core references from the manifest, applying the null rules of design section 9.1.\n * @param value - manifest.core\n * @returns the references\n */\nfunction readCoreRefs(value: unknown): CoreRefs {\n const core = asObject(value, \"core\");\n const optionalRef = (name: string): WireBufferRef | null => {\n const v = core[name];\n return v === null || v === undefined ? null : readRef(v, `core.${name}`);\n };\n return {\n rowPtr: readRef(core.rowPtr, \"core.rowPtr\"),\n colIdx: optionalRef(\"colIdx\"),\n weights: optionalRef(\"weights\"),\n arcToEdge: optionalRef(\"arcToEdge\"),\n edgeToArc: optionalRef(\"edgeToArc\"),\n };\n}\n\n/**\n * Build the core arrays: a null colIdx is a zero-arc graph, a null weights array an unweighted (or\n * zero-arc weighted) graph, a null permutation the identity (when the flag says so) or zero length.\n * @param decoder - the decoder\n * @param refs - the core references\n * @param counts - the manifest counts\n * @param flags - the manifest flags\n * @returns the arrays\n */\nfunction decodeCore(decoder: WireDecoder, refs: CoreRefs, counts: WireCounts, flags: SnapshotFlags): CoreArrays {\n const rowPtr = decoder.u32(refs.rowPtr, \"core.rowPtr\", \"core\");\n let colIdx: U32;\n if (refs.colIdx === null) {\n if (counts.arcs !== 0) {\n throw badWire(\"core.colIdx\", `null although counts.arcs is ${counts.arcs}`);\n }\n colIdx = new Uint32Array(0);\n } else {\n colIdx = decoder.u32(refs.colIdx, \"core.colIdx\", \"core\");\n }\n let weights: F32 | null = null;\n if (refs.weights !== null) {\n if (!flags.weighted) {\n throw badWire(\"core.weights\", \"present although flags.weighted is false\");\n }\n weights = decoder.array(refs.weights, \"core.weights\", \"f32\", \"core\") as F32;\n } else if (flags.weighted) {\n if (counts.arcs !== 0) {\n throw badWire(\"core.weights\", `null although flags.weighted is true and counts.arcs is ${counts.arcs}`);\n }\n weights = new Float32Array(0);\n }\n const identity = flags.arcToEdgeIsIdentity;\n const permutation = (ref: WireBufferRef | null, name: \"arcToEdge\" | \"edgeToArc\", count: number): U32 | null => {\n if (ref !== null) {\n if (identity) {\n throw badWire(`core.${name}`, \"present although flags.arcToEdgeIsIdentity is true\");\n }\n return decoder.u32(ref, `core.${name}`, \"core\");\n }\n if (identity) {\n return null;\n }\n if (count !== 0) {\n throw badWire(\n `core.${name}`,\n `null although the permutation is not the identity and the count is ${count}`,\n );\n }\n return new Uint32Array(0);\n };\n return {\n rowPtr,\n colIdx,\n weights,\n arcToEdge: permutation(refs.arcToEdge, \"arcToEdge\", counts.arcs),\n edgeToArc: permutation(refs.edgeToArc, \"edgeToArc\", counts.edges),\n };\n}\n\n/**\n * Honour the manifest's arena descriptor (design sections 9.1 and 10.3): the core arrays lying at\n * 256-aligned offsets inside the described range become its segments; hotByteLength is recomputed\n * and, at the structure level, compared with the manifest.\n * @param value - manifest.arena\n * @param regions - the buffer regions\n * @param refs - the core references\n * @param arrays - the core arrays\n * @param structure - whether the structure checks run\n * @returns the arena layout, or null when the manifest carries none or the region is chunked\n */\nfunction decodeArena(\n value: unknown,\n regions: readonly WireRegion[],\n refs: CoreRefs,\n arrays: CoreArrays,\n structure: boolean,\n): ArenaLayout | null {\n if (value === null || value === undefined) {\n return null;\n }\n const a = asObject(value, \"arena\");\n const buffer = asCount(a.buffer, \"arena.buffer\");\n const byteOffset = asCount(a.byteOffset, \"arena.byteOffset\");\n const byteLength = asCount(a.byteLength, \"arena.byteLength\");\n const region = regions[buffer] as WireRegion | undefined;\n if (region === undefined) {\n throw badWire(\"arena.buffer\", `buffer index ${buffer} is out of range`, { found: buffer });\n }\n if (byteOffset + byteLength > region.byteLength) {\n throw badWire(\"arena\", `range [${byteOffset}, ${byteOffset + byteLength}) exceeds the buffer`, {\n byteOffset,\n byteLength,\n bufferByteLength: region.byteLength,\n });\n }\n const located = region.locate(byteOffset, byteLength);\n if (located === null) {\n return null;\n }\n const segments: Record<CoreArrayName, ArenaSegment | null> = {\n rowPtr: null,\n colIdx: null,\n weights: null,\n arcToEdge: null,\n edgeToArc: null,\n };\n let hotByteLength = 0;\n const names: readonly CoreArrayName[] = CORE_ORDER;\n for (const name of names) {\n const ref = refs[name];\n const array = arrays[name];\n if (ref === null || array === null || array.length === 0) {\n continue;\n }\n const inside =\n ref.buffer === buffer &&\n ref.byteOffset >= byteOffset &&\n ref.byteOffset + ref.byteLength <= byteOffset + byteLength;\n if (!inside) {\n continue;\n }\n const relative = ref.byteOffset - byteOffset;\n if (relative % ALIGNMENT !== 0) {\n throw badWire(`core.${name}`, `inside the arena at offset ${relative}, not a multiple of ${ALIGNMENT}`, {\n byteOffset: relative,\n });\n }\n if (array.buffer !== located.buffer || array.byteOffset !== located.byteOffset + relative) {\n throw badWire(`core.${name}`, \"the arena describes a segment the array is not a view of\");\n }\n segments[name] = Object.freeze({ byteOffset: located.byteOffset + relative, byteLength: ref.byteLength });\n if (name === \"rowPtr\" || name === \"colIdx\" || name === \"weights\") {\n hotByteLength = relative + ref.byteLength;\n }\n }\n if (structure && a.hotByteLength !== hotByteLength) {\n throw badWire(\n \"arena.hotByteLength\",\n `manifest says ${String(a.hotByteLength)}, the segments say ${hotByteLength}`,\n {\n expected: hotByteLength,\n found: a.hotByteLength,\n },\n );\n }\n return Object.freeze({\n buffer: located.buffer,\n byteOffset: located.byteOffset,\n byteLength,\n alignment: ALIGNMENT,\n segments: Object.freeze(segments),\n hotByteLength,\n });\n}\n\n/**\n * Read the flags (every member a boolean).\n * @param value - manifest.flags\n * @returns the flags\n */\nfunction readFlags(value: unknown): SnapshotFlags {\n const o = asObject(value, \"flags\");\n const flag = (name: keyof SnapshotFlags): boolean => asBoolean(o[name], `flags.${name}`);\n return {\n multigraph: flag(\"multigraph\"),\n hasSelfLoops: flag(\"hasSelfLoops\"),\n arcToEdgeIsIdentity: flag(\"arcToEdgeIsIdentity\"),\n weighted: flag(\"weighted\"),\n allWeightsOne: flag(\"allWeightsOne\"),\n nonNegativeWeights: flag(\"nonNegativeWeights\"),\n finiteWeights: flag(\"finiteWeights\"),\n };\n}\n\n/**\n * Read a column origin (every field a string or null).\n * @param value - the manifest member\n * @param path - its path\n * @returns the origin, or null\n */\nfunction readOrigin(value: unknown, path: string): ColumnOrigin | null {\n if (value === null || value === undefined) {\n return null;\n }\n const o = asObject(value, path);\n const field = (key: keyof ColumnOrigin): string | null => asStringOrNull(o[key], `${path}.${key}`);\n return {\n format: field(\"format\"),\n id: field(\"id\"),\n title: field(\"title\"),\n type: field(\"type\"),\n namespace: field(\"namespace\"),\n };\n}\n\n/**\n * Read the graph metadata (design section 5.9); unknown fields are ignored, missing ones are null.\n * @param value - manifest.meta\n * @returns the frozen metadata\n */\nfunction readGraphMeta(value: unknown): GraphMeta {\n const o = asObject(value, \"meta\");\n const keywordsRaw = o.keywords ?? [];\n const keywords = asArray(keywordsRaw, \"meta.keywords\").map((k, i) => asString(k, `meta.keywords[${i}]`));\n const extraRaw = decodeJsonValue(o.extra ?? {}, \"meta.extra\");\n if (!isPlainObject(extraRaw)) {\n throw badWire(\"meta.extra\", \"expected an object\");\n }\n return Object.freeze({\n name: asStringOrNull(o.name, \"meta.name\"),\n description: asStringOrNull(o.description, \"meta.description\"),\n creator: asStringOrNull(o.creator, \"meta.creator\"),\n created: asStringOrNull(o.created, \"meta.created\"),\n modified: asStringOrNull(o.modified, \"meta.modified\"),\n keywords: Object.freeze(keywords),\n sourceFormat: asStringOrNull(o.sourceFormat, \"meta.sourceFormat\"),\n sourceVersion: asStringOrNull(o.sourceVersion, \"meta.sourceVersion\"),\n idType: asEnum(o.idType, \"meta.idType\", ID_TYPES),\n timeFormat: asEnum(o.timeFormat, \"meta.timeFormat\", TIME_FORMATS),\n timeRepresentation: asEnum(o.timeRepresentation, \"meta.timeRepresentation\", TIME_REPRESENTATIONS),\n mode: asEnum(o.mode, \"meta.mode\", MODES),\n declaredMultigraph: asBooleanOrNull(o.declaredMultigraph, \"meta.declaredMultigraph\"),\n weightOrigin: readOrigin(o.weightOrigin, \"meta.weightOrigin\"),\n extra: Object.freeze(extraRaw),\n });\n}\n\n/**\n * Check the manifest's discriminator and versions (design sections 9.1 and 13.5): `format`, the\n * wire major (E_UNSUPPORTED_VERSION kind \"wire\") and `formatVersion` (kind \"format\"). A newer wire\n * minor is accepted.\n * @param manifest - the manifest object\n * @returns the wire version pair\n */\nexport function checkManifestVersions(manifest: Record<string, unknown>): readonly [number, number] {\n if (manifest.format !== WIRE_FORMAT) {\n throw badWire(\"format\", `expected \"${WIRE_FORMAT}\", found ${describe(manifest.format)}`, {\n found: manifest.format,\n });\n }\n const wire = asArray(manifest.wire, \"wire\");\n const major = wire[0];\n const minor = wire[1];\n if (\n typeof major !== \"number\" ||\n typeof minor !== \"number\" ||\n !Number.isInteger(major) ||\n !Number.isInteger(minor)\n ) {\n throw badWire(\"wire\", \"expected [major, minor] integers\", { found: manifest.wire });\n }\n if (major !== WIRE_MAJOR) {\n throw new GraphFormatError(\n \"E_UNSUPPORTED_VERSION\",\n `wire major ${major} is not supported (reader: ${WIRE_MAJOR})`,\n {\n kind: \"wire\",\n found: major,\n supported: WIRE_MAJOR,\n },\n );\n }\n if (manifest.formatVersion !== FORMAT_VERSION) {\n throw new GraphFormatError(\n \"E_UNSUPPORTED_VERSION\",\n `formatVersion ${describe(manifest.formatVersion)} is not supported (reader: ${FORMAT_VERSION})`,\n { kind: \"format\", found: manifest.formatVersion, supported: FORMAT_VERSION },\n );\n }\n return [major, minor];\n}\n\n// ============================================================ the manifest reader\n\n/**\n * Rebuild a snapshot from a manifest and the regions its references index (design sections 9.1 and\n * 9.5): versions checked, core arrays and arena adopted, id map and tables decoded, then the\n * snapshot validated at the requested level.\n * @param manifestRaw - the manifest (an object; already parsed for a container)\n * @param regions - one region per buffer index\n * @param options - the resolved options\n * @param honourArena - whether the manifest's arena descriptor is adopted (false for chunked input)\n * @returns the snapshot\n */\nexport function decodeManifest(\n manifestRaw: unknown,\n regions: readonly WireRegion[],\n options: ResolvedFromWireOptions,\n honourArena: boolean,\n): GraphSnapshot {\n const manifest = asObject(manifestRaw, \"manifest\");\n checkManifestVersions(manifest);\n const decoder = new WireDecoder(regions, options);\n const directed = asBoolean(manifest.directed, \"directed\");\n const countsRaw = asObject(manifest.counts, \"counts\");\n const counts: WireCounts = {\n nodes: asCount(countsRaw.nodes, \"counts.nodes\"),\n edges: asCount(countsRaw.edges, \"counts.edges\"),\n arcs: asCount(countsRaw.arcs, \"counts.arcs\"),\n selfLoops: asCount(countsRaw.selfLoops, \"counts.selfLoops\"),\n };\n const flags = readFlags(manifest.flags);\n if (flags.arcToEdgeIsIdentity && (!directed || counts.arcs !== counts.edges)) {\n throw badWire(\"flags.arcToEdgeIsIdentity\", \"set on an undirected graph or with arcs !== edges\");\n }\n const coreRefs = readCoreRefs(manifest.core);\n const core = decodeCore(decoder, coreRefs, counts, flags);\n const arena = honourArena ? decodeArena(manifest.arena, regions, coreRefs, core, decoder.structure) : null;\n const ids = decoder.ids(manifest.ids);\n const nodes = decoder.table(manifest.nodeColumns ?? [], \"node\", null, counts.nodes, \"nodeColumns\");\n const edges = decoder.table(manifest.edgeColumns ?? [], \"edge\", null, counts.edges, \"edgeColumns\");\n const graph = decoder.table(manifest.graphColumns ?? [], \"graph\", null, 1, \"graphColumns\");\n const extensions = new Map<string, AttributeTable>();\n const extensionsRaw = asArray(manifest.extensions ?? [], \"extensions\");\n for (let i = 0; i < extensionsRaw.length; i++) {\n const path = `extensions[${i}]`;\n const ext = asObject(extensionsRaw[i], path);\n const name = asString(ext.name, `${path}.name`);\n if (extensions.has(name)) {\n throw badWire(`${path}.name`, `extension table \"${name}\" appears twice`, { table: name });\n }\n const rowCount = asCount(ext.rowCount, `${path}.rowCount`);\n extensions.set(name, decoder.table(ext.columns, \"extension\", name, rowCount, `${path}.columns`));\n }\n let meta = readGraphMeta(manifest.meta ?? {});\n if (decoder.skipped.length > 0) {\n const skipped = Object.freeze(decoder.skipped.map((s) => Object.freeze({ ...s })));\n meta = Object.freeze({ ...meta, extra: Object.freeze({ ...meta.extra, [SKIPPED_COLUMNS_KEY]: skipped }) });\n }\n const carried = decoder.views(manifest.views);\n if (decoder.structure) {\n decoder.checkOverlaps();\n }\n const parts: SnapshotParts = {\n label: asStringOrNull(manifest.label, \"label\"),\n serial: null,\n directed,\n nodeCount: counts.nodes,\n edgeCount: counts.edges,\n arcCount: counts.arcs,\n selfLoopCount: counts.selfLoops,\n rowPtr: core.rowPtr,\n colIdx: core.colIdx,\n weights: core.weights,\n arcToEdge: core.arcToEdge,\n edgeToArc: core.edgeToArc,\n flags,\n ids,\n nodes,\n edges,\n graph,\n extensions,\n meta,\n arena,\n checksum: false,\n };\n const snapshot = createSnapshot(parts);\n if (options.level === \"full\") {\n snapshot.validate({ level: \"full\" });\n } else if (options.level === \"structure\") {\n snapshot.validate({ level: \"structure\" });\n }\n if (options.level !== \"full\") {\n installViews(snapshot, carried, options.level === \"structure\");\n }\n return snapshot;\n}\n\n/**\n * Rebuild a snapshot from its wire form (design section 9.1). Defaults: `validate: \"structure\"`\n * (the manifest is trusted to have come from this package; the cheap checks still run) and `copy:\n * false` (the arrays are views into `wire.buffers`; a SharedArrayBuffer is copied). The reverse id\n * Map and decoded strings are rebuilt lazily; carried views (`includeViews`) are installed on the\n * receiver below \"full\" and recomputed under \"full\", where nothing carried is trusted.\n * @param wire - the wire snapshot\n * @param options - validation level, copy and unknown-column policy\n * @returns the snapshot; E_UNSUPPORTED_VERSION, E_UNSUPPORTED, E_BAD_SERIALIZATION or E_INVALID_SNAPSHOT on bad input\n */\nexport function fromWire(wire: WireSnapshot, options?: FromWireOptions): GraphSnapshot {\n const resolved = resolveFromWireOptions(options, \"structure\");\n const w = asObject(wire, \"wire\");\n const buffersRaw = asArray(w.buffers, \"wire.buffers\");\n const regions: WireRegion[] = [];\n for (let i = 0; i < buffersRaw.length; i++) {\n const b: unknown = buffersRaw[i];\n let buffer: ArrayBuffer;\n if (b instanceof ArrayBuffer) {\n buffer = resolved.copy ? copyBuffer(b) : b;\n } else if (isSharedArrayBuffer(b)) {\n buffer = copyBuffer(b);\n } else {\n throw badWire(`wire.buffers[${i}]`, \"expected an ArrayBuffer\");\n }\n regions.push(bufferRegion(buffer, 0, buffer.byteLength));\n }\n return decodeManifest(w.manifest, regions, resolved, true);\n}\n","/**\n * The GSNP byte container (design section 9.2): `toBytes()` writes one contiguous buffer,\n * `toByteChunks()` the same bytes as a sequence (header + manifest, then every 256-padded segment\n * in manifest order), `fromBytes()` adopts a container's buffer region as the arena and\n * `fromByteChunks()` adopts each chunk's buffer per segment. The snapshot's `toBytes` /\n * `toByteChunks` methods call the functions of this module directly.\n *\n * Layout, all integers little-endian:\n *\n * ```\n * offset size field\n * 0 4 magic \"GSNP\"\n * 4 2 wire major (u16)\n * 6 2 wire minor (u16)\n * 8 4 endianness probe: 0x01020304 written through a host-order Uint32Array\n * 12 4 manifest byte length L (u32)\n * 16 L manifest: UTF-8 JSON of the WireManifest, every reference into buffer 0 with a\n * region-relative byteOffset\n * 16+L pad zero padding to the next multiple of 256\n * B ... buffer region: each array at a 256-aligned offset in manifest order, core arrays\n * first so the region's prefix is the arena; every segment padded to 256 bytes\n * ```\n *\n * The reader refuses a bad magic, an unexpected probe, a truncated header or manifest, a manifest\n * whose versions disagree with the header (E_BAD_SERIALIZATION), an unknown wire major\n * (E_UNSUPPORTED_VERSION) and everything the manifest reader of from-wire.ts refuses.\n */\n\nimport { ALIGNMENT, CONTAINER_MAGIC, ENDIAN_PROBE, IS_LITTLE_ENDIAN, WIRE_MAJOR, WIRE_MINOR } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type GraphSnapshot } from \"../snapshot/graph-snapshot.js\";\nimport { type FromWireOptions, type ToBytesOptions, type TypedArrayData, type U8 } from \"../types/index.js\";\nimport { alignUp, padTo4 } from \"../util/typed-array.js\";\nimport {\n badWire,\n bufferRegion,\n checkManifestVersions,\n decodeManifest,\n isSharedArrayBuffer,\n type LocatedRange,\n parseGuardedJson,\n resolveFromWireOptions,\n type WireRegion,\n} from \"./from-wire.js\";\nimport { collectWire, type ContainerSegment, encodeManifest, WireLayout } from \"./to-wire.js\";\n\n// ============================================================ constants\n\n/** Bytes before the manifest: magic, major, minor, probe and manifest length. */\nexport const CONTAINER_HEADER_BYTES = 16;\n\nconst fatalDecoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n// ============================================================ writing\n\n/** Everything a container write needs, computed once per call. */\ninterface ContainerPlan {\n /** The manifest's UTF-8 bytes. */\n readonly manifestBytes: Uint8Array;\n /** B: the start of the buffer region (header + manifest padded to 256). */\n readonly regionStart: number;\n /** The placed arrays in region order. */\n readonly segments: readonly ContainerSegment[];\n /** The padded region length. */\n readonly regionLength: number;\n}\n\n/**\n * Lay a snapshot out for the container.\n * @param snapshot - the snapshot\n * @param options - the views to carry\n * @returns the plan\n */\nfunction planContainer(snapshot: GraphSnapshot, options: ToBytesOptions): ContainerPlan {\n const layout = new WireLayout(\"container\");\n const { manifest } = collectWire(snapshot, layout, options.includeViews, true);\n const manifestBytes = encodeManifest(manifest);\n return {\n manifestBytes,\n regionStart: alignUp(CONTAINER_HEADER_BYTES + manifestBytes.byteLength, ALIGNMENT),\n segments: layout.segments,\n regionLength: layout.regionLength,\n };\n}\n\n/**\n * Write the 16-byte header into a fresh buffer (design section 9.2).\n * @param out - a Uint8Array at offset 0 of its buffer with at least 16 bytes\n * @param manifestLength - L\n */\nfunction writeHeader(out: U8, manifestLength: number): void {\n out.set(CONTAINER_MAGIC, 0);\n const view = new DataView(out.buffer, out.byteOffset, out.byteLength);\n view.setUint16(4, WIRE_MAJOR, true);\n view.setUint16(6, WIRE_MINOR, true);\n new Uint32Array(out.buffer, out.byteOffset + 8, 1)[0] = ENDIAN_PROBE;\n view.setUint32(12, manifestLength, true);\n}\n\n/**\n * The bytes of a typed array as a Uint8Array view.\n * @param view - the array\n * @returns the byte view\n */\nfunction bytesOf(view: TypedArrayData): Uint8Array {\n return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);\n}\n\n/**\n * The GSNP container of a snapshot as one contiguous buffer (design section 9.2).\n * @param snapshot - the snapshot\n * @param options - the cached views to carry\n * @returns the container bytes at offset 0 of a fresh ArrayBuffer; E_UNSUPPORTED on a big-endian host\n */\nexport function toBytes(snapshot: GraphSnapshot, options: ToBytesOptions = {}): U8 {\n const plan = planContainer(snapshot, options);\n const out = new Uint8Array(plan.regionStart + plan.regionLength);\n writeHeader(out, plan.manifestBytes.byteLength);\n out.set(plan.manifestBytes, CONTAINER_HEADER_BYTES);\n for (const segment of plan.segments) {\n out.set(bytesOf(segment.view), plan.regionStart + segment.ref.byteOffset);\n }\n return out;\n}\n\n/**\n * Yield the chunks of a plan: the padded header + manifest, then every non-empty segment padded to\n * 256 bytes.\n * @param plan - the plan\n * @yields the chunks in order\n */\nfunction* chunksOf(plan: ContainerPlan): Generator<U8, void, undefined> {\n const head = new Uint8Array(plan.regionStart);\n writeHeader(head, plan.manifestBytes.byteLength);\n head.set(plan.manifestBytes, CONTAINER_HEADER_BYTES);\n yield head;\n for (const segment of plan.segments) {\n if (segment.ref.byteLength === 0) {\n continue;\n }\n const chunk = new Uint8Array(alignUp(segment.ref.byteLength, ALIGNMENT));\n chunk.set(bytesOf(segment.view));\n yield chunk;\n }\n}\n\n/**\n * The GSNP container as a sequence of chunks whose concatenation equals `toBytes()` (design section\n * 9.2): the header + manifest padded to 256, then each non-empty segment padded to 256, in manifest\n * order. The layout is computed when this function is called; the chunk copies are made lazily.\n * @param snapshot - the snapshot\n * @param options - the cached views to carry\n * @returns the chunks; E_UNSUPPORTED on a big-endian host\n */\nexport function toByteChunks(snapshot: GraphSnapshot, options: ToBytesOptions = {}): Iterable<U8> {\n return chunksOf(planContainer(snapshot, options));\n}\n\n// ============================================================ reading\n\n/** The fields of a container header. */\ninterface ContainerHeader {\n /** The wire major. */\n readonly major: number;\n /** The wire minor. */\n readonly minor: number;\n /** L, the manifest byte length. */\n readonly manifestLength: number;\n}\n\n/**\n * Check and read the 16-byte header (design section 9.2).\n * @param head - at least the first 16 bytes of the container\n * @param totalLength - the container's total byte length\n * @returns the header fields\n */\nfunction readHeader(head: Uint8Array, totalLength: number): ContainerHeader {\n if (totalLength < CONTAINER_HEADER_BYTES) {\n throw badWire(\"header\", `truncated: ${totalLength} bytes, expected at least ${CONTAINER_HEADER_BYTES}`, {\n byteLength: totalLength,\n });\n }\n for (let i = 0; i < CONTAINER_MAGIC.length; i++) {\n if (head[i] !== CONTAINER_MAGIC[i]) {\n throw badWire(\"magic\", \"not a GSNP container\", { found: Array.from(head.subarray(0, 4)) });\n }\n }\n const view = new DataView(head.buffer, head.byteOffset, head.byteLength);\n const major = view.getUint16(4, true);\n const minor = view.getUint16(6, true);\n if (major !== WIRE_MAJOR) {\n throw new GraphFormatError(\n \"E_UNSUPPORTED_VERSION\",\n `wire major ${major} is not supported (reader: ${WIRE_MAJOR})`,\n {\n kind: \"wire\",\n found: major,\n supported: WIRE_MAJOR,\n },\n );\n }\n const probe = view.getUint32(8, IS_LITTLE_ENDIAN);\n if (probe !== ENDIAN_PROBE) {\n throw badWire(\n \"endianness\",\n `probe reads 0x${probe.toString(16)}; the container was written on another endianness`,\n {\n found: probe,\n expected: ENDIAN_PROBE,\n },\n );\n }\n const manifestLength = view.getUint32(12, true);\n if (CONTAINER_HEADER_BYTES + manifestLength > totalLength) {\n throw badWire(\n \"manifest\",\n `truncated: ${manifestLength} manifest bytes declared, ${totalLength} bytes in total`,\n {\n manifestLength,\n byteLength: totalLength,\n },\n );\n }\n return { major, minor, manifestLength };\n}\n\n/**\n * Parse the manifest bytes: a fatal UTF-8 decode, the guarding JSON reviver, then the version check\n * against the header.\n * @param bytes - the manifest bytes\n * @param header - the header the manifest must agree with\n * @returns the manifest object\n */\nfunction readManifest(bytes: Uint8Array, header: ContainerHeader): Record<string, unknown> {\n let text: string;\n try {\n text = fatalDecoder.decode(bytes);\n } catch {\n throw badWire(\"manifest\", \"not valid UTF-8\");\n }\n const manifest: unknown = parseGuardedJson(text, \"manifest\");\n if (typeof manifest !== \"object\" || manifest === null || Array.isArray(manifest)) {\n throw badWire(\"manifest\", \"expected an object\");\n }\n const record = manifest as Record<string, unknown>;\n const [major, minor] = checkManifestVersions(record);\n if (major !== header.major || minor !== header.minor) {\n throw badWire(\n \"wire\",\n `manifest says [${major}, ${minor}], the header says [${header.major}, ${header.minor}]`,\n {\n found: [major, minor],\n header: [header.major, header.minor],\n },\n );\n }\n return record;\n}\n\n/**\n * Rebuild a snapshot from a GSNP container (design section 9.2). Defaults: `validate: \"full\"` and\n * `copy: false`. The buffer region is adopted as the arena when the container is a plain\n * ArrayBuffer viewed at a byteOffset that is a multiple of 8 (so f64 segments align); a\n * SharedArrayBuffer, an odd offset or `copy: true` take the copy path into a fresh 256-aligned\n * buffer.\n * @param bytes - the container: a Uint8Array, an ArrayBuffer or a SharedArrayBuffer\n * @param options - validation level, copy and unknown-column policy\n * @returns the snapshot; E_BAD_SERIALIZATION / E_UNSUPPORTED_VERSION / E_UNSUPPORTED / E_INVALID_SNAPSHOT on bad input\n */\nexport function fromBytes(bytes: Uint8Array | ArrayBufferLike, options?: FromWireOptions): GraphSnapshot {\n const resolved = resolveFromWireOptions(options, \"full\");\n const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);\n const header = readHeader(view, view.byteLength);\n const manifest = readManifest(\n view.subarray(CONTAINER_HEADER_BYTES, CONTAINER_HEADER_BYTES + header.manifestLength),\n header,\n );\n const regionStart = alignUp(CONTAINER_HEADER_BYTES + header.manifestLength, ALIGNMENT);\n const regionLength = Math.max(0, view.byteLength - regionStart);\n const { buffer } = view;\n let region: WireRegion;\n if (!resolved.copy && !isSharedArrayBuffer(buffer) && view.byteOffset % 8 === 0) {\n region = bufferRegion(buffer, view.byteOffset + regionStart, regionLength);\n } else {\n const copy = new Uint8Array(alignUp(regionLength, ALIGNMENT));\n if (regionLength > 0) {\n copy.set(view.subarray(regionStart));\n }\n region = bufferRegion(copy.buffer, 0, regionLength);\n }\n return decodeManifest(manifest, [region], resolved, true);\n}\n\n/**\n * A byte stream made of chunks, addressed by absolute offset: ranges inside one chunk are located\n * for adoption, ranges spanning chunks are copied.\n */\nclass ChunkedBytes {\n private readonly chunks: readonly Uint8Array[];\n private readonly starts: number[];\n /** The total byte length. */\n readonly byteLength: number;\n\n /**\n * Wrap the chunks.\n * @param chunks - the chunks in order\n */\n constructor(chunks: readonly Uint8Array[]) {\n this.chunks = chunks;\n this.starts = [];\n let total = 0;\n for (const chunk of chunks) {\n this.starts.push(total);\n total += chunk.byteLength;\n }\n this.byteLength = total;\n }\n\n /**\n * The chunk index holding an absolute offset (the last chunk starting at or before it).\n * @param offset - the absolute offset\n * @returns the index, or -1 when there is no chunk\n */\n private chunkAt(offset: number): number {\n let lo = 0;\n let hi = this.starts.length - 1;\n let found = -1;\n while (lo <= hi) {\n const mid = (lo + hi) >>> 1;\n if (this.starts[mid] <= offset) {\n found = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return found;\n }\n\n /**\n * Find a range inside one chunk over a plain ArrayBuffer.\n * @param offset - the absolute start\n * @param length - the byte length\n * @returns the buffer and absolute offset, or null when the range spans chunks or a SharedArrayBuffer\n */\n locate(offset: number, length: number): LocatedRange | null {\n const i = this.chunkAt(offset);\n if (i < 0) {\n return null;\n }\n const chunk = this.chunks[i];\n const start = this.starts[i];\n if (offset + length > start + chunk.byteLength || isSharedArrayBuffer(chunk.buffer)) {\n return null;\n }\n return { buffer: chunk.buffer, byteOffset: chunk.byteOffset + (offset - start) };\n }\n\n /**\n * Copy a range out of the stream.\n * @param offset - the absolute start\n * @param length - the byte length\n * @returns a fresh Uint8Array of `length` bytes at offset 0 of a padded buffer\n */\n read(offset: number, length: number): U8 {\n if (offset + length > this.byteLength) {\n throw badWire(\"chunks\", `range [${offset}, ${offset + length}) exceeds the ${this.byteLength} bytes given`);\n }\n const out = new Uint8Array(new ArrayBuffer(padTo4(length)), 0, length);\n let written = 0;\n let i = this.chunkAt(offset);\n while (written < length && i < this.chunks.length) {\n const chunk = this.chunks[i];\n const start = this.starts[i];\n const from = offset + written - start;\n const take = Math.min(length - written, chunk.byteLength - from);\n out.set(chunk.subarray(from, from + take), written);\n written += take;\n i++;\n }\n return out;\n }\n\n /**\n * A view when the range lies inside one chunk, a copy otherwise.\n * @param offset - the absolute start\n * @param length - the byte length\n * @returns the bytes\n */\n span(offset: number, length: number): Uint8Array {\n const i = this.chunkAt(offset);\n if (i >= 0) {\n const chunk = this.chunks[i];\n const start = this.starts[i];\n if (offset + length <= start + chunk.byteLength) {\n return chunk.subarray(offset - start, offset - start + length);\n }\n }\n return this.read(offset, length);\n }\n\n /**\n * The stream from `base` onward as a decoder region.\n * @param base - the absolute offset of the region's start\n * @returns the region\n */\n region(base: number): WireRegion {\n return {\n byteLength: Math.max(0, this.byteLength - base),\n locate: (byteOffset: number, byteLength: number): LocatedRange | null =>\n this.locate(base + byteOffset, byteLength),\n read: (byteOffset: number, byteLength: number): U8 => this.read(base + byteOffset, byteLength),\n };\n }\n}\n\n/**\n * Rebuild a snapshot from the chunks `toByteChunks()` produced (or any split of a container's\n * bytes): each segment is adopted as a view into the chunk that holds it (a segment spanning two\n * chunks, or one in a SharedArrayBuffer, is copied) and the snapshot has `arena === null` (design\n * section 9.2). Defaults: `validate: \"full\"`, `copy: false`.\n * @param chunks - the chunks in order\n * @param options - validation level, copy and unknown-column policy\n * @returns the snapshot\n */\nexport function fromByteChunks(chunks: Iterable<Uint8Array>, options?: FromWireOptions): GraphSnapshot {\n const resolved = resolveFromWireOptions(options, \"full\");\n const list: Uint8Array[] = [];\n for (const chunk of chunks) {\n if (!(chunk instanceof Uint8Array)) {\n throw badWire(`chunks[${list.length}]`, \"expected a Uint8Array\");\n }\n list.push(resolved.copy ? chunk.slice() : chunk);\n }\n const bytes = new ChunkedBytes(list);\n const header = readHeader(bytes.span(0, Math.min(CONTAINER_HEADER_BYTES, bytes.byteLength)), bytes.byteLength);\n const manifest = readManifest(bytes.span(CONTAINER_HEADER_BYTES, header.manifestLength), header);\n const regionStart = alignUp(CONTAINER_HEADER_BYTES + header.manifestLength, ALIGNMENT);\n return decodeManifest(manifest, [bytes.region(regionStart)], resolved, false);\n}\n","/**\n * The two stable counting-sort passes of the freeze pipeline (design section 6.3 steps 3-6, 8): arc\n * materialisation (doubled storage for undirected graphs, self-loops once, invariant I7), the\n * identity check for directed input that is already grouped by source and sorted by target (step 4),\n * pass 1 by target, pass 2 by source into rowPtr with the scatter writing colIdx / arcToEdge /\n * edgeToArc straight into the target arrays (the arena, for a \"keep\" freeze), and the flag\n * predicates of design section 3.8 computed on the way (I9). There is no comparator sort anywhere;\n * the cost is O(n + A).\n *\n * Because pass 2 is stable and consumes arcs in pass-1 order, every row ends sorted by target with\n * parallel arcs in ascending logical-edge order (I4), and the k-th `u -> v` arc in row u and the\n * k-th `v -> u` arc in row v come from the same edge (design section 6.4).\n *\n * Layout of the passes, chosen from the memory profile of the 100k-node / 1M-edge benchmark (the\n * scatters are cache-miss bound, so the rule is: as few random streams per loop as possible, and no\n * random LOAD whose value a branch depends on inside a scatter):\n *\n * - One sequential pass over the edges counts arcs per target and per source (both prefix sums come\n * out of it), counts the self-loops, and scans the weights (NaN refusal, I8; the min / max of the\n * stored f32 values, from which the three weight flags follow, I9). Every edge lands on at least\n * one arc, so predicates over the edges equal predicates over the arcs.\n * - Pass 1 scatters (source, edge) PAIRS into target order, one 8-byte write per arc into a single\n * `byTarget` transient of 2A words; for an undirected graph a bitmap over the pass-1 positions\n * marks the arc whose stored orientation is the declared one (the mirror arc of an edge is\n * emitted right after it, so arcs stay in edge order within a bucket).\n * - Pass 2 reads `byTarget` sequentially bucket by bucket and scatters ONLY colIdx and arcToEdge (and\n * edgeToArc when undirected, where the declared bit is at hand).\n * - Sequential post-passes derive edgeToArc from arcToEdge (directed), gather the arc weights\n * through arcToEdge, and test adjacent targets within each row for the multigraph flag.\n *\n * Every loop lives in its own small function: V8 optimises a hot loop by on-stack replacement of the\n * function that contains it, and a function invoked once per freeze with a dozen loops in it is\n * re-entered through stale OSR code that deoptimises at every loop exit.\n *\n * Transients of the non-identity path: 2 x U32(n + 1), U32(2A), and for an undirected graph a bitmap\n * of A bits.\n */\n\nimport { GraphFormatError } from \"../errors.js\";\nimport { type F32, type F64, type SnapshotFlags, type U32 } from \"../types/index.js\";\nimport { allocateCoreArrays, type CoreArrays } from \"./arena.js\";\n\n/** The per-logical-edge input of the sort: views over the (compacted) staging arrays. */\nexport interface SortInput {\n /** Whether the graph is directed. */\n readonly directed: boolean;\n /** The node count n; every endpoint is below it. */\n readonly nodeCount: number;\n /** The logical edge count E; only the first E entries of src / dst / weights are read. */\n readonly edgeCount: number;\n /** Declared source of every edge. */\n readonly src: U32;\n /** Declared target of every edge. */\n readonly dst: U32;\n /** Per-edge staging weights (f32 or f64), or null when unweighted. */\n readonly weights: F32 | F64 | null;\n}\n\n/** What the sort produces: the core arrays, the counts and the truthful flags. */\nexport interface SortResult {\n /** The core arrays (in the arena when requested). */\n readonly core: CoreArrays;\n /** colIdx.length. */\n readonly arcCount: number;\n /** Logical edges with source === target. */\n readonly selfLoopCount: number;\n /** The flags of design section 3.8, computed from the arrays (invariant I9). */\n readonly flags: SnapshotFlags;\n}\n\n/**\n * The number of self-loop edges among the first `edgeCount` entries.\n * @param src - sources\n * @param dst - targets\n * @param edgeCount - how many edges to inspect\n * @returns the loop count\n */\nexport function countSelfLoops(src: U32, dst: U32, edgeCount: number): number {\n let loops = 0;\n for (let e = 0; e < edgeCount; e++) {\n if (src[e] === dst[e]) {\n loops++;\n }\n }\n return loops;\n}\n\n/**\n * The identity check of design section 6.3 step 4: whether (src[e], dst[e]) is non-decreasing\n * lexicographically, so that a stable sort by (source, target) moves nothing and the CSR permutation is\n * the identity.\n * @param src - sources\n * @param dst - targets\n * @param edgeCount - how many edges to inspect\n * @returns true when the edges are already in CSR order\n */\nexport function isSortedEdgeList(src: U32, dst: U32, edgeCount: number): boolean {\n for (let e = 1; e < edgeCount; e++) {\n const u = src[e];\n const prev = src[e - 1];\n if (u < prev || (u === prev && dst[e] < dst[e - 1])) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * The E_INVALID_WEIGHT error for a NaN staging weight (invariant I8).\n * @param e - the logical edge\n * @param w - the value\n * @returns the error\n */\nfunction nanWeight(e: number, w: number): GraphFormatError {\n return new GraphFormatError(\"E_INVALID_WEIGHT\", `edge ${e} has a NaN weight`, { edge: e, weight: w });\n}\n\n// ============================================================ the sequential edge pass\n\n/**\n * The weight scan of design section 6.3 step 8 over the first `edgeCount` staging weights: NaN is\n * refused (invariant I8, the bulk-input re-check, naming the lowest such edge), and the smallest and\n * largest STORED values -- the values as the f32 arc array holds them (invariant I9: an f64 that\n * rounds to 1, to -0 or to Infinity counts as its rounded value) -- are left in `bounds[0]` and\n * `bounds[1]`. They are written from inside the loop whenever they change, so the loop's optimised\n * code has no exit path without type feedback.\n * @param edgeWeights - the staging weights\n * @param edgeCount - how many edges to inspect; at least 1\n * @param bounds - two slots initialised to +Infinity / -Infinity; receive the minimum and the maximum\n */\nfunction scanStoredWeights(edgeWeights: F32 | F64, edgeCount: number, bounds: F64): void {\n let min = Infinity;\n let max = -Infinity;\n for (let e = 0; e < edgeCount; e++) {\n const w = Math.fround(edgeWeights[e]);\n if (w !== w) {\n throw nanWeight(e, edgeWeights[e]);\n }\n if (w < min) {\n min = w;\n bounds[0] = w;\n }\n if (w > max) {\n max = w;\n bounds[1] = w;\n }\n }\n}\n\n/**\n * The counting half of the directed sort (design section 6.3 steps 5 and 6, the `cnt` arrays):\n * arcs per target into `targetCount[v + 1]` and arcs per source into `rowCount[u + 1]`, ready for the\n * exclusive prefix sums.\n * @param src - sources\n * @param dst - targets\n * @param edgeCount - the logical edge count\n * @param targetCount - n + 1 zeroed counters, by target\n * @param rowCount - n + 1 zeroed counters, by source\n * @returns the self-loop count\n */\nfunction countDirectedArcs(src: U32, dst: U32, edgeCount: number, targetCount: U32, rowCount: U32): number {\n let loops = 0;\n for (let e = 0; e < edgeCount; e++) {\n const u = src[e];\n const v = dst[e];\n targetCount[v + 1]++;\n rowCount[u + 1]++;\n if (u === v) {\n loops++;\n }\n }\n return loops;\n}\n\n/**\n * The counting half of the undirected sort (design section 6.3 steps 3, 5 and 6): every non-loop\n * edge contributes an arc in each direction, a self-loop one arc (invariant I7).\n * @param src - sources\n * @param dst - targets\n * @param edgeCount - the logical edge count\n * @param targetCount - n + 1 zeroed counters, by target\n * @param rowCount - n + 1 zeroed counters, by source\n * @returns the self-loop count\n */\nfunction countUndirectedArcs(src: U32, dst: U32, edgeCount: number, targetCount: U32, rowCount: U32): number {\n let loops = 0;\n for (let e = 0; e < edgeCount; e++) {\n const u = src[e];\n const v = dst[e];\n targetCount[v + 1]++;\n rowCount[u + 1]++;\n if (u === v) {\n loops++;\n } else {\n targetCount[u + 1]++;\n rowCount[v + 1]++;\n }\n }\n return loops;\n}\n\n/**\n * Turn per-node counts stored at index + 1 into exclusive prefix sums in place: afterwards\n * `counts[v]` is the start of v's bucket and `counts[nodeCount]` the total.\n * @param counts - n + 1 counters with `counts[0] === 0`\n * @param nodeCount - n\n */\nfunction prefixSum(counts: U32, nodeCount: number): void {\n for (let v = 0; v < nodeCount; v++) {\n counts[v + 1] += counts[v];\n }\n}\n\n// ============================================================ the identity path\n\n/**\n * The identity path of design section 6.3 step 4 (directed input already in CSR order): colIdx is a\n * copy of dst, and the multigraph flag is one comparison of adjacent edges.\n * @param src - sources, grouped\n * @param dst - targets, sorted within each group\n * @param edgeCount - the logical edge count\n * @param colIdx - receives dst\n * @returns true when two adjacent edges connect the same pair\n */\nfunction copySortedTargets(src: U32, dst: U32, edgeCount: number, colIdx: U32): boolean {\n let multigraph = false;\n for (let e = 0; e < edgeCount; e++) {\n const v = dst[e];\n colIdx[e] = v;\n if (e > 0 && src[e] === src[e - 1] && dst[e - 1] === v) {\n multigraph = true;\n }\n }\n return multigraph;\n}\n\n// ============================================================ pass 1: by target\n\n/**\n * Pass 1 of a directed sort (design section 6.3 step 5): scatter every edge into target order as a\n * (source, edge) pair, `byTarget[2p] = src[e]`, `byTarget[2p + 1] = e`.\n * @param src - sources\n * @param dst - targets\n * @param edgeCount - the logical edge count\n * @param cursor - the target bucket starts; advanced in place\n * @param byTarget - 2A words receiving the pairs\n */\nfunction scatterDirectedByTarget(src: U32, dst: U32, edgeCount: number, cursor: U32, byTarget: U32): void {\n for (let e = 0; e < edgeCount; e++) {\n const p = 2 * cursor[dst[e]]++;\n byTarget[p] = src[e];\n byTarget[p + 1] = e;\n }\n}\n\n/**\n * Pass 1 of an undirected sort (design section 6.3 steps 3 and 5, fused): the declared arc\n * `(src, dst, e)` goes into bucket dst and, for a non-loop, the mirror `(dst, src, e)` into bucket\n * src right after it, so arcs stay in edge order within every bucket. The pass-1 position of every\n * declared arc is marked in `declared` (bit p).\n * @param src - sources\n * @param dst - targets\n * @param edgeCount - the logical edge count\n * @param cursor - the target bucket starts; advanced in place\n * @param byTarget - 2A words receiving the (source, edge) pairs\n * @param declared - a zeroed bitmap of A bits\n */\nfunction scatterUndirectedByTarget(\n src: U32,\n dst: U32,\n edgeCount: number,\n cursor: U32,\n byTarget: U32,\n declared: U32,\n): void {\n for (let e = 0; e < edgeCount; e++) {\n const u = src[e];\n const v = dst[e];\n const p = cursor[v]++;\n byTarget[2 * p] = u;\n byTarget[2 * p + 1] = e;\n declared[p >>> 5] |= 1 << (p & 31);\n if (u !== v) {\n const q = 2 * cursor[u]++;\n byTarget[q] = v;\n byTarget[q + 1] = e;\n }\n }\n}\n\n// ============================================================ pass 2: by source\n\n/**\n * Pass 2 of a directed sort (design section 6.3 step 6): walk the target buckets in order and\n * scatter every arc into its row, writing colIdx and arcToEdge. Stable, so rows end sorted by target\n * with parallels in edge order (I4).\n * @param nodeCount - n\n * @param targetStart - the target bucket starts (pass-1 layout)\n * @param byTarget - the pass-1 (source, edge) pairs\n * @param cursor - the row starts (a copy of rowPtr); advanced in place\n * @param colIdx - receives the targets\n * @param arcToEdge - receives the edges\n */\nfunction scatterDirectedBySource(\n nodeCount: number,\n targetStart: U32,\n byTarget: U32,\n cursor: U32,\n colIdx: U32,\n arcToEdge: U32,\n): void {\n for (let v = 0; v < nodeCount; v++) {\n const end = 2 * targetStart[v + 1];\n for (let p = 2 * targetStart[v]; p < end; p += 2) {\n const a = cursor[byTarget[p]]++;\n colIdx[a] = v;\n arcToEdge[a] = byTarget[p + 1];\n }\n }\n}\n\n/**\n * Pass 2 of an undirected sort (design section 6.3 step 6): as the directed pass, plus\n * `edgeToArc[e] = a` for the arc whose stored orientation is the declared one (for a self-loop the\n * single arc), which the pass-1 bitmap identifies.\n * @param nodeCount - n\n * @param targetStart - the target bucket starts (pass-1 layout)\n * @param byTarget - the pass-1 (source, edge) pairs\n * @param declared - bit p set when pass-1 position p holds a declared arc\n * @param cursor - the row starts (a copy of rowPtr); advanced in place\n * @param colIdx - receives the targets\n * @param arcToEdge - receives the edges\n * @param edgeToArc - receives the declared arc of every edge\n */\nfunction scatterUndirectedBySource(\n nodeCount: number,\n targetStart: U32,\n byTarget: U32,\n declared: U32,\n cursor: U32,\n colIdx: U32,\n arcToEdge: U32,\n edgeToArc: U32,\n): void {\n for (let v = 0; v < nodeCount; v++) {\n const end = targetStart[v + 1];\n for (let p = targetStart[v]; p < end; p++) {\n const e = byTarget[2 * p + 1];\n const a = cursor[byTarget[2 * p]]++;\n colIdx[a] = v;\n arcToEdge[a] = e;\n if (((declared[p >>> 5] >>> (p & 31)) & 1) === 1) {\n edgeToArc[e] = a;\n }\n }\n }\n}\n\n// ============================================================ sequential post-passes\n\n/**\n * The inverse of a directed permutation: `edgeToArc[arcToEdge[a]] = a` (every arc is its edge's only\n * arc).\n * @param arcToEdge - the arc permutation\n * @param edgeToArc - receives the inverse\n */\nfunction invertPermutation(arcToEdge: U32, edgeToArc: U32): void {\n const arcCount = arcToEdge.length;\n for (let a = 0; a < arcCount; a++) {\n edgeToArc[arcToEdge[a]] = a;\n }\n}\n\n/**\n * The arc weights (design section 3.7): `weights[a] = f32(edgeWeights[arcToEdge[a]])`, a sequential\n * write with one independent random read per arc.\n * @param arcToEdge - the arc permutation\n * @param edgeWeights - the staging weights\n * @param weights - receives the f32 arc weights\n */\nfunction gatherWeights(arcToEdge: U32, edgeWeights: F32 | F64, weights: F32): void {\n const arcCount = arcToEdge.length;\n for (let a = 0; a < arcCount; a++) {\n weights[a] = edgeWeights[arcToEdge[a]];\n }\n}\n\n/**\n * The multigraph flag (design section 3.8): whether some row holds two adjacent arcs with the same\n * target; rows are sorted by target, so parallels are adjacent (I4).\n * @param rowPtr - the row starts\n * @param colIdx - the sorted targets\n * @param nodeCount - n\n * @returns true when a parallel pair exists\n */\nfunction hasAdjacentParallels(rowPtr: U32, colIdx: U32, nodeCount: number): boolean {\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u] + 1; a < end; a++) {\n if (colIdx[a] === colIdx[a - 1]) {\n return true;\n }\n }\n }\n return false;\n}\n\n// ============================================================ the sort\n\n/**\n * Sort a per-edge list into a CSR core (design section 6.3 steps 3-6 and 8). Directed input that is\n * already in CSR order takes the identity path (one count + scan + copy, no permutation arrays,\n * `flags.arcToEdgeIsIdentity`); everything else takes the two counting-sort passes. Undirected input\n * emits the mirror arc of every non-loop edge (I7). Weights are stored as f32 (design section 3.7) and\n * the flags are computed from the stored values (I9). A NaN weight is E_INVALID_WEIGHT (I8) naming\n * the lowest such edge, thrown before anything is allocated.\n * @param input - the per-edge arrays\n * @param useArena - allocate the core inside one 256-aligned arena (true) or as separate buffers\n * @returns the core, the counts and the flags\n */\nexport function sortIntoCore(input: SortInput, useArena: boolean): SortResult {\n const { directed, nodeCount, edgeCount, src, dst } = input;\n const edgeWeights = input.weights;\n\n // step 8's weight predicates, over the edges: every edge lands on at least one arc, so the\n // per-value predicates over the stored arc weights equal those over the f32-rounded edge weights\n let allOne = true;\n let nonNegative = true;\n let finite = true;\n if (edgeWeights !== null && edgeCount > 0) {\n const bounds = new Float64Array([Infinity, -Infinity]);\n scanStoredWeights(edgeWeights, edgeCount, bounds);\n const min = bounds[0];\n const max = bounds[1];\n allOne = min === 1 && max === 1;\n nonNegative = min >= 0;\n finite = min > -Infinity && max < Infinity;\n }\n\n // steps 3-6 counts: one sequential pass over the edges yields both prefix sums and the loop count\n const targetStart = new Uint32Array(nodeCount + 1);\n const rowCount = new Uint32Array(nodeCount + 1);\n const selfLoopCount = directed\n ? countDirectedArcs(src, dst, edgeCount, targetStart, rowCount)\n : countUndirectedArcs(src, dst, edgeCount, targetStart, rowCount);\n const arcCount = directed ? edgeCount : 2 * edgeCount - selfLoopCount;\n const identity = directed && isSortedEdgeList(src, dst, edgeCount);\n const core = allocateCoreArrays(\n { nodeCount, arcCount, edgeCount, weighted: edgeWeights !== null, identity },\n useArena,\n );\n const { rowPtr, colIdx, weights, arcToEdge, edgeToArc } = core;\n prefixSum(rowCount, nodeCount);\n rowPtr.set(rowCount);\n let multigraph: boolean;\n\n if (identity) {\n // step 4: the edge arrays are the arc arrays -- copy, and round the weights to f32\n multigraph = copySortedTargets(src, dst, edgeCount, colIdx);\n if (weights !== null && edgeWeights !== null) {\n weights.set(edgeWeights.subarray(0, edgeCount));\n }\n } else if (arcToEdge !== null && edgeToArc !== null) {\n // step 5: pass 1 by target; `rowCount` is reused as the pass-1 cursor\n prefixSum(targetStart, nodeCount);\n const cursor = rowCount;\n cursor.set(targetStart);\n const byTarget = new Uint32Array(2 * arcCount);\n let declared: U32 | null = null;\n if (directed) {\n scatterDirectedByTarget(src, dst, edgeCount, cursor, byTarget);\n } else {\n declared = new Uint32Array((arcCount + 31) >>> 5);\n scatterUndirectedByTarget(src, dst, edgeCount, cursor, byTarget, declared);\n }\n // step 6: pass 2 by source into the rows; the cursor now walks rowPtr\n cursor.set(rowPtr);\n if (declared === null) {\n scatterDirectedBySource(nodeCount, targetStart, byTarget, cursor, colIdx, arcToEdge);\n invertPermutation(arcToEdge, edgeToArc);\n } else {\n scatterUndirectedBySource(nodeCount, targetStart, byTarget, declared, cursor, colIdx, arcToEdge, edgeToArc);\n }\n if (weights !== null && edgeWeights !== null) {\n gatherWeights(arcToEdge, edgeWeights, weights);\n }\n multigraph = hasAdjacentParallels(rowPtr, colIdx, nodeCount);\n } else {\n // allocateCoreArrays materialises both permutations whenever the sort is not the identity\n throw new GraphFormatError(\"E_UNSUPPORTED\", \"unreachable: a non-identity core without permutation arrays\", {\n directed,\n arcCount,\n });\n }\n\n const flags: SnapshotFlags = Object.freeze({\n multigraph,\n hasSelfLoops: selfLoopCount > 0,\n arcToEdgeIsIdentity: identity,\n weighted: weights !== null,\n allWeightsOne: allOne,\n nonNegativeWeights: nonNegative,\n finiteWeights: finite,\n });\n return { core, arcCount, selfLoopCount, flags };\n}\n","/**\n * Remap and gather helpers for raw typed arrays, columns and whole tables (design section 5.11):\n * the propagation of attribute data through compaction (freeze step 10), derived graphs (section\n * 7.3) and consumer re-attachment after a builder mutation. One name per shape:\n *\n * - `remapArray(data, remap, newLength, fill, components)` and `remapColumn(column, remap,\n * newLength)` take an OLD -> NEW map (`INVALID_INDEX` drops the row);\n * - `gatherArray(data, indexMap, components)` and `gatherColumn(column, indexMap)` take a NEW ->\n * OLD map (`out[i] = source[indexMap[i]]`);\n * - `scatterArray(out, values, indexMap, components)` writes results computed on a derived graph\n * back into the parent's index space (`out[indexMap[i]] = values[i]`).\n *\n * Index-valued columns (`meta.refersTo`, a u32 column or a list of u32) have their VALUES rewritten\n * through the remap of the space they reference: an in-range value maps to its new index, a\n * dangling reference becomes `INVALID_INDEX` with the row unset (invariant I12; for a list, the\n * dangling items are dropped and a row whose every item dangled becomes unset and empty).\n */\n\nimport { INVALID_INDEX } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type Column, type ColumnMeta, type F32, type TypedArrayData, type U32 } from \"../types/index.js\";\nimport { type MutableColumnParts } from \"../types/internal.js\";\nimport { bitmapClear, bitmapGet, bitmapSet, bitmapWordCount, makeBitmap } from \"./bitmap.js\";\nimport { allocU8, columnOfValues, createColumn, partsOf } from \"./column.js\";\nimport { AttributeTable } from \"./table.js\";\n\n// ============================================================ raw arrays\n\n/**\n * A zeroed array of the same class as `like` (a padded store for u8).\n * @param like - the array whose class to match\n * @param length - the element count\n * @returns the new array\n */\nfunction allocLike<T extends TypedArrayData>(like: T, length: number): T {\n if (like instanceof Uint8Array) {\n return allocU8(length) as T;\n }\n if (like instanceof Uint32Array) {\n return new Uint32Array(length) as T;\n }\n if (like instanceof Int32Array) {\n return new Int32Array(length) as T;\n }\n if (like instanceof Float32Array) {\n return new Float32Array(length) as T;\n }\n return new Float64Array(length) as T;\n}\n\nfunction checkComponents(components: number, data: ArrayLike<unknown>): void {\n if (!(Number.isInteger(components) && components >= 1)) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `components must be a positive integer, found ${components}`, {\n field: \"components\",\n found: components,\n });\n }\n if (data.length % components !== 0) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `array length ${data.length} is not a multiple of ${components}`,\n {\n expected: components,\n found: data.length,\n },\n );\n }\n}\n\n/**\n * Move rows of an index-aligned array from an old index space to a new one through an OLD -> NEW\n * remap (`FreezeReport.nodeRemap` / `edgeRemap`, `DerivedGraph.nodeRemap` / `edgeRemap`): row `i`\n * lands at `remap[i]`, rows mapped to `INVALID_INDEX` are dropped, and rows of the new space no old\n * row maps to hold `fill`.\n * @param data - the old array, `oldRows * components` long\n * @param remap - old index -> new index or INVALID_INDEX; rows beyond `remap.length` are dropped\n * @param newLength - the row count of the new space\n * @param fill - the value of rows no old row maps to\n * @param components - values per row (default 1)\n * @returns a new array of `newLength * components` values\n */\nexport function remapArray<T extends TypedArrayData>(\n data: T,\n remap: U32,\n newLength: number,\n fill: number,\n components = 1,\n): T {\n checkComponents(components, data);\n const out = allocLike(data, newLength * components);\n if (fill !== 0) {\n out.fill(fill);\n }\n const rows = Math.min(remap.length, data.length / components);\n for (let i = 0; i < rows; i++) {\n const target = remap[i];\n if (target === INVALID_INDEX) {\n continue;\n }\n if (target >= newLength) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `remap[${i}] = ${target} is outside the new space of ${newLength} rows`,\n {\n index: i,\n found: target,\n length: newLength,\n },\n );\n }\n if (components === 1) {\n out[target] = data[i];\n } else {\n for (let k = 0; k < components; k++) {\n out[target * components + k] = data[i * components + k];\n }\n }\n }\n return out;\n}\n\n/**\n * Gather rows through a NEW -> OLD index map: `out[i] = data[indexMap[i]]` (`DerivedGraph.nodeOrigin`\n * / `edgeOrigin`).\n * @param data - the source array, `oldRows * components` long\n * @param indexMap - new index -> old index, every entry in range\n * @param components - values per row (default 1)\n * @returns a new array of `indexMap.length * components` values\n */\nexport function gatherArray<T extends TypedArrayData>(data: T, indexMap: U32, components = 1): T {\n checkComponents(components, data);\n const out = allocLike(data, indexMap.length * components);\n const rows = data.length / components;\n for (let i = 0; i < indexMap.length; i++) {\n const source = indexMap[i];\n if (source >= rows) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `indexMap[${i}] = ${source} is outside the source of ${rows} rows`,\n {\n index: i,\n found: source,\n length: rows,\n },\n );\n }\n if (components === 1) {\n out[i] = data[source];\n } else {\n for (let k = 0; k < components; k++) {\n out[i * components + k] = data[source * components + k];\n }\n }\n }\n return out;\n}\n\n/**\n * Scatter values computed on a derived graph back into the parent's index space: `out[indexMap[i]]\n * = values[i]` (through `nodeOrigin` / `edgeOrigin`). Rows of `out` no value maps to are untouched.\n * @param out - the destination in the parent's index space\n * @param values - the values in the derived index space, `indexMap.length * components` long\n * @param indexMap - derived index -> parent index, every entry in range\n * @param components - values per row (default 1)\n * @returns `out`\n */\nexport function scatterArray<T extends TypedArrayData>(out: T, values: T, indexMap: U32, components = 1): T {\n checkComponents(components, values);\n if (values.length !== indexMap.length * components) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `values has ${values.length} entries, expected ${indexMap.length * components}`,\n {\n expected: indexMap.length * components,\n found: values.length,\n },\n );\n }\n const rows = out.length / components;\n for (let i = 0; i < indexMap.length; i++) {\n const target = indexMap[i];\n if (target >= rows) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `indexMap[${i}] = ${target} is outside the destination of ${rows} rows`,\n {\n index: i,\n found: target,\n length: rows,\n },\n );\n }\n if (components === 1) {\n out[target] = values[i];\n } else {\n for (let k = 0; k < components; k++) {\n out[target * components + k] = values[i * components + k];\n }\n }\n }\n return out;\n}\n\n// ============================================================ columns\n\n/**\n * Gather the validity bits of a column through a NEW -> OLD index map; entries equal to\n * INVALID_INDEX are unset rows of the result.\n * @param column - the source column\n * @param indexMap - new index -> old index or INVALID_INDEX\n * @returns the validity bitmap of the result (null when every row is set) and its null count\n */\nfunction gatherValidity(column: Column, indexMap: U32): { validity: U32 | null; nullCount: number } {\n const source = column.validity;\n let validity: U32 | null = null;\n let nullCount = 0;\n for (let i = 0; i < indexMap.length; i++) {\n const from = indexMap[i];\n const set = from !== INVALID_INDEX && (source === null || bitmapGet(source, from));\n if (!set) {\n validity ??= makeBitmap(indexMap.length, true);\n bitmapClear(validity, i);\n nullCount++;\n }\n }\n return { validity, nullCount };\n}\n\n/**\n * The metadata of a gathered column: the source metadata, made nullable when the gather produced\n * unset rows that the source could not have had.\n * @param meta - the source metadata\n * @param nullCount - the result's null count\n * @returns the metadata to use\n */\nfunction gatheredMeta(meta: ColumnMeta, nullCount: number): ColumnMeta {\n if (meta.nullable || nullCount === 0) {\n return meta;\n }\n return Object.freeze({ ...meta, nullable: true });\n}\n\n/**\n * Gather the rows of a column through a NEW -> OLD index map: `out[i] = column[indexMap[i]]`\n * (design section 5.11, `DerivedGraph.nodeOrigin` / `edgeOrigin`). An INVALID_INDEX entry yields an\n * unset row holding the fill (the column becomes nullable if it was not). Values of a refersTo\n * column are NOT rewritten here; compose with remapReferences() when the referenced space changed.\n * @param column - the source column\n * @param indexMap - new index -> old index (or INVALID_INDEX for a row with no source)\n * @returns a new column of `indexMap.length` rows\n */\nexport function gatherColumn(column: Column, indexMap: U32): Column {\n const { length } = indexMap;\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n if (from !== INVALID_INDEX && from >= column.length) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `indexMap[${i}] = ${from} is outside the column of ${column.length} rows`,\n {\n index: i,\n found: from,\n length: column.length,\n column: column.meta.name,\n },\n );\n }\n }\n const { validity, nullCount } = gatherValidity(column, indexMap);\n const meta = gatheredMeta(column.meta, nullCount);\n const parts: MutableColumnParts = {\n ...partsOf(column),\n meta,\n length,\n validity,\n nullCount,\n };\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\": {\n const { components, fill } = meta;\n const out = allocLike(column.data, length * components);\n if (typeof fill === \"number\" && fill !== 0) {\n out.fill(fill);\n }\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n if (from === INVALID_INDEX) {\n continue;\n }\n for (let k = 0; k < components; k++) {\n out[i * components + k] = column.data[from * components + k];\n }\n }\n parts.data = out;\n break;\n }\n case \"bool\": {\n const out = new Uint32Array(bitmapWordCount(length)).fill(meta.fill === true ? 0xffffffff : 0);\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n if (from === INVALID_INDEX) {\n continue;\n }\n if (bitmapGet(column.data, from)) {\n bitmapSet(out, i);\n } else {\n bitmapClear(out, i);\n }\n }\n parts.data = out;\n break;\n }\n case \"dict\": {\n const code = typeof meta.fill === \"string\" ? column.codeOf(meta.fill) : INVALID_INDEX;\n const fillCode = code === INVALID_INDEX ? 0 : code;\n const out = new Uint32Array(length);\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n out[i] = from === INVALID_INDEX ? fillCode : column.codes[from];\n }\n parts.data = out;\n break;\n }\n case \"string\": {\n const fillText = typeof meta.fill === \"string\" ? meta.fill : \"\";\n const strings = new Array<string>(length);\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n strings[i] = from === INVALID_INDEX ? fillText : column.valueAt(from);\n }\n parts.offsets = null;\n parts.utf8 = null;\n parts.strings = strings;\n break;\n }\n case \"list\": {\n const { offsets, child } = column;\n const newOffsets = new Uint32Array(length + 1);\n let total = 0;\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n if (from !== INVALID_INDEX) {\n total += offsets[from + 1] - offsets[from];\n }\n newOffsets[i + 1] = total;\n }\n const itemMap = new Uint32Array(total);\n let at = 0;\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n if (from === INVALID_INDEX) {\n continue;\n }\n for (let j = offsets[from]; j < offsets[from + 1]; j++) {\n itemMap[at++] = j;\n }\n }\n parts.offsets = newOffsets;\n parts.child = gatherColumn(child, itemMap);\n break;\n }\n case \"json\": {\n const out = new Array<unknown>(length);\n for (let i = 0; i < length; i++) {\n const from = indexMap[i];\n out[i] = from === INVALID_INDEX ? undefined : column.values[from];\n }\n parts.values = out;\n break;\n }\n default: {\n const name: string = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${name}`, { dtype: name });\n }\n }\n return createColumn(parts);\n}\n\n/**\n * The NEW -> OLD index map equivalent to an OLD -> NEW remap: entries of the new space no old row\n * maps to are INVALID_INDEX.\n * @param remap - old index -> new index or INVALID_INDEX\n * @param oldLength - the number of old rows to consider (entries beyond are ignored)\n * @param newLength - the row count of the new space\n * @returns the inverse map\n */\nfunction invertRemap(remap: U32, oldLength: number, newLength: number): U32 {\n const indexMap = new Uint32Array(newLength).fill(INVALID_INDEX);\n const rows = Math.min(remap.length, oldLength);\n for (let i = 0; i < rows; i++) {\n const target = remap[i];\n if (target === INVALID_INDEX) {\n continue;\n }\n if (target >= newLength) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `remap[${i}] = ${target} is outside the new space of ${newLength} rows`,\n {\n index: i,\n found: target,\n length: newLength,\n },\n );\n }\n indexMap[target] = i;\n }\n return indexMap;\n}\n\n/**\n * Rewrite the values of an index-valued column through the remap of the space it references\n * (design section 5.11): an in-range value maps to its new index; a dangling reference (mapped to\n * INVALID_INDEX or out of range) becomes INVALID_INDEX with the row unset. For a list of u32 the\n * dangling items are dropped and a row whose every item dangled becomes unset and empty. A column\n * without refersTo is returned as it is.\n * @param column - the column\n * @param valueRemap - old index -> new index or INVALID_INDEX, over the referenced space\n * @returns a new column when anything was rewritten; the same object otherwise\n */\nexport function remapReferences(column: Column, valueRemap: U32): Column {\n if (column.meta.refersTo === null) {\n return column;\n }\n const mapValue = (value: number): number => {\n if (value === INVALID_INDEX || value >= valueRemap.length) {\n return INVALID_INDEX;\n }\n return valueRemap[value];\n };\n if (column.dtype === \"u32\") {\n const { length } = column;\n const data = new Uint32Array(length);\n let validity = column.validity === null ? null : column.validity.slice();\n let { nullCount } = column;\n for (let row = 0; row < length; row++) {\n const mapped = mapValue(column.data[row]);\n data[row] = mapped;\n if (mapped === INVALID_INDEX && (validity === null || bitmapGet(validity, row))) {\n validity ??= makeBitmap(length, true);\n bitmapClear(validity, row);\n nullCount++;\n }\n }\n const parts: MutableColumnParts = {\n ...partsOf(column),\n meta: gatheredMeta(column.meta, nullCount),\n data,\n validity,\n nullCount,\n };\n return createColumn(parts);\n }\n if (column.dtype === \"list\" && column.child.dtype === \"u32\") {\n const { length, offsets, child } = column;\n const rows = new Array<number[]>(length);\n let validity = column.validity === null ? null : column.validity.slice();\n let { nullCount } = column;\n for (let row = 0; row < length; row++) {\n const items: number[] = [];\n const start = offsets[row];\n const end = offsets[row + 1];\n for (let j = start; j < end; j++) {\n const mapped = mapValue(child.data[j]);\n if (mapped !== INVALID_INDEX) {\n items.push(mapped);\n }\n }\n rows[row] = items;\n if (end > start && items.length === 0 && (validity === null || bitmapGet(validity, row))) {\n validity ??= makeBitmap(length, true);\n bitmapClear(validity, row);\n nullCount++;\n }\n }\n const meta = gatheredMeta(column.meta, nullCount);\n const rebuilt = columnOfValues(Object.freeze({ ...meta, nullable: true }), rows);\n const parts: MutableColumnParts = {\n ...partsOf(rebuilt),\n meta,\n validity,\n nullCount,\n };\n return createColumn(parts);\n }\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${column.meta.name}\" has refersTo but is not u32 or a list of u32`,\n {\n column: column.meta.name,\n field: \"refersTo\",\n },\n );\n}\n\n/**\n * Move a column's rows from an old index space to a new one through an OLD -> NEW remap, rewriting\n * its values through `valueRemap` when it is an index-valued column (design section 5.11): rows\n * mapped to INVALID_INDEX are dropped, rows of the new space no old row maps to are unset and hold\n * the fill (the column becomes nullable if it was not), and dangling references become\n * INVALID_INDEX with the row unset.\n * @param column - the source column\n * @param remap - old row -> new row or INVALID_INDEX\n * @param newLength - the row count of the new space\n * @param valueRemap - the remap of the space the column's values reference, or null to leave values alone\n * @returns a new column of `newLength` rows\n */\nexport function remapColumnWith(column: Column, remap: U32, newLength: number, valueRemap: U32 | null): Column {\n if (remap.length !== column.length) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `remap has ${remap.length} entries for a column of ${column.length} rows`,\n { column: column.meta.name, expected: column.length, found: remap.length },\n );\n }\n const gathered = gatherColumn(column, invertRemap(remap, column.length, newLength));\n return valueRemap === null ? gathered : remapReferences(gathered, valueRemap);\n}\n\n/**\n * Move a column's rows through an OLD -> NEW remap and, when the column refers to its OWN index\n * space (a node column with `refersTo: \"node\"` such as `parent`, an edge column with `refersTo:\n * \"edge\"` such as `pair`), rewrite its values through the SAME remap (design sections 5.11 and\n * 12.2). A column whose values reference the OTHER space (a node column referring to edges) has its\n * rows moved and its values left untouched, because `remap` says nothing about that space; the\n * internal remapColumnWith() / remapTable() take a second remap for it.\n * @param column - the source column\n * @param remap - old row -> new row or INVALID_INDEX\n * @param newLength - the row count of the new space\n * @returns a new column of `newLength` rows\n */\nexport function remapColumn(column: Column, remap: U32, newLength: number): Column {\n const { refersTo, domain } = column.meta;\n const ownSpace = refersTo !== null && refersTo === domain;\n return remapColumnWith(column, remap, newLength, ownSpace ? remap : null);\n}\n\n/**\n * Change the stride of an interleaved f32 array (design section 5.2, the generic stride helper):\n * every row of `from` values becomes a row of `to` values, extra lanes filled with `fill` and\n * surplus lanes dropped. A 2D layout result expands to the 3-component position column with\n * `withComponents(xy, 2, 3, 0)`; the inverse drops `z`. Returns `data` itself when `from === to`.\n * @param data - the interleaved values, `rows * from` long\n * @param from - values per row of `data`, 1..16\n * @param to - values per row of the result, 1..16\n * @param fill - the value of the lanes `to` adds beyond `from`\n * @returns a new array of `rows * to` values (the input when the stride is unchanged)\n */\nexport function withComponents(data: F32, from: number, to: number, fill: number): F32 {\n for (const [field, value] of [\n [\"from\", from],\n [\"to\", to],\n ] as const) {\n if (!Number.isInteger(value) || value < 1 || value > 16) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `${field} must be an integer in 1..16, found ${value}`, {\n field,\n found: value,\n });\n }\n }\n checkComponents(from, data);\n if (from === to) {\n return data;\n }\n const rows = data.length / from;\n const out = new Float32Array(rows * to);\n const keep = Math.min(from, to);\n if (to > from && fill !== 0) {\n out.fill(fill);\n }\n for (let row = 0; row < rows; row++) {\n const src = row * from;\n const dst = row * to;\n for (let k = 0; k < keep; k++) {\n out[dst + k] = data[src + k];\n }\n }\n return out;\n}\n\n// ============================================================ tables\n\n/**\n * The remaps of the two index spaces a column's values may reference; null when that space was not\n * renumbered.\n */\ninterface ReferenceRemaps {\n /** Old node index -> new node index or INVALID_INDEX; null when nodes were not renumbered. */\n readonly node: U32 | null;\n /** Old edge index -> new edge index or INVALID_INDEX; null when edges were not renumbered. */\n readonly edge: U32 | null;\n}\n\n/**\n * The value remap that applies to a column, if any.\n * @param meta - the column metadata\n * @param refs - the reference remaps\n * @returns the remap of the referenced space, or null\n */\nfunction valueRemapFor(meta: ColumnMeta, refs: ReferenceRemaps): U32 | null {\n if (meta.refersTo === \"node\") {\n return refs.node;\n }\n if (meta.refersTo === \"edge\") {\n return refs.edge;\n }\n return null;\n}\n\n/**\n * Remap every column of a table (freeze step 10, the compaction case; extension tables with\n * `rowRemap` null): rows move through `rowRemap` when given, and every refersTo column's values are\n * rewritten through the remap of the space it references. The result is a new table; the source is\n * untouched.\n * @param table - the source table\n * @param rowRemap - old row -> new row or INVALID_INDEX; null when the table's rows are unchanged\n * @param newLength - the row count of the new table (ignored, and equal to table.rowCount, when rowRemap is null)\n * @param refs - the node and edge remaps for index-valued columns\n * @returns the remapped table\n */\nexport function remapTable(\n table: AttributeTable,\n rowRemap: U32 | null,\n newLength: number,\n refs: ReferenceRemaps,\n): AttributeTable {\n const rowCount = rowRemap === null ? table.rowCount : newLength;\n const columns: Column[] = [];\n for (const column of table) {\n const valueRemap = valueRemapFor(column.meta, refs);\n let out = column;\n if (rowRemap !== null) {\n out = remapColumnWith(column, rowRemap, newLength, valueRemap);\n } else if (valueRemap !== null) {\n out = remapReferences(column, valueRemap);\n }\n columns.push(out);\n }\n return new AttributeTable({ domain: table.domain, rowCount, columns });\n}\n\n/**\n * Gather every column of a table through a NEW -> OLD index map (derived graphs: `nodeOrigin` /\n * `edgeOrigin`), rewriting refersTo values through the remaps of the spaces they reference.\n * @param table - the source table\n * @param indexMap - new row -> old row\n * @param refs - the node and edge remaps for index-valued columns\n * @returns the gathered table of `indexMap.length` rows\n */\nexport function gatherTable(table: AttributeTable, indexMap: U32, refs: ReferenceRemaps): AttributeTable {\n const columns: Column[] = [];\n for (const column of table) {\n const gathered = gatherColumn(column, indexMap);\n const valueRemap = valueRemapFor(column.meta, refs);\n columns.push(valueRemap === null ? gathered : remapReferences(gathered, valueRemap));\n }\n return new AttributeTable({ domain: table.domain, rowCount: indexMap.length, columns });\n}\n","/**\n * The public packed-mask helpers of design section 7.4 (makeMask, maskTest, maskSet, maskCount,\n * maskToIndices) plus the E_MASK_LENGTH check that filterEdges() and inducedSubgraph({ mask }) apply\n * to a caller's mask. A NodeMask / EdgeMask is the same layout as a validity bitmap and a bool column\n * (decision C13): ceil(length / 32) Uint32Array words, LSB-first, bit i set means index i is included.\n * Masks are not part of the snapshot contract; no kernel is required to honour one.\n */\n\nimport {\n bitmapCount,\n bitmapGet,\n bitmapToIndices,\n bitmapWordCount,\n bitmapWrite,\n makeBitmap,\n} from \"../columns/bitmap.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type U32 } from \"../types/index.js\";\n\n/**\n * Allocate a packed mask over `length` indices: ceil(length / 32) words, every bit clear, or every bit\n * below `length` set when `fill` is true (design section 7.4).\n * @param length - the number of indices the mask covers (nodeCount, edgeCount or arcCount)\n * @param fill - the initial value of every bit; defaults to false\n * @returns the mask words\n */\nexport function makeMask(length: number, fill?: boolean): U32 {\n return makeBitmap(length, fill === true);\n}\n\n/**\n * Whether index i is in the mask.\n * @param mask - the mask words\n * @param i - the index, below the mask's length\n * @returns true when bit i is set\n */\nexport function maskTest(mask: U32, i: number): boolean {\n return bitmapGet(mask, i);\n}\n\n/**\n * Include or exclude index i.\n * @param mask - the mask words\n * @param i - the index, below the mask's length\n * @param value - true to include, false to exclude\n */\nexport function maskSet(mask: U32, i: number, value: boolean): void {\n bitmapWrite(mask, i, value);\n}\n\n/**\n * The number of included indices below `length` (the loop guard of an algorithm-owned alive mask,\n * design section 7.4).\n * @param mask - the mask words, at least ceil(length / 32) of them\n * @param length - the number of indices the mask covers\n * @returns the number of set bits in [0, length)\n */\nexport function maskCount(mask: U32, length: number): number {\n return bitmapCount(mask, length);\n}\n\n/**\n * The included indices below `length` in ascending order, as a fresh U32.\n * @param mask - the mask words, at least ceil(length / 32) of them\n * @param length - the number of indices the mask covers\n * @returns the set bit indices\n */\nexport function maskToIndices(mask: U32, length: number): U32 {\n return bitmapToIndices(mask, length);\n}\n\n/**\n * Check that a caller-supplied mask has enough words for `length` indices; filterEdges() and\n * inducedSubgraph({ mask }) call it before reading the mask (design section 11.2). Throws\n * E_MASK_LENGTH when mask.length < ceil(length / 32).\n * @param mask - the mask words\n * @param length - the number of indices the mask must cover\n * @param what - what the mask is over, for the message (\"edges\", \"nodes\")\n */\nexport function checkMaskLength(mask: U32, length: number, what: string): void {\n const required = bitmapWordCount(length);\n if (mask.length < required) {\n throw new GraphFormatError(\n \"E_MASK_LENGTH\",\n `mask over ${what} has ${mask.length} words; ${required} needed for ${length} ${what}`,\n { found: mask.length, required, length },\n );\n }\n}\n","/**\n * Derived graphs (design section 7.3): `toUndirected`, `transpose`, `simplified`, `withoutSelfLoops`,\n * `filterEdges`, `inducedSubgraph`, `contract`, `relabel` and `withColumns`, each returning the\n * `SnapshotParts` of a NEW snapshot plus the index maps back to the source (`DerivedParts`), and the\n * `renumberPartition` helper of design section 7.5. GraphSnapshot wraps the parts with\n * `createSnapshot()`; this module imports the class type only, so there is no runtime cycle.\n *\n * Every derived core is built by `buildCore()`, the two stable counting-sort passes of design section\n * 6.3 steps 3-6 over a per-logical-edge list (src, dst, weight) in declared orientation, into a fresh\n * 256-aligned arena (section 10.3), so every derived snapshot inherits invariants I1-I10 by\n * construction and `flags` are computed by the one predicate set in validate.ts (I9).\n *\n * Index-map conventions (design section 7.3): `nodeOrigin` / `edgeOrigin` are NEW -> SOURCE,\n * `nodeRemap` / `edgeRemap` SOURCE -> NEW with INVALID_INDEX for a dropped row and the SURVIVOR's new\n * index for a merged edge; each map is null exactly when its index space is unchanged (same length,\n * identity). New edges are numbered in ascending order of their survivor's source index, so relative\n * edge order is preserved (I14). Attribute tables follow the propagation table of design section\n * 5.11: same node space -> the SAME `AttributeTable` instance; gathered otherwise; `refersTo` values\n * rewritten through the matching remap.\n */\n\nimport { sortIntoCore } from \"../builder/counting-sort.js\";\nimport { bitmapClear, makeBitmap } from \"../columns/bitmap.js\";\nimport { createColumn, emptyParts, resolveColumnMeta } from \"../columns/column.js\";\nimport { gatherColumn, gatherTable, remapTable } from \"../columns/remap.js\";\nimport { AttributeTable as AttributeTableClass, tableWithColumns } from \"../columns/table.js\";\nimport { INVALID_INDEX } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { gatherNodeIdMap, identityNodeIdMap } from \"../ids/node-id-map.js\";\nimport {\n type ArenaLayout,\n type AttributeTable,\n type Column,\n type ColumnInput,\n type ColumnReducer,\n type ContractOptions,\n type EdgeListView,\n type EdgeMask,\n type F32,\n type GraphSnapshot,\n type NodeIdMap,\n type NodeMask,\n type ReverseView,\n type SimplifyOptions,\n type SnapshotFlags,\n type ToUndirectedOptions,\n type TypedArrayData,\n type U32,\n type WeightReducer,\n} from \"../types/index.js\";\nimport { type SnapshotParts } from \"../types/internal.js\";\nimport { checkMaskLength, maskTest, maskToIndices } from \"../util/mask.js\";\nimport { assertOneOf, COLUMN_REDUCERS, WEIGHT_REDUCERS } from \"../util/options.js\";\nimport { noteShared } from \"../util/shared-buffers.js\";\nimport { arcRangeIn } from \"./queries.js\";\nimport { computeFlags, isIdentity } from \"./validate.js\";\n\n// ============================================================ result shape\n\n/** The report of a derived graph: how many source edges were dropped and how many merged into a survivor. */\ninterface DerivedReport {\n /** Source edges with no counterpart in the derived graph. */\n readonly droppedEdges: number;\n /** Source edges collapsed into another edge (the survivor). */\n readonly mergedEdges: number;\n}\n\n/**\n * What a derive function returns: the parts of the new snapshot (null when the operation is the\n * identity and the caller returns the source itself) and the maps of `DerivedGraph`.\n */\nexport interface DerivedParts {\n /** The parts of the new snapshot, or null for \"return this\". */\n readonly parts: SnapshotParts | null;\n /** New node index -> source node index, or null when the node space is unchanged. */\n readonly nodeOrigin: U32 | null;\n /** New edge index -> source edge index (survivor), or null when the edge space is unchanged. */\n readonly edgeOrigin: U32 | null;\n /** Source node index -> new node index or INVALID_INDEX, or null when unchanged. */\n readonly nodeRemap: U32 | null;\n /** Source edge index -> new edge index (survivor) or INVALID_INDEX, or null when unchanged. */\n readonly edgeRemap: U32 | null;\n /** contract only: source nodes per block. */\n readonly blockSizes: U32 | null;\n /** Dropped and merged edge counts. */\n readonly report: DerivedReport;\n}\n\nconst NO_REPORT: DerivedReport = Object.freeze({ droppedEdges: 0, mergedEdges: 0 });\n\n/**\n * The DerivedParts of an identity operation: the caller returns the source snapshot itself.\n * @returns parts null, every map null, an empty report\n */\nexport function identityDerived(): DerivedParts {\n return {\n parts: null,\n nodeOrigin: null,\n edgeOrigin: null,\n nodeRemap: null,\n edgeRemap: null,\n blockSizes: null,\n report: NO_REPORT,\n };\n}\n\n// ============================================================ core builder (6.3 steps 3-6, 10.3)\n\n/** A per-logical-edge description of a graph in declared orientation: the input of `buildCore()`. */\ninterface EdgeArrays {\n /** Whether the graph is directed. */\n readonly directed: boolean;\n /** The node count. */\n readonly nodeCount: number;\n /** The logical edge count. */\n readonly edgeCount: number;\n /** Declared source of every edge. */\n readonly src: U32;\n /** Declared target of every edge. */\n readonly dst: U32;\n /** Per-edge f32 weights, or null when unweighted. */\n readonly weights: F32 | null;\n}\n\n/** The core a `buildCore()` call produces: exactly the core fields of SnapshotParts. */\ninterface BuiltCore {\n /** colIdx.length. */\n readonly arcCount: number;\n /** Logical edges with source === target. */\n readonly selfLoopCount: number;\n /** nodeCount + 1 row offsets. */\n readonly rowPtr: U32;\n /** Sorted targets. */\n readonly colIdx: U32;\n /** Per-arc weights, or null. */\n readonly weights: F32 | null;\n /** arcCount entries, or null when the permutation is the identity. */\n readonly arcToEdge: U32 | null;\n /** edgeCount entries, or null when the permutation is the identity. */\n readonly edgeToArc: U32 | null;\n /** The truthful flags (I9). */\n readonly flags: SnapshotFlags;\n /** The arena the arrays are views into, or null when `arena: false`. */\n readonly arena: ArenaLayout | null;\n}\n\n/** Options of `buildCore()`. */\ninterface BuildCoreOptions {\n /** Allocate the arrays inside one 256-aligned arena (default true) or as separate buffers. */\n readonly arena?: boolean | undefined;\n}\n\n/**\n * Build the core of a derived graph from a per-logical-edge list in declared orientation: the two\n * stable counting-sort passes of design section 6.3 steps 3-6 (`sortIntoCore` of the builder module,\n * so derived graphs and freezes share one implementation), into a fresh 256-aligned arena unless\n * `arena: false`. Invariants I1-I10 hold by construction and the flags are computed from the stored\n * values (I9). A NaN weight (a reducer summing +Infinity and -Infinity) is E_INVALID_WEIGHT (I8).\n * @param edges - the per-edge arrays; only the first `edgeCount` entries are read\n * @param options - arena or separate buffers\n * @returns the core, the counts and the flags\n */\nexport function buildCore(edges: EdgeArrays, options: BuildCoreOptions = {}): BuiltCore {\n const result = sortIntoCore(edges, options.arena !== false);\n const { core } = result;\n return {\n arcCount: result.arcCount,\n selfLoopCount: result.selfLoopCount,\n rowPtr: core.rowPtr,\n colIdx: core.colIdx,\n weights: core.weights,\n arcToEdge: core.arcToEdge,\n edgeToArc: core.edgeToArc,\n flags: result.flags,\n arena: core.arena,\n };\n}\n\n// ============================================================ assembling parts\n\n/** The side structures of a derived snapshot. */\ninterface DerivedSides {\n readonly directed: boolean;\n readonly nodeCount: number;\n readonly edgeCount: number;\n readonly ids: NodeIdMap;\n readonly nodes: AttributeTable;\n readonly edges: AttributeTable;\n readonly extensions: ReadonlyMap<string, AttributeTable>;\n}\n\n/**\n * Combine a built core with the side structures into SnapshotParts (serial null: a new core identity;\n * checksum false: the caller substitutes its own setting).\n * @param source - the source snapshot (label, meta and graph table are carried over)\n * @param core - the built core\n * @param sides - the side structures\n * @returns the parts\n */\nfunction assembleParts(source: GraphSnapshot, core: BuiltCore, sides: DerivedSides): SnapshotParts {\n return {\n label: source.label,\n serial: null,\n directed: sides.directed,\n nodeCount: sides.nodeCount,\n edgeCount: sides.edgeCount,\n arcCount: core.arcCount,\n selfLoopCount: core.selfLoopCount,\n rowPtr: core.rowPtr,\n colIdx: core.colIdx,\n weights: core.weights,\n arcToEdge: core.arcToEdge,\n edgeToArc: core.edgeToArc,\n flags: core.flags,\n ids: sides.ids,\n nodes: sides.nodes,\n edges: sides.edges,\n graph: source.graph,\n extensions: sides.extensions,\n meta: source.meta,\n arena: core.arena,\n checksum: false,\n };\n}\n\n/**\n * Extension tables with refersTo values rewritten through the remaps; the source map itself when\n * neither space changed.\n * @param source - the source snapshot\n * @param nodeRemap - the node remap or null\n * @param edgeRemap - the edge remap or null\n * @returns the extension map to use\n */\nfunction remapExtensions(\n source: GraphSnapshot,\n nodeRemap: U32 | null,\n edgeRemap: U32 | null,\n): ReadonlyMap<string, AttributeTable> {\n if ((nodeRemap === null && edgeRemap === null) || source.extensions.size === 0) {\n return source.extensions;\n }\n const out = new Map<string, AttributeTable>();\n for (const [name, table] of source.extensions) {\n out.set(name, remapTable(table, null, table.rowCount, { node: nodeRemap, edge: edgeRemap }));\n }\n return out;\n}\n\n// ============================================================ edge selection and grouping\n\n/**\n * A grouping of source edges into new edges: `remap` (source -> new or INVALID_INDEX), `origin` (new\n * -> survivor = lowest source index of the group) and the new count. Null maps mean \"unchanged\".\n */\ninterface EdgeGrouping {\n readonly count: number;\n readonly remap: U32 | null;\n readonly origin: U32 | null;\n readonly dropped: number;\n readonly merged: number;\n}\n\n/**\n * Build the new -> survivor map and count from a source -> new remap whose survivors are numbered in\n * ascending source order.\n * @param remap - source edge -> new edge or INVALID_INDEX, survivors ascending\n * @param count - the new edge count\n * @returns the origin map\n */\nfunction originOf(remap: U32, count: number): U32 {\n const origin = new Uint32Array(count).fill(INVALID_INDEX);\n for (let e = 0; e < remap.length; e++) {\n const d = remap[e];\n if (d !== INVALID_INDEX && origin[d] === INVALID_INDEX) {\n origin[d] = e;\n }\n }\n return origin;\n}\n\n/**\n * Turn a per-edge \"survivor of e\" array (`INVALID_INDEX` = dropped, `e` itself = survivor, another\n * index = merged into that survivor) into an EdgeGrouping with new indices in ascending survivor order.\n * @param survivorOf - source edge -> its survivor, or INVALID_INDEX\n * @returns the grouping; maps null when every edge survives on its own\n */\nfunction groupingFromSurvivors(survivorOf: U32): EdgeGrouping {\n const edgeCount = survivorOf.length;\n const newIndex = new Uint32Array(edgeCount).fill(INVALID_INDEX);\n let count = 0;\n let dropped = 0;\n let merged = 0;\n for (let e = 0; e < edgeCount; e++) {\n if (survivorOf[e] === e) {\n newIndex[e] = count++;\n } else if (survivorOf[e] === INVALID_INDEX) {\n dropped++;\n } else {\n merged++;\n }\n }\n if (dropped === 0 && merged === 0) {\n return { count, remap: null, origin: null, dropped, merged };\n }\n const remap = new Uint32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n const s = survivorOf[e];\n remap[e] = s === INVALID_INDEX ? INVALID_INDEX : newIndex[s];\n }\n return { count, remap, origin: originOf(remap, count), dropped, merged };\n}\n\n/**\n * Whether two arrays of node indices are the identity selection.\n * @param origin - new -> source\n * @param nodeCount - the source node count\n * @returns true when origin is 0..nodeCount-1\n */\nfunction isIdentitySelection(origin: U32, nodeCount: number): boolean {\n return origin.length === nodeCount && isIdentity(origin);\n}\n\n/**\n * The declared endpoints and weights of the surviving edges, endpoints mapped through `nodeRemap`\n * when given, in new-index order.\n * @param list - the source edge list\n * @param grouping - the grouping (origin null = all edges in order)\n * @param nodeRemap - source node -> new node, or null\n * @returns the edge arrays without weights (weights are reduced separately)\n */\nfunction gatherEndpoints(list: EdgeListView, grouping: EdgeGrouping, nodeRemap: U32 | null): { src: U32; dst: U32 } {\n const { count, origin } = grouping;\n const src = new Uint32Array(count);\n const dst = new Uint32Array(count);\n for (let d = 0; d < count; d++) {\n const e = origin === null ? d : origin[d];\n src[d] = nodeRemap === null ? list.src[e] : nodeRemap[list.src[e]];\n dst[d] = nodeRemap === null ? list.dst[e] : nodeRemap[list.dst[e]];\n }\n return { src, dst };\n}\n\n/**\n * Check every reducer of a per-column reducer record (design section 7.3) before anything is built.\n * @param field - the option name\n * @param reducers - the record, or undefined\n */\nfunction checkReducers(field: string, reducers: Readonly<Record<string, unknown>> | undefined): void {\n if (reducers === undefined) {\n return;\n }\n for (const name of Object.keys(reducers)) {\n assertOneOf(`${field}.${name}`, reducers[name], COLUMN_REDUCERS);\n }\n}\n\n/**\n * Reduce per-edge weights over a grouping (design section 7.3): `\"first\"` keeps the survivor's\n * (lowest index) weight, `\"last\"` the highest index's, `\"sum\"` / `\"min\"` / `\"max\"` combine the group.\n * On an unweighted source `\"sum\"` yields the multiplicities as an F32 and every other reducer null.\n * @param weights - the per-edge source weights, or null\n * @param grouping - the grouping\n * @param reducer - the weight reducer\n * @returns the per-new-edge weights, or null\n */\nfunction reduceWeights(weights: F32 | null, grouping: EdgeGrouping, reducer: WeightReducer): F32 | null {\n const { count, remap, origin } = grouping;\n if (weights === null) {\n if (reducer !== \"sum\") {\n return null;\n }\n const out = new Float32Array(count);\n if (remap === null) {\n out.fill(1);\n return out;\n }\n for (let e = 0; e < remap.length; e++) {\n if (remap[e] !== INVALID_INDEX) {\n out[remap[e]]++;\n }\n }\n return out;\n }\n if (remap === null || origin === null) {\n return weights;\n }\n const out = new Float32Array(count);\n for (let d = 0; d < count; d++) {\n out[d] = weights[origin[d]];\n }\n if (reducer === \"first\") {\n return out;\n }\n for (let e = 0; e < remap.length; e++) {\n const d = remap[e];\n if (d === INVALID_INDEX || origin[d] === e) {\n continue;\n }\n const w = weights[e];\n switch (reducer) {\n case \"last\":\n out[d] = w;\n break;\n case \"sum\":\n out[d] += w;\n break;\n case \"min\":\n if (w < out[d]) {\n out[d] = w;\n }\n break;\n case \"max\":\n if (w > out[d]) {\n out[d] = w;\n }\n break;\n default: {\n const unknown: never = reducer;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown weight reducer ${String(unknown)}`, {\n reducer: unknown,\n });\n }\n }\n }\n return out;\n}\n\n/**\n * The grouping of a per-edge keep predicate: kept edges survive on their own in order, others are\n * dropped.\n * @param edgeCount - the source edge count\n * @param keep - whether edge e is kept\n * @returns the grouping\n */\nfunction groupingFromPredicate(edgeCount: number, keep: (e: number) => boolean): EdgeGrouping {\n const survivorOf = new Uint32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n survivorOf[e] = keep(e) ? e : INVALID_INDEX;\n }\n return groupingFromSurvivors(survivorOf);\n}\n\n// ============================================================ column reduction\n\n/** The five flat numeric column shapes the group reducers accumulate. */\ntype NumericColumn = Extract<Column, { dtype: \"f32\" | \"f64\" | \"i32\" | \"u32\" | \"u8\" }>;\n\n/**\n * A group reducer's numeric accumulation for one column into a new row space.\n * @param column - a numeric column\n * @param grouping - the grouping (remap non-null)\n * @param reducer - sum / min / max / mean\n * @returns the reduced column\n */\nfunction reduceNumericColumn(\n column: NumericColumn,\n grouping: EdgeGrouping,\n reducer: \"sum\" | \"min\" | \"max\" | \"mean\",\n): Column {\n const { count, remap } = grouping;\n const { components } = column.meta;\n const width = components;\n const acc = new Float64Array(count * width);\n const members = new Uint32Array(count);\n const seen = new Uint8Array(count);\n const source = column.data;\n const rows = remap === null ? column.length : remap.length;\n for (let r = 0; r < rows; r++) {\n const d = remap === null ? r : remap[r];\n if (d === INVALID_INDEX || !column.isSet(r)) {\n continue;\n }\n members[d]++;\n for (let k = 0; k < width; k++) {\n const value = source[r * width + k];\n const at = d * width + k;\n if (seen[d] === 0) {\n acc[at] = value;\n } else {\n switch (reducer) {\n case \"sum\":\n case \"mean\":\n acc[at] += value;\n break;\n case \"min\":\n if (value < acc[at]) {\n acc[at] = value;\n }\n break;\n case \"max\":\n if (value > acc[at]) {\n acc[at] = value;\n }\n break;\n default: {\n const unknown: never = reducer;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown reducer ${String(unknown)}`, {\n reducer: unknown,\n });\n }\n }\n }\n }\n seen[d] = 1;\n }\n if (reducer === \"mean\") {\n for (let d = 0; d < count; d++) {\n if (members[d] > 1) {\n for (let k = 0; k < width; k++) {\n acc[d * width + k] /= members[d];\n }\n }\n }\n }\n // \"mean\" is f64; a \"sum\" over an integer dtype widens to f64 too, so a total can never wrap\n // silently in a typed array that every write path would have refused (design section 5.1)\n const widen = reducer === \"mean\" || (reducer === \"sum\" && column.dtype !== \"f32\" && column.dtype !== \"f64\");\n const dtype = widen ? \"f64\" : column.dtype;\n let data: TypedArrayData;\n switch (dtype) {\n case \"f64\":\n data = acc;\n break;\n case \"f32\":\n data = new Float32Array(acc);\n break;\n case \"i32\":\n data = new Int32Array(acc);\n break;\n case \"u32\":\n data = new Uint32Array(acc);\n break;\n case \"u8\":\n data = new Uint8Array(new ArrayBuffer(Math.ceil((count * width) / 4) * 4), 0, count * width);\n data.set(acc);\n break;\n default: {\n const unknown: never = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `cannot reduce a ${String(unknown)} column`, {\n dtype: unknown,\n });\n }\n }\n let validity: U32 | null = null;\n let nullCount = 0;\n for (let d = 0; d < count; d++) {\n if (seen[d] === 0) {\n validity ??= makeBitmap(count, true);\n bitmapClear(validity, d);\n nullCount++;\n }\n }\n const meta = resolveColumnMeta(column.meta.name, column.meta.domain, {\n dtype,\n components,\n nullable: column.meta.nullable || nullCount > 0,\n role: column.meta.role ?? undefined,\n extra: column.meta.extra,\n });\n return createColumn({ ...emptyParts(meta, count, validity), data, nullCount });\n}\n\n/**\n * The u32 column of group sizes (\"count\").\n * @param column - the source column (name, domain, role and extra are kept)\n * @param grouping - the grouping\n * @returns the count column\n */\nfunction countColumn(column: Column, grouping: EdgeGrouping): Column {\n const { count, remap } = grouping;\n const sizes = new Uint32Array(count);\n if (remap === null) {\n sizes.fill(1);\n } else {\n for (let r = 0; r < remap.length; r++) {\n if (remap[r] !== INVALID_INDEX) {\n sizes[remap[r]]++;\n }\n }\n }\n const meta = resolveColumnMeta(column.meta.name, column.meta.domain, {\n dtype: \"u32\",\n nullable: false,\n role: column.meta.role ?? undefined,\n extra: column.meta.extra,\n });\n return createColumn({ ...emptyParts(meta, count, null), data: sizes });\n}\n\n/**\n * Reduce one column over a grouping with a ColumnReducer (design section 7.3): `\"first\"` / `\"last\"`\n * gather the lowest / highest member's row (any dtype), `\"count\"` yields the group sizes, `\"sum\"` /\n * `\"min\"` / `\"max\"` / `\"mean\"` combine the set members of a numeric column (`\"mean\"` as f64, and so\n * is a `\"sum\"` over an i32 / u32 / u8 column, which would otherwise wrap; `\"min\"` / `\"max\"` keep\n * the dtype since the result is a member), `\"drop\"` omits the column. Index-valued (refersTo)\n * columns are always dropped: their values would refer to the source space.\n * @param column - the source column\n * @param grouping - the grouping\n * @param reducer - the reducer\n * @returns the reduced column, or null to drop it; E_COLUMN_TYPE for a numeric reducer on a non-numeric column\n */\nfunction reduceColumn(column: Column, grouping: EdgeGrouping, reducer: ColumnReducer): Column | null {\n if (reducer === \"drop\" || column.meta.refersTo !== null) {\n return null;\n }\n const { count, remap, origin } = grouping;\n switch (reducer) {\n case \"first\":\n return origin === null ? column : gatherColumn(column, origin);\n case \"last\": {\n if (remap === null) {\n return column;\n }\n const last = new Uint32Array(count);\n for (let r = 0; r < remap.length; r++) {\n if (remap[r] !== INVALID_INDEX) {\n last[remap[r]] = r;\n }\n }\n return gatherColumn(column, last);\n }\n case \"count\":\n return countColumn(column, grouping);\n case \"sum\":\n case \"min\":\n case \"max\":\n case \"mean\": {\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n return reduceNumericColumn(column, grouping, reducer);\n case \"bool\":\n case \"dict\":\n case \"string\":\n case \"list\":\n case \"json\":\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `reducer \"${reducer}\" needs a numeric column; \"${column.meta.name}\" is ${dtype}`,\n { column: column.meta.name, dtype, reducer },\n );\n default: {\n const unknown: never = dtype;\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `unknown dtype ${String(unknown)}`, { dtype: unknown });\n }\n }\n }\n default: {\n const unknown: never = reducer;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown column reducer ${String(unknown)}`, {\n reducer: unknown,\n });\n }\n }\n}\n\n/**\n * The edge table of a merging derived graph: named columns reduced per `reducers`, every other column\n * gathered from the survivor's row (the default of design section 5.11), refersTo values rewritten.\n * @param source - the source snapshot\n * @param grouping - the edge grouping\n * @param reducers - per-column reducers, or undefined for survivor rows throughout\n * @param nodeRemap - the node remap for refersTo node columns, or null\n * @returns the new edge table (the source table when the edge space is unchanged and no reducer applies)\n */\nfunction reduceEdgeTable(\n source: GraphSnapshot,\n grouping: EdgeGrouping,\n reducers: Readonly<Record<string, ColumnReducer>> | undefined,\n nodeRemap: U32 | null,\n): AttributeTable {\n const refs = { node: nodeRemap, edge: grouping.remap };\n if (reducers === undefined || Object.keys(reducers).length === 0) {\n if (grouping.origin === null) {\n return nodeRemap === null ? source.edges : remapTable(source.edges, null, source.edgeCount, refs);\n }\n return gatherTable(source.edges, grouping.origin, refs);\n }\n const columns: Column[] = [];\n for (const column of source.edges) {\n const reducer = reducers[column.meta.name];\n if (reducer === undefined) {\n const gathered = grouping.origin === null ? column : gatherColumn(column, grouping.origin);\n columns.push(gathered);\n continue;\n }\n const reduced = reduceColumn(column, grouping, reducer);\n if (reduced !== null) {\n columns.push(reduced);\n }\n }\n const table = new AttributeTableClass({ domain: \"edge\", rowCount: grouping.count, columns });\n return remapTable(table, null, grouping.count, refs);\n}\n\n// ============================================================ filterEdges, withoutSelfLoops\n\n/**\n * The derived graph keeping the edges a predicate accepts, in the same node space (design section\n * 7.3: `filterEdges`, `withoutSelfLoops`). Always a new snapshot; the maps are null when every edge\n * is kept.\n * @param source - the source snapshot\n * @param list - the source edge list\n * @param keep - whether edge e is kept\n * @returns the derived parts\n */\nfunction deriveKeptEdges(source: GraphSnapshot, list: EdgeListView, keep: (e: number) => boolean): DerivedParts {\n const grouping = groupingFromPredicate(source.edgeCount, keep);\n const { src, dst } = gatherEndpoints(list, grouping, null);\n const weights = reduceWeights(list.weights, grouping, \"first\");\n const core = buildCore({\n directed: source.directed,\n nodeCount: source.nodeCount,\n edgeCount: grouping.count,\n src,\n dst,\n weights,\n });\n const edges = reduceEdgeTable(source, grouping, undefined, null);\n const parts = assembleParts(source, core, {\n directed: source.directed,\n nodeCount: source.nodeCount,\n edgeCount: grouping.count,\n ids: source.ids,\n nodes: source.nodes,\n edges,\n extensions: remapExtensions(source, null, grouping.remap),\n });\n return {\n parts,\n nodeOrigin: null,\n edgeOrigin: grouping.origin,\n nodeRemap: null,\n edgeRemap: grouping.remap,\n blockSizes: null,\n report: { droppedEdges: grouping.dropped, mergedEdges: 0 },\n };\n}\n\n/**\n * `filterEdges(keep)`: the logical edges whose mask bit is set (design section 7.3).\n * @param source - the source snapshot\n * @param list - the source edge list\n * @param keep - packed bitmap over logical edges; E_MASK_LENGTH when short\n * @returns the derived parts\n */\nexport function deriveFilterEdges(source: GraphSnapshot, list: EdgeListView, keep: EdgeMask): DerivedParts {\n checkMaskLength(keep, source.edgeCount, \"edges\");\n return deriveKeptEdges(source, list, (e) => maskTest(keep, e));\n}\n\n/**\n * `withoutSelfLoops()`: every edge with source !== target (design section 7.3).\n * @param source - the source snapshot\n * @param list - the source edge list\n * @returns the derived parts\n */\nexport function deriveWithoutSelfLoops(source: GraphSnapshot, list: EdgeListView): DerivedParts {\n return deriveKeptEdges(source, list, (e) => list.src[e] !== list.dst[e]);\n}\n\n// ============================================================ inducedSubgraph, relabel\n\n/**\n * The E_INDEX_RANGE error of a bad inducedSubgraph index list entry.\n * @param position - the position in the list\n * @param value - the offending value\n * @param nodeCount - the node count\n * @param reason - \"out of range\" or \"repeated\"\n * @returns the error\n */\nfunction selectionError(position: number, value: number, nodeCount: number, reason: string): GraphFormatError {\n return new GraphFormatError(\n \"E_INDEX_RANGE\",\n `inducedSubgraph selection[${position}] = ${value} is ${reason} (nodeCount ${nodeCount})`,\n { index: position, found: value, nodeCount, reason },\n );\n}\n\n/**\n * Resolve an inducedSubgraph selection to the new -> source node list (design section 7.3): an\n * index list in the given order (E_INDEX_RANGE for an out-of-range or repeated index) or a packed\n * mask in ascending order (E_MASK_LENGTH when short).\n * @param source - the source snapshot\n * @param selection - the index list or mask\n * @returns the node origin list (a fresh array)\n */\nfunction resolveSelection(source: GraphSnapshot, selection: U32 | { readonly mask: NodeMask }): U32 {\n const { nodeCount } = source;\n if (selection instanceof Uint32Array) {\n const seen = new Uint8Array(nodeCount);\n const origin = new Uint32Array(selection.length);\n for (let i = 0; i < selection.length; i++) {\n const u = selection[i];\n if (u >= nodeCount) {\n throw selectionError(i, u, nodeCount, \"out of range\");\n }\n if (seen[u] === 1) {\n throw selectionError(i, u, nodeCount, \"repeated\");\n }\n seen[u] = 1;\n origin[i] = u;\n }\n return origin;\n }\n checkMaskLength(selection.mask, nodeCount, \"nodes\");\n return maskToIndices(selection.mask, nodeCount);\n}\n\n/**\n * The inverse of a new -> source node list: source -> new or INVALID_INDEX.\n * @param origin - new -> source\n * @param nodeCount - the source node count\n * @returns the remap\n */\nfunction invertOrigin(origin: U32, nodeCount: number): U32 {\n const remap = new Uint32Array(nodeCount).fill(INVALID_INDEX);\n for (let i = 0; i < origin.length; i++) {\n remap[origin[i]] = i;\n }\n return remap;\n}\n\n/**\n * Assemble a derived graph over a gathered node space (inducedSubgraph, relabel): the node table and\n * id map gathered through `nodeOrigin`, the edge table gathered through the edge grouping (or the\n * source table with refersTo node values rewritten when the edge space is unchanged).\n * @param source - the source snapshot\n * @param list - the source edge list\n * @param nodeOrigin - new -> source node, or null for the identity\n * @param grouping - the edge grouping\n * @returns the derived parts\n */\nfunction deriveOverNodeSpace(\n source: GraphSnapshot,\n list: EdgeListView,\n nodeOrigin: U32 | null,\n grouping: EdgeGrouping,\n): DerivedParts {\n const nodeCount = nodeOrigin === null ? source.nodeCount : nodeOrigin.length;\n const nodeRemap = nodeOrigin === null ? null : invertOrigin(nodeOrigin, source.nodeCount);\n const { src, dst } = gatherEndpoints(list, grouping, nodeRemap);\n const weights = reduceWeights(list.weights, grouping, \"first\");\n const core = buildCore({ directed: source.directed, nodeCount, edgeCount: grouping.count, src, dst, weights });\n const refs = { node: nodeRemap, edge: grouping.remap };\n const nodes = nodeOrigin === null ? source.nodes : gatherTable(source.nodes, nodeOrigin, refs);\n const ids = nodeOrigin === null ? source.ids : gatherNodeIdMap(source.ids, nodeOrigin);\n const edges = reduceEdgeTable(source, grouping, undefined, nodeRemap);\n const parts = assembleParts(source, core, {\n directed: source.directed,\n nodeCount,\n edgeCount: grouping.count,\n ids,\n nodes,\n edges,\n extensions: remapExtensions(source, nodeRemap, grouping.remap),\n });\n return {\n parts,\n nodeOrigin,\n edgeOrigin: grouping.origin,\n nodeRemap,\n edgeRemap: grouping.remap,\n blockSizes: null,\n report: { droppedEdges: grouping.dropped, mergedEdges: grouping.merged },\n };\n}\n\n/**\n * `inducedSubgraph(selection)`: the subgraph on a node selection with every edge whose endpoints are\n * both kept (design section 7.3); a compact new node space unless the selection is the identity.\n * @param source - the source snapshot\n * @param list - the source edge list\n * @param selection - an index list (new index order) or a packed mask (ascending)\n * @returns the derived parts\n */\nexport function deriveInducedSubgraph(\n source: GraphSnapshot,\n list: EdgeListView,\n selection: U32 | { readonly mask: NodeMask },\n): DerivedParts {\n const origin = resolveSelection(source, selection);\n const identity = isIdentitySelection(origin, source.nodeCount);\n const nodeOrigin = identity ? null : origin;\n const nodeRemap = identity ? null : invertOrigin(origin, source.nodeCount);\n const grouping =\n nodeRemap === null\n ? groupingFromPredicate(source.edgeCount, () => true)\n : groupingFromPredicate(\n source.edgeCount,\n (e) => nodeRemap[list.src[e]] !== INVALID_INDEX && nodeRemap[list.dst[e]] !== INVALID_INDEX,\n );\n return deriveOverNodeSpace(source, list, nodeOrigin, grouping);\n}\n\n/**\n * `relabel(perm)`: the node space permuted with `perm[newIndex] = oldIndex`, edge order preserved\n * (design section 7.3); E_INVALID_PERMUTATION unless perm is a permutation of 0..n-1.\n * @param source - the source snapshot\n * @param list - the source edge list\n * @param perm - the permutation\n * @returns the derived parts\n */\nexport function deriveRelabel(source: GraphSnapshot, list: EdgeListView, perm: U32): DerivedParts {\n const { nodeCount } = source;\n if (perm.length !== nodeCount) {\n throw new GraphFormatError(\"E_INVALID_PERMUTATION\", `perm has ${perm.length} entries, expected ${nodeCount}`, {\n expected: nodeCount,\n found: perm.length,\n });\n }\n const seen = new Uint8Array(nodeCount);\n for (let i = 0; i < nodeCount; i++) {\n const u = perm[i];\n if (u >= nodeCount || seen[u] === 1) {\n throw new GraphFormatError(\n \"E_INVALID_PERMUTATION\",\n `perm[${i}] = ${u} is out of range or repeated (nodeCount ${nodeCount})`,\n { index: i, found: u, nodeCount },\n );\n }\n seen[u] = 1;\n }\n const nodeOrigin = isIdentity(perm) ? null : perm.slice();\n const grouping = groupingFromPredicate(source.edgeCount, () => true);\n return deriveOverNodeSpace(source, list, nodeOrigin, grouping);\n}\n\n// ============================================================ toUndirected, transpose\n\n/**\n * `toUndirected(options)` on a directed snapshot (design section 7.3): every edge becomes undirected;\n * reciprocal pairs u -> v / v -> u (paired k-th to k-th among parallels, in edge order) collapse to\n * one edge keeping the lower index's row and the reduced weight (default \"first\"); with\n * `reciprocal: true` only paired edges survive. Self-loops are kept.\n * @param source - a directed snapshot\n * @param list - the source edge list\n * @param options - reciprocal filtering and the weight reducer\n * @returns the derived parts\n */\nexport function deriveToUndirected(\n source: GraphSnapshot,\n list: EdgeListView,\n options: ToUndirectedOptions = {},\n): DerivedParts {\n const reciprocal = options.reciprocal === true;\n const reducer = assertOneOf(\"weights\", options.weights, WEIGHT_REDUCERS) ?? \"first\";\n const { nodeCount, edgeCount, rowPtr, colIdx, arcToEdge } = source;\n const survivorOf = new Uint32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n survivorOf[e] = reciprocal && list.src[e] !== list.dst[e] ? INVALID_INDEX : e;\n }\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n let a = rowPtr[u];\n while (a < end) {\n const v = colIdx[a];\n let g = a + 1;\n while (g < end && colIdx[g] === v) {\n g++;\n }\n if (v > u) {\n const [lo, hi] = arcRangeIn(rowPtr, colIdx, v, u);\n const pairs = Math.min(g - a, hi - lo);\n for (let i = 0; i < pairs; i++) {\n const e1 = arcToEdge[a + i];\n const e2 = arcToEdge[lo + i];\n const low = Math.min(e1, e2);\n const high = Math.max(e1, e2);\n survivorOf[low] = low;\n survivorOf[high] = low;\n }\n }\n a = g;\n }\n }\n const grouping = groupingFromSurvivors(survivorOf);\n const { src, dst } = gatherEndpoints(list, grouping, null);\n const weights = reduceWeights(list.weights, grouping, reducer);\n const core = buildCore({ directed: false, nodeCount, edgeCount: grouping.count, src, dst, weights });\n const edges = reduceEdgeTable(source, grouping, undefined, null);\n const parts = assembleParts(source, core, {\n directed: false,\n nodeCount,\n edgeCount: grouping.count,\n ids: source.ids,\n nodes: source.nodes,\n edges,\n extensions: remapExtensions(source, null, grouping.remap),\n });\n return {\n parts,\n nodeOrigin: null,\n edgeOrigin: grouping.origin,\n nodeRemap: null,\n edgeRemap: grouping.remap,\n blockSizes: null,\n report: { droppedEdges: grouping.dropped, mergedEdges: grouping.merged },\n };\n}\n\n/**\n * `transpose()` on a directed snapshot (design section 7.3): the orientation of every edge swapped by\n * adopting the reverse view's arrays as the core (zero copy, so `arena` is null); node and edge\n * spaces unchanged, tables shared.\n * @param source - a directed snapshot\n * @param reverse - its reverse view\n * @returns the derived parts\n */\nexport function deriveTranspose(source: GraphSnapshot, reverse: ReverseView): DerivedParts {\n const { nodeCount, edgeCount, arcCount, selfLoopCount } = source;\n const revArcToEdge = reverse.arcToEdge;\n const identity = isIdentity(revArcToEdge);\n let arcToEdge: U32 | null = null;\n let edgeToArc: U32 | null = null;\n if (!identity) {\n arcToEdge = revArcToEdge;\n edgeToArc = new Uint32Array(edgeCount);\n for (let k = 0; k < arcCount; k++) {\n edgeToArc[revArcToEdge[k]] = k;\n }\n }\n const flags = computeFlags({\n directed: true,\n nodeCount,\n rowPtr: reverse.rowPtr,\n colIdx: reverse.colIdx,\n weights: reverse.weights,\n arcToEdge,\n selfLoopCount,\n });\n // the adopted arrays stay held by the source's cached reverse view (design section 9.1)\n noteShared(reverse.rowPtr.buffer);\n noteShared(reverse.colIdx.buffer);\n if (reverse.weights !== null) {\n noteShared(reverse.weights.buffer);\n }\n if (arcToEdge !== null) {\n noteShared(arcToEdge.buffer);\n }\n const parts: SnapshotParts = {\n label: source.label,\n serial: null,\n directed: true,\n nodeCount,\n edgeCount,\n arcCount,\n selfLoopCount,\n rowPtr: reverse.rowPtr,\n colIdx: reverse.colIdx,\n weights: reverse.weights,\n arcToEdge,\n edgeToArc,\n flags,\n ids: source.ids,\n nodes: source.nodes,\n edges: source.edges,\n graph: source.graph,\n extensions: source.extensions,\n meta: source.meta,\n arena: null,\n checksum: false,\n };\n return {\n parts,\n nodeOrigin: null,\n edgeOrigin: null,\n nodeRemap: null,\n edgeRemap: null,\n blockSizes: null,\n report: NO_REPORT,\n };\n}\n\n// ============================================================ simplified\n\n/**\n * `simplified(options)` (design section 7.3): one edge per (u, v) group (parallels are adjacent by\n * I4; undirected groups are unordered pairs), survivor = lowest index, weights per `weights`\n * (default \"first\"), self-loops kept or dropped, other edge columns per `edgeReducers` (default: the\n * survivor's row). `flags.multigraph` is false afterwards.\n * @param source - the source snapshot\n * @param list - the source edge list\n * @param options - reducers and self-loop policy\n * @returns the derived parts\n */\nexport function deriveSimplified(\n source: GraphSnapshot,\n list: EdgeListView,\n options: SimplifyOptions = {},\n): DerivedParts {\n const reducer = assertOneOf(\"weights\", options.weights, WEIGHT_REDUCERS) ?? \"first\";\n const dropLoops = assertOneOf(\"selfLoops\", options.selfLoops, [\"keep\", \"drop\"] as const) === \"drop\";\n checkReducers(\"edgeReducers\", options.edgeReducers);\n const { nodeCount, edgeCount, rowPtr, colIdx, arcToEdge } = source;\n const survivorOf = new Uint32Array(edgeCount).fill(INVALID_INDEX);\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n let a = rowPtr[u];\n while (a < end) {\n const v = colIdx[a];\n let g = a + 1;\n while (g < end && colIdx[g] === v) {\n g++;\n }\n if (source.directed || v >= u) {\n if (!(v === u && dropLoops)) {\n const survivor = arcToEdge[a];\n for (let i = a; i < g; i++) {\n survivorOf[arcToEdge[i]] = survivor;\n }\n }\n }\n a = g;\n }\n }\n const grouping = groupingFromSurvivors(survivorOf);\n const { src, dst } = gatherEndpoints(list, grouping, null);\n const weights = reduceWeights(list.weights, grouping, reducer);\n const core = buildCore({ directed: source.directed, nodeCount, edgeCount: grouping.count, src, dst, weights });\n const edges = reduceEdgeTable(source, grouping, options.edgeReducers, null);\n const parts = assembleParts(source, core, {\n directed: source.directed,\n nodeCount,\n edgeCount: grouping.count,\n ids: source.ids,\n nodes: source.nodes,\n edges,\n extensions: remapExtensions(source, null, grouping.remap),\n });\n return {\n parts,\n nodeOrigin: null,\n edgeOrigin: grouping.origin,\n nodeRemap: null,\n edgeRemap: grouping.remap,\n blockSizes: null,\n report: { droppedEdges: grouping.dropped, mergedEdges: grouping.merged },\n };\n}\n\n// ============================================================ contract\n\n/**\n * Renumber an arbitrary u32 labelling to dense 0..k-1 in first-seen order (design section 7.5; what\n * `contract()` does with non-dense labels). INVALID_INDEX is not a legal label (E_PARTITION).\n * @param labels - the labels\n * @param out - an optional destination of the same length (may be `labels` itself)\n * @returns the dense labels and the block count\n */\nexport function renumberPartition(labels: U32, out?: U32): { readonly labels: U32; readonly count: number } {\n const n = labels.length;\n const result = out ?? new Uint32Array(n);\n if (result.length !== n) {\n throw new GraphFormatError(\"E_COLUMN_LENGTH\", `out has ${result.length} entries, expected ${n}`, {\n expected: n,\n found: result.length,\n });\n }\n let maxLabel = 0;\n for (let i = 0; i < n; i++) {\n const label = labels[i];\n if (label === INVALID_INDEX) {\n throw new GraphFormatError(\"E_PARTITION\", `labels[${i}] is INVALID_INDEX`, { index: i });\n }\n if (label > maxLabel) {\n maxLabel = label;\n }\n }\n let count = 0;\n if (maxLabel < 4 * n + 1024) {\n const lookup = new Uint32Array(maxLabel + 1).fill(INVALID_INDEX);\n for (let i = 0; i < n; i++) {\n const label = labels[i];\n let dense = lookup[label];\n if (dense === INVALID_INDEX) {\n dense = count++;\n lookup[label] = dense;\n }\n result[i] = dense;\n }\n } else {\n const lookup = new Map<number, number>();\n for (let i = 0; i < n; i++) {\n const label = labels[i];\n let dense = lookup.get(label);\n if (dense === undefined) {\n dense = count++;\n lookup.set(label, dense);\n }\n result[i] = dense;\n }\n }\n return { labels: result, count };\n}\n\n/**\n * The dense block labels of a contract partition (design section 7.3): labels already forming the\n * set 0..k-1 are kept, any other labelling is renumbered in first-seen order. E_PARTITION for a wrong\n * length or an INVALID_INDEX label.\n * @param partition - the caller's labels\n * @param nodeCount - the node count\n * @returns the dense labels (a fresh array) and the block count\n */\nfunction denseBlocks(partition: U32, nodeCount: number): { readonly labels: U32; readonly count: number } {\n if (partition.length !== nodeCount) {\n throw new GraphFormatError(\n \"E_PARTITION\",\n `partition has ${partition.length} entries, expected nodeCount ${nodeCount}`,\n { expected: nodeCount, found: partition.length },\n );\n }\n let maxLabel = -1;\n for (let i = 0; i < nodeCount; i++) {\n const label = partition[i];\n if (label === INVALID_INDEX) {\n throw new GraphFormatError(\"E_PARTITION\", `partition[${i}] is INVALID_INDEX`, { index: i });\n }\n if (label > maxLabel) {\n maxLabel = label;\n }\n }\n if (maxLabel < nodeCount) {\n const seen = new Uint8Array(maxLabel + 1);\n let distinct = 0;\n for (let i = 0; i < nodeCount; i++) {\n if (seen[partition[i]] === 0) {\n seen[partition[i]] = 1;\n distinct++;\n }\n }\n if (distinct === maxLabel + 1) {\n return { labels: partition.slice(), count: maxLabel + 1 };\n }\n }\n return renumberPartition(partition);\n}\n\n/**\n * Reduce the node columns of a contracted graph per `nodeReducers` over the blocks; columns not named\n * are dropped (design section 7.3).\n * @param source - the source snapshot\n * @param blocks - the block labels (source node -> block)\n * @param blockCount - the number of blocks\n * @param blockOrigin - block -> lowest source node\n * @param reducers - the named reducers\n * @returns the new node table\n */\nfunction contractNodeTable(\n source: GraphSnapshot,\n blocks: U32,\n blockCount: number,\n blockOrigin: U32,\n reducers: Readonly<Record<string, ColumnReducer>> | undefined,\n): AttributeTable {\n const columns: Column[] = [];\n if (reducers !== undefined) {\n const grouping: EdgeGrouping = { count: blockCount, remap: blocks, origin: blockOrigin, dropped: 0, merged: 0 };\n for (const column of source.nodes) {\n const reducer = reducers[column.meta.name];\n if (reducer === undefined) {\n continue;\n }\n const reduced = reduceColumn(column, grouping, reducer);\n if (reduced !== null) {\n columns.push(reduced);\n }\n }\n }\n return new AttributeTableClass({ domain: \"node\", rowCount: blockCount, columns });\n}\n\n/**\n * Group the kept contracted edges by block pair with two stable counting-sort passes (by second key,\n * then by first key), so each run of equal pairs is one group and the first member of a run is the\n * lowest source edge index.\n * @param first - the first key of every source edge (INVALID_INDEX = dropped)\n * @param second - the second key of every source edge\n * @param blockCount - the key range\n * @returns source edge -> survivor (INVALID_INDEX when dropped)\n */\nfunction groupByBlockPair(first: U32, second: U32, blockCount: number): U32 {\n const edgeCount = first.length;\n const kept: number[] = [];\n for (let e = 0; e < edgeCount; e++) {\n if (first[e] !== INVALID_INDEX) {\n kept.push(e);\n }\n }\n const start = new Uint32Array(blockCount + 1);\n for (const e of kept) {\n start[second[e] + 1]++;\n }\n for (let b = 0; b < blockCount; b++) {\n start[b + 1] += start[b];\n }\n const bySecond = new Uint32Array(kept.length);\n for (const e of kept) {\n bySecond[start[second[e]]++] = e;\n }\n start.fill(0);\n for (const e of kept) {\n start[first[e] + 1]++;\n }\n for (let b = 0; b < blockCount; b++) {\n start[b + 1] += start[b];\n }\n const sorted = new Uint32Array(kept.length);\n for (let k = 0; k < bySecond.length; k++) {\n const e = bySecond[k];\n sorted[start[first[e]]++] = e;\n }\n const survivorOf = new Uint32Array(edgeCount).fill(INVALID_INDEX);\n let runStart = 0;\n while (runStart < sorted.length) {\n const leader = sorted[runStart];\n let runEnd = runStart + 1;\n while (\n runEnd < sorted.length &&\n first[sorted[runEnd]] === first[leader] &&\n second[sorted[runEnd]] === second[leader]\n ) {\n runEnd++;\n }\n for (let k = runStart; k < runEnd; k++) {\n survivorOf[sorted[k]] = leader;\n }\n runStart = runEnd;\n }\n return survivorOf;\n}\n\n/**\n * `contract(partition, options)` (design section 7.3): the nodes of each block become one node (block\n * indices as labels, ids 0..k-1), every source edge contributes once: an inter-block edge becomes an\n * edge block(u) -> block(v), an intra-block edge one self-loop with weight w, kept or dropped per\n * `selfLoops`; parallels merge per `parallel` with the `weights` reducer (default \"sum\"; on an\n * unweighted source \"sum\" materialises multiplicities). Node and edge columns are kept only through\n * `nodeReducers` / `edgeReducers`.\n * @param source - the source snapshot\n * @param list - the source edge list\n * @param partition - one label per node; E_PARTITION for a wrong length or an INVALID_INDEX label\n * @param options - the contraction options\n * @returns the derived parts with blockSizes\n */\nexport function deriveContract(\n source: GraphSnapshot,\n list: EdgeListView,\n partition: U32,\n options: ContractOptions = {},\n): DerivedParts {\n const reducer = assertOneOf(\"weights\", options.weights, WEIGHT_REDUCERS) ?? \"sum\";\n const dropLoops = assertOneOf(\"selfLoops\", options.selfLoops, [\"keep\", \"drop\"] as const) === \"drop\";\n const merge = (assertOneOf(\"parallel\", options.parallel, [\"merge\", \"keep\"] as const) ?? \"merge\") === \"merge\";\n checkReducers(\"nodeReducers\", options.nodeReducers);\n checkReducers(\"edgeReducers\", options.edgeReducers);\n const { nodeCount, edgeCount } = source;\n const { labels: blocks, count: blockCount } = denseBlocks(partition, nodeCount);\n const blockSizes = new Uint32Array(blockCount);\n const blockOrigin = new Uint32Array(blockCount).fill(INVALID_INDEX);\n for (let u = 0; u < nodeCount; u++) {\n const b = blocks[u];\n blockSizes[b]++;\n if (blockOrigin[b] === INVALID_INDEX) {\n blockOrigin[b] = u;\n }\n }\n const first = new Uint32Array(edgeCount);\n const second = new Uint32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n const bu = blocks[list.src[e]];\n const bv = blocks[list.dst[e]];\n if (bu === bv && dropLoops) {\n first[e] = INVALID_INDEX;\n second[e] = INVALID_INDEX;\n } else if (source.directed || bu <= bv) {\n first[e] = bu;\n second[e] = bv;\n } else {\n first[e] = bv;\n second[e] = bu;\n }\n }\n let survivorOf: U32;\n if (merge) {\n survivorOf = groupByBlockPair(first, second, blockCount);\n } else {\n survivorOf = new Uint32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n survivorOf[e] = first[e] === INVALID_INDEX ? INVALID_INDEX : e;\n }\n }\n const grouping = groupingFromSurvivors(survivorOf);\n const { src, dst } = gatherEndpoints(list, grouping, blocks);\n const weights = reduceWeights(list.weights, grouping, reducer);\n const core = buildCore({\n directed: source.directed,\n nodeCount: blockCount,\n edgeCount: grouping.count,\n src,\n dst,\n weights,\n });\n const nodes = contractNodeTable(source, blocks, blockCount, blockOrigin, options.nodeReducers);\n const edgeColumns: Column[] = [];\n if (options.edgeReducers !== undefined) {\n for (const column of source.edges) {\n const columnReducer = options.edgeReducers[column.meta.name];\n if (columnReducer === undefined) {\n continue;\n }\n const reduced = reduceColumn(column, grouping, columnReducer);\n if (reduced !== null) {\n edgeColumns.push(reduced);\n }\n }\n }\n const edges = new AttributeTableClass({ domain: \"edge\", rowCount: grouping.count, columns: edgeColumns });\n const parts = assembleParts(source, core, {\n directed: source.directed,\n nodeCount: blockCount,\n edgeCount: grouping.count,\n ids: identityNodeIdMap(blockCount),\n nodes,\n edges,\n extensions: remapExtensions(source, blocks, grouping.remap),\n });\n return {\n parts,\n nodeOrigin: blockOrigin,\n edgeOrigin: grouping.origin,\n nodeRemap: blocks,\n edgeRemap: grouping.remap,\n blockSizes,\n report: { droppedEdges: grouping.dropped, mergedEdges: grouping.merged },\n };\n}\n\n// ============================================================ withColumns\n\n/**\n * `withColumns(nodes, edges)` (design section 7.3): the parts of a snapshot sharing the core, the id\n * map and the SERIAL of the source with a CLONED column set plus the given columns (the graph table is\n * cloned too; extension tables are shared).\n * @param source - the source snapshot\n * @param nodes - node columns to add, keyed by name\n * @param edges - edge columns to add, keyed by name\n * @param arcToEdge - the source's permutation arrays as the constructor holds them (null when identity)\n * @param edgeToArc - see arcToEdge\n * @returns the parts\n */\nexport function withColumnsParts(\n source: GraphSnapshot,\n nodes: Readonly<Record<string, TypedArrayData | ColumnInput>> | undefined,\n edges: Readonly<Record<string, TypedArrayData | ColumnInput>> | undefined,\n arcToEdge: U32 | null,\n edgeToArc: U32 | null,\n): SnapshotParts {\n return {\n label: source.label,\n serial: source.serial,\n directed: source.directed,\n nodeCount: source.nodeCount,\n edgeCount: source.edgeCount,\n arcCount: source.arcCount,\n selfLoopCount: source.selfLoopCount,\n rowPtr: source.rowPtr,\n colIdx: source.colIdx,\n weights: source.weights,\n arcToEdge,\n edgeToArc,\n flags: source.flags,\n ids: source.ids,\n nodes: tableWithColumns(source.nodes, nodes ?? {}),\n edges: tableWithColumns(source.edges, edges ?? {}),\n graph: source.graph.clone(),\n extensions: source.extensions,\n meta: source.meta,\n arena: source.arena,\n checksum: false,\n };\n}\n","/**\n * Content hashing and checksums of @graphty/graph-format (design sections 5.8 and 9.3).\n *\n * `contentHash()` is a 64-bit hash of the core arrays computed as two independent 32-bit FNV-1a-style\n * lanes over u32 words with `Math.imul`, returned as 16 hex characters: the key a cache uses for a\n * snapshot's topology. The same hasher produces the per-array checksums that `freeze({ checksum:\n * true })` records and `validate({ checksum: true })` compares, so a consumer that wrote into a frozen\n * array or a shared view is caught by the tests that opt in (invariant I17).\n *\n * The hash is a pure function of the topology: it covers `directed`, the four counts, `rowPtr`,\n * `colIdx`, `weights` (as raw f32 bit patterns), `arcToEdge` and `edgeToArc`. An identity permutation\n * is hashed as the sequence 0..len-1 WITHOUT materialising it, so two snapshots with the same\n * topology hash identically whether or not their getters were touched (P11). Nothing here depends on\n * the arena, the id map or the columns.\n */\n\nimport { isColumnDetached } from \"../columns/column.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type Column, type GraphSnapshot } from \"../types/index.js\";\nimport { unsupportedDtype } from \"../util/typed-array.js\";\n\n/** Lane A: the 32-bit FNV-1a offset basis. */\nconst LANE_A_BASIS = 0x811c9dc5;\n/** Lane A: the 32-bit FNV prime. */\nconst LANE_A_PRIME = 0x01000193;\n/** Lane B: the high word of the 64-bit FNV offset basis (0xcbf29ce484222325), as an independent seed. */\nconst LANE_B_BASIS = 0xcbf29ce4;\n/** Lane B: an odd multiplier unrelated to the FNV prime (the MurmurHash2 constant), so the lanes decorrelate. */\nconst LANE_B_MULTIPLIER = 0x5bd1e995;\n\n/**\n * Two-lane FNV-1a-style hasher over u32 words (design section 9.3). Lane A is standard 32-bit FNV-1a\n * applied word-wise (`h = imul(h ^ w, 0x01000193)`); lane B uses a different basis and multiplier\n * (`h = imul(h ^ w, 0x5bd1e995)`) and additionally rotates the word by 16 bits before mixing so the\n * two lanes never agree on which bits they weight. `digest()` renders both lanes as 8 zero-padded hex\n * characters each, lane A first.\n */\nexport class Fnv1aHasher {\n private laneA: number;\n private laneB: number;\n\n /** Start a fresh hasher at the two offset bases. */\n constructor() {\n this.laneA = LANE_A_BASIS;\n this.laneB = LANE_B_BASIS;\n }\n\n /**\n * Mix one u32 word (any number is coerced with `>>> 0`).\n * @param word - the word to mix\n * @returns this hasher\n */\n word(word: number): this {\n const w = word >>> 0;\n this.laneA = Math.imul(this.laneA ^ w, LANE_A_PRIME) >>> 0;\n const rotated = ((w << 16) | (w >>> 16)) >>> 0;\n this.laneB = Math.imul(this.laneB ^ rotated, LANE_B_MULTIPLIER) >>> 0;\n return this;\n }\n\n /**\n * Mix a length prefix followed by every word of a u32 array, so arrays of different lengths with a\n * common prefix hash differently and consecutive arrays cannot be re-split.\n * @param words - the words to mix\n * @returns this hasher\n */\n words(words: Uint32Array): this {\n this.word(words.length);\n for (let i = 0; i < words.length; i++) {\n this.word(words[i]);\n }\n return this;\n }\n\n /**\n * Mix the sequence 0..length-1 (an identity permutation) with the same framing as `words()`, without\n * allocating it.\n * @param length - the permutation length\n * @returns this hasher\n */\n identity(length: number): this {\n this.word(length);\n for (let i = 0; i < length; i++) {\n this.word(i);\n }\n return this;\n }\n\n /**\n * Mix a byte length prefix followed by the bytes of any ArrayBufferView, four bytes per word\n * (little-endian packing, the last word zero-padded). A view whose byte range is 4-byte aligned\n * is read as u32 words directly.\n * @param view - the bytes to mix\n * @returns this hasher\n */\n bytes(view: ArrayBufferView): this {\n const { byteLength, byteOffset } = view;\n this.word(byteLength);\n if (byteOffset % 4 === 0 && byteLength % 4 === 0) {\n const words = new Uint32Array(view.buffer, byteOffset, byteLength / 4);\n for (let i = 0; i < words.length; i++) {\n this.word(words[i]);\n }\n return this;\n }\n const bytes = new Uint8Array(view.buffer, byteOffset, byteLength);\n let i = 0;\n for (; i + 4 <= byteLength; i += 4) {\n this.word(bytes[i] | (bytes[i + 1] << 8) | (bytes[i + 2] << 16) | (bytes[i + 3] << 24));\n }\n if (i < byteLength) {\n let tail = 0;\n for (let k = 0; i + k < byteLength; k++) {\n tail |= bytes[i + k] << (8 * k);\n }\n this.word(tail);\n }\n return this;\n }\n\n /**\n * Mix a JS string as its length followed by its UTF-16 code units.\n * @param text - the string to mix\n * @returns this hasher\n */\n text(text: string): this {\n this.word(text.length);\n for (let i = 0; i < text.length; i++) {\n this.word(text.charCodeAt(i));\n }\n return this;\n }\n\n /**\n * The 16-character lowercase hex digest: lane A then lane B, each 8 zero-padded characters.\n * @returns the digest\n */\n digest(): string {\n return this.laneA.toString(16).padStart(8, \"0\") + this.laneB.toString(16).padStart(8, \"0\");\n }\n}\n\n/**\n * The digest of one typed array's bytes (a core array, a view array, a column buffer).\n * @param view - the array to hash\n * @returns the 16-character hex digest\n */\nexport function hashTypedArray(view: ArrayBufferView): string {\n return new Fnv1aHasher().bytes(view).digest();\n}\n\n/**\n * Mix everything that determines a column's contents: dtype, length, null count, validity words,\n * and per dtype the data / codes / dictionary / offsets / utf8 / child / json text. Used for the\n * immutable-column checksums of design section 5.8.\n * @param hasher - the hasher to mix into\n * @param column - the column\n */\nfunction mixColumn(hasher: Fnv1aHasher, column: Column): void {\n hasher.text(column.dtype).word(column.length).word(column.nullCount);\n if (column.validity !== null) {\n hasher.words(column.validity);\n } else {\n hasher.word(0);\n }\n const { dtype } = column;\n switch (dtype) {\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n case \"bool\":\n hasher.bytes(column.data);\n break;\n case \"dict\":\n hasher.words(column.codes).word(column.dictionary.length);\n for (const entry of column.dictionary) {\n hasher.text(entry);\n }\n break;\n case \"string\":\n hasher.words(column.offsets).bytes(column.utf8);\n break;\n case \"list\":\n hasher.words(column.offsets);\n mixColumn(hasher, column.child);\n break;\n case \"json\":\n hasher.text(JSON.stringify(column.values));\n break;\n default:\n unsupportedDtype(dtype);\n }\n}\n\n/**\n * The digest of a column's contents (data, validity, dictionary, strings, child, json text).\n * @param column - the column to hash\n * @returns the 16-character hex digest\n */\nexport function hashColumn(column: Column): string {\n if (isColumnDetached(column)) {\n throw new GraphFormatError(\"E_DETACHED\", `column \"${column.meta.name}\" was transferred away`, {\n column: column.meta.name,\n });\n }\n const hasher = new Fnv1aHasher();\n mixColumn(hasher, column);\n return hasher.digest();\n}\n\n/**\n * The content hash of a snapshot's topology (design section 9.3): `directed`, the four counts, then\n * `rowPtr`, `colIdx`, `weights` (raw f32 bit patterns; an absent array hashes as length 0),\n * `arcToEdge` and `edgeToArc`, with an identity permutation hashed as 0..len-1 without being\n * materialised (P11: the digest does not depend on which getters were touched).\n * @param snapshot - the snapshot to hash\n * @returns the 16-character hex digest\n */\nexport function contentHashOf(snapshot: GraphSnapshot): string {\n const hasher = new Fnv1aHasher();\n hasher\n .word(snapshot.directed ? 1 : 0)\n .word(snapshot.nodeCount)\n .word(snapshot.edgeCount)\n .word(snapshot.arcCount)\n .word(snapshot.selfLoopCount);\n hasher.words(snapshot.rowPtr).words(snapshot.colIdx);\n if (snapshot.weights === null) {\n hasher.word(0);\n } else {\n hasher.bytes(snapshot.weights);\n }\n if (snapshot.flags.arcToEdgeIsIdentity) {\n hasher.identity(snapshot.arcCount).identity(snapshot.edgeCount);\n } else {\n hasher.words(snapshot.arcToEdge).words(snapshot.edgeToArc);\n }\n return hasher.digest();\n}\n","/**\n * The concrete GraphSnapshot class (design sections 3, 5.8, 7, 9.3 and 11.4) and its factory\n * `createSnapshot(parts)`, plus the boundary helpers `isGraphSnapshot` / `equalsTopology` (design\n * section 7.5) and the arena helpers a GPU consumer binds segments with (section 10.3).\n *\n * The object is frozen with `Object.freeze` so `snapshot.rowPtr = x` throws in strict mode; every\n * lazily populated member (the identity permutations of design section 3.1, the view cache of\n * section 7.2, the checksum records of section 5.8, the content hash, the edge id index) lives in\n * one mutable state record reachable only through a private field, which `Object.freeze` does not\n * reach. `arcToEdge` / `edgeToArc` are prototype getters that materialise an identity permutation on\n * first access outside the arena (never on the wire, never in `byteLength()`); `rowPtr`, `colIdx`\n * and `weights` are plain data properties so hot loops pay nothing. Every method that reads the core\n * throws `E_DETACHED` once the core buffer was transferred away (`detached` is derived:\n * `rowPtr.length === 0`).\n *\n * Views are computed by views.ts, queries by queries.ts, derived graphs by derived.ts (which returns\n * SnapshotParts that this module wraps), invariant checks by validate.ts and hashes by hash.ts. The\n * wire methods (`toWire`, `toBytes`, `toByteChunks`, `transferables`) call the wire module directly;\n * the wire module imports this one too, and the cycle is safe because each side reaches the other\n * only through hoisted function declarations invoked at call time, never at module load.\n */\n\nimport { dropGpuViewCache, isColumnDetached } from \"../columns/column.js\";\nimport { columnSetVersion } from \"../columns/table.js\";\nimport { FORMAT_VERSION, INVALID_INDEX, SNAPSHOT_BRAND } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { EdgeIdIndex } from \"../ids/edge-id-index.js\";\nimport { idMapBuffers, idMapDetached } from \"../ids/node-id-map.js\";\nimport {\n type ArenaLayout,\n type AttributeTable,\n type ByteLengthOptions,\n type Column,\n type ColumnInput,\n type ContractOptions,\n type CooView,\n type CoreArrayName,\n type DegreeOrderOptions,\n type DegreeOrderView,\n type DerivedGraph,\n type EdgeId,\n type EdgeListView,\n type EdgeMask,\n type F32,\n type F64,\n type GraphMeta,\n type GraphSnapshotContract,\n type NodeIdMap,\n type NodeMask,\n type ReverseView,\n type SimplifyOptions,\n type SnapshotFlags,\n type ToBytesOptions,\n type ToUndirectedOptions,\n type ToWireOptions,\n type TypedArrayData,\n type U8,\n type U32,\n type ValidateOptions,\n type ViewName,\n type WireSnapshot,\n} from \"../types/index.js\";\nimport { type SnapshotParts, type ViewCache } from \"../types/internal.js\";\nimport { assertOneOf } from \"../util/options.js\";\nimport { claimHolder } from \"../util/shared-buffers.js\";\nimport { toByteChunks, toBytes } from \"../wire/bytes.js\";\nimport { toWire, transferables } from \"../wire/to-wire.js\";\nimport {\n deriveContract,\n type DerivedParts,\n deriveFilterEdges,\n deriveInducedSubgraph,\n deriveRelabel,\n deriveSimplified,\n deriveToUndirected,\n deriveTranspose,\n deriveWithoutSelfLoops,\n identityDerived,\n withColumnsParts,\n} from \"./derived.js\";\nimport { contentHashOf, hashColumn, hashTypedArray } from \"./hash.js\";\nimport { arcRangeIn, arcSourceIn, findArcIn, multiplicityIn, selfLoopsAtIn } from \"./queries.js\";\nimport { validateFull, validateStructure } from \"./validate.js\";\nimport {\n computeCoo,\n computeDegreeOrder,\n computeEdgeList,\n computeMate,\n computeReverse,\n computeSelfLoops,\n computeSelfLoopWeight,\n computeSymmetric,\n computeTotalWeight,\n identityPermutation,\n rowLengths,\n rowWeightSums,\n sumDegrees,\n sumF64,\n viewArrays,\n viewByteLength,\n widenToF64,\n} from \"./views.js\";\n\n// ============================================================ module state\n\n/** The next process-unique serial (design section 5.8). */\nlet nextSerial = 1;\n\n/** Every view name in the order `cachedViews()` reports them. */\nconst VIEW_NAMES: readonly ViewName[] = [\n \"reverse\",\n \"coo\",\n \"edgeList\",\n \"outDegree\",\n \"inDegree\",\n \"degree\",\n \"weightedOutDegree\",\n \"weightedInDegree\",\n \"weightedDegree\",\n \"selfLoopWeight\",\n \"totalWeight\",\n \"selfLoopArcs\",\n \"selfLoopsPerNode\",\n \"mate\",\n \"degreeOrder\",\n \"reverseDegreeOrder\",\n \"symmetric\",\n];\n\n/**\n * The own enumerable property every snapshot carries whose value is a function, so that\n * `structuredClone(snapshot)` and `postMessage(snapshot)` throw `DataCloneError` immediately (design\n * section 7.5; the structured clone algorithm refuses functions and visits enumerable own\n * properties only).\n */\nexport const CLONE_GUARD_KEY = \"__graphtyNoStructuredClone\";\n\nexport { EMPTY_GRAPH_META } from \"./graph-meta.js\";\n\n/**\n * The value of the clone guard property.\n * @returns nothing\n */\nfunction cloneGuard(): void {\n return undefined;\n}\n\n/** The FNV-1a records of design section 5.8, kept when the snapshot was built with `checksum: true`. */\ninterface ChecksumRecords {\n /** Core array name -> digest (identity permutations recorded when materialised). */\n readonly core: Map<string, string>;\n /** Immutable column -> digest, at construction. */\n readonly columns: WeakMap<Column, string>;\n /** \"<view>.<member>\" -> digest, at first materialisation. */\n readonly views: Map<string, string>;\n}\n\n/** The mutable state behind a frozen snapshot object. */\ninterface SnapshotState {\n /** The arc -> edge permutation, or null until an identity permutation is materialised. */\n arcToEdge: U32 | null;\n /** The edge -> arc permutation, or null until an identity permutation is materialised. */\n edgeToArc: U32 | null;\n /** The view cache (one slot per ViewName). */\n readonly views: ViewCache;\n /** Checksum records, or null when the snapshot was built without `checksum: true`. */\n readonly checksums: ChecksumRecords | null;\n /** The cached content hash. */\n contentHash: string | null;\n /** The lazily built edge id index and the column it was built over. */\n edgeIds: { readonly version: number; readonly column: Column | null; readonly index: EdgeIdIndex | null } | null;\n}\n\n/** Module-private access to the state of a snapshot for the helpers below. */\nconst STATES = new WeakMap<GraphSnapshot, SnapshotState>();\n\n/**\n * A fresh view cache with every slot empty.\n * @returns the cache\n */\nfunction emptyViewCache(): ViewCache {\n return {\n reverse: null,\n coo: null,\n edgeList: null,\n outDegree: null,\n inDegree: null,\n degree: null,\n weightedOutDegree: null,\n weightedInDegree: null,\n weightedDegree: null,\n selfLoopWeight: null,\n totalWeight: null,\n selfLoopArcs: null,\n selfLoopsPerNode: null,\n mate: null,\n degreeOrder: null,\n reverseDegreeOrder: null,\n symmetric: null,\n };\n}\n\n/**\n * The E_INVALID_SNAPSHOT error of a SnapshotParts inconsistency caught at construction.\n * @param invariant - the invariant number\n * @param message - the description\n * @param details - the location\n * @returns the error\n */\nfunction partsError(invariant: string, message: string, details: Readonly<Record<string, unknown>>): GraphFormatError {\n return new GraphFormatError(\"E_INVALID_SNAPSHOT\", `invariant ${invariant} violated: ${message}`, {\n invariant,\n ...details,\n });\n}\n\n/**\n * The O(1) consistency checks the constructor runs on the parts a producer hands it (lengths and\n * the identity-flag rule); everything deeper is `validate()`.\n * @param parts - the parts\n */\nfunction checkParts(parts: SnapshotParts): void {\n const { nodeCount, edgeCount, arcCount, flags } = parts;\n if (parts.rowPtr.length !== nodeCount + 1) {\n throw partsError(\"I1\", `rowPtr has ${parts.rowPtr.length} entries, expected ${nodeCount + 1}`, {\n expected: nodeCount + 1,\n found: parts.rowPtr.length,\n });\n }\n if (parts.colIdx.length !== arcCount) {\n throw partsError(\"I1\", `colIdx has ${parts.colIdx.length} entries, expected ${arcCount}`, {\n expected: arcCount,\n found: parts.colIdx.length,\n });\n }\n if (parts.weights !== null && parts.weights.length !== arcCount) {\n throw partsError(\"I8\", `weights has ${parts.weights.length} entries, expected ${arcCount}`, {\n expected: arcCount,\n found: parts.weights.length,\n });\n }\n const identity = flags.arcToEdgeIsIdentity;\n if ((parts.arcToEdge === null) !== identity || (parts.edgeToArc === null) !== identity) {\n throw partsError(\"I9\", \"arcToEdge / edgeToArc must be null exactly when flags.arcToEdgeIsIdentity\", {\n flag: \"arcToEdgeIsIdentity\",\n found: identity,\n });\n }\n if (identity && (!parts.directed || arcCount !== edgeCount)) {\n throw partsError(\"I9\", \"flags.arcToEdgeIsIdentity requires a directed snapshot with arcCount === edgeCount\", {\n flag: \"arcToEdgeIsIdentity\",\n directed: parts.directed,\n arcCount,\n edgeCount,\n });\n }\n if (parts.arcToEdge !== null && parts.arcToEdge.length !== arcCount) {\n throw partsError(\"I5\", `arcToEdge has ${parts.arcToEdge.length} entries, expected ${arcCount}`, {\n expected: arcCount,\n found: parts.arcToEdge.length,\n });\n }\n if (parts.edgeToArc !== null && parts.edgeToArc.length !== edgeCount) {\n throw partsError(\"I5\", `edgeToArc has ${parts.edgeToArc.length} entries, expected ${edgeCount}`, {\n expected: edgeCount,\n found: parts.edgeToArc.length,\n });\n }\n if (parts.ids.size !== nodeCount) {\n throw partsError(\"I11\", `ids.size is ${parts.ids.size}, expected ${nodeCount}`, {\n expected: nodeCount,\n found: parts.ids.size,\n });\n }\n if (parts.nodes.rowCount !== nodeCount || parts.edges.rowCount !== edgeCount || parts.graph.rowCount !== 1) {\n throw partsError(\"I12\", \"table row counts do not match nodeCount / edgeCount / 1\", {\n nodes: parts.nodes.rowCount,\n edges: parts.edges.rowCount,\n graph: parts.graph.rowCount,\n });\n }\n}\n\n/**\n * Record the digests of every immutable column of a table.\n * @param records - the records\n * @param table - the table\n */\nfunction recordColumns(records: ChecksumRecords, table: AttributeTable): void {\n for (const column of table) {\n if (!column.meta.mutable) {\n records.columns.set(column, hashColumn(column));\n }\n }\n}\n\n// ============================================================ the class\n\n/**\n * The frozen graph (design section 3): a CSR core over 4-byte typed arrays, the id map, the\n * attribute tables, the flags and a per-instance view cache. Topology, counts, flags, id map and\n * immutable columns never change after construction (invariant I17); the column SET of `nodes` /\n * `edges` / `graph` and the CONTENTS of columns declared mutable are mutable side tables (design\n * section 5.8). Every view is a pure function of the core, memoised once and SHARED: a call returns\n * the cached array itself, so writing into a view is a contract violation; call `.slice()` for\n * scratch. Index-taking queries are total for in-range arguments and unchecked otherwise (design\n * section 11.1). Instances come from `createSnapshot()` (the builder, `fromCsr`, `fromWire` and the\n * derived-graph methods); `isGraphSnapshot()` recognises them structurally by brand and\n * formatVersion.\n */\nexport class GraphSnapshot implements GraphSnapshotContract {\n /** Symbol.for brand read by isGraphSnapshot() (design section 7.5). */\n readonly [SNAPSHOT_BRAND]: true;\n /** Process-unique identity of the CORE; shared by withColumns() snapshots (design section 5.8). */\n readonly serial: number;\n /** Debugging aid supplied at freeze. */\n readonly label: string | null;\n /** The data-model major (design section 13.5). */\n readonly formatVersion: 1;\n /** Whether the graph is directed. */\n readonly directed: boolean;\n /** n (invariant I3). */\n readonly nodeCount: number;\n /** Number of logical edges (invariant I13). */\n readonly edgeCount: number;\n /** colIdx.length (invariants I6, I7). */\n readonly arcCount: number;\n /** Logical edges with source === target. */\n readonly selfLoopCount: number;\n /** nodeCount + 1 row offsets (invariant I1). */\n readonly rowPtr: U32;\n /** Target node index of each arc, sorted within each row (invariants I2, I4). */\n readonly colIdx: U32;\n /** arcCount f32 weights; null when unweighted. */\n readonly weights: F32 | null;\n /** Flags kernels branch on (design section 3.8). */\n readonly flags: SnapshotFlags;\n /** The id map (design section 4). */\n readonly ids: NodeIdMap;\n /** Node attribute table, rowCount === nodeCount. */\n readonly nodes: AttributeTable;\n /** Edge attribute table, rowCount === edgeCount, indexed by logical edge. */\n readonly edges: AttributeTable;\n /** Graph attribute table, rowCount === 1. */\n readonly graph: AttributeTable;\n /** Extension tables keyed by name (design section 5.10). */\n readonly extensions: ReadonlyMap<string, AttributeTable>;\n /** Graph-level metadata (design section 5.9). */\n readonly meta: GraphMeta;\n /** The arena holding the core arrays, or null (design section 10.3). */\n readonly arena: ArenaLayout | null;\n\n /**\n * The lazily populated members (design section 5.8): defined as a NON-enumerable own property in\n * the constructor (`declare` keeps tsc from emitting a field), so `Object.keys(snapshot)` lists\n * exactly the public fields plus the documented clone guard, and JSON / spread / structured\n * clone never walk the view cache.\n */\n declare private readonly state: SnapshotState;\n\n /**\n * Wrap prepared parts. Producers call `createSnapshot()`; the constructor is not part of the public\n * surface. The producer has established I1-I13; the constructor checks the O(1) length rules,\n * records checksums when asked, freezes the object and installs the clone guard.\n * @param parts - the parts (no array may alias memory a builder can still write, invariant I18)\n * @internal\n */\n constructor(parts: SnapshotParts) {\n checkParts(parts);\n this[SNAPSHOT_BRAND] = true;\n this.serial = parts.serial ?? nextSerial++;\n this.label = parts.label;\n this.formatVersion = FORMAT_VERSION;\n this.directed = parts.directed;\n this.nodeCount = parts.nodeCount;\n this.edgeCount = parts.edgeCount;\n this.arcCount = parts.arcCount;\n this.selfLoopCount = parts.selfLoopCount;\n this.rowPtr = parts.rowPtr;\n this.colIdx = parts.colIdx;\n this.weights = parts.weights;\n this.flags = Object.freeze({ ...parts.flags });\n this.ids = parts.ids;\n this.nodes = parts.nodes;\n this.edges = parts.edges;\n this.graph = parts.graph;\n this.extensions = parts.extensions;\n this.meta = parts.meta;\n this.arena = parts.arena;\n let checksums: ChecksumRecords | null = null;\n if (parts.checksum) {\n checksums = { core: new Map(), columns: new WeakMap(), views: new Map() };\n checksums.core.set(\"rowPtr\", hashTypedArray(parts.rowPtr));\n checksums.core.set(\"colIdx\", hashTypedArray(parts.colIdx));\n if (parts.weights !== null) {\n checksums.core.set(\"weights\", hashTypedArray(parts.weights));\n }\n if (parts.arcToEdge !== null) {\n checksums.core.set(\"arcToEdge\", hashTypedArray(parts.arcToEdge));\n }\n if (parts.edgeToArc !== null) {\n checksums.core.set(\"edgeToArc\", hashTypedArray(parts.edgeToArc));\n }\n recordColumns(checksums, parts.nodes);\n recordColumns(checksums, parts.edges);\n recordColumns(checksums, parts.graph);\n for (const table of parts.extensions.values()) {\n recordColumns(checksums, table);\n }\n }\n const state: SnapshotState = {\n arcToEdge: parts.arcToEdge,\n edgeToArc: parts.edgeToArc,\n views: emptyViewCache(),\n checksums,\n contentHash: null,\n edgeIds: null,\n };\n Object.defineProperty(this, \"state\", { value: state, enumerable: false, writable: false, configurable: false });\n STATES.set(this, state);\n claimStorage(parts);\n Object.defineProperty(this, CLONE_GUARD_KEY, {\n value: cloneGuard,\n enumerable: true,\n writable: false,\n configurable: false,\n });\n Object.freeze(this);\n }\n\n // ---------------------------------------------------------------- core accessors\n\n /**\n * rowPtr.length === 0: the core buffer was transferred away (design section 9.4). Derived from the\n * array state, never a stored bit, so every holder of the same core agrees.\n * @returns true when detached\n */\n get detached(): boolean {\n return this.rowPtr.length === 0;\n }\n\n /**\n * Logical edge of every arc (invariant I5); an identity permutation is materialised on first\n * access as a separate 4-byte-aligned array outside the arena. GPU code tests\n * `flags.arcToEdgeIsIdentity` before reading it.\n * @returns arcCount entries; E_DETACHED after a consuming transfer\n */\n get arcToEdge(): U32 {\n this.assertAttached();\n const { state } = this;\n if (state.arcToEdge === null) {\n state.arcToEdge = identityPermutation(this.arcCount);\n state.checksums?.core.set(\"arcToEdge\", hashTypedArray(state.arcToEdge));\n }\n return state.arcToEdge;\n }\n\n /**\n * The arc holding the declared orientation of every logical edge (invariant I5); an identity\n * permutation is materialised on first access outside the arena.\n * @returns edgeCount entries; E_DETACHED after a consuming transfer\n */\n get edgeToArc(): U32 {\n this.assertAttached();\n const { state } = this;\n if (state.edgeToArc === null) {\n state.edgeToArc = identityPermutation(this.edgeCount);\n state.checksums?.core.set(\"edgeToArc\", hashTypedArray(state.edgeToArc));\n }\n return state.edgeToArc;\n }\n\n // ---------------------------------------------------------------- queries (3.9)\n\n /**\n * The out-arc range of a node: [rowPtr[u], rowPtr[u + 1]]. Allocates a tuple; hot loops read\n * rowPtr directly.\n * @param u - the node index\n * @returns the half-open arc range as [start, end]\n */\n outArcs(u: number): readonly [start: number, end: number] {\n this.assertAttached();\n return [this.rowPtr[u], this.rowPtr[u + 1]];\n }\n\n /**\n * rowPtr[u + 1] - rowPtr[u]: the out-arc count (a self-loop counted once).\n * @param u - the node index\n * @returns the out-degree\n */\n outDegreeOf(u: number): number {\n this.assertAttached();\n return this.rowPtr[u + 1] - this.rowPtr[u];\n }\n\n /**\n * Binary search for the first arc u -> v (the lowest logical edge index among parallels).\n * @param u - the source node index\n * @param v - the target node index\n * @returns the arc index, or INVALID_INDEX when absent\n */\n findArc(u: number, v: number): number {\n this.assertAttached();\n return findArcIn(this.rowPtr, this.colIdx, u, v);\n }\n\n /**\n * Whether an arc u -> v exists.\n * @param u - the source node index\n * @param v - the target node index\n * @returns findArc(u, v) !== INVALID_INDEX\n */\n hasArc(u: number, v: number): boolean {\n return this.findArc(u, v) !== INVALID_INDEX;\n }\n\n /**\n * The half-open arc range [lo, hi) of every arc u -> v; empty when lo === hi. Allocates a tuple.\n * @param u - the source node index\n * @param v - the target node index\n * @returns the range as [lo, hi]\n */\n arcsBetween(u: number, v: number): readonly [lo: number, hi: number] {\n this.assertAttached();\n return arcRangeIn(this.rowPtr, this.colIdx, u, v);\n }\n\n /**\n * Number of parallel arcs u -> v.\n * @param u - the source node index\n * @param v - the target node index\n * @returns hi - lo of arcsBetween(u, v)\n */\n multiplicity(u: number, v: number): number {\n this.assertAttached();\n return multiplicityIn(this.rowPtr, this.colIdx, u, v);\n }\n\n /**\n * The row containing an arc: O(1) through the cached coo() view, else a binary search on rowPtr.\n * @param a - the arc index\n * @returns the source node index\n */\n arcSource(a: number): number {\n this.assertAttached();\n const { coo } = this.state.views;\n if (coo !== null) {\n return coo.src[a];\n }\n return arcSourceIn(this.rowPtr, a);\n }\n\n /**\n * Declared source of a logical edge: arcSource(edgeToArc[e]).\n * @param e - the logical edge index\n * @returns the source node index\n */\n edgeSource(e: number): number {\n this.assertAttached();\n const list = this.state.views.edgeList;\n if (list !== null) {\n return list.src[e];\n }\n return this.arcSource(this.edgeToArc[e]);\n }\n\n /**\n * Declared target of a logical edge: colIdx[edgeToArc[e]].\n * @param e - the logical edge index\n * @returns the target node index\n */\n edgeTarget(e: number): number {\n return this.colIdx[this.edgeToArc[e]];\n }\n\n /**\n * Lookup through the role \"id\" edge column, backed by a Map built on first call and rebuilt when the\n * column is replaced or a mutable id column's version changes (design section 4.6).\n * @param id - the edge id\n * @returns the logical edge index, or INVALID_INDEX on a miss or when no id column exists\n */\n edgeIndexOf(id: EdgeId): number {\n const { state } = this;\n const version = columnSetVersion(this.edges);\n if (state.edgeIds === null || state.edgeIds.version !== version) {\n // the role lookup is repeated only when the column set changed\n const column = this.edges.byRole(\"id\");\n state.edgeIds = { version, column, index: column === null ? null : new EdgeIdIndex(column) };\n }\n return state.edgeIds.index === null ? INVALID_INDEX : state.edgeIds.index.indexOf(id);\n }\n\n // ---------------------------------------------------------------- views (7.2)\n\n /**\n * The in-adjacency, rows sorted by source; the forward arrays themselves when undirected. Cached\n * and shared.\n * @returns the reverse view\n */\n reverse(): ReverseView {\n return this.cached(\"reverse\", () => computeReverse(this));\n }\n\n /**\n * Per-arc COO form; src is the only new array. Cached and shared.\n * @returns the COO view\n */\n coo(): CooView {\n return this.cached(\"coo\", () => computeCoo(this));\n }\n\n /**\n * Every logical edge once in declared orientation. Cached and shared.\n * @returns the edge list view\n */\n edgeList(): EdgeListView {\n return this.cached(\"edgeList\", () => computeEdgeList(this));\n }\n\n /**\n * rowPtr differences materialised; a self-loop counted once. Cached and shared: call `.slice()`\n * before writing.\n * @returns Uint32Array(n)\n */\n outDegree(): U32 {\n return this.cached(\"outDegree\", () => rowLengths(this.rowPtr, this.nodeCount));\n }\n\n /**\n * Arcs targeting each node, via reverse().rowPtr; the same object as outDegree() when undirected.\n * Cached and shared: call `.slice()` before writing.\n * @returns Uint32Array(n)\n */\n inDegree(): U32 {\n return this.cached(\"inDegree\", () =>\n this.directed ? rowLengths(this.reverse().rowPtr, this.nodeCount) : this.outDegree(),\n );\n }\n\n /**\n * Graph-theoretic degree (NetworkX convention, design section 3.4): in + out when directed; out\n * plus self-loops when undirected. Cached and shared: call `.slice()` before writing.\n * @returns Uint32Array(n)\n */\n degree(): U32 {\n return this.cached(\"degree\", () =>\n sumDegrees(this.outDegree(), this.directed ? this.inDegree() : this.selfLoopsPerNode()),\n );\n }\n\n /**\n * Row sums of weights (a self-loop arc counted once); outDegree widened when unweighted. F64 for\n * CPU precision; may be 0 for a node with out-arcs. Cached and shared: call `.slice()` before\n * writing.\n * @returns Float64Array(n)\n */\n weightedOutDegree(): F64 {\n return this.cached(\"weightedOutDegree\", () =>\n this.weights === null\n ? widenToF64(this.outDegree())\n : rowWeightSums(this.rowPtr, this.weights, this.nodeCount),\n );\n }\n\n /**\n * Weight sums over incoming arcs; the same object as weightedOutDegree() when undirected. Cached\n * and shared: call `.slice()` before writing.\n * @returns Float64Array(n)\n */\n weightedInDegree(): F64 {\n return this.cached(\"weightedInDegree\", () => {\n if (!this.directed) {\n return this.weightedOutDegree();\n }\n const reverse = this.reverse();\n return reverse.weights === null\n ? widenToF64(this.inDegree())\n : rowWeightSums(reverse.rowPtr, reverse.weights, this.nodeCount);\n });\n }\n\n /**\n * NetworkX weighted degree: weightedOutDegree + (directed ? weightedInDegree : selfLoopWeight), so\n * the sum is 2 * totalWeight() when undirected. Cached and shared: call `.slice()` before writing.\n * @returns Float64Array(n)\n */\n weightedDegree(): F64 {\n return this.cached(\"weightedDegree\", () =>\n sumF64(this.weightedOutDegree(), this.directed ? this.weightedInDegree() : this.selfLoopWeight()),\n );\n }\n\n /**\n * Sum of weights over each node's self-loop arcs (selfLoopsPerNode widened when unweighted).\n * Cached and shared: call `.slice()` before writing.\n * @returns Float64Array(n)\n */\n selfLoopWeight(): F64 {\n return this.cached(\"selfLoopWeight\", () =>\n computeSelfLoopWeight(this, {\n selfLoopArcs: this.selfLoopArcs(),\n selfLoopsPerNode: this.selfLoopsPerNode(),\n }),\n );\n }\n\n /**\n * Sum of weights over logical edges (each undirected edge once). Cached.\n * @returns the total weight\n */\n totalWeight(): number {\n return this.cached(\"totalWeight\", () => computeTotalWeight(this));\n }\n\n /**\n * The arcs a with colIdx[a] === row(a), found by binary search per row. Cached and shared: call\n * `.slice()` before writing.\n * @returns Uint32Array(selfLoopCount)\n */\n selfLoopArcs(): U32 {\n return this.cached(\"selfLoopArcs\", () => this.materialiseSelfLoops().selfLoopArcs);\n }\n\n /**\n * Self-loop arcs per node. Cached and shared: call `.slice()` before writing.\n * @returns Uint32Array(n)\n */\n selfLoopsPerNode(): U32 {\n return this.cached(\"selfLoopsPerNode\", () => this.materialiseSelfLoops().selfLoopsPerNode);\n }\n\n /**\n * Point query: self-loop arcs at one node, O(log d).\n * @param u - the node index\n * @returns the count\n */\n selfLoopsAt(u: number): number {\n this.assertAttached();\n return selfLoopsAtIn(this.rowPtr, this.colIdx, u);\n }\n\n /**\n * For every arc, the arc storing the opposite orientation of the same edge (a self-loop maps to\n * itself); the lockstep walk of design section 6.4. Undirected only. Cached and shared: call\n * `.slice()` before writing.\n * @returns Uint32Array(arcCount); E_DIRECTED on a directed snapshot\n */\n mate(): U32 {\n return this.cached(\"mate\", () => computeMate(this));\n }\n\n /**\n * Nodes ordered by descending out-degree of the forward or reverse adjacency with the cuGraph tier\n * boundaries. Both variants cached; on an undirected snapshot they are the same object.\n * @param options - which adjacency's degree to order by\n * @returns the permutation and its tier offsets\n */\n degreeOrder(options?: DegreeOrderOptions): DegreeOrderView {\n const of = assertOneOf(\"of\", options?.of, [\"forward\", \"reverse\"] as const) ?? \"forward\";\n if (of === \"reverse\" && this.directed) {\n return this.cached(\"reverseDegreeOrder\", () => computeDegreeOrder(this.reverse().rowPtr, this.nodeCount));\n }\n const forward = this.cached(\"degreeOrder\", () => computeDegreeOrder(this.rowPtr, this.nodeCount));\n if (!this.directed) {\n this.state.views.reverseDegreeOrder = forward;\n }\n return forward;\n }\n\n /**\n * Whether the arc set is closed under reversal with equal weights (forward row v equals reverse row\n * v for every v); true without work when undirected. Cached.\n * @returns true when symmetric\n */\n isSymmetric(): boolean {\n return this.cached(\"symmetric\", () => (this.directed ? computeSymmetric(this, this.reverse()) : true));\n }\n\n /**\n * Compute a set of views eagerly (inside freeze() through FreezeOptions.prepare, or off the critical\n * path).\n * @param views - the views to materialise\n * @returns this snapshot\n */\n prepare(views: readonly ViewName[]): this {\n for (const name of views) {\n this.materialiseView(name);\n }\n return this;\n }\n\n /**\n * Release every cached view (and every identity permutation materialised on demand) and every\n * cached `gpuView()` f32 copy of an f64 column (design section 7.2); they are recomputed on\n * demand. The checksum records of the dropped views are dropped with them.\n */\n dropCaches(): void {\n const { state } = this;\n for (const name of VIEW_NAMES) {\n state.views[name] = null;\n }\n state.checksums?.views.clear();\n if (this.flags.arcToEdgeIsIdentity) {\n state.arcToEdge = null;\n state.edgeToArc = null;\n state.checksums?.core.delete(\"arcToEdge\");\n state.checksums?.core.delete(\"edgeToArc\");\n }\n for (const table of [this.nodes, this.edges, this.graph, ...this.extensions.values()]) {\n for (const column of table) {\n dropGpuViewCache(column);\n }\n }\n }\n\n /**\n * Which views are resident.\n * @returns the names of the cached views, in the fixed ViewName order\n */\n cachedViews(): readonly ViewName[] {\n if (this.detached) {\n // design section 9.1: the view caches of a detached snapshot are dropped\n this.dropCaches();\n return [];\n }\n const { views } = this.state;\n return VIEW_NAMES.filter((name) => views[name] !== null);\n }\n\n // ---------------------------------------------------------------- derived graphs (7.3)\n\n /**\n * Every directed edge becomes undirected; reciprocal pairs collapse to one edge keeping the lower\n * index's row (keep-first). Returns `{ snapshot: this, null maps }` on an undirected snapshot.\n * @param options - reciprocal filtering and the weight reducer\n * @returns the derived graph\n */\n toUndirected(options?: ToUndirectedOptions): DerivedGraph {\n this.assertAttached();\n if (!this.directed) {\n return this.wrapDerived(identityDerived());\n }\n return this.wrapDerived(deriveToUndirected(this, this.edgeEndpoints(), options));\n }\n\n /**\n * Orientation of every edge swapped: the reverse view's arrays become the core. Returns this on an\n * undirected snapshot.\n * @returns the derived graph (same node and edge spaces)\n */\n transpose(): DerivedGraph {\n this.assertAttached();\n if (!this.directed) {\n return this.wrapDerived(identityDerived());\n }\n return this.wrapDerived(deriveTranspose(this, this.reverse()));\n }\n\n /**\n * One edge per (u, v) group (parallels are adjacent by invariant I4), survivor = lowest index;\n * flags.multigraph is false afterwards.\n * @param options - reducers and self-loop policy\n * @returns the derived graph\n */\n simplified(options?: SimplifyOptions): DerivedGraph {\n this.assertAttached();\n return this.wrapDerived(deriveSimplified(this, this.edgeEndpoints(), options));\n }\n\n /**\n * Every edge with source !== target.\n * @returns the derived graph\n */\n withoutSelfLoops(): DerivedGraph {\n this.assertAttached();\n return this.wrapDerived(deriveWithoutSelfLoops(this, this.edgeEndpoints()));\n }\n\n /**\n * Keep the logical edges whose mask bit is set.\n * @param keep - packed bitmap over logical edges; E_MASK_LENGTH when shorter than ceil(edgeCount / 32) words\n * @returns the derived graph\n */\n filterEdges(keep: EdgeMask): DerivedGraph {\n this.assertAttached();\n return this.wrapDerived(deriveFilterEdges(this, this.edgeEndpoints(), keep));\n }\n\n /**\n * The subgraph induced by a node selection: an index list (order = new index order; E_INDEX_RANGE\n * for an out-of-range or repeated index) or a packed mask (ascending order; E_MASK_LENGTH when\n * short). Edges with both endpoints kept.\n * @param selection - the node indices or a mask\n * @returns the derived graph\n */\n inducedSubgraph(selection: U32 | { readonly mask: NodeMask }): DerivedGraph {\n this.assertAttached();\n return this.wrapDerived(deriveInducedSubgraph(this, this.edgeEndpoints(), selection));\n }\n\n /**\n * Contract the nodes of each partition block into one node (design section 7.3).\n * @param partition - one label per node; E_PARTITION for a wrong length or an INVALID_INDEX label\n * @param options - weight reducer, self-loop and parallel policies, column reducers\n * @returns the derived graph with blockSizes and an identity id map\n */\n contract(partition: U32, options?: ContractOptions): DerivedGraph {\n this.assertAttached();\n return this.wrapDerived(deriveContract(this, this.edgeEndpoints(), partition, options));\n }\n\n /**\n * Permute the node space: perm[newIndex] = oldIndex; the id map follows; edge order is preserved.\n * @param perm - a permutation of 0..n-1; E_INVALID_PERMUTATION otherwise\n * @returns the derived graph\n */\n relabel(perm: U32): DerivedGraph {\n this.assertAttached();\n return this.wrapDerived(deriveRelabel(this, this.edgeEndpoints(), perm));\n }\n\n /**\n * A new snapshot object sharing the core, the id map and the serial with a CLONED column set plus\n * the given columns (the only operation that clones the column set).\n * @param nodes - node columns to add, keyed by name\n * @param edges - edge columns to add, keyed by name\n * @returns the new snapshot\n */\n withColumns(\n nodes?: Readonly<Record<string, TypedArrayData | ColumnInput>>,\n edges?: Readonly<Record<string, TypedArrayData | ColumnInput>>,\n ): GraphSnapshot {\n this.assertAttached();\n const identity = this.flags.arcToEdgeIsIdentity;\n const parts = withColumnsParts(\n this,\n nodes,\n edges,\n identity ? null : this.arcToEdge,\n identity ? null : this.edgeToArc,\n );\n return new GraphSnapshot({ ...parts, checksum: this.state.checksums !== null });\n }\n\n // ---------------------------------------------------------------- memory, transfer, checks (9, 11)\n\n /**\n * Resident bytes of the core (an identity permutation counts zero even when materialised), plus\n * the side structures selected by the options.\n * @param options - which side structures to include\n * @returns the byte count\n */\n byteLength(options: ByteLengthOptions = {}): number {\n let bytes = this.rowPtr.byteLength + this.colIdx.byteLength;\n if (this.weights !== null) {\n bytes += this.weights.byteLength;\n }\n if (!this.flags.arcToEdgeIsIdentity) {\n bytes += this.arcToEdge.byteLength + this.edgeToArc.byteLength;\n }\n if (options.views === true) {\n const { views } = this.state;\n for (const name of VIEW_NAMES) {\n const value = views[name];\n if (value !== null && !(name === \"reverseDegreeOrder\" && value === views.degreeOrder)) {\n bytes += viewByteLength(this, name, value);\n }\n }\n }\n if (options.columns === true) {\n for (const table of [this.nodes, this.edges, this.graph, ...this.extensions.values()]) {\n for (const column of table) {\n bytes += column.byteLength;\n }\n }\n }\n if (options.ids === true) {\n bytes += this.ids.byteLength();\n }\n return bytes;\n }\n\n /**\n * A 64-bit content hash of the core arrays (two 32-bit FNV-1a lanes) as 16 hex characters,\n * computed lazily and cached (design section 9.3).\n * @returns the hash\n */\n contentHash(): string {\n this.assertAttached();\n const { state } = this;\n state.contentHash ??= contentHashOf(this);\n return state.contentHash;\n }\n\n /**\n * The distinct, exclusively owned backing buffers: the postMessage transfer list (design section\n * 9.1). Buffers shared with another holder (a withColumns() sibling, a derived graph sharing the\n * node table) are excluded.\n * @returns the buffers\n */\n transferables(): ArrayBuffer[] {\n this.assertAttached();\n return transferables(this);\n }\n\n /**\n * The plain-object wire form (design section 9.1): a JSON-serialisable manifest plus the backing\n * buffers. With `transfer: true` only exclusively owned buffers are listed as transferables and\n * shared ones are copied.\n * @param options - transfer mode, views and columns to include\n * @returns the wire snapshot\n */\n toWire(options?: ToWireOptions): WireSnapshot {\n this.assertAttached();\n return toWire(this, options);\n }\n\n /**\n * The GSNP byte container as one contiguous buffer (design section 9.2).\n * @param options - views to include\n * @returns the container bytes\n */\n toBytes(options?: ToBytesOptions): U8 {\n this.assertAttached();\n return toBytes(this, options);\n }\n\n /**\n * The GSNP container as a sequence of chunks (design section 9.2): the header plus manifest,\n * then one chunk per non-empty segment.\n * @param options - views to include\n * @returns the chunks\n */\n toByteChunks(options?: ToBytesOptions): Iterable<U8> {\n this.assertAttached();\n return toByteChunks(this, options);\n }\n\n /**\n * Check the invariants (design section 11.4): the recorded checksums first when `checksum` is set\n * (a mutated frozen array is the most useful diagnosis, details.reason \"checksum\"; \"no-checksum\"\n * when none were recorded), then \"structure\" or \"full\" (default) per the level table of design\n * section 9.5. Throws E_INVALID_SNAPSHOT with details.invariant and the location on the first\n * violation.\n * @param options - level and checksum comparison\n */\n validate(options: ValidateOptions = {}): void {\n this.assertAttached();\n const level = assertOneOf(\"level\", options.level, [\"structure\", \"full\"] as const) ?? \"full\";\n if (typeof options.checksum !== \"boolean\" && options.checksum !== undefined) {\n throw new GraphFormatError(\"E_UNSUPPORTED\", \"validate option checksum must be a boolean\", {\n field: \"checksum\",\n found: options.checksum,\n reason: \"unsupported option\",\n });\n }\n // a column or id store transferred away underneath the snapshot (a holder outside the owner\n // count, design section 9.1) is E_DETACHED, not a length-rule violation\n if (idMapDetached(this.ids)) {\n throw new GraphFormatError(\"E_DETACHED\", \"the id map's storage was transferred away\", {\n serial: this.serial,\n });\n }\n for (const table of [this.nodes, this.edges, this.graph, ...this.extensions.values()]) {\n for (const column of table) {\n if (isColumnDetached(column)) {\n throw new GraphFormatError(\"E_DETACHED\", `column \"${column.meta.name}\" was transferred away`, {\n column: column.meta.name,\n serial: this.serial,\n });\n }\n }\n }\n if (options.checksum === true) {\n this.verifyChecksums();\n }\n if (level === \"structure\") {\n validateStructure(this);\n } else {\n validateFull(this);\n }\n }\n\n // ---------------------------------------------------------------- private helpers\n\n /**\n * Throw E_DETACHED when the core was transferred away.\n */\n private assertAttached(): void {\n if (this.rowPtr.length === 0) {\n throw new GraphFormatError(\"E_DETACHED\", \"the snapshot's core buffer was transferred away\", {\n serial: this.serial,\n });\n }\n }\n\n /**\n * Return the cached value of a view, computing and recording it on first use.\n * @param name - the view name\n * @param compute - the computation\n * @returns the cached value\n */\n private cached<K extends ViewName>(name: K, compute: () => NonNullable<ViewCache[K]>): NonNullable<ViewCache[K]> {\n this.assertAttached();\n const { views } = this.state;\n const existing = views[name];\n if (existing !== null) {\n return existing;\n }\n const value = compute();\n views[name] = value;\n this.recordView(name, value);\n return value;\n }\n\n /**\n * Compute both self-loop views in one pass and seed the slot the caller did not ask for.\n * @returns the two views\n */\n private materialiseSelfLoops(): { selfLoopArcs: U32; selfLoopsPerNode: U32 } {\n const loops = computeSelfLoops(this);\n const { views } = this.state;\n if (views.selfLoopArcs === null) {\n views.selfLoopArcs = loops.selfLoopArcs;\n this.recordView(\"selfLoopArcs\", loops.selfLoopArcs);\n }\n if (views.selfLoopsPerNode === null) {\n views.selfLoopsPerNode = loops.selfLoopsPerNode;\n this.recordView(\"selfLoopsPerNode\", loops.selfLoopsPerNode);\n }\n return { selfLoopArcs: views.selfLoopArcs, selfLoopsPerNode: views.selfLoopsPerNode };\n }\n\n /**\n * Record the digests of a freshly materialised view when checksums are on.\n * @param name - the view name\n * @param value - the view\n */\n private recordView(name: ViewName, value: unknown): void {\n recordViewDigests(this, this.state, name, value);\n }\n\n /**\n * Compare every recorded checksum with the current bytes (design section 5.8).\n */\n private verifyChecksums(): void {\n const records = this.state.checksums;\n if (records === null) {\n throw new GraphFormatError(\"E_INVALID_SNAPSHOT\", \"no checksums were recorded for this snapshot\", {\n reason: \"no-checksum\",\n });\n }\n const mismatch = (what: string, details: Readonly<Record<string, unknown>>): GraphFormatError =>\n new GraphFormatError(\"E_INVALID_SNAPSHOT\", `checksum mismatch: ${what} was modified after freeze`, {\n reason: \"checksum\",\n ...details,\n });\n const { state } = this;\n const core: readonly [CoreArrayName, ArrayBufferView | null][] = [\n [\"rowPtr\", this.rowPtr],\n [\"colIdx\", this.colIdx],\n [\"weights\", this.weights],\n [\"arcToEdge\", state.arcToEdge],\n [\"edgeToArc\", state.edgeToArc],\n ];\n for (const [name, array] of core) {\n const recorded = records.core.get(name);\n if (recorded !== undefined && array !== null && hashTypedArray(array) !== recorded) {\n throw mismatch(`core array ${name}`, { array: name });\n }\n }\n const tables: readonly [string, AttributeTable][] = [\n [\"nodes\", this.nodes],\n [\"edges\", this.edges],\n [\"graph\", this.graph],\n ...[...this.extensions].map(([name, table]): [string, AttributeTable] => [`extensions[${name}]`, table]),\n ];\n for (const [tableName, table] of tables) {\n for (const column of table) {\n const recorded = records.columns.get(column);\n if (recorded !== undefined && hashColumn(column) !== recorded) {\n throw mismatch(`column \"${column.meta.name}\" of ${tableName}`, {\n table: tableName,\n column: column.meta.name,\n });\n }\n }\n }\n for (const name of VIEW_NAMES) {\n const value = state.views[name];\n if (value === null) {\n continue;\n }\n for (const [member, array] of Object.entries(viewArrays(this, name, value))) {\n const recorded = records.views.get(`${name}.${member}`);\n if (recorded !== undefined && hashTypedArray(array) !== recorded) {\n throw mismatch(`view ${name}.${member}`, { view: name, member });\n }\n }\n }\n }\n\n /**\n * The edge endpoints in declared orientation for the derived-graph functions: the cached edge list\n * when resident, else a fresh one that is NOT cached (derived graphs must not grow the source's\n * resident size, design section 7.3).\n * @returns an edge list view\n */\n private edgeEndpoints(): EdgeListView {\n return this.state.views.edgeList ?? computeEdgeList(this);\n }\n\n /**\n * Wrap derived parts into a DerivedGraph, creating the new snapshot (with this snapshot's checksum\n * setting) or returning this for the identity cases.\n * @param derived - the derived parts\n * @returns the derived graph\n */\n private wrapDerived(derived: DerivedParts): DerivedGraph {\n const snapshot =\n derived.parts === null\n ? this\n : new GraphSnapshot({ ...derived.parts, checksum: this.state.checksums !== null });\n return {\n snapshot,\n nodeOrigin: derived.nodeOrigin,\n edgeOrigin: derived.edgeOrigin,\n nodeRemap: derived.nodeRemap,\n edgeRemap: derived.edgeRemap,\n blockSizes: derived.blockSizes,\n report: derived.report,\n };\n }\n\n /**\n * Materialise one named view (the prepare() dispatch).\n * @param name - the view name\n */\n private materialiseView(name: ViewName): void {\n switch (name) {\n case \"reverse\":\n this.reverse();\n break;\n case \"coo\":\n this.coo();\n break;\n case \"edgeList\":\n this.edgeList();\n break;\n case \"outDegree\":\n this.outDegree();\n break;\n case \"inDegree\":\n this.inDegree();\n break;\n case \"degree\":\n this.degree();\n break;\n case \"weightedOutDegree\":\n this.weightedOutDegree();\n break;\n case \"weightedInDegree\":\n this.weightedInDegree();\n break;\n case \"weightedDegree\":\n this.weightedDegree();\n break;\n case \"selfLoopWeight\":\n this.selfLoopWeight();\n break;\n case \"totalWeight\":\n this.totalWeight();\n break;\n case \"selfLoopArcs\":\n this.selfLoopArcs();\n break;\n case \"selfLoopsPerNode\":\n this.selfLoopsPerNode();\n break;\n case \"mate\":\n this.mate();\n break;\n case \"degreeOrder\":\n this.degreeOrder();\n break;\n case \"reverseDegreeOrder\":\n this.degreeOrder({ of: \"reverse\" });\n break;\n case \"symmetric\":\n this.isSymmetric();\n break;\n default: {\n const unknown: never = name;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown view ${String(unknown)}`, { view: unknown });\n }\n }\n }\n}\n\n/**\n * Record this snapshot as a holder of every buffer, table and id map it keeps (design section 9.1):\n * a second snapshot claiming the same storage (a withColumns() sibling, a derived graph sharing the\n * node table) marks it shared, so a transfer copies it instead of emptying the sibling. Each distinct\n * buffer is claimed once per snapshot (the arena backs several core arrays).\n * @param parts - the parts the snapshot was built from\n */\nfunction claimStorage(parts: SnapshotParts): void {\n const buffers = new Set<ArrayBuffer>([parts.rowPtr.buffer, parts.colIdx.buffer]);\n if (parts.weights !== null) {\n buffers.add(parts.weights.buffer);\n }\n if (parts.arcToEdge !== null) {\n buffers.add(parts.arcToEdge.buffer);\n }\n if (parts.edgeToArc !== null) {\n buffers.add(parts.edgeToArc.buffer);\n }\n for (const buffer of idMapBuffers(parts.ids)) {\n buffers.add(buffer);\n }\n for (const buffer of buffers) {\n claimHolder(buffer);\n }\n claimHolder(parts.ids);\n claimHolder(parts.nodes);\n claimHolder(parts.edges);\n claimHolder(parts.graph);\n for (const table of parts.extensions.values()) {\n claimHolder(table);\n }\n}\n\n// ============================================================ factory and helpers\n\n/**\n * Create a snapshot from prepared parts (design section 6.3 step 12): the constructor freezes the\n * object, records checksums when `parts.checksum` is set and allocates the per-instance view cache.\n * @param parts - the parts; I1-I13 established by the producer, O(1) length rules checked here\n * @returns the frozen snapshot\n */\nexport function createSnapshot(parts: SnapshotParts): GraphSnapshot {\n return new GraphSnapshot(parts);\n}\n\n/**\n * Structural check for a snapshot (design section 7.5): the SNAPSHOT_BRAND property plus the\n * formatVersion, never instanceof, so a duplicated package copy still interoperates.\n * @param x - any value\n * @returns true when x is a GraphSnapshot of this format version\n */\nexport function isGraphSnapshot(x: unknown): x is GraphSnapshot {\n if (typeof x !== \"object\" || x === null) {\n return false;\n }\n const candidate = x as { [SNAPSHOT_BRAND]?: unknown; formatVersion?: unknown };\n return candidate[SNAPSHOT_BRAND] === true && candidate.formatVersion === FORMAT_VERSION;\n}\n\n/**\n * Whether two typed arrays hold the same elements.\n * @param a - the first array\n * @param b - the second array\n * @returns true when equal element by element\n */\nfunction sameElements(a: ArrayLike<number>, b: ArrayLike<number>): boolean {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Compare the core arrays and id maps of two snapshots element by element (design section 7.5):\n * directedness, counts, rowPtr, colIdx, weights (both absent or equal), arcToEdge / edgeToArc\n * (identity compared without materialising) and every id (SameValueZero).\n * @param a - the first snapshot\n * @param b - the second snapshot\n * @returns true when the topologies and id maps are equal\n */\nexport function equalsTopology(a: GraphSnapshot, b: GraphSnapshot): boolean {\n if (\n a.directed !== b.directed ||\n a.nodeCount !== b.nodeCount ||\n a.edgeCount !== b.edgeCount ||\n a.arcCount !== b.arcCount ||\n a.selfLoopCount !== b.selfLoopCount\n ) {\n return false;\n }\n if (!sameElements(a.rowPtr, b.rowPtr) || !sameElements(a.colIdx, b.colIdx)) {\n return false;\n }\n if ((a.weights === null) !== (b.weights === null)) {\n return false;\n }\n if (a.weights !== null && b.weights !== null && !sameElements(a.weights, b.weights)) {\n return false;\n }\n const identityA = a.flags.arcToEdgeIsIdentity;\n const identityB = b.flags.arcToEdgeIsIdentity;\n if (!identityA || !identityB) {\n if (!sameElements(a.arcToEdge, b.arcToEdge) || !sameElements(a.edgeToArc, b.edgeToArc)) {\n return false;\n }\n }\n if (a.ids.size !== b.ids.size) {\n return false;\n }\n for (let i = 0; i < a.nodeCount; i++) {\n const idA = a.ids.idOf(i);\n const idB = b.ids.idOf(i);\n if (\n idA !== idB &&\n !(typeof idA === \"number\" && typeof idB === \"number\" && Number.isNaN(idA) && Number.isNaN(idB))\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Record the digests of a materialised view in the checksum records, when the snapshot keeps any.\n * @param snapshot - the snapshot\n * @param state - its state record\n * @param name - the view name\n * @param value - the view\n */\nfunction recordViewDigests(snapshot: GraphSnapshot, state: SnapshotState, name: ViewName, value: unknown): void {\n const records = state.checksums;\n if (records === null) {\n return;\n }\n for (const [member, array] of Object.entries(viewArrays(snapshot, name, value))) {\n records.views.set(`${name}.${member}`, hashTypedArray(array));\n }\n}\n\n/**\n * Install a view value the wire carried (`includeViews`, design section 9.1) into the snapshot's\n * cache, so the receiver does not recompute it. The caller has already checked that the value has\n * the shape of the view; the slot is only filled when it is still empty.\n * @param snapshot - the snapshot\n * @param name - the view name\n * @param value - the view value\n * @returns true when the view was installed, false when the slot was already resident\n */\nexport function seedView<K extends ViewName>(\n snapshot: GraphSnapshot,\n name: K,\n value: NonNullable<ViewCache[K]>,\n): boolean {\n const state = STATES.get(snapshot);\n if (state === undefined || state.views[name] !== null) {\n return false;\n }\n state.views[name] = value;\n recordViewDigests(snapshot, state, name, value);\n return true;\n}\n\n/**\n * The cached value of a view without computing it (for tests and for the wire module's\n * `includeViews`).\n * @param snapshot - the snapshot\n * @param name - the view name\n * @returns the cached value, or null when not resident\n */\nexport function peekView<K extends ViewName>(snapshot: GraphSnapshot, name: K): ViewCache[K] {\n const state = STATES.get(snapshot);\n if (state === undefined) {\n return null;\n }\n return state.views[name];\n}\n\n/**\n * Whether the snapshot's permutation arrays are held (materialised) rather than lazy, for tests of\n * the identity rule and for the wire module (which never serialises an identity permutation).\n * @param snapshot - the snapshot\n * @returns true when arcToEdge has been materialised or was supplied\n */\nexport function permutationMaterialised(snapshot: GraphSnapshot): boolean {\n const state = STATES.get(snapshot);\n return state !== undefined && state.arcToEdge !== null;\n}\n\n/**\n * Whether checksums were recorded at construction (design section 5.8).\n * @param snapshot - the snapshot\n * @returns true when validate({ checksum: true }) can compare\n */\nexport function hasChecksums(snapshot: GraphSnapshot): boolean {\n const state = STATES.get(snapshot);\n return state !== undefined && state.checksums !== null;\n}\n\n// ============================================================ arena helpers (10.3)\n","/**\n * The enum vocabularies of the builder options (design section 12.2) shared by the constructor and\n * the per-freeze overrides, so a value outside its set is refused the same way on every path\n * (E_UNSUPPORTED, never a silent substitute).\n */\n\nimport { type GraphFormatError } from \"../errors.js\";\nimport { type DuplicatePolicy } from \"../types/index.js\";\n\n/** The DuplicatePolicy members. */\nconst DUPLICATE_POLICIES: ReadonlySet<string> = new Set([\"keep\", \"error\", \"first\", \"last\", \"sum\", \"min\", \"max\"]);\n\n/**\n * Check a duplicateEdges value.\n * @param field - the option name for the error\n * @param value - the value\n * @param error - builds the error for an unsupported value\n * @returns the value as a DuplicatePolicy\n */\nexport function assertDuplicatePolicy(\n field: string,\n value: unknown,\n error: (field: string, found: unknown) => GraphFormatError,\n): DuplicatePolicy {\n if (typeof value !== \"string\" || !DUPLICATE_POLICIES.has(value)) {\n throw error(field, value);\n }\n return value as DuplicatePolicy;\n}\n","/**\n * The freeze pipeline of design section 6.3, exactly: the pre-checks that throw without touching the\n * builder (self-loop \"error\", arc-count bound), compaction of tombstones and dropped loops (steps 1-2,\n * into a fresh staging the builder commits only on success), the two counting-sort passes into the\n * arena (steps 3-6, counting-sort.ts), the duplicate-policy walk with its one repeat after a merge\n * (step 7), the weight flags and the f64 / explicit-weight shadow column (step 8), the id map (step\n * 9), the attribute tables (step 10), the arena and prepared views (step 11) and the snapshot itself\n * with its FreezeReport (step 12).\n *\n * Nothing here mutates the builder: `runFreeze` returns the staging the builder must adopt (the\n * source staging when nothing was renumbered, a compacted one otherwise) so that a throw anywhere in\n * the pipeline leaves the builder as it was (design section 11.1).\n */\n\nimport { bitmapClear, bitmapGet, bitmapSet, bitmapWordCount } from \"../columns/bitmap.js\";\nimport { columnFromValues, createColumn, emptyParts, resolveColumnMeta } from \"../columns/column.js\";\nimport { AttributeTable, verifyUniqueColumns } from \"../columns/table.js\";\nimport { INVALID_INDEX, MAX_COUNT } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { identityNodeIdMap, nodeIdMapFromIds } from \"../ids/node-id-map.js\";\nimport { createSnapshot, type GraphSnapshot } from \"../snapshot/graph-snapshot.js\";\nimport { isIdentity } from \"../snapshot/validate.js\";\nimport {\n type Column,\n type ColumnDeclPatch,\n type ColumnDomain,\n type Dtype,\n type DuplicatePolicy,\n type F32,\n type F64,\n type FreezeOptions,\n type FreezeReport,\n type GraphMeta,\n type NodeIdMap,\n type ResolvedBuilderOptions,\n type U32,\n} from \"../types/index.js\";\nimport { type SnapshotParts } from \"../types/internal.js\";\nimport { copyCoreIntoArena } from \"./arena.js\";\nimport {\n compactStaging,\n type IndexRemap,\n remapKeepingBits,\n remapSurvivors,\n type Staging,\n type StagingColumn,\n} from \"./compact.js\";\nimport { type SortInput, sortIntoCore, type SortResult } from \"./counting-sort.js\";\nimport { assertDuplicatePolicy } from \"./options.js\";\n\n// ============================================================ context and outcome\n\n/** One graph-level attribute the builder holds until freeze (design section 5.9). */\nexport interface GraphValue {\n /** The declaration patch given to setGraphValue, or undefined. */\n readonly decl: ColumnDeclPatch | undefined;\n /** The value; undefined = unset. */\n readonly value: unknown;\n}\n\n/** A widening recorded by the builder since the previous freeze (design section 5.1). */\nexport interface Widening {\n /** The column name. */\n readonly column: string;\n /** The column's table. */\n readonly domain: ColumnDomain;\n /** The dtype before. */\n readonly from: Dtype;\n /** The dtype after. */\n readonly to: Dtype;\n}\n\n/** Everything the pipeline reads from the builder. */\nexport interface FreezeContext {\n /** The staging to freeze; never modified. */\n readonly staging: Staging;\n /** The builder's current direction. */\n readonly directed: boolean;\n /** The resolved builder options (policies, precision). */\n readonly options: ResolvedBuilderOptions;\n /** The graph-level attributes in declaration order. */\n readonly graphValues: ReadonlyMap<string, GraphValue>;\n /** The graph metadata. */\n readonly meta: GraphMeta;\n /** The widenings since the previous freeze. */\n readonly widened: readonly Widening[];\n}\n\n/** What a freeze produces: the snapshot, its report, and the staging the builder must adopt. */\ninterface FreezeOutcome {\n /** The frozen snapshot. */\n readonly snapshot: GraphSnapshot;\n /** The report. */\n readonly report: FreezeReport;\n /** The staging the builder holds afterwards: the source staging, or the compacted one. */\n readonly staging: Staging;\n}\n\n/** The name of the shadow weight column the freeze writes (design sections 3.7 and 5.6). */\nexport const WEIGHT_COLUMN_NAME = \"graphty.weight\";\n\n/**\n * A millisecond clock for the profile timings.\n * @returns the current time in milliseconds\n */\nfunction now(): number {\n return performance.now();\n}\n\n/** A per-edge scratch: which survivor an edge folds into, and the reduced weights. */\ninterface DuplicateWalk {\n /** old edge -> its survivor (itself for a survivor). */\n readonly survivorOf: U32;\n /** Per old edge: the reduced weight to store on a survivor, meaningful where `stored` is set; null when none. */\n readonly reduced: Float64Array | null;\n /** Per old edge: bit set on a survivor whose group produced a reduced weight to store; null when none. */\n readonly stored: U32 | null;\n /** Per old edge: bit set on a survivor whose weight is explicit after the merge although it was not before; null when none. */\n readonly explicit: U32 | null;\n /** How many edges folded into a survivor. */\n readonly merged: number;\n}\n\n// ============================================================ steps\n\n/**\n * The E_SELF_LOOP pre-check of design section 6.3 step 2 (policy \"error\"): the first live loop is\n * named. Runs before anything is renumbered so the builder is untouched.\n * @param staging - the source staging\n */\nfunction checkSelfLoops(staging: Staging): void {\n if (staging.selfLoopCount === 0) {\n return;\n }\n const bound = staging.edgeBound;\n for (let e = 0; e < bound; e++) {\n if (staging.edgeAlive.get(e) && staging.src.get(e) === staging.dst.get(e)) {\n const node = staging.src.get(e);\n throw new GraphFormatError(\"E_SELF_LOOP\", `edge ${e} is a self-loop at node ${node}`, { edge: e, node });\n }\n }\n}\n\n/**\n * The live edges that are not self-loops, as a bitmap over the edge index space (the edges a\n * `selfLoops: \"drop\"` freeze keeps, design section 6.3 step 2).\n * @param staging - the source staging\n * @returns a fresh bitmap: bit e set = edge e is live and src !== dst\n */\nfunction liveNonLoopBits(staging: Staging): U32 {\n const keep = staging.edgeAlive.view().slice();\n const src = staging.src.view();\n const dst = staging.dst.view();\n const bound = staging.edgeBound;\n for (let e = 0; e < bound; e++) {\n if (src[e] === dst[e] && bitmapGet(keep, e)) {\n bitmapClear(keep, e);\n }\n }\n return keep;\n}\n\n/**\n * The sort input over a staging's live (compacted) edges.\n * @param staging - a staging without tombstones\n * @param directed - the direction\n * @returns the per-edge views\n */\nfunction sortInputOf(staging: Staging, directed: boolean): SortInput {\n const edgeCount = staging.edgeBound;\n return {\n directed,\n nodeCount: staging.nodeBound,\n edgeCount,\n src: staging.src.view(),\n dst: staging.dst.view(),\n weights: staging.weight === null ? null : (staging.weight.view() as F32 | F64),\n };\n}\n\n/**\n * The duplicate-policy walk of design section 6.3 step 7 over sorted rows: adjacent arcs with equal\n * colIdx form a group; \"error\" throws E_DUPLICATE_EDGE; the merge policies choose a survivor (the\n * lowest edge index, or the highest for \"last\"), reduce the weights over the group from the staging\n * values (f64 precision), and fold every other member into the survivor. A reducer that produces NaN\n * (a \"sum\" over +Infinity and -Infinity) is the E_INVALID_WEIGHT re-check of step 8 and throws before\n * anything is renumbered. A reduced value makes the survivor's weight explicit (the merge stored it,\n * design section 6.5), as does an explicit weight anywhere in the group. For an undirected graph the\n * `(u, v)` and `(v, u)` groups are one group, walked once from the row of the lower endpoint.\n * @param sorted - the sorted core\n * @param staging - the (compacted) staging the core was built from\n * @param directed - the direction\n * @param policy - a policy other than \"keep\"\n * @param countMultiplicity - whether \"sum\" on an unweighted staging materialises multiplicities (false on a `weighted: false` builder, which never gains a weight array)\n * @param builderIndex - compacted edge index -> the builder's own index, for error details\n * @returns the walk, or null when no group had more than one member\n */\nfunction walkDuplicates(\n sorted: SortResult,\n staging: Staging,\n directed: boolean,\n policy: Exclude<DuplicatePolicy, \"keep\">,\n countMultiplicity: boolean,\n builderIndex: (e: number) => number,\n): DuplicateWalk | null {\n const { rowPtr, colIdx, arcToEdge } = sorted.core;\n const nodeCount = staging.nodeBound;\n const edgeCount = staging.edgeBound;\n const weights = staging.weight === null ? null : staging.weight.view();\n const survivorOf = new Uint32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n survivorOf[e] = e;\n }\n let reduced: Float64Array | null = null;\n let stored: U32 | null = null;\n let explicit: U32 | null = null;\n let merged = 0;\n const group: number[] = [];\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n let a = rowPtr[u];\n while (a < end) {\n const v = colIdx[a];\n let b = a + 1;\n while (b < end && colIdx[b] === v) {\n b++;\n }\n if (b - a > 1 && (directed || v >= u)) {\n group.length = 0;\n for (let k = a; k < b; k++) {\n group.push(arcToEdge === null ? k : arcToEdge[k]);\n }\n if (policy === \"error\") {\n const edges = [builderIndex(group[0]), builderIndex(group[1])];\n throw new GraphFormatError(\n \"E_DUPLICATE_EDGE\",\n `edges ${edges[0]} and ${edges[1]} both connect ${u} -> ${v}`,\n { source: u, target: v, edges },\n );\n }\n const survivor = policy === \"last\" ? group[group.length - 1] : group[0];\n let value: number | null = null;\n if (policy === \"sum\" || policy === \"min\" || policy === \"max\") {\n value = reduceGroup(weights, group, policy, countMultiplicity);\n if (value !== null && Number.isNaN(value)) {\n const edges = group.map(builderIndex);\n throw new GraphFormatError(\n \"E_INVALID_WEIGHT\",\n `duplicateEdges \"${policy}\" over edges ${edges.join(\", \")} (${u} -> ${v}) yields NaN`,\n { source: u, target: v, edges, policy, reason: \"reducer\" },\n );\n }\n }\n if (value !== null) {\n reduced ??= new Float64Array(edgeCount);\n stored ??= new Uint32Array(bitmapWordCount(edgeCount));\n reduced[survivor] = value;\n bitmapSet(stored, survivor);\n }\n let anyExplicit = value !== null;\n for (let i = 0; i < group.length && !anyExplicit; i++) {\n anyExplicit = staging.weightExplicit(group[i]);\n }\n if (anyExplicit && !staging.weightExplicit(survivor)) {\n explicit ??= new Uint32Array(bitmapWordCount(edgeCount));\n bitmapSet(explicit, survivor);\n }\n for (const e of group) {\n if (e !== survivor) {\n survivorOf[e] = survivor;\n merged++;\n }\n }\n }\n a = b;\n }\n }\n return merged === 0 ? null : { survivorOf, reduced, stored, explicit, merged };\n}\n\n/**\n * Reduce the weights of a parallel group (design section 6.5): sum / min / max over the staging\n * values; on an unweighted staging every weight is 1, so \"sum\" yields the group size (the\n * multiplicity, when the builder may gain a weight array) and min / max leave 1 (nothing to store).\n * @param weights - the staging weights, or null\n * @param group - the edge indices of the group\n * @param policy - the reducer\n * @param countMultiplicity - whether \"sum\" on an unweighted staging yields the group size\n * @returns the reduced weight (NaN when the operands cancel), or null when the survivor's own value already holds it\n */\nfunction reduceGroup(\n weights: ArrayLike<number> | null,\n group: readonly number[],\n policy: \"sum\" | \"min\" | \"max\",\n countMultiplicity: boolean,\n): number | null {\n if (weights === null) {\n return policy === \"sum\" && countMultiplicity ? group.length : null;\n }\n let value = weights[group[0]];\n for (let i = 1; i < group.length; i++) {\n const w = weights[group[i]];\n switch (policy) {\n case \"sum\":\n value += w;\n break;\n case \"min\":\n value = Math.min(value, w);\n break;\n case \"max\":\n value = Math.max(value, w);\n break;\n default: {\n const name: string = policy;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown reducer ${name}`, { policy: name });\n }\n }\n }\n return value;\n}\n\n/**\n * The role-\"weight\" edge column of design section 3.7, when one is needed: the f64 shadow when the\n * staging precision is f64 and some value is not f32-exact, and / or the explicit-weight record (the\n * `weightSet` bitmap as validity) when some edge omitted its weight while another supplied it, or when\n * a `weighted: true` builder's edges all omitted it.\n * @param staging - the final staging\n * @param edgeCount - the logical edge count\n * @param weightDtype - the staging precision\n * @returns the column, or null when the arc array already says everything\n */\nfunction weightShadowColumn(staging: Staging, edgeCount: number, weightDtype: \"f32\" | \"f64\"): Column | null {\n const { weight } = staging;\n if (weight === null || edgeCount === 0) {\n return null;\n }\n const values = weight.view();\n let inexact = false;\n if (weightDtype === \"f64\") {\n for (let e = 0; e < edgeCount; e++) {\n const w = values[e];\n if (Math.fround(w) !== w) {\n inexact = true;\n break;\n }\n }\n }\n const needValidity = staging.weightSet !== null || staging.weightMode === \"omitted\";\n if (!inexact && !needValidity) {\n return null;\n }\n const dtype = inexact ? \"f64\" : \"f32\";\n const meta = resolveColumnMeta(WEIGHT_COLUMN_NAME, \"edge\", { dtype, role: \"weight\", nullable: needValidity });\n const data = dtype === \"f64\" ? new Float64Array(edgeCount) : new Float32Array(edgeCount);\n data.set(values.subarray(0, edgeCount));\n let validity: U32 | null = null;\n if (needValidity) {\n validity = new Uint32Array(bitmapWordCount(edgeCount));\n for (let e = 0; e < edgeCount; e++) {\n if (staging.weightExplicit(e)) {\n bitmapSet(validity, e);\n }\n }\n }\n return createColumn({ ...emptyParts(meta, edgeCount, validity), data });\n}\n\n/**\n * The id map of design section 6.3 step 9: identity with no storage while every node is anonymous,\n * otherwise the kind detected from the ids with the builder's `Map` and `ids` array shared by reference\n * (decision C17).\n * @param staging - the final staging\n * @param nodeCount - the node count\n * @returns the id map\n */\nfunction idMapOf(staging: Staging, nodeCount: number): NodeIdMap {\n if (staging.ids === null || staging.idToIndex === null) {\n return identityNodeIdMap(nodeCount);\n }\n return nodeIdMapFromIds(staging.ids, nodeCount, { map: staging.idToIndex });\n}\n\n/**\n * Freeze a list of staging columns into a table (design section 6.3 step 10) and enforce its unique\n * columns.\n * @param domain - the table domain\n * @param rowCount - the row count\n * @param columns - the staging columns\n * @param extra - columns to append (the weight shadow)\n * @returns the table\n */\nfunction tableOf(\n domain: ColumnDomain,\n rowCount: number,\n columns: readonly StagingColumn[],\n extra: readonly Column[] = [],\n): AttributeTable {\n const frozen: Column[] = columns.map((column) => column.toColumn(rowCount));\n const table = new AttributeTable({ domain, rowCount, columns: [...frozen, ...extra] });\n verifyUniqueColumns(table);\n return table;\n}\n\n/**\n * The graph table (one row) from the builder's graph values.\n * @param values - the graph values in declaration order\n * @returns the table\n */\nfunction graphTableOf(values: ReadonlyMap<string, GraphValue>): AttributeTable {\n const columns: Column[] = [];\n for (const [name, entry] of values) {\n columns.push(columnFromValues(\"graph\", 1, name, [entry.value], entry.decl ?? {}));\n }\n return new AttributeTable({ domain: \"graph\", rowCount: 1, columns });\n}\n\n/**\n * Compose the report's edge remap out of the compaction remap (old -> compacted) and the merge walk\n * (compacted -> survivor -> final): every old edge maps to its final index, or to INVALID_INDEX when\n * tombstoned or dropped; a merged edge maps to its survivor (design section 6.5).\n * @param oldBound - the old edge index space\n * @param first - the compaction remap, or null when none ran\n * @param walk - the merge walk, or null\n * @param second - the post-merge remap, or null\n * @returns the composed remap, or null when it is the identity\n */\nfunction composeEdgeRemap(\n oldBound: number,\n first: IndexRemap | null,\n walk: DuplicateWalk | null,\n second: IndexRemap | null,\n): U32 | null {\n if (first === null && walk === null) {\n return null;\n }\n const out = new Uint32Array(oldBound);\n for (let e = 0; e < oldBound; e++) {\n let index = first === null ? e : first.remap[e];\n if (index !== INVALID_INDEX && walk !== null && second !== null) {\n index = second.remap[walk.survivorOf[index]];\n }\n out[e] = index;\n }\n return isIdentity(out) ? null : out;\n}\n\n/**\n * The identity remap of a space of `count` indices (a compaction that only renumbers edges).\n * @param count - the space size\n * @returns the identity\n */\nfunction identityRemap(count: number): IndexRemap {\n const remap = new Uint32Array(count);\n for (let i = 0; i < count; i++) {\n remap[i] = i;\n }\n return { remap, origin: remap, count };\n}\n\n/**\n * The E_UNSUPPORTED error for a freeze option outside its documented set (design section 12.2\n * FreezeOptions), thrown before any staging work so the builder is untouched.\n * @param field - the option name\n * @param found - the value\n * @returns the error\n */\nfunction freezeOptionError(field: string, found: unknown): GraphFormatError {\n return new GraphFormatError(\"E_UNSUPPORTED\", `freeze option ${field} has an unsupported value ${String(found)}`, {\n field,\n found,\n reason: \"unsupported option\",\n });\n}\n\n/**\n * Validate every FreezeOptions field (design section 12.2): the per-freeze duplicateEdges override\n * against the DuplicatePolicy set (a merge policy rewrites the builder, so an unknown value must\n * never act as one), the booleans, the label and the prepare list's shape. View names are checked\n * by `prepare()` itself.\n * @param options - the freeze options\n */\nfunction checkFreezeOptions(options: FreezeOptions): void {\n if (options.duplicateEdges !== undefined) {\n assertDuplicatePolicy(\"duplicateEdges\", options.duplicateEdges, freezeOptionError);\n }\n for (const field of [\"arena\", \"release\", \"profile\", \"checksum\"] as const) {\n const value = options[field];\n if (value !== undefined && typeof value !== \"boolean\") {\n throw freezeOptionError(field, value);\n }\n }\n if (options.label !== undefined && typeof options.label !== \"string\") {\n throw freezeOptionError(\"label\", options.label);\n }\n if (options.prepare !== undefined && !Array.isArray(options.prepare)) {\n throw freezeOptionError(\"prepare\", options.prepare);\n }\n}\n\n// ============================================================ the pipeline\n\n/**\n * Run the freeze pipeline of design section 6.3 over a builder's state and produce the snapshot, the\n * FreezeReport and the staging the builder should hold afterwards. The context is never mutated: a\n * throw (E_SELF_LOOP, E_DUPLICATE_EDGE, E_DUPLICATE_EDGE_ID, E_TOO_LARGE, E_INVALID_WEIGHT,\n * E_COLUMN_TYPE) leaves the builder exactly as it was.\n * @param ctx - the builder's state\n * @param options - the freeze options\n * @returns the snapshot, the report and the staging to adopt\n */\nexport function runFreeze(ctx: FreezeContext, options: FreezeOptions): FreezeOutcome {\n const profile = options.profile === true;\n const timings: Record<string, number> = {};\n const start = profile ? now() : 0;\n let mark = start;\n const lap = (phase: string): void => {\n if (profile) {\n const t = now();\n timings[phase] = (timings[phase] ?? 0) + (t - mark);\n mark = t;\n }\n };\n const { directed } = ctx;\n const source = ctx.staging;\n checkFreezeOptions(options);\n const useArena = options.arena !== false;\n const policy = options.duplicateEdges ?? ctx.options.duplicateEdges;\n const loopPolicy = ctx.options.selfLoops;\n const oldNodeBound = source.nodeBound;\n const oldEdgeBound = source.edgeBound;\n const tombstonedEdges = oldEdgeBound - source.liveEdgeCount;\n\n // pre-checks that must not leave a half-applied freeze behind\n if (loopPolicy === \"error\") {\n checkSelfLoops(source);\n }\n const liveArcs = directed ? source.liveEdgeCount : 2 * source.liveEdgeCount - source.selfLoopCount;\n if (liveArcs > MAX_COUNT) {\n throw new GraphFormatError(\"E_TOO_LARGE\", `arc count ${liveArcs} exceeds MAX_COUNT`, {\n count: liveArcs,\n max: MAX_COUNT,\n });\n }\n\n // steps 1-2: compaction of tombstones and dropped loops into a fresh staging\n let staging = source;\n let nodeRemap: IndexRemap | null = null;\n let edgeRemap: IndexRemap | null = null;\n let droppedSelfLoops = 0;\n const dropLoops = loopPolicy === \"drop\" && source.selfLoopCount > 0;\n if (source.hasTombstones || dropLoops) {\n const nodes = remapKeepingBits(oldNodeBound, source.nodeAlive.view());\n const edges = remapKeepingBits(oldEdgeBound, dropLoops ? liveNonLoopBits(source) : source.edgeAlive.view());\n droppedSelfLoops = dropLoops ? source.selfLoopCount : 0;\n staging = compactStaging(source, {\n nodes,\n edges,\n edgeValues: null,\n mergedWeights: null,\n mergedWeightStored: null,\n mergedWeightSet: null,\n });\n nodeRemap = nodes;\n edgeRemap = edges;\n }\n lap(\"compact\");\n\n // steps 3-6: arcs and the two counting sorts\n const nodeCount = staging.nodeBound;\n let sorted = sortIntoCore(sortInputOf(staging, directed), useArena && policy === \"keep\");\n lap(\"sort\");\n\n // step 7: duplicate policy\n let walk: DuplicateWalk | null = null;\n let mergeRemap: IndexRemap | null = null;\n if (policy !== \"keep\") {\n const compaction = edgeRemap;\n walk = walkDuplicates(sorted, staging, directed, policy, ctx.options.weighted !== false, (e) =>\n compaction === null ? e : compaction.origin[e],\n );\n if (walk !== null) {\n const { survivorOf } = walk;\n const edges = remapSurvivors(survivorOf);\n let mergedWeights: Float64Array | null = null;\n let mergedWeightStored: U32 | null = null;\n if (walk.reduced !== null && walk.stored !== null) {\n mergedWeights = new Float64Array(edges.count);\n mergedWeightStored = new Uint32Array(bitmapWordCount(edges.count));\n for (let e = 0; e < survivorOf.length; e++) {\n if (survivorOf[e] === e && bitmapGet(walk.stored, e)) {\n mergedWeights[edges.remap[e]] = walk.reduced[e];\n bitmapSet(mergedWeightStored, edges.remap[e]);\n }\n }\n }\n let mergedWeightSet: U32 | null = null;\n if (walk.explicit !== null) {\n mergedWeightSet = new Uint32Array(bitmapWordCount(edges.count));\n for (let e = 0; e < survivorOf.length; e++) {\n if (survivorOf[e] === e && bitmapGet(walk.explicit, e)) {\n bitmapSet(mergedWeightSet, edges.remap[e]);\n }\n }\n }\n // refersTo edge values follow the survivor (design sections 5.11 and 7.3), not the row remap\n const edgeValues = new Uint32Array(survivorOf.length);\n for (let e = 0; e < survivorOf.length; e++) {\n edgeValues[e] = edges.remap[survivorOf[e]];\n }\n staging = compactStaging(staging, {\n nodes: identityRemap(nodeCount),\n edges,\n edgeValues,\n mergedWeights,\n mergedWeightStored,\n mergedWeightSet,\n });\n mergeRemap = edges;\n sorted = sortIntoCore(sortInputOf(staging, directed), useArena);\n } else if (useArena) {\n sorted = { ...sorted, core: copyCoreIntoArena(sorted.core) };\n }\n lap(\"duplicates\");\n }\n const edgeCount = staging.edgeBound;\n const { core, arcCount, selfLoopCount, flags } = sorted;\n\n // steps 8-10: weights, id map, columns\n const shadow = weightShadowColumn(staging, edgeCount, ctx.options.weightDtype);\n lap(\"weights\");\n const ids = idMapOf(staging, nodeCount);\n lap(\"ids\");\n const nodes = tableOf(\"node\", nodeCount, staging.nodeColumns);\n const edges = tableOf(\"edge\", edgeCount, staging.edgeColumns, shadow === null ? [] : [shadow]);\n const graph = graphTableOf(ctx.graphValues);\n const extensions = new Map<string, AttributeTable>();\n for (const table of staging.extensions) {\n extensions.set(table.name, tableOf(\"extension\", table.rowCount, table.columns));\n }\n lap(\"columns\");\n\n // step 12: the snapshot\n const parts: SnapshotParts = {\n label: options.label ?? null,\n serial: null,\n directed,\n nodeCount,\n edgeCount,\n arcCount,\n selfLoopCount,\n rowPtr: core.rowPtr,\n colIdx: core.colIdx,\n weights: core.weights,\n arcToEdge: core.arcToEdge,\n edgeToArc: core.edgeToArc,\n flags,\n ids,\n nodes,\n edges,\n graph,\n extensions,\n meta: ctx.meta,\n arena: core.arena,\n checksum: options.checksum === true,\n };\n const snapshot = createSnapshot(parts);\n if (options.prepare !== undefined && options.prepare.length > 0) {\n snapshot.prepare(options.prepare);\n }\n lap(\"snapshot\");\n if (profile) {\n timings.total = now() - start;\n }\n\n const nodeRemapOut = nodeRemap !== null && !isIdentity(nodeRemap.remap) ? nodeRemap.remap : null;\n const edgeRemapOut = composeEdgeRemap(oldEdgeBound, edgeRemap, walk, mergeRemap);\n const mergedEdges = walk === null ? 0 : walk.merged;\n const report: FreezeReport = Object.freeze({\n nodeRemap: nodeRemapOut,\n edgeRemap: edgeRemapOut,\n compacted: nodeRemapOut !== null || edgeRemapOut !== null,\n droppedSelfLoops,\n mergedEdges,\n droppedEdges: tombstonedEdges + droppedSelfLoops + mergedEdges,\n widened: Object.freeze(ctx.widened.map((w) => Object.freeze({ ...w }))),\n timings: Object.freeze({ ...timings }),\n });\n return { snapshot, report, staging };\n}\n","/**\n * GraphBuilder: the only mutable object in the package and the producer of snapshots (design\n * section 6). A long-lived, structure-of-arrays accumulator (compact.ts) that can be frozen\n * repeatedly through the pipeline of freeze.ts. Node indices are assigned in first-seen order and\n * edge indices in addEdge order (invariant I14); removal tombstones in O(degree) through the two\n * incidence lists; a compacting freeze renumbers the builder's own indices to equal the new\n * snapshot's (decision C7) and reports the remaps; freeze() never shares core arrays or columns with\n * the snapshot (I18) while the id `Map` and `ids` array are shared by design (section 4.2).\n *\n * Every public method and getter throws E_BUILDER_DISPOSED after dispose(); every throw leaves the\n * builder in a consistent state (design section 11.1): the failing operation is not applied (the\n * record, composition and expansion methods validate everything they will write before the first\n * mutation), and a freeze that fails commits nothing.\n */\n\nimport { assertJsonValue, dtypeOfArray, metaToDecl, resolveColumnMeta } from \"../columns/column.js\";\nimport { assertWellFormedString } from \"../columns/dictionary.js\";\nimport { type InferredDtype, wideningRank } from \"../columns/infer.js\";\nimport { INVALID_INDEX, MAX_COUNT } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { describeId, validateNodeId } from \"../ids/node-id-map.js\";\nimport { detachString } from \"../ids/string-store.js\";\nimport { EMPTY_GRAPH_META, resolveGraphMeta } from \"../snapshot/graph-meta.js\";\nimport {\n type BuilderOptionsPatch,\n type Column,\n type ColumnDecl,\n type ColumnDeclPatch,\n type ColumnDomain,\n type ColumnHandle,\n type ColumnMeta,\n type Dtype,\n type DuplicatePolicy,\n type ExtensionHandle,\n type F32,\n type F64,\n type FreezeOptions,\n type FreezeReport,\n type GraphBuilderContract,\n type GraphBuilderOptions,\n type GraphMeta,\n type GraphMetaPatch,\n type GraphSnapshot,\n type NodeId,\n type ResolvedBuilderOptions,\n type SetDirectedOptions,\n type TypedArrayData,\n type U32,\n} from \"../types/index.js\";\nimport {\n createStagingColumn,\n type ExtensionStaging,\n type IndexMaps,\n inferInitialDtype,\n inferredEquivalent,\n Staging,\n StagingColumn,\n} from \"./compact.js\";\nimport { type FreezeContext, type GraphValue, runFreeze, type Widening } from \"./freeze.js\";\nimport { assertDuplicatePolicy } from \"./options.js\";\n\n// ============================================================ option handling\n\nconst SELF_LOOP_POLICIES: ReadonlySet<string> = new Set([\"keep\", \"drop\", \"error\"]);\nconst WEIGHT_DTYPES: ReadonlySet<string> = new Set([\"f32\", \"f64\"]);\n/** The name of the bool edge column written by an in-place expansion (design section 3.6). */\nconst DIRECTED_COLUMN = \"graphty.directed\";\n\n/** The name of the u32 edge column pairing the halves of an expanded edge (design section 3.6). */\nconst PAIR_COLUMN = \"graphty.pair\";\n\n/** The builder's option fields other than the current direction, resolved once at construction. */\ninterface FixedOptions {\n readonly weighted: boolean | \"auto\";\n readonly weightDtype: \"f32\" | \"f64\";\n readonly duplicateEdges: DuplicatePolicy;\n readonly selfLoops: \"keep\" | \"drop\" | \"error\";\n readonly addMissingNodes: boolean;\n readonly expectedNodes: number | null;\n readonly expectedEdges: number | null;\n}\n\n/**\n * The E_UNSUPPORTED error for an option value outside its documented set.\n * @param field - the option name\n * @param found - the value\n * @returns the error\n */\nfunction optionError(field: string, found: unknown): GraphFormatError {\n return new GraphFormatError(\"E_UNSUPPORTED\", `builder option ${field} has an unsupported value ${String(found)}`, {\n field,\n found,\n reason: \"unsupported option\",\n });\n}\n\n/**\n * Resolve the constructor options (design section 12.2) with their defaults, checking every enum.\n * @param options - the constructor options\n * @returns the fixed options and the initial direction\n */\nfunction resolveOptions(options: GraphBuilderOptions): { readonly fixed: FixedOptions; readonly directed: boolean } {\n if (typeof options !== \"object\" || options === null) {\n throw optionError(\"options\", options);\n }\n if (typeof options.directed !== \"boolean\") {\n throw optionError(\"directed\", options.directed);\n }\n const weighted = options.weighted ?? \"auto\";\n if (weighted !== \"auto\" && typeof weighted !== \"boolean\") {\n throw optionError(\"weighted\", weighted);\n }\n const weightDtype = options.weightDtype ?? \"f32\";\n if (!WEIGHT_DTYPES.has(weightDtype)) {\n throw optionError(\"weightDtype\", weightDtype);\n }\n const duplicateEdges = assertDuplicatePolicy(\"duplicateEdges\", options.duplicateEdges ?? \"keep\", optionError);\n const selfLoops = options.selfLoops ?? \"keep\";\n if (!SELF_LOOP_POLICIES.has(selfLoops)) {\n throw optionError(\"selfLoops\", selfLoops);\n }\n const addMissingNodes = options.addMissingNodes ?? true;\n if (typeof addMissingNodes !== \"boolean\") {\n throw optionError(\"addMissingNodes\", addMissingNodes);\n }\n const hint = (field: \"expectedNodes\" | \"expectedEdges\"): number | null => {\n const value = options[field];\n if (value === undefined) {\n return null;\n }\n if (!Number.isInteger(value) || value < 0) {\n throw optionError(field, value);\n }\n return value;\n };\n return {\n fixed: {\n weighted,\n weightDtype,\n duplicateEdges,\n selfLoops,\n addMissingNodes,\n expectedNodes: hint(\"expectedNodes\"),\n expectedEdges: hint(\"expectedEdges\"),\n },\n directed: options.directed,\n };\n}\n\n/**\n * Drop the explicitly undefined fields of a patch so it can be spread over defaults.\n * @param patch - the patch\n * @returns the defined fields\n */\nfunction definedFields(patch: BuilderOptionsPatch): Partial<GraphBuilderOptions> {\n const out: Partial<GraphBuilderOptions> = {};\n for (const key of Object.keys(patch) as (keyof GraphBuilderOptions)[]) {\n const value = patch[key];\n if (value !== undefined) {\n (out as Record<string, unknown>)[key] = value;\n }\n }\n return out;\n}\n\n/**\n * Whether two column declarations describe the same storage (the \"same declaration\" rule of design\n * section 11.3 for a repeated declare*Column).\n * @param a - one resolved metadata\n * @param b - the other\n * @returns true when dtype, components and the list child agree\n */\nfunction sameShape(a: ColumnMeta, b: ColumnMeta): boolean {\n return (\n a.dtype === b.dtype &&\n a.components === b.components &&\n a.itemDtype === b.itemDtype &&\n a.itemComponents === b.itemComponents\n );\n}\n\n/** The name index of one staging column array (see GraphBuilder.columnIndex). */\ninterface ColumnNameIndex {\n /** The array the map describes. */\n readonly columns: readonly StagingColumn[];\n /** Column name -> index in `columns`. */\n readonly map: Map<string, number>;\n}\n\n// ============================================================ the class\n\n/**\n * The mutable accumulator that produces frozen snapshots (design sections 6 and 12.2). Construct\n * with `{ directed }` (required) and the policies of GraphBuilderOptions; push nodes and edges by id\n * or by index; declare and write attribute columns; call `freeze()` as often as needed. Implements\n * GraphSink, the subset importers program against (design section 8.3).\n */\nexport class GraphBuilder implements GraphBuilderContract {\n private readonly fixed: FixedOptions;\n\n private directedValue: boolean;\n\n private locked = false;\n\n private optionsCache: ResolvedBuilderOptions | null = null;\n\n private staging: Staging;\n\n /** Column name -> index of the node staging columns; rebuilt when the column array is replaced. */\n private nodeNames: ColumnNameIndex | null = null;\n\n /** Column name -> index of the edge staging columns; rebuilt when the column array is replaced. */\n private edgeNames: ColumnNameIndex | null = null;\n\n private graphValues = new Map<string, GraphValue>();\n\n private metaValue: GraphMeta = EMPTY_GRAPH_META;\n\n private widenings: Widening[] = [];\n\n private mutations = 0;\n\n private dirtyFlag = true;\n\n private disposed = false;\n\n /**\n * Create an empty builder.\n * @param options - the options; `directed` is required\n */\n constructor(options: GraphBuilderOptions) {\n const resolved = resolveOptions(options);\n this.fixed = resolved.fixed;\n this.directedValue = resolved.directed;\n this.staging = this.freshStaging();\n }\n\n /**\n * Seed a builder from a snapshot in O(n + m) (design section 6.6): ids, edges in logical order\n * with their declared orientation, weights (through the role-\"weight\" column when present, so an\n * f64 shadow and the explicit / omitted record survive), columns, extension tables and meta;\n * indices are preserved. The staging precision follows an f64 shadow unless the patch says\n * otherwise.\n * @param snapshot - the snapshot to continue\n * @param options - option overrides; `directed` defaults to the snapshot's\n * @returns the builder\n */\n static from(snapshot: GraphSnapshot, options?: BuilderOptionsPatch): GraphBuilder {\n const patch = definedFields(options ?? {});\n const shadow = snapshot.edges.byRole(\"weight\");\n const weightDtype = patch.weightDtype ?? (shadow !== null && shadow.dtype === \"f64\" ? \"f64\" : undefined);\n // a declared weight array is never dropped (design section 3.7): a weighted snapshot whose\n // edges all omitted the weight seeds a `weighted: true` builder unless the patch says otherwise\n const weighted = patch.weighted ?? (snapshot.flags.weighted ? true : undefined);\n const builder = new GraphBuilder({\n directed: snapshot.directed,\n expectedNodes: snapshot.nodeCount,\n expectedEdges: snapshot.edgeCount,\n ...patch,\n ...(weightDtype === undefined ? {} : { weightDtype }),\n ...(weighted === undefined ? {} : { weighted }),\n });\n builder.addGraph(snapshot, { onDuplicateNode: \"error\" });\n builder.setMeta(snapshot.meta);\n return builder;\n }\n\n // ---------------------------------------------------------------- options and state\n\n /**\n * The resolved options; `directed` is the current value.\n * @returns the options\n */\n get options(): ResolvedBuilderOptions {\n this.check();\n this.optionsCache ??= Object.freeze({ directed: this.directedValue, ...this.fixed });\n return this.optionsCache;\n }\n\n /**\n * The current direction.\n * @returns true when directed\n */\n get directed(): boolean {\n this.check();\n return this.directedValue;\n }\n\n /**\n * Whether lockDirected() was called.\n * @returns true when locked\n */\n get directedLocked(): boolean {\n this.check();\n return this.locked;\n }\n\n /**\n * Live node count.\n * @returns the count\n */\n get nodeCount(): number {\n this.check();\n return this.staging.liveNodeCount;\n }\n\n /**\n * Live edge count (exact, from the incidence lists).\n * @returns the count\n */\n get edgeCount(): number {\n this.check();\n return this.staging.liveEdgeCount;\n }\n\n /**\n * Next node index to be assigned.\n * @returns the bound\n */\n get nodeBound(): number {\n this.check();\n return this.staging.nodeBound;\n }\n\n /**\n * Next logical edge index to be assigned.\n * @returns the bound\n */\n get edgeBound(): number {\n this.check();\n return this.staging.edgeBound;\n }\n\n /**\n * Increments on every topology or weight mutation; column writes and freeze() do not count.\n * @returns the count\n */\n get mutationCount(): number {\n this.check();\n return this.mutations;\n }\n\n /**\n * Whether the builder was mutated since the last freeze() (true for a builder never frozen).\n * @returns true when a fresh freeze would differ from the last one\n */\n get dirty(): boolean {\n this.check();\n return this.dirtyFlag;\n }\n\n /**\n * Change the direction (design section 6.6): a no-op when unchanged; free while no live edge\n * exists; with live edges only undirected -> directed with `expand`, which appends a mirror edge\n * for every live edge and writes the graphty.directed / graphty.pair columns. E_DIRECTED when\n * locked or refused.\n * @param directed - the new direction\n * @param options - `expand` for the in-place expansion\n */\n setDirected(directed: boolean, options?: SetDirectedOptions): void {\n this.check();\n if (directed === this.directedValue) {\n return;\n }\n if (this.locked) {\n throw new GraphFormatError(\"E_DIRECTED\", \"the builder's direction is locked\", {\n reason: \"locked\",\n directed: this.directedValue,\n });\n }\n if (this.staging.liveEdgeCount === 0) {\n this.directedValue = directed;\n this.optionsCache = null;\n this.mutated();\n return;\n }\n if (!directed) {\n throw new GraphFormatError(\"E_DIRECTED\", \"a builder with edges cannot become undirected\", {\n reason: \"edges present\",\n edgeCount: this.staging.liveEdgeCount,\n });\n }\n if (options?.expand !== true) {\n throw new GraphFormatError(\n \"E_DIRECTED\",\n \"an undirected builder with edges becomes directed only with { expand: true }\",\n { reason: \"expand required\", edgeCount: this.staging.liveEdgeCount },\n );\n }\n this.expandToDirected();\n }\n\n /** Fix the direction: every later changing setDirected() throws E_DIRECTED. */\n lockDirected(): void {\n this.check();\n this.locked = true;\n }\n\n // ---------------------------------------------------------------- nodes\n\n /**\n * Add a node, or return the index of the live node with this id; a tombstoned id is revived at\n * its old index (design section 6.6).\n * @param id - the node id; E_INVALID_ID when illegal\n * @returns the node index\n */\n addNode(id: NodeId): number {\n this.check();\n return this.addValidatedNode(validateNodeId(id));\n }\n\n /**\n * Add many nodes, writing every id's index (new or existing) into `out`.\n * @param ids - the ids\n * @param out - receives the indices; allocated when omitted; E_COLUMN_LENGTH when too short\n * @returns `out`\n */\n addNodes(ids: Iterable<NodeId>, out?: U32): U32 {\n this.check();\n const list = Array.isArray(ids) ? (ids as readonly NodeId[]) : [...ids];\n const validated = list.map((id) => validateNodeId(id));\n if (out !== undefined && out.length < validated.length) {\n throw new GraphFormatError(\"E_COLUMN_LENGTH\", `out has ${out.length} entries for ${validated.length} ids`, {\n expected: validated.length,\n found: out.length,\n });\n }\n const target = out ?? new Uint32Array(validated.length);\n for (let i = 0; i < validated.length; i++) {\n target[i] = this.addValidatedNode(validated[i]);\n }\n return target;\n }\n\n /**\n * Append `count` nodes whose ids are their own indices, never touching the id Map while every\n * node is anonymous (design section 6.6).\n * @param count - how many; E_TOO_LARGE beyond MAX_COUNT; E_DUPLICATE_ID when an index is already an id\n * @returns the first new index\n */\n addAnonymousNodes(count: number): number {\n this.check();\n if (!Number.isInteger(count) || count < 0) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `node count ${count} is not a non-negative integer`, {\n count,\n });\n }\n const { staging } = this;\n const first = staging.nodeBound;\n this.checkNodeLimit(count);\n if (staging.idToIndex !== null) {\n for (let i = first; i < first + count; i++) {\n if (staging.idToIndex.has(i)) {\n throw new GraphFormatError(\n \"E_DUPLICATE_ID\",\n `node id ${i} exists; anonymous node ${i} cannot use it`,\n {\n id: i,\n index: staging.idToIndex.get(i),\n },\n );\n }\n }\n }\n for (let i = 0; i < count; i++) {\n staging.pushNode(null);\n }\n if (count > 0) {\n this.mutated();\n }\n return first;\n }\n\n /**\n * Whether a live node has this id (total: an illegal id is simply absent).\n * @param id - the id\n * @returns true when present and alive\n */\n hasNode(id: NodeId): boolean {\n this.check();\n return this.lookup(id) !== INVALID_INDEX;\n }\n\n /**\n * Total lookup of a live node.\n * @param id - the id\n * @returns the index, or INVALID_INDEX\n */\n indexOf(id: NodeId): number {\n this.check();\n return this.lookup(id);\n }\n\n /**\n * The id of a live node index.\n * @param index - the index; E_INDEX_RANGE when out of range or tombstoned\n * @returns the id\n */\n idOf(index: number): NodeId {\n this.check();\n const { staging } = this;\n if (!this.isLiveNode(index)) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `node index ${index} is out of range or removed`, {\n index,\n bound: staging.nodeBound,\n });\n }\n return staging.ids === null ? index : staging.ids[index];\n }\n\n /**\n * Tombstone a node and every live incident edge (O(degree)); bumps mutationCount.\n * @param id - the id; E_UNKNOWN_NODE when absent or already removed\n * @returns the removed live incident edge indices, ascending\n */\n removeNode(id: NodeId): U32 {\n this.check();\n const index = this.lookup(id);\n if (index === INVALID_INDEX) {\n throw new GraphFormatError(\"E_UNKNOWN_NODE\", `unknown node id ${describeId(id)}`, { id });\n }\n return this.removeLiveNode(index);\n }\n\n /**\n * Tombstone a node by index and every live incident edge.\n * @param index - the index; E_UNKNOWN_NODE (details.index) when out of range or removed\n * @returns the removed live incident edge indices, ascending\n */\n removeNodeByIndex(index: number): U32 {\n this.check();\n if (!this.isLiveNode(index)) {\n throw new GraphFormatError(\"E_UNKNOWN_NODE\", `node index ${index} is out of range or removed`, { index });\n }\n return this.removeLiveNode(index);\n }\n\n /**\n * Grow staging capacity ahead of a bulk push.\n * @param nodes - the node count to fit\n * @param edges - the edge count to fit\n */\n reserve(nodes?: number, edges?: number): void {\n this.check();\n const check = (field: string, value: number | undefined): number => {\n if (value === undefined) {\n return 0;\n }\n if (!Number.isInteger(value) || value < 0 || value > MAX_COUNT) {\n throw new GraphFormatError(\n \"E_TOO_LARGE\",\n `reserve(${field}) ${value} is not an integer in [0, MAX_COUNT]`,\n {\n field,\n count: value,\n max: MAX_COUNT,\n },\n );\n }\n return value;\n };\n this.staging.reserve(check(\"nodes\", nodes), check(\"edges\", edges));\n }\n\n // ---------------------------------------------------------------- edges\n\n /**\n * Add a logical edge by id; unknown endpoints are created when addMissingNodes is set (a\n * tombstoned endpoint is revived), else E_UNKNOWN_NODE. A NaN weight is E_INVALID_WEIGHT.\n * @param source - source id\n * @param target - target id\n * @param weight - the weight; 1 when omitted\n * @returns the logical edge index\n */\n addEdge(source: NodeId, target: NodeId, weight?: number): number {\n this.check();\n const w = this.checkWeight(weight, undefined);\n const u = this.resolveEndpoint(validateNodeId(source));\n const v = this.resolveEndpoint(validateNodeId(target));\n return this.pushEdge(u, v, w);\n }\n\n /**\n * Add a logical edge by node index.\n * @param u - source index; E_UNKNOWN_NODE (details.index) when out of range or removed\n * @param v - target index\n * @param weight - the weight; 1 when omitted\n * @returns the logical edge index\n */\n addEdgeByIndex(u: number, v: number, weight?: number): number {\n this.check();\n const w = this.checkWeight(weight, undefined);\n this.checkLiveNode(u);\n this.checkLiveNode(v);\n return this.pushEdge(u, v, w);\n }\n\n /**\n * Bulk add edges by node index (the index-space path used with addAnonymousNodes). Everything is\n * validated before the first edge is pushed.\n * @param src - source indices\n * @param dst - target indices; E_COLUMN_LENGTH when the lengths differ\n * @param weights - per-edge weights; 1 when omitted; E_INVALID_WEIGHT for NaN\n * @returns the first new logical edge index\n */\n addEdges(src: U32, dst: U32, weights?: F32 | F64): number {\n this.check();\n const count = src.length;\n if (dst.length !== count || (weights !== undefined && weights.length !== count)) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `addEdges: src has ${count} entries, dst ${dst.length}, weights ${weights === undefined ? \"none\" : weights.length}`,\n { src: count, dst: dst.length, weights: weights?.length ?? null },\n );\n }\n for (let i = 0; i < count; i++) {\n this.checkLiveNode(src[i]);\n this.checkLiveNode(dst[i]);\n }\n let explicit: F32 | F64 | null = null;\n if (weights !== undefined) {\n for (let i = 0; i < count; i++) {\n this.checkWeight(weights[i], i);\n }\n explicit = this.fixed.weighted === false ? null : weights;\n }\n this.checkEdgeLimit(count, this.arcsOf(src, dst, count));\n const { staging } = this;\n staging.reserve(0, staging.edgeBound + count);\n const first = staging.pushEdges(src, dst, explicit);\n if (count > 0) {\n this.mutated();\n }\n return first;\n }\n\n /**\n * Bulk add edges by id. Every id and weight is validated before anything is added.\n * @param src - source ids\n * @param dst - target ids; E_COLUMN_LENGTH when the lengths differ\n * @param weights - per-edge weights; 1 when omitted\n * @returns the first new logical edge index\n */\n addEdgesByIds(src: ArrayLike<NodeId>, dst: ArrayLike<NodeId>, weights?: ArrayLike<number>): number {\n this.check();\n const count = src.length;\n if (dst.length !== count || (weights !== undefined && weights.length !== count)) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `addEdgesByIds: src has ${count} entries, dst ${dst.length}, weights ${weights === undefined ? \"none\" : weights.length}`,\n { src: count, dst: dst.length, weights: weights?.length ?? null },\n );\n }\n const sources = new Array<NodeId>(count);\n const targets = new Array<NodeId>(count);\n const checked = new Array<number | undefined>(count);\n for (let i = 0; i < count; i++) {\n sources[i] = validateNodeId(src[i]);\n targets[i] = validateNodeId(dst[i]);\n checked[i] = this.checkWeight(weights === undefined ? undefined : weights[i], i);\n }\n if (!this.fixed.addMissingNodes) {\n for (let i = 0; i < count; i++) {\n this.requireLive(sources[i]);\n this.requireLive(targets[i]);\n }\n }\n this.checkEdgeLimit(count, this.directedValue ? count : 2 * count);\n const first = this.staging.edgeBound;\n for (let i = 0; i < count; i++) {\n const u = this.resolveEndpoint(sources[i]);\n const v = this.resolveEndpoint(targets[i]);\n this.staging.pushEdge(u, v, checked[i]);\n }\n if (count > 0) {\n this.mutated();\n }\n return first;\n }\n\n /**\n * Tombstone an edge (O(1)); bumps mutationCount when something was removed.\n * @param edge - the logical edge index\n * @returns true when a live edge was removed\n */\n removeEdge(edge: number): boolean {\n this.check();\n if (!this.isLiveEdge(edge)) {\n return false;\n }\n this.staging.killEdge(edge);\n this.mutated();\n return true;\n }\n\n /**\n * Whether an edge index is live.\n * @param edge - the logical edge index\n * @returns true when live\n */\n hasEdge(edge: number): boolean {\n this.check();\n return this.isLiveEdge(edge);\n }\n\n /**\n * Read a live edge's endpoints back.\n * @param edge - the logical edge index; E_INDEX_RANGE when out of range or removed\n * @returns [source index, target index] in declared orientation\n */\n edgeEndpoints(edge: number): readonly [source: number, target: number] {\n this.check();\n this.checkEdge(edge);\n return [this.staging.src.get(edge), this.staging.dst.get(edge)];\n }\n\n /**\n * Read a live edge's weight back.\n * @param edge - the logical edge index; E_INDEX_RANGE when out of range or removed\n * @returns the weight (1 when unweighted)\n */\n edgeWeight(edge: number): number {\n this.check();\n this.checkEdge(edge);\n const { weight } = this.staging;\n return weight === null ? 1 : weight.get(edge);\n }\n\n /**\n * Set the weight of a live edge, allocating the weight array on first use and marking the weight\n * explicit; bumps mutationCount.\n * @param edge - the logical edge index; E_INDEX_RANGE when out of range or removed\n * @param weight - the weight; E_INVALID_WEIGHT for NaN\n */\n setEdgeWeight(edge: number, weight: number): void {\n this.check();\n this.checkEdge(edge);\n const w = this.checkWeight(weight, undefined);\n const { staging } = this;\n if (w !== undefined) {\n staging.ensureWeights().set(edge, w);\n staging.trackWeight(edge, true);\n }\n this.mutated();\n }\n\n /**\n * Live edges leaving a node, from the out-list (O(degree)). On an undirected builder every\n * incident edge leaves the node (invariant I7, the snapshot's row holds both orientations), so\n * both lists are walked and a self-loop is listed once.\n * @param index - the node index; E_INDEX_RANGE when out of range\n * @returns a fresh ascending array of live edge indices\n */\n outEdgesOf(index: number): U32 {\n this.check();\n this.checkNodeIndex(index);\n return this.directedValue ? this.staging.outEdges(index) : this.staging.incidentEdges(index);\n }\n\n /**\n * Live edges entering a node, from the in-list (O(degree)); on an undirected builder the same\n * set as outEdgesOf (the alias rule of inDegree === outDegree).\n * @param index - the node index; E_INDEX_RANGE when out of range\n * @returns a fresh ascending array of live edge indices\n */\n inEdgesOf(index: number): U32 {\n this.check();\n this.checkNodeIndex(index);\n return this.directedValue ? this.staging.inEdges(index) : this.staging.incidentEdges(index);\n }\n\n /**\n * Live edges u -> v (undirected: either orientation), from the incidence lists.\n * @param u - source index; E_INDEX_RANGE when out of range\n * @param v - target index; E_INDEX_RANGE when out of range\n * @returns a fresh ascending array of live edge indices\n */\n findEdges(u: number, v: number): U32 {\n this.check();\n this.checkNodeIndex(u);\n this.checkNodeIndex(v);\n const { staging } = this;\n const found: number[] = [];\n for (let e = staging.firstOut.get(u); e !== INVALID_INDEX; e = staging.nextOut.get(e)) {\n if (staging.edgeAlive.get(e) && staging.dst.get(e) === v) {\n found.push(e);\n }\n }\n if (!this.directedValue && u !== v) {\n for (let e = staging.firstIn.get(u); e !== INVALID_INDEX; e = staging.nextIn.get(e)) {\n if (staging.edgeAlive.get(e) && staging.src.get(e) === v) {\n found.push(e);\n }\n }\n }\n return Uint32Array.from(found).sort();\n }\n\n // ---------------------------------------------------------------- attributes\n\n /**\n * Declare a node column; the same shape again returns the existing handle, a different shape is\n * E_COLUMN_EXISTS, a taken role E_DUPLICATE_ROLE.\n * @param decl - the declaration\n * @returns the column handle\n */\n declareNodeColumn(decl: ColumnDecl): ColumnHandle {\n this.check();\n return this.declare(\"node\", decl);\n }\n\n /**\n * Declare an edge column; the same shape again returns the existing handle, a different shape is\n * E_COLUMN_EXISTS, a taken role E_DUPLICATE_ROLE.\n * @param decl - the declaration\n * @returns the column handle\n */\n declareEdgeColumn(decl: ColumnDecl): ColumnHandle {\n this.check();\n return this.declare(\"edge\", decl);\n }\n\n /**\n * Look up a node column handle.\n * @param name - the column name\n * @returns the handle, or INVALID_INDEX when absent\n */\n nodeColumn(name: string): ColumnHandle {\n this.check();\n return this.handleOf(this.staging.nodeColumns, name);\n }\n\n /**\n * Look up an edge column handle.\n * @param name - the column name\n * @returns the handle, or INVALID_INDEX when absent\n */\n edgeColumn(name: string): ColumnHandle {\n this.check();\n return this.handleOf(this.staging.edgeColumns, name);\n }\n\n /**\n * Set one node cell; a string column name auto-declares an inferred column (design section 5.1)\n * on the first set value, and an unset value for an undeclared name is a no-op.\n * @param column - the handle (E_UNKNOWN_COLUMN when stale) or name\n * @param index - the node index; E_INDEX_RANGE when out of range\n * @param value - the value; undefined / null unset the row\n */\n setNodeValue(column: ColumnHandle | string, index: number, value: unknown): void {\n this.check();\n this.checkNodeIndex(index);\n this.writeCell(\"node\", column, index, value);\n }\n\n /**\n * Set one edge cell; a string column name auto-declares an inferred column.\n * @param column - the handle (E_UNKNOWN_COLUMN when stale) or name\n * @param edge - the logical edge index; E_INDEX_RANGE when out of range\n * @param value - the value; undefined / null unset the row\n */\n setEdgeValue(column: ColumnHandle | string, edge: number, value: unknown): void {\n this.check();\n this.checkEdgeIndex(edge);\n this.writeCell(\"edge\", column, edge, value);\n }\n\n /**\n * Widen an inferred node column to a wider dtype of the design section 5.1 order without\n * changing any value (an importer that knows from the lexical grammar that a column of `2.0`\n * cells is f64 although every value so far was integral). A no-op when the column is already\n * as wide; E_COLUMN_TYPE for a declared (non-inferred) column, a dtype outside the inference\n * order or a narrower one; the widening is reported in FreezeReport.widened.\n * @param column - the handle (E_UNKNOWN_COLUMN when stale) or name (E_UNKNOWN_COLUMN when absent)\n * @param dtype - the dtype to widen to\n */\n widenNodeColumn(column: ColumnHandle | string, dtype: Dtype): void {\n this.check();\n this.widenColumn(\"node\", column, dtype);\n }\n\n /**\n * Widen an inferred edge column to a wider dtype of the design section 5.1 order without\n * changing any value; see widenNodeColumn().\n * @param column - the handle (E_UNKNOWN_COLUMN when stale) or name (E_UNKNOWN_COLUMN when absent)\n * @param dtype - the dtype to widen to\n */\n widenEdgeColumn(column: ColumnHandle | string, dtype: Dtype): void {\n this.check();\n this.widenColumn(\"edge\", column, dtype);\n }\n\n /**\n * Bulk-set a node column from a typed array (copied into staging); replaces a column of the same\n * name. The length must be nodeBound * components (bool: ceil(nodeBound / 32) words).\n * @param name - the column name\n * @param data - the values\n * @param decl - declaration fields (dtype defaults to the array's)\n */\n setNodeColumn(name: string, data: TypedArrayData, decl?: ColumnDeclPatch): void {\n this.check();\n this.setBulkColumn(\"node\", this.staging.nodeBound, name, data, decl ?? {});\n }\n\n /**\n * Bulk-set an edge column from a typed array (copied into staging); replaces a column of the same\n * name. The length must be edgeBound * components.\n * @param name - the column name\n * @param data - the values\n * @param decl - declaration fields (dtype defaults to the array's)\n */\n setEdgeColumn(name: string, data: TypedArrayData, decl?: ColumnDeclPatch): void {\n this.check();\n this.setBulkColumn(\"edge\", this.staging.edgeBound, name, data, decl ?? {});\n }\n\n /**\n * Set a graph-level attribute (the graph table's single row); the value and declaration are\n * checked now, the column is built at freeze.\n * @param name - the column name\n * @param value - the value; undefined unsets it\n * @param decl - declaration fields for the column\n */\n setGraphValue(name: string, value: unknown, decl?: ColumnDeclPatch): void {\n this.check();\n const patch = decl ?? {};\n // build once now so a bad value or declaration fails at the call, not at freeze\n resolveColumnMeta(name, \"graph\", { dtype: \"json\", ...patch });\n if (value !== undefined) {\n buildGraphColumn(name, value, patch);\n }\n this.graphValues.set(name, { decl: patch, value });\n }\n\n /**\n * Merge fields into the graph metadata (design section 5.9); undefined fields are left alone,\n * `extra` must be a JSON value (E_COLUMN_TYPE with details.field otherwise).\n * @param meta - the fields to set\n */\n setMeta(meta: GraphMetaPatch): void {\n this.check();\n this.metaValue = resolveGraphMeta(this.metaValue, meta);\n }\n\n /**\n * Create an extension table (design section 5.10).\n * @param name - the table name; E_COLUMN_EXISTS when taken\n * @param decls - its columns; E_COLUMN_EXISTS for a repeated name, E_DUPLICATE_ROLE for a repeated role\n * @returns the table handle\n */\n addExtensionTable(name: string, decls: readonly ColumnDecl[]): ExtensionHandle {\n this.check();\n const { staging } = this;\n if (staging.extensions.some((table) => table.name === name)) {\n throw new GraphFormatError(\"E_COLUMN_EXISTS\", `extension table \"${name}\" already exists`, { table: name });\n }\n const columns: StagingColumn[] = [];\n for (const decl of decls) {\n const column = createStagingColumn(decl.name, \"extension\", decl, false);\n if (columns.some((other) => other.meta.name === column.meta.name)) {\n throw new GraphFormatError(\"E_COLUMN_EXISTS\", `column \"${decl.name}\" is declared twice in \"${name}\"`, {\n table: name,\n column: decl.name,\n });\n }\n checkRole(columns, column.meta, name);\n columns.push(column);\n }\n staging.extensions.push({ name, columns, rowCount: 0 });\n return (staging.extensions.length - 1) as ExtensionHandle;\n }\n\n /**\n * Append a row to an extension table.\n * @param table - the table handle; E_INDEX_RANGE when unknown\n * @param values - one value per declared column; E_COLUMN_LENGTH otherwise\n * @returns the new row index\n */\n addExtensionRow(table: ExtensionHandle, values: readonly unknown[]): number {\n this.check();\n const target = this.extensionOf(table);\n if (values.length !== target.columns.length) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `extension table \"${target.name}\" has ${target.columns.length} columns; ${values.length} values given`,\n { table: target.name, expected: target.columns.length, found: values.length },\n );\n }\n const row = target.rowCount;\n const checked = target.columns.map((column, i) => {\n const value = this.checkReference(column.meta, values[i]);\n column.checkValue(row, value);\n return value;\n });\n for (let i = 0; i < checked.length; i++) {\n target.columns[i].write(row, checked[i]);\n }\n target.rowCount = row + 1;\n return row;\n }\n\n /**\n * Add a node from a record: every key present overwrites that row (last-write-wins per attribute,\n * design section 6.6), auto-declaring inferred columns.\n * @param id - the node id\n * @param attrs - attribute values keyed by column name\n * @returns the node index\n */\n addNodeRecord(id: NodeId, attrs: Readonly<Record<string, unknown>>): number {\n this.check();\n const validated = validateNodeId(id);\n const keys = Object.keys(attrs);\n // every attribute is validated before the node is added (design section 11.1)\n this.checkCells(\"node\", this.prospectiveNodeIndex(validated), keys, attrs);\n const index = this.addValidatedNode(validated);\n for (const key of keys) {\n this.writeCell(\"node\", key, index, attrs[key]);\n }\n return index;\n }\n\n /**\n * Add an edge from a record; always a new edge (parallels are kept). The weight comes from\n * `weightKey` (\"weight\" by default; null = none) and must be a number (E_INVALID_WEIGHT).\n * @param source - source id\n * @param target - target id\n * @param attrs - attribute values keyed by column name\n * @param weightKey - the key holding the weight; default \"weight\"; null = no weight\n * @returns the logical edge index\n */\n addEdgeRecord(\n source: NodeId,\n target: NodeId,\n attrs: Readonly<Record<string, unknown>>,\n weightKey?: string | null,\n ): number {\n this.check();\n const key = weightKey === undefined ? \"weight\" : weightKey;\n let weight: number | undefined;\n if (key !== null && Object.prototype.hasOwnProperty.call(attrs, key)) {\n const raw = attrs[key];\n if (raw !== undefined && raw !== null) {\n if (typeof raw !== \"number\") {\n throw new GraphFormatError(\"E_INVALID_WEIGHT\", `edge weight \"${key}\" is not a number`, {\n key,\n found: typeof raw,\n });\n }\n weight = raw;\n }\n }\n const keys = Object.keys(attrs).filter((name) => name !== key);\n // every attribute is validated before the edge (and any missing endpoint) is added (design 11.1)\n this.checkWeight(weight, undefined);\n this.checkCells(\"edge\", this.staging.edgeBound, keys, attrs);\n const edge = this.addEdge(source, target, weight);\n for (const name of keys) {\n this.writeCell(\"edge\", name, edge, attrs[name]);\n }\n return edge;\n }\n\n // ---------------------------------------------------------------- composition\n\n /**\n * Append another snapshot (design section 6.6): nodes are merged by id (\"merge\": the incoming set\n * rows overwrite; \"error\": E_DUPLICATE_ID), edges are appended in logical order with their\n * declared orientation and weights, columns declared in both graphs widen to the union dtype of\n * design section 5.1, dictionaries are re-interned, extension tables are appended with their\n * references rewritten, and graph attributes overwrite by name.\n * @param snapshot - the snapshot to append\n * @param options - duplicate-id handling\n * @param options.onDuplicateNode - \"merge\" (default) or \"error\"\n */\n addGraph(snapshot: GraphSnapshot, options?: { readonly onDuplicateNode?: \"merge\" | \"error\" | undefined }): void {\n this.check();\n const onDuplicate = options?.onDuplicateNode ?? \"merge\";\n if (onDuplicate !== \"merge\" && onDuplicate !== \"error\") {\n throw new GraphFormatError(\n \"E_UNSUPPORTED\",\n `addGraph option onDuplicateNode has an unsupported value ${String(onDuplicate)}`,\n { field: \"onDuplicateNode\", found: onDuplicate, reason: \"unsupported option\" },\n );\n }\n if (snapshot.directed !== this.directedValue) {\n throw new GraphFormatError(\n \"E_DIRECTED\",\n `a ${snapshot.directed ? \"directed\" : \"undirected\"} snapshot cannot be appended to a ${this.directedValue ? \"directed\" : \"undirected\"} builder`,\n { reason: \"direction mismatch\", directed: this.directedValue, found: snapshot.directed },\n );\n }\n const { staging } = this;\n const { nodeCount, edgeCount } = snapshot;\n // everything that can be refused is checked before the first mutation (design section 11.1):\n // duplicate ids, the count limits, weights, roles and extension column names\n const anonymous =\n staging.ids === null &&\n staging.nodeBound === 0 &&\n snapshot.ids.kind === \"identity\" &&\n snapshot.ids.offset === 0;\n const nodeMap = new Uint32Array(nodeCount);\n let newNodes = nodeCount;\n if (!anonymous) {\n newNodes = 0;\n for (let i = 0; i < nodeCount; i++) {\n const id = snapshot.ids.idOf(i);\n const existing = this.lookup(id);\n if (existing === INVALID_INDEX) {\n newNodes++;\n } else if (onDuplicate === \"error\") {\n throw new GraphFormatError(\"E_DUPLICATE_ID\", `node id ${describeId(id)} already exists`, {\n id,\n index: existing,\n });\n }\n }\n }\n this.checkNodeLimit(newNodes);\n const list = snapshot.edgeList();\n this.checkEdgeLimit(edgeCount, this.arcsOf(list.src, list.dst, edgeCount));\n const shadow = snapshot.edges.byRole(\"weight\");\n const weights = new Array<number | undefined>(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n let weight: number | undefined;\n if (shadow !== null) {\n weight = shadow.isSet(e) ? (shadow.value(e) as number) : undefined;\n } else if (list.weights !== null) {\n weight = list.weights[e];\n }\n weights[e] = this.checkWeight(weight, e);\n }\n for (const column of snapshot.nodes) {\n this.checkIncomingColumn(\"node\", column);\n }\n for (const column of snapshot.edges) {\n if (column !== shadow) {\n this.checkIncomingColumn(\"edge\", column);\n }\n }\n for (const [name, table] of snapshot.extensions) {\n this.checkIncomingExtension(name, table);\n }\n // nodes\n if (anonymous) {\n const first = this.addAnonymousNodes(nodeCount);\n for (let i = 0; i < nodeCount; i++) {\n nodeMap[i] = first + i;\n }\n } else {\n for (let i = 0; i < nodeCount; i++) {\n const id = snapshot.ids.idOf(i);\n const existing = this.lookup(id);\n nodeMap[i] = existing === INVALID_INDEX ? this.addValidatedNode(id) : existing;\n }\n }\n // edges: declared orientation, weights through the role column when present; a weighted\n // snapshot keeps its declared weight array (design section 3.7) unless the builder is unweighted\n if (snapshot.flags.weighted && this.fixed.weighted !== false) {\n staging.ensureWeights();\n }\n const edgeMap = new Uint32Array(edgeCount);\n for (let e = 0; e < edgeCount; e++) {\n edgeMap[e] = this.pushEdge(nodeMap[list.src[e]], nodeMap[list.dst[e]], weights[e]);\n }\n // columns\n const refs: IndexMaps = { node: nodeMap, edge: edgeMap };\n for (const column of snapshot.nodes) {\n this.copyColumn(\"node\", column, nodeMap, refs);\n }\n for (const column of snapshot.edges) {\n if (column !== shadow) {\n this.copyColumn(\"edge\", column, edgeMap, refs);\n }\n }\n for (const column of snapshot.graph) {\n if (column.isSet(0)) {\n this.setGraphValue(column.meta.name, column.value(0), metaToDecl(column.meta));\n }\n }\n for (const [name, table] of snapshot.extensions) {\n this.appendExtension(name, table, refs);\n }\n }\n\n // ---------------------------------------------------------------- output and lifecycle\n\n /**\n * Run the freeze pipeline of design section 6.3 and return a snapshot; the builder keeps its\n * staging (compacted and renumbered when tombstones existed, rewritten by a merge policy) unless\n * `release` is set.\n * @param options - the freeze options\n * @returns the snapshot\n */\n freeze(options?: FreezeOptions): GraphSnapshot {\n return this.freezeWithReport(options).snapshot;\n }\n\n /**\n * freeze() plus the report of what was renumbered, merged, dropped and widened (design section\n * 6.6): the remaps are relative to the previous freeze (the builder's own index space on the\n * first) and null exactly when nothing was renumbered.\n * @param options - the freeze options\n * @returns the snapshot and its report\n */\n freezeWithReport(options?: FreezeOptions): { snapshot: GraphSnapshot; report: FreezeReport } {\n this.check();\n const opts = options ?? {};\n const context: FreezeContext = {\n staging: this.staging,\n directed: this.directedValue,\n options: this.options,\n graphValues: this.graphValues,\n meta: this.metaValue,\n widened: this.widenings,\n };\n const outcome = runFreeze(context, opts);\n this.staging = outcome.staging;\n this.widenings = [];\n this.dirtyFlag = false;\n if (opts.release === true) {\n this.staging = this.freshStaging();\n }\n return { snapshot: outcome.snapshot, report: outcome.report };\n }\n\n /** Empty the builder (nodes, edges, columns, extension tables, graph attributes, meta), keeping its options and lock. */\n clear(): void {\n this.check();\n this.staging = this.freshStaging();\n this.graphValues = new Map();\n this.metaValue = EMPTY_GRAPH_META;\n this.widenings = [];\n this.mutated();\n }\n\n /** Release everything; every further call throws E_BUILDER_DISPOSED. */\n dispose(): void {\n if (this.disposed) {\n return;\n }\n this.staging = new Staging({\n weightDtype: this.fixed.weightDtype,\n weighted: false,\n expectedNodes: null,\n expectedEdges: null,\n resizable: undefined,\n });\n this.graphValues = new Map();\n this.metaValue = EMPTY_GRAPH_META;\n this.widenings = [];\n this.disposed = true;\n }\n\n /**\n * Bytes of typed staging currently held (capacity, not length; JS arrays and the id Map excluded).\n * @returns the byte count\n */\n byteLength(): number {\n this.check();\n return this.staging.byteLength();\n }\n\n // ---------------------------------------------------------------- private: state\n\n private check(): void {\n if (this.disposed) {\n throw new GraphFormatError(\"E_BUILDER_DISPOSED\", \"the builder was disposed\", {});\n }\n }\n\n private mutated(): void {\n this.mutations++;\n this.dirtyFlag = true;\n }\n\n private freshStaging(): Staging {\n return new Staging({\n weightDtype: this.fixed.weightDtype,\n weighted: this.fixed.weighted === true,\n expectedNodes: this.fixed.expectedNodes,\n expectedEdges: this.fixed.expectedEdges,\n resizable: undefined,\n });\n }\n\n // ---------------------------------------------------------------- private: nodes\n\n /**\n * The index a validated id would get from addValidatedNode: its existing (live or tombstoned)\n * index, or the next one.\n * @param id - a validated id\n * @returns the prospective index\n */\n private prospectiveNodeIndex(id: NodeId): number {\n const { staging } = this;\n if (staging.idToIndex === null) {\n return typeof id === \"number\" && Number.isInteger(id) && id >= 0 && id < staging.nodeBound\n ? id\n : staging.nodeBound;\n }\n return staging.idToIndex.get(typeof id === \"number\" && id === 0 ? 0 : id) ?? staging.nodeBound;\n }\n\n /**\n * The live index of an id, total.\n * @param id - any value\n * @returns the index, or INVALID_INDEX when absent, illegal or tombstoned\n */\n private lookup(id: NodeId): number {\n const { staging } = this;\n if (staging.idToIndex === null) {\n if (typeof id !== \"number\" || !Number.isInteger(id) || id < 0 || id >= staging.nodeBound) {\n return INVALID_INDEX;\n }\n return staging.nodeAlive.get(id) ? id : INVALID_INDEX;\n }\n const index = staging.idToIndex.get(typeof id === \"number\" && id === 0 ? 0 : id);\n if (index === undefined || !staging.nodeAlive.get(index)) {\n return INVALID_INDEX;\n }\n return index;\n }\n\n private isLiveNode(index: number): boolean {\n const { staging } = this;\n return Number.isInteger(index) && index >= 0 && index < staging.nodeBound && staging.nodeAlive.get(index);\n }\n\n private isLiveEdge(edge: number): boolean {\n const { staging } = this;\n return Number.isInteger(edge) && edge >= 0 && edge < staging.edgeBound && staging.edgeAlive.get(edge);\n }\n\n private checkNodeIndex(index: number): void {\n if (!Number.isInteger(index) || index < 0 || index >= this.staging.nodeBound) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `node index ${index} is out of range`, {\n index,\n bound: this.staging.nodeBound,\n });\n }\n }\n\n private checkEdgeIndex(edge: number): void {\n if (!Number.isInteger(edge) || edge < 0 || edge >= this.staging.edgeBound) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `edge index ${edge} is out of range`, {\n edge,\n bound: this.staging.edgeBound,\n });\n }\n }\n\n private checkLiveNode(index: number): void {\n if (!this.isLiveNode(index)) {\n throw new GraphFormatError(\"E_UNKNOWN_NODE\", `node index ${index} is out of range or removed`, { index });\n }\n }\n\n private checkEdge(edge: number): void {\n if (!this.isLiveEdge(edge)) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `edge index ${edge} is out of range or removed`, {\n edge,\n bound: this.staging.edgeBound,\n });\n }\n }\n\n private checkNodeLimit(adding: number): void {\n if (this.staging.nodeBound + adding > MAX_COUNT) {\n throw new GraphFormatError(\n \"E_TOO_LARGE\",\n `node count ${this.staging.nodeBound + adding} exceeds MAX_COUNT`,\n {\n count: this.staging.nodeBound + adding,\n max: MAX_COUNT,\n },\n );\n }\n }\n\n /**\n * The E_TOO_LARGE check of invariant I3 at the add* call that would cross the limit: the edge\n * index space and the live arc count (doubled for an undirected graph, loops once) must both\n * stay at or below MAX_COUNT.\n * @param addingEdges - edges about to be added\n * @param addingArcs - arcs they contribute (1 per directed edge or loop, 2 per undirected non-loop)\n */\n private checkEdgeLimit(addingEdges: number, addingArcs: number): void {\n const { staging } = this;\n const edges = staging.edgeBound + addingEdges;\n const liveArcs = this.directedValue ? staging.liveEdgeCount : 2 * staging.liveEdgeCount - staging.selfLoopCount;\n const arcs = liveArcs + addingArcs;\n if (edges > MAX_COUNT || arcs > MAX_COUNT) {\n throw new GraphFormatError(\"E_TOO_LARGE\", `edge count ${edges} (${arcs} arcs) exceeds MAX_COUNT`, {\n count: edges,\n arcs,\n max: MAX_COUNT,\n });\n }\n }\n\n /**\n * The arcs a batch of edges contributes.\n * @param src - sources\n * @param dst - targets\n * @param count - how many\n * @returns the arc count\n */\n private arcsOf(src: ArrayLike<number>, dst: ArrayLike<number>, count: number): number {\n if (this.directedValue) {\n return count;\n }\n let arcs = 0;\n for (let i = 0; i < count; i++) {\n arcs += src[i] === dst[i] ? 1 : 2;\n }\n return arcs;\n }\n\n /**\n * Add or revive a validated id.\n * @param id - a validated id\n * @returns the index\n */\n private addValidatedNode(id: NodeId): number {\n const { staging } = this;\n staging.materialiseIds();\n const map = staging.idToIndex as Map<NodeId, number>;\n const existing = map.get(id);\n if (existing !== undefined) {\n if (!staging.nodeAlive.get(existing)) {\n staging.nodeAlive.set(existing, true);\n staging.liveNodeCount++;\n this.mutated();\n }\n return existing;\n }\n this.checkNodeLimit(1);\n const index = staging.pushNode(typeof id === \"string\" ? detachString(id) : id);\n this.mutated();\n return index;\n }\n\n /**\n * Resolve an edge endpoint id: the live index, a revived or new node under addMissingNodes, or\n * E_UNKNOWN_NODE.\n * @param id - a validated id\n * @returns the index\n */\n private resolveEndpoint(id: NodeId): number {\n const index = this.lookup(id);\n if (index !== INVALID_INDEX) {\n return index;\n }\n if (this.fixed.addMissingNodes) {\n return this.addValidatedNode(id);\n }\n throw new GraphFormatError(\"E_UNKNOWN_NODE\", `unknown node id ${describeId(id)}`, { id });\n }\n\n private requireLive(id: NodeId): void {\n if (this.lookup(id) === INVALID_INDEX) {\n throw new GraphFormatError(\"E_UNKNOWN_NODE\", `unknown node id ${describeId(id)}`, { id });\n }\n }\n\n private removeLiveNode(index: number): U32 {\n const { staging } = this;\n const removed: number[] = [];\n for (let e = staging.firstOut.get(index); e !== INVALID_INDEX; e = staging.nextOut.get(e)) {\n if (staging.edgeAlive.get(e)) {\n staging.killEdge(e);\n removed.push(e);\n }\n }\n for (let e = staging.firstIn.get(index); e !== INVALID_INDEX; e = staging.nextIn.get(e)) {\n if (staging.edgeAlive.get(e)) {\n staging.killEdge(e);\n removed.push(e);\n }\n }\n staging.nodeAlive.set(index, false);\n staging.liveNodeCount--;\n this.mutated();\n return Uint32Array.from(removed).sort();\n }\n\n // ---------------------------------------------------------------- private: edges\n\n /**\n * Validate a weight argument: NaN is E_INVALID_WEIGHT; on an unweighted (`weighted: false`) builder\n * only 1 is accepted and it is treated as omitted.\n * @param weight - the argument\n * @param edge - the bulk position, for the error details\n * @returns the weight to store, or undefined when omitted\n */\n private checkWeight(weight: number | undefined, edge: number | undefined): number | undefined {\n if (weight === undefined) {\n return undefined;\n }\n if (typeof weight !== \"number\" || Number.isNaN(weight)) {\n throw new GraphFormatError(\"E_INVALID_WEIGHT\", `weight ${String(weight)} is not a number`, {\n weight,\n ...(edge === undefined ? {} : { edge }),\n });\n }\n if (this.fixed.weighted === false) {\n if (weight !== 1) {\n throw new GraphFormatError(\"E_INVALID_WEIGHT\", `weight ${weight} on a builder declared unweighted`, {\n weight,\n reason: \"unweighted builder\",\n ...(edge === undefined ? {} : { edge }),\n });\n }\n return undefined;\n }\n return weight;\n }\n\n private pushEdge(u: number, v: number, weight: number | undefined): number {\n this.checkEdgeLimit(1, this.directedValue || u === v ? 1 : 2);\n const e = this.staging.pushEdge(u, v, weight);\n this.mutated();\n return e;\n }\n\n /**\n * The in-place expansion of design section 6.6: every live edge u -> v gets a mirror v -> u at a\n * new index (loops are not mirrored), graphty.directed is 0 for both halves and graphty.pair links\n * them; every other column's mirror rows stay unset.\n */\n private expandToDirected(): void {\n const { staging } = this;\n const live = staging.liveEdgeCount;\n this.checkEdgeLimit(live, live);\n const directedDecl: ColumnDecl = { name: DIRECTED_COLUMN, dtype: \"bool\", role: \"directed\" };\n const pairDecl: ColumnDecl = { name: PAIR_COLUMN, dtype: \"u32\", role: \"pair\", refersTo: \"edge\" };\n // both declarations are checked before either is applied (design section 11.1)\n this.checkDeclaration(\"edge\", directedDecl);\n this.checkDeclaration(\"edge\", pairDecl);\n const directedHandle = this.declare(\"edge\", directedDecl);\n const pairHandle = this.declare(\"edge\", pairDecl);\n const directedColumn = staging.edgeColumns[directedHandle];\n const pairColumn = staging.edgeColumns[pairHandle];\n const bound = staging.edgeBound;\n for (let e = 0; e < bound; e++) {\n if (!staging.edgeAlive.get(e)) {\n continue;\n }\n directedColumn.write(e, false);\n const u = staging.src.get(e);\n const v = staging.dst.get(e);\n if (u === v) {\n continue;\n }\n const explicit = staging.weightExplicit(e);\n const weight = explicit && staging.weight !== null ? staging.weight.get(e) : undefined;\n const mirror = staging.pushEdge(v, u, weight);\n directedColumn.write(mirror, false);\n pairColumn.write(e, mirror);\n pairColumn.write(mirror, e);\n }\n this.directedValue = true;\n this.optionsCache = null;\n this.mutated();\n }\n\n // ---------------------------------------------------------------- private: columns\n\n private columnsOf(domain: \"node\" | \"edge\"): StagingColumn[] {\n return domain === \"node\" ? this.staging.nodeColumns : this.staging.edgeColumns;\n }\n\n private handleOf(columns: readonly StagingColumn[], name: string): ColumnHandle {\n const index = this.columnIndex(columns, name);\n return (index < 0 ? INVALID_INDEX : index) as ColumnHandle;\n }\n\n /**\n * The index of a staging column by name in O(1): a Map beside each column array, rebuilt when\n * the array is replaced (a fresh staging, a compaction) and kept in step by pushColumn().\n * Column names never change, so the map is invalidated only by identity or length.\n * @param columns - the node or edge staging columns\n * @param name - the column name\n * @returns the index, or -1 when absent\n */\n private columnIndex(columns: readonly StagingColumn[], name: string): number {\n const cached = columns === this.staging.nodeColumns ? this.nodeNames : this.edgeNames;\n let index = cached;\n if (index === null || index.columns !== columns || index.map.size !== columns.length) {\n const map = new Map<string, number>();\n for (let i = 0; i < columns.length; i++) {\n map.set(columns[i].meta.name, i);\n }\n index = { columns, map };\n if (columns === this.staging.nodeColumns) {\n this.nodeNames = index;\n } else if (columns === this.staging.edgeColumns) {\n this.edgeNames = index;\n }\n }\n return index.map.get(name) ?? -1;\n }\n\n /**\n * Append a staging column and keep the name index in step.\n * @param columns - the node or edge staging columns\n * @param column - the column to append\n * @returns the new column's index\n */\n private pushColumn(columns: StagingColumn[], column: StagingColumn): number {\n columns.push(column);\n const index = columns === this.staging.nodeColumns ? this.nodeNames : this.edgeNames;\n if (index !== null && index.columns === columns && index.map.size === columns.length - 1) {\n index.map.set(column.meta.name, columns.length - 1);\n }\n return columns.length - 1;\n }\n\n /**\n * Declare a column (design section 11.3): the same shape returns the existing handle, another\n * shape is E_COLUMN_EXISTS, a role held by another column E_DUPLICATE_ROLE.\n * @param domain - node or edge\n * @param decl - the declaration\n * @returns the handle\n */\n private declare(domain: \"node\" | \"edge\", decl: ColumnDecl): ColumnHandle {\n const { meta, existing } = this.checkDeclaration(domain, decl);\n if (existing !== INVALID_INDEX) {\n return existing as ColumnHandle;\n }\n const columns = this.columnsOf(domain);\n return this.pushColumn(columns, new StagingColumn(meta, false)) as ColumnHandle;\n }\n\n /**\n * The checks of declare() without applying anything: the resolved metadata and, when a column\n * of the same shape exists, its handle.\n * @param domain - node or edge\n * @param decl - the declaration\n * @returns the metadata and the existing handle (INVALID_INDEX when the column is new)\n */\n private checkDeclaration(domain: \"node\" | \"edge\", decl: ColumnDecl): { meta: ColumnMeta; existing: number } {\n if (typeof decl.name !== \"string\" || decl.name.length === 0) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", \"a column declaration needs a non-empty name\", {\n field: \"name\",\n found: decl.name,\n });\n }\n const meta = resolveColumnMeta(decl.name, domain, decl);\n const columns = this.columnsOf(domain);\n const existing = this.columnIndex(columns, meta.name);\n if (existing >= 0) {\n if (sameShape(columns[existing].meta, meta)) {\n return { meta, existing };\n }\n throw new GraphFormatError(\n \"E_COLUMN_EXISTS\",\n `${domain} column \"${meta.name}\" is already declared as ${columns[existing].meta.dtype}`,\n { column: meta.name, domain, found: columns[existing].meta.dtype, expected: meta.dtype },\n );\n }\n checkRole(columns, meta, domain);\n return { meta, existing: INVALID_INDEX };\n }\n\n /**\n * The staging column a handle or name refers to, auto-declaring an inferred column for an unknown\n * name when the value is set.\n * @param domain - node or edge\n * @param column - the handle or name\n * @param value - the value about to be written (decides the inferred dtype)\n * @returns the column, or null when an unknown name receives an unset value\n */\n private resolveColumn(\n domain: \"node\" | \"edge\",\n column: ColumnHandle | string,\n value: unknown,\n ): StagingColumn | null {\n const columns = this.columnsOf(domain);\n if (typeof column === \"number\") {\n if (!Number.isInteger(column) || column < 0 || column >= columns.length) {\n throw new GraphFormatError(\"E_UNKNOWN_COLUMN\", `no ${domain} column with handle ${column}`, {\n domain,\n handle: column,\n });\n }\n return columns[column];\n }\n const index = this.columnIndex(columns, column);\n if (index >= 0) {\n return columns[index];\n }\n if (value === undefined || value === null) {\n return null;\n }\n const dtype = inferInitialDtype(value);\n const created = createStagingColumn(column, domain, { dtype, nullable: true }, true);\n this.pushColumn(columns, created);\n return created;\n }\n\n /**\n * Validate every value of a record against the columns it would be written to, without writing\n * (design section 11.1: a record whose value is refused is not applied at all). An existing\n * column checks the value as its `write` would; a new name must be inferrable (a JSON value or a\n * well-formed string) unless the value is unset.\n * @param domain - node or edge\n * @param row - the row the record is meant for (error details only)\n * @param keys - the record keys\n * @param attrs - the record\n */\n private checkCells(\n domain: \"node\" | \"edge\",\n row: number,\n keys: readonly string[],\n attrs: Readonly<Record<string, unknown>>,\n ): void {\n const columns = this.columnsOf(domain);\n for (const key of keys) {\n const value = attrs[key];\n const at = this.columnIndex(columns, key);\n const column = at < 0 ? undefined : columns[at];\n if (column !== undefined) {\n column.checkValue(row, this.checkReference(column.meta, value));\n } else if (value !== undefined && value !== null) {\n inferInitialDtype(value);\n if (typeof value === \"string\") {\n assertWellFormedString(value, { column: key, row });\n } else if (typeof value === \"object\") {\n assertJsonValue(value, `${key}[${row}]`);\n }\n }\n }\n }\n\n /**\n * The refersTo range rule of invariant I12 at the write: an index-valued cell of a refersTo\n * column must be below the referenced space's current bound (a tombstoned target is a dangling\n * reference the next compaction resolves) or INVALID_INDEX; E_INDEX_RANGE otherwise. A scalar\n * INVALID_INDEX means \"no reference\" and is written as an unset row (E_COLUMN_TYPE on a\n * non-nullable column, which cannot hold it). Values of other shapes are left to the column's\n * own type check.\n * @param meta - the column\n * @param value - the value about to be written\n * @returns the value to write (undefined for a scalar INVALID_INDEX)\n */\n private checkReference(meta: ColumnMeta, value: unknown): unknown {\n if (meta.refersTo === null || value === undefined || value === null) {\n return value;\n }\n const bound = meta.refersTo === \"node\" ? this.staging.nodeBound : this.staging.edgeBound;\n const check = (index: unknown): void => {\n if (typeof index === \"number\" && index !== INVALID_INDEX && !(index >= 0 && index < bound)) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `column \"${meta.name}\" refers to ${String(meta.refersTo)} ${index}, which is not below ${bound}`,\n { column: meta.name, refersTo: meta.refersTo, found: index, bound },\n );\n }\n };\n if (Array.isArray(value)) {\n for (const item of value as unknown[]) {\n check(item);\n }\n return value;\n }\n check(value);\n return value === INVALID_INDEX ? undefined : value;\n }\n\n /**\n * The checks copyColumn would fail on before it writes anything: a new column's role must be\n * free (E_DUPLICATE_ROLE).\n * @param domain - node or edge\n * @param column - the incoming column\n */\n private checkIncomingColumn(domain: \"node\" | \"edge\", column: Column): void {\n const columns = this.columnsOf(domain);\n if (this.columnIndex(columns, column.meta.name) < 0) {\n checkRole(columns, column.meta, domain);\n }\n }\n\n /**\n * The checks appendExtension would fail on before it writes anything: an existing table of the\n * same name must hold every incoming column (E_UNKNOWN_COLUMN); a new table's declarations must\n * resolve (E_COLUMN_EXISTS / E_DUPLICATE_ROLE).\n * @param name - the table name\n * @param table - the incoming table\n */\n private checkIncomingExtension(name: string, table: Iterable<Column>): void {\n const target = this.staging.extensions.find((t) => t.name === name);\n const columns = [...table];\n if (target === undefined) {\n const seen: StagingColumn[] = [];\n for (const column of columns) {\n const decl = { ...metaToDecl(column.meta), name: column.meta.name } as ColumnDecl;\n const created = createStagingColumn(decl.name, \"extension\", decl, false);\n if (seen.some((other) => other.meta.name === created.meta.name)) {\n throw new GraphFormatError(\n \"E_COLUMN_EXISTS\",\n `column \"${decl.name}\" is declared twice in \"${name}\"`,\n {\n table: name,\n column: decl.name,\n },\n );\n }\n checkRole(seen, created.meta, name);\n seen.push(created);\n }\n return;\n }\n for (const column of columns) {\n if (!target.columns.some((c) => c.meta.name === column.meta.name)) {\n throw new GraphFormatError(\n \"E_UNKNOWN_COLUMN\",\n `extension table \"${name}\" has no column \"${column.meta.name}\"`,\n { table: name, column: column.meta.name },\n );\n }\n }\n }\n\n /**\n * The widening of widenNodeColumn / widenEdgeColumn.\n * @param domain - node or edge\n * @param column - the handle or name\n * @param dtype - the dtype to widen to\n */\n private widenColumn(domain: \"node\" | \"edge\", column: ColumnHandle | string, dtype: Dtype): void {\n const columns = this.columnsOf(domain);\n let target: StagingColumn | undefined;\n if (typeof column === \"number\") {\n target = Number.isInteger(column) && column >= 0 && column < columns.length ? columns[column] : undefined;\n } else {\n const index = this.columnIndex(columns, column);\n target = index < 0 ? undefined : columns[index];\n }\n if (target === undefined) {\n throw new GraphFormatError(\"E_UNKNOWN_COLUMN\", `no ${domain} column ${String(column)}`, { domain, column });\n }\n const current = target.inferredDtype;\n if (current === null) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `${domain} column \"${target.meta.name}\" is declared, not inferred`,\n {\n column: target.meta.name,\n domain,\n },\n );\n }\n if (wideningRank(dtype as InferredDtype) < 0) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `${dtype} is not a dtype inference widens to`, {\n column: target.meta.name,\n dtype,\n });\n }\n const next = dtype as InferredDtype;\n if (wideningRank(next) < wideningRank(current)) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `${domain} column \"${target.meta.name}\" is ${current}; it cannot narrow to ${next}`,\n { column: target.meta.name, found: current, expected: next },\n );\n }\n if (next === current) {\n return;\n }\n target.widenTo(next);\n this.widenings.push({ column: target.meta.name, domain, from: current, to: next });\n this.mutated();\n }\n\n private writeCell(domain: \"node\" | \"edge\", column: ColumnHandle | string, row: number, value: unknown): void {\n const target = this.resolveColumn(domain, column, value);\n if (target === null) {\n return;\n }\n const widened = target.write(row, this.checkReference(target.meta, value));\n if (widened !== null) {\n this.widenings.push({ column: target.meta.name, domain, from: widened.from, to: widened.to });\n }\n }\n\n /**\n * Replace or create a column from a typed array (setNodeColumn / setEdgeColumn).\n * @param domain - node or edge\n * @param rows - the table's current bound\n * @param name - the column name\n * @param data - the values\n * @param decl - the declaration patch\n */\n private setBulkColumn(\n domain: \"node\" | \"edge\",\n rows: number,\n name: string,\n data: TypedArrayData,\n decl: ColumnDeclPatch,\n ): void {\n const column = stagingColumnFromTypedArray(domain, rows, name, data, decl, {\n node: this.staging.nodeBound,\n edge: this.staging.edgeBound,\n });\n const columns = this.columnsOf(domain);\n const existing = this.columnIndex(columns, name);\n checkRole(\n columns.filter((c) => c.meta.name !== name),\n column.meta,\n domain,\n );\n if (existing >= 0) {\n columns[existing] = column;\n } else {\n this.pushColumn(columns, column);\n }\n }\n\n private extensionOf(handle: ExtensionHandle): ExtensionStaging {\n const { extensions } = this.staging;\n if (!Number.isInteger(handle) || handle < 0 || handle >= extensions.length) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `no extension table with handle ${handle}`, { handle });\n }\n return extensions[handle];\n }\n\n /**\n * Copy a snapshot column into the builder (addGraph): declared under the same metadata when the\n * name is new, else widened to the union dtype (design section 6.6); every set row is written\n * through `rowMap`, with refersTo values rewritten through `refs`.\n * @param domain - node or edge\n * @param column - the source column\n * @param rowMap - source row -> builder row\n * @param refs - source node / edge index -> builder index\n */\n private copyColumn(domain: \"node\" | \"edge\", column: Column, rowMap: U32, refs: IndexMaps): void {\n const columns = this.columnsOf(domain);\n const { name } = column.meta;\n let index = this.columnIndex(columns, name);\n if (index < 0) {\n const decl = { ...metaToDecl(column.meta), name };\n checkRole(columns, column.meta, domain);\n index = this.pushColumn(columns, createStagingColumn(name, domain, decl, false));\n } else {\n const target = columns[index];\n if (!sameShape(target.meta, column.meta)) {\n const union = wider(inferredEquivalent(target.meta.dtype), inferredEquivalent(column.meta.dtype));\n if (target.meta.dtype !== union) {\n const from = target.meta.dtype;\n target.widenTo(union);\n this.widenings.push({ column: name, domain, from, to: union });\n }\n }\n }\n const target = columns[index];\n const valueMap = referenceMap(column.meta, refs);\n for (let row = 0; row < column.length; row++) {\n if (!column.isSet(row)) {\n continue;\n }\n let value = column.value(row);\n if (valueMap !== null) {\n value = remapReference(value, valueMap);\n if (value === undefined) {\n continue;\n }\n }\n target.write(rowMap[row], value);\n }\n }\n\n /**\n * Append the rows of a snapshot extension table (addGraph): into the table of the same name when\n * the columns match, else a new table is declared from the source columns.\n * @param name - the table name\n * @param table - the source table\n * @param refs - source node / edge index -> builder index\n */\n private appendExtension(\n name: string,\n table: Iterable<Column> & { readonly rowCount: number },\n refs: IndexMaps,\n ): void {\n const { staging } = this;\n const sourceColumns = [...table];\n let target = staging.extensions.find((t) => t.name === name);\n if (target === undefined) {\n const decls = sourceColumns.map(\n (column) => ({ ...metaToDecl(column.meta), name: column.meta.name }) as ColumnDecl,\n );\n const handle = this.addExtensionTable(name, decls);\n target = staging.extensions[handle];\n }\n const targetColumns = target.columns;\n const first = target.rowCount;\n for (const column of sourceColumns) {\n const into = targetColumns.find((c) => c.meta.name === column.meta.name);\n if (into === undefined) {\n throw new GraphFormatError(\n \"E_UNKNOWN_COLUMN\",\n `extension table \"${name}\" has no column \"${column.meta.name}\"`,\n { table: name, column: column.meta.name },\n );\n }\n const valueMap = referenceMap(column.meta, refs);\n for (let row = 0; row < column.length; row++) {\n if (!column.isSet(row)) {\n into.ensureLength(first + row + 1);\n continue;\n }\n let value = column.value(row);\n if (valueMap !== null) {\n value = remapReference(value, valueMap);\n if (value === undefined) {\n into.ensureLength(first + row + 1);\n continue;\n }\n }\n into.write(first + row, value);\n }\n }\n for (const column of targetColumns) {\n column.ensureLength(first + table.rowCount);\n }\n target.rowCount = first + table.rowCount;\n }\n}\n\n// ============================================================ module helpers\n\n/**\n * Enforce \"at most one column per role\" among staging columns (design section 5.5).\n * @param columns - the existing columns\n * @param meta - the column being added\n * @param where - the table, for the message\n */\nfunction checkRole(columns: readonly StagingColumn[], meta: ColumnMeta, where: string): void {\n if (meta.role === null) {\n return;\n }\n const holder = columns.find((column) => column.meta.name !== meta.name && column.meta.role === meta.role);\n if (holder !== undefined) {\n throw new GraphFormatError(\n \"E_DUPLICATE_ROLE\",\n `role \"${meta.role}\" is already held by column \"${holder.meta.name}\" in ${where}`,\n { role: meta.role, column: meta.name, holder: holder.meta.name },\n );\n }\n}\n\n/**\n * The wider of two inferred dtypes in the order of design section 5.1.\n * @param a - one dtype\n * @param b - the other\n * @returns the wider\n */\nfunction wider(a: InferredDtype, b: InferredDtype): InferredDtype {\n return wideningRank(a) >= wideningRank(b) ? a : b;\n}\n\n/**\n * The index map a refersTo column's values are rewritten through, if any.\n * @param meta - the column\n * @param refs - the node and edge maps\n * @returns the map of the referenced space, or null\n */\nfunction referenceMap(meta: ColumnMeta, refs: IndexMaps): U32 | null {\n switch (meta.refersTo) {\n case \"node\":\n return refs.node;\n case \"edge\":\n return refs.edge;\n default:\n return null;\n }\n}\n\n/**\n * Rewrite an index-valued cell (a number, or an array of numbers for a list) through an index map;\n * dangling references are dropped, and a cell with nothing left is unset.\n * @param value - the cell\n * @param map - source index -> builder index\n * @returns the rewritten cell, or undefined to unset\n */\nfunction remapReference(value: unknown, map: U32): unknown {\n if (typeof value === \"number\") {\n return value < map.length ? map[value] : undefined;\n }\n if (typeof value === \"object\" && value !== null) {\n const items = Array.from(value as ArrayLike<number>);\n const kept = items.filter((item) => item < map.length).map((item) => map[item]);\n return kept.length === 0 && items.length > 0 ? undefined : kept;\n }\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `a refersTo cell holds a ${typeof value}, not an index or a list`, {\n found: typeof value,\n reason: \"refersTo\",\n });\n}\n\n/**\n * Build a one-row graph column now to validate a setGraphValue call.\n * @param name - the column name\n * @param value - the value\n * @param decl - the declaration patch\n */\nfunction buildGraphColumn(name: string, value: unknown, decl: ColumnDeclPatch): void {\n const column = createStagingColumn(\n name,\n \"graph\",\n decl.dtype === undefined ? { ...decl, dtype: inferInitialDtype(value) } : decl,\n decl.dtype === undefined,\n );\n column.write(0, value);\n}\n\n/**\n * A staging column from a typed array (setNodeColumn / setEdgeColumn, design section 12.2): the\n * dtype comes from the array class unless the patch names one (bool and dict over a Uint32Array), the\n * length must be rows * components (bool: ceil(rows / 32) words), and every row is set unless the\n * patch declares the column nullable.\n * @param domain - node or edge\n * @param rows - the row count\n * @param name - the column name\n * @param data - the values\n * @param decl - the declaration patch\n * @param bounds - the builder's node and edge bounds, for refersTo range checks (E_INDEX_RANGE)\n * @returns the staging column\n */\nfunction stagingColumnFromTypedArray(\n domain: ColumnDomain,\n rows: number,\n name: string,\n data: TypedArrayData,\n decl: ColumnDeclPatch,\n bounds: IndexBounds,\n): StagingColumn {\n const arrayDtype = dtypeOfArray(data);\n const dtype = decl.dtype ?? arrayDtype;\n const compatible = dtype === arrayDtype || (arrayDtype === \"u32\" && (dtype === \"bool\" || dtype === \"dict\"));\n if (!compatible) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${name}\": a ${arrayDtype} array cannot back a ${dtype} column`,\n {\n column: name,\n field: \"dtype\",\n found: arrayDtype,\n expected: dtype,\n },\n );\n }\n const column = createStagingColumn(name, domain, { nullable: false, ...decl, dtype }, false);\n const { components } = column.meta;\n let expected: number;\n switch (dtype) {\n case \"bool\":\n expected = Math.ceil(rows / 32);\n break;\n case \"dict\":\n expected = rows;\n break;\n case \"f32\":\n case \"f64\":\n case \"i32\":\n case \"u32\":\n case \"u8\":\n expected = rows * components;\n break;\n default:\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${name}\": a ${String(dtype)} column cannot adopt a typed array`,\n {\n column: name,\n field: \"dtype\",\n },\n );\n }\n if (data.length !== expected) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `column \"${name}\": array length ${data.length}, expected ${expected}`,\n {\n column: name,\n expected,\n found: data.length,\n },\n );\n }\n column.ensureLength(rows);\n switch (dtype) {\n case \"bool\": {\n const words = data as U32;\n for (let row = 0; row < rows; row++) {\n column.write(row, ((words[row >>> 5] >>> (row & 31)) & 1) === 1);\n }\n break;\n }\n case \"dict\": {\n const { dictionary } = column;\n if (dictionary === null) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `column \"${name}\" has no dictionary`, { column: name });\n }\n for (let row = 0; row < rows; row++) {\n const code = data[row];\n if (code >= dictionary.size) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${name}\": code ${code} at row ${row} is outside the ${dictionary.size} declared options`,\n {\n column: name,\n row,\n code,\n },\n );\n }\n column.write(row, dictionary.values[code]);\n }\n break;\n }\n default: {\n const { typed } = column;\n if (typed === null) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", `column \"${name}\" has no typed storage`, { column: name });\n }\n const { refersTo } = column.meta;\n const bound = refersTo === \"node\" ? bounds.node : bounds.edge;\n for (let i = 0; i < data.length; i++) {\n const value = data[i];\n if (refersTo !== null && value !== INVALID_INDEX && value >= bound) {\n throw new GraphFormatError(\n \"E_INDEX_RANGE\",\n `column \"${name}\" refers to ${refersTo} ${value} at row ${i}, which is not below ${bound}`,\n { column: name, row: i, refersTo, found: value, bound },\n );\n }\n if (refersTo !== null && value === INVALID_INDEX && column.validity === null) {\n throw new GraphFormatError(\n \"E_COLUMN_TYPE\",\n `column \"${name}\": row ${i} of a non-nullable refersTo column holds INVALID_INDEX`,\n { column: name, row: i, field: \"nullable\" },\n );\n }\n typed.set(i, value);\n }\n if (column.validity !== null) {\n for (let row = 0; row < rows; row++) {\n column.validity.set(row, refersTo === null || data[row] !== INVALID_INDEX);\n }\n }\n break;\n }\n }\n return column;\n}\n\n/** The current node and edge bounds of a builder, for refersTo range checks. */\ninterface IndexBounds {\n /** The node index bound. */\n readonly node: number;\n /** The edge index bound. */\n readonly edge: number;\n}\n","/**\n * `fromCsr()` (design section 8.1, entry point 2; decision C12): adopt prebuilt CSR arrays -- from\n * a file, a worker, another package or a generator that emits CSR directly -- without copying by\n * default (GraphBLAS pack semantics: the caller transfers ownership and must not mutate them\n * afterwards), with full validation by default because adopted arrays typically come from a file or\n * the network (design section 9.5).\n *\n * The pipeline: resolve the optional arrays (an absent `arcToEdge` is the identity of a directed\n * graph, an absent `edgeToArc` is derived in one O(m) pass, `edgeCount` defaults to the arc count or\n * is derived from `arcToEdge`); adopt or copy; detect an already-aligned shared buffer as the arena\n * (design section 10.3); build a candidate snapshot; check the rows (invariant I4) when `sortRows`\n * is set and, when some row is unsorted, rebuild a fresh sorted core through the freeze pipeline's\n * counting sorts over the declared edge list (the caller's arrays are not modified; the cost is a\n * freeze); validate at the requested level; verify the caller's flag claims (invariant I9).\n *\n * `detectArena()` is exported for `fromWire`, which applies the same detection when a manifest\n * carries no arena descriptor (design section 8.1).\n */\n\nimport { copyCoreIntoArena, CORE_ORDER, type CoreArrays } from \"../builder/arena.js\";\nimport { sortIntoCore } from \"../builder/counting-sort.js\";\nimport { createTable, tableWithColumns } from \"../columns/table.js\";\nimport { ALIGNMENT, INVALID_INDEX, MAX_COUNT } from \"../constants.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { identityNodeIdMap, nodeIdMapFromF64, nodeIdMapFromIds } from \"../ids/node-id-map.js\";\nimport { EMPTY_GRAPH_META, resolveGraphMeta as resolveSharedGraphMeta } from \"../snapshot/graph-meta.js\";\nimport { createSnapshot, type GraphSnapshot } from \"../snapshot/graph-snapshot.js\";\nimport {\n checkI5Orientation,\n checkI6,\n checkI8NaN,\n checkI11Bijection,\n checkUniqueColumn,\n computeFlags,\n countLoopArcs,\n invariantViolation,\n isIdentity,\n validateFull,\n validateStructure,\n} from \"../snapshot/validate.js\";\nimport {\n type ArenaLayout,\n type ArenaSegment,\n type AttributeTable,\n type ColumnInput,\n type CoreArrayName,\n type CsrInput,\n type F32,\n type F64,\n type FlagClaims,\n type FromCsrOptions,\n type GraphMeta,\n type GraphMetaPatch,\n type NodeIdMap,\n type SnapshotFlags,\n type TypedArrayData,\n type U32,\n type ValidationLevel,\n} from \"../types/index.js\";\nimport { type SnapshotParts } from \"../types/internal.js\";\nimport { isOverPlainBuffer } from \"../util/typed-array.js\";\n\n// ============================================================ constants\n\n/** The flag names, for claim verification. */\nconst FLAG_NAMES: readonly (keyof SnapshotFlags)[] = [\n \"multigraph\",\n \"hasSelfLoops\",\n \"arcToEdgeIsIdentity\",\n \"weighted\",\n \"allWeightsOne\",\n \"nonNegativeWeights\",\n \"finiteWeights\",\n];\n\nconst VALIDATION_LEVELS: ReadonlySet<string> = new Set([\"none\", \"structure\", \"full\"]);\n// ============================================================ input shape\n\n/** The core arrays after the optional ones are resolved; `arcToEdge` / `edgeToArc` are null when identity. */\ninterface ResolvedCore {\n readonly rowPtr: U32;\n readonly colIdx: U32;\n readonly weights: F32 | null;\n readonly arcToEdge: U32 | null;\n readonly edgeToArc: U32 | null;\n readonly edgeCount: number;\n readonly arcCount: number;\n readonly selfLoopCount: number;\n}\n\n/**\n * The E_INVALID_SNAPSHOT error for an input array of the wrong class.\n * @param name - the array\n * @param expected - the class name expected\n * @returns the error\n */\nfunction arrayTypeError(name: string, expected: string): GraphFormatError {\n return new GraphFormatError(\"E_INVALID_SNAPSHOT\", `${name} must be a ${expected}`, {\n array: name,\n expected,\n reason: \"dtype\",\n });\n}\n\n/**\n * Check the classes of the input arrays (a Float64Array passed as weights or a plain array passed as\n * colIdx would otherwise produce a snapshot whose bytes are wrong on the GPU) and the node count.\n * @param input - the input\n */\nfunction checkShape(input: CsrInput): void {\n if (!Number.isInteger(input.nodeCount) || input.nodeCount < 0 || input.nodeCount > MAX_COUNT) {\n throw new GraphFormatError(\"E_TOO_LARGE\", `nodeCount ${input.nodeCount} is not an integer in [0, MAX_COUNT]`, {\n count: input.nodeCount,\n max: MAX_COUNT,\n });\n }\n if (!(input.rowPtr instanceof Uint32Array)) {\n throw arrayTypeError(\"rowPtr\", \"Uint32Array\");\n }\n if (!(input.colIdx instanceof Uint32Array)) {\n throw arrayTypeError(\"colIdx\", \"Uint32Array\");\n }\n if (input.weights !== undefined && input.weights !== null && !(input.weights instanceof Float32Array)) {\n throw arrayTypeError(\"weights\", \"Float32Array\");\n }\n if (input.arcToEdge !== undefined && !(input.arcToEdge instanceof Uint32Array)) {\n throw arrayTypeError(\"arcToEdge\", \"Uint32Array\");\n }\n if (input.edgeToArc !== undefined && !(input.edgeToArc instanceof Uint32Array)) {\n throw arrayTypeError(\"edgeToArc\", \"Uint32Array\");\n }\n if (input.edgeCount !== undefined && (!Number.isInteger(input.edgeCount) || input.edgeCount < 0)) {\n throw invariantViolation(\"I3\", `edgeCount ${input.edgeCount} is not a non-negative integer`, {\n count: \"edgeCount\",\n found: input.edgeCount,\n });\n }\n if (input.rowPtr.length !== input.nodeCount + 1) {\n throw invariantViolation(\"I1\", `rowPtr has ${input.rowPtr.length} entries, expected ${input.nodeCount + 1}`, {\n expected: input.nodeCount + 1,\n found: input.rowPtr.length,\n });\n }\n}\n\n/**\n * Whether a typed array is backed by a plain, fixed-length ArrayBuffer (a SharedArrayBuffer is never\n * adopted, decision D-SAB; a resizable buffer's view can change length, invariants I10 and I17).\n * @param array - the array\n * @returns true for a plain ArrayBuffer\n */\nfunction overPlainBuffer(array: ArrayBufferView): boolean {\n return isOverPlainBuffer(array);\n}\n\n/**\n * Derive `edgeToArc` from `arcToEdge`: the first (lowest) arc holding each edge, which for a directed\n * graph is the edge's only arc and for an undirected graph the arc in the lower-numbered row\n * (design section 8.1: \"derived in one O(m) pass\"). An edge no arc holds is left INVALID_INDEX so the\n * I5 range check names it.\n * @param arcToEdge - the arc -> edge map\n * @param edgeCount - the edge count\n * @returns the edge -> arc map\n */\nfunction deriveEdgeToArc(arcToEdge: U32, edgeCount: number): U32 {\n const edgeToArc = new Uint32Array(edgeCount).fill(INVALID_INDEX);\n for (let a = 0; a < arcToEdge.length; a++) {\n const e = arcToEdge[a];\n if (e < edgeCount && edgeToArc[e] === INVALID_INDEX) {\n edgeToArc[e] = a;\n }\n }\n return edgeToArc;\n}\n\n/**\n * The E_INVALID_SNAPSHOT error for an identity-flag contradiction between the input arrays.\n * @param message - what is wrong\n * @param details - the location\n * @returns the error\n */\nfunction identityError(message: string, details: Readonly<Record<string, unknown>>): GraphFormatError {\n return invariantViolation(\"I5\", message, details);\n}\n\n/**\n * Resolve the optional core arrays and counts (design section 8.1). For a directed input an absent\n * `arcToEdge` is the identity and a supplied one that happens to be the identity is dropped (the\n * snapshot materialises identity permutations lazily, design section 3.1); an undirected input must\n * supply `arcToEdge` (E_INVALID_SNAPSHOT, invariant I5). `edgeCount` defaults to the arc count\n * (directed) or to max(arcToEdge) + 1 (undirected). `selfLoopCount` is the number of loop arcs.\n * @param input - the input\n * @param level - the validation level (\"none\" skips the edgeToArc identity check)\n * @returns the resolved core\n */\nfunction resolveCore(input: CsrInput, level: ValidationLevel): ResolvedCore {\n const { directed, nodeCount, rowPtr, colIdx } = input;\n const arcCount = colIdx.length;\n const weights = input.weights ?? null;\n const selfLoopCount = countLoopArcs(rowPtr, colIdx, nodeCount);\n let arcToEdge: U32 | null = input.arcToEdge ?? null;\n let edgeToArc: U32 | null = input.edgeToArc ?? null;\n let edgeCount: number;\n if (directed) {\n edgeCount = input.edgeCount ?? arcCount;\n if (edgeCount !== arcCount) {\n throw invariantViolation(\"I6\", `directed input has arcCount ${arcCount} but edgeCount ${edgeCount}`, {\n arcCount,\n edgeCount,\n });\n }\n // decided from the supplied array at every level (O(m)): a flag claim never drops an array\n const identity = arcToEdge === null || (arcToEdge.length === arcCount && isIdentity(arcToEdge));\n if (identity) {\n if (edgeToArc !== null && level !== \"none\" && (edgeToArc.length !== edgeCount || !isIdentity(edgeToArc))) {\n throw identityError(\"arcToEdge is the identity but edgeToArc is not\", {\n array: \"edgeToArc\",\n found: edgeToArc.length,\n expected: edgeCount,\n });\n }\n arcToEdge = null;\n edgeToArc = null;\n } else if (edgeToArc === null) {\n edgeToArc = deriveEdgeToArc(arcToEdge as U32, edgeCount);\n }\n } else {\n if (arcToEdge === null) {\n throw identityError(\"an undirected input must supply arcToEdge\", {\n array: \"arcToEdge\",\n reason: \"missing arcToEdge\",\n });\n }\n const { edgeCount: given } = input;\n if (given === undefined) {\n let max = -1;\n for (let a = 0; a < arcToEdge.length; a++) {\n if (arcToEdge[a] > max) {\n max = arcToEdge[a];\n }\n }\n edgeCount = max + 1;\n } else {\n edgeCount = given;\n }\n edgeToArc ??= deriveEdgeToArc(arcToEdge, edgeCount);\n }\n return { rowPtr, colIdx, weights, arcToEdge, edgeToArc, edgeCount, arcCount, selfLoopCount };\n}\n\n// ============================================================ adoption and the arena\n\n/**\n * The core arrays of a resolved core in the shape the arena helpers take.\n * @param core - the resolved core\n * @param arena - the arena, or null\n * @returns the core arrays\n */\nfunction coreArraysOf(core: ResolvedCore, arena: ArenaLayout | null): CoreArrays {\n return {\n rowPtr: core.rowPtr,\n colIdx: core.colIdx,\n weights: core.weights,\n arcToEdge: core.arcToEdge,\n edgeToArc: core.edgeToArc,\n arena,\n };\n}\n\n/**\n * Detect whether adopted core arrays already form an arena (design sections 8.1 and 10.3): every\n * present, non-empty, non-identity core array is a view over ONE plain ArrayBuffer, laid out hot to\n * cold (rowPtr, colIdx, weights, arcToEdge, edgeToArc) without overlap, each starting at a multiple\n * of 256 bytes relative to `rowPtr`. When they do, that buffer is the arena: `byteOffset` is\n * rowPtr's, `byteLength` spans to the end of the last array and `hotByteLength` ends at the weights\n * (or colIdx, or rowPtr) segment. Otherwise null. Arrays whose segment would be null (a zero-length\n * array, an absent weights array, an identity permutation given as null) do not take part.\n * @param core - the core arrays; `arcToEdge` / `edgeToArc` null when identity\n * @returns the arena layout, or null when the arrays are not an aligned shared buffer\n */\nexport function detectArena(core: Omit<CoreArrays, \"arena\">): ArenaLayout | null {\n const { buffer } = core.rowPtr;\n if (!(buffer instanceof ArrayBuffer)) {\n return null;\n }\n const base = core.rowPtr.byteOffset;\n const arrays: readonly (ArrayBufferView | null)[] = [\n core.rowPtr,\n core.colIdx,\n core.weights,\n core.arcToEdge,\n core.edgeToArc,\n ];\n const segments: Record<CoreArrayName, ArenaSegment | null> = {\n rowPtr: null,\n colIdx: null,\n weights: null,\n arcToEdge: null,\n edgeToArc: null,\n };\n let cursor = base;\n let hotEnd = base;\n for (let i = 0; i < CORE_ORDER.length; i++) {\n const array = arrays[i];\n if (array === null || array.byteLength === 0) {\n continue;\n }\n if (array.buffer !== buffer || array.byteOffset < cursor || (array.byteOffset - base) % ALIGNMENT !== 0) {\n return null;\n }\n segments[CORE_ORDER[i]] = Object.freeze({ byteOffset: array.byteOffset, byteLength: array.byteLength });\n cursor = array.byteOffset + array.byteLength;\n if (i <= 2) {\n hotEnd = cursor;\n }\n }\n return Object.freeze({\n buffer,\n byteOffset: base,\n byteLength: cursor - base,\n alignment: ALIGNMENT,\n segments: Object.freeze(segments),\n hotByteLength: hotEnd - base,\n });\n}\n\n/**\n * Whether any present core array is not over a plain ArrayBuffer, which forces the copy path.\n * @param core - the resolved core\n * @returns true when a copy is required\n */\nfunction needsCopy(core: ResolvedCore): boolean {\n const arrays = [core.rowPtr, core.colIdx, core.weights, core.arcToEdge, core.edgeToArc];\n return arrays.some((array) => array !== null && !overPlainBuffer(array));\n}\n\n// ============================================================ ids, columns, meta\n\n/**\n * The id map of a CsrInput (design section 4.2): identity with no storage when no ids are given;\n * otherwise the kind detected from the ids, validated (E_INVALID_ID / E_DUPLICATE_ID) unless the\n * level is \"none\". A Float64Array is adopted by reference unless `copy` is set.\n * @param input - the input\n * @param level - the validation level\n * @param copy - whether to copy an F64 array\n * @returns the id map; E_COLUMN_LENGTH when ids.length !== nodeCount\n */\nfunction idMapOf(input: CsrInput, level: ValidationLevel, copy: boolean): NodeIdMap {\n const { ids, nodeCount } = input;\n if (ids === undefined) {\n return identityNodeIdMap(nodeCount);\n }\n if (ids.length !== nodeCount) {\n throw new GraphFormatError(\n \"E_COLUMN_LENGTH\",\n `ids has ${ids.length} entries, expected nodeCount ${nodeCount}`,\n {\n field: \"ids\",\n expected: nodeCount,\n found: ids.length,\n },\n );\n }\n const validate = level !== \"none\";\n if (ids instanceof Float64Array) {\n const values: F64 = copy || !overPlainBuffer(ids) ? new Float64Array(ids) : ids;\n return nodeIdMapFromF64(values, { validate });\n }\n return nodeIdMapFromIds(copy ? [...ids] : ids, nodeCount, { validate });\n}\n\n/**\n * The node or edge table of a CsrInput: the caller's columns attached through the same path as\n * `withColumns()` (typed arrays adopted by reference, JS arrays resolved with inference; design\n * section 5.7), copied first when `copy` is set.\n * @param domain - \"node\" or \"edge\"\n * @param rowCount - the table's row count\n * @param columns - the caller's columns, or undefined\n * @param copy - whether to copy typed arrays\n * @returns the table\n */\nfunction tableOf(\n domain: \"node\" | \"edge\",\n rowCount: number,\n columns: Readonly<Record<string, TypedArrayData | ColumnInput>> | undefined,\n copy: boolean,\n): AttributeTable {\n const table = createTable(domain, rowCount);\n if (columns === undefined) {\n return table;\n }\n // a typed array over a SharedArrayBuffer or a resizable buffer is copied like the core (D-SAB)\n const copied: Record<string, TypedArrayData | ColumnInput> = {};\n for (const name of Object.keys(columns)) {\n const value = columns[name];\n if (ArrayBuffer.isView(value)) {\n copied[name] = copy || !overPlainBuffer(value) ? value.slice() : value;\n } else if (ArrayBuffer.isView(value.data)) {\n copied[name] =\n copy || !overPlainBuffer(value.data) ? { data: value.data.slice(), decl: value.decl } : value;\n } else {\n copied[name] = value;\n }\n }\n return tableWithColumns(table, copied);\n}\n\n/**\n * Resolve a GraphMetaPatch into a complete GraphMeta (design section 5.9) with the builder's\n * `setMeta` rules over empty metadata (E_COLUMN_TYPE with details.field on a bad field).\n * @param patch - the patch, or undefined for no metadata\n * @returns the metadata, frozen\n */\nexport function resolveGraphMeta(patch: GraphMetaPatch | undefined): GraphMeta {\n return patch === undefined ? EMPTY_GRAPH_META : resolveSharedGraphMeta(EMPTY_GRAPH_META, patch);\n}\n\n// ============================================================ flags\n\n/**\n * Whether every flag is claimed, so no pass over the arrays is needed to know them.\n * @param claims - the caller's claims\n * @returns true when all seven flags are defined\n */\nfunction fullyClaimed(claims: FlagClaims | undefined): claims is SnapshotFlags {\n return claims !== undefined && FLAG_NAMES.every((name) => claims[name] !== undefined);\n}\n\n/**\n * The truthful flags of a core (design section 3.8) computed from the arrays.\n * @param directed - the direction\n * @param nodeCount - the node count\n * @param core - the core arrays\n * @param selfLoopCount - the loop count\n * @returns the flags\n */\nfunction flagsOf(directed: boolean, nodeCount: number, core: CoreArrays, selfLoopCount: number): SnapshotFlags {\n return computeFlags({\n directed,\n nodeCount,\n rowPtr: core.rowPtr,\n colIdx: core.colIdx,\n weights: core.weights,\n arcToEdge: core.arcToEdge,\n selfLoopCount,\n });\n}\n\n/**\n * Verify the caller's flag claims against the computed flags (invariant I9): every claimed flag must\n * equal the truth.\n * @param claims - the claims, or undefined\n * @param flags - the truthful flags\n */\nfunction verifyClaims(claims: FlagClaims | undefined, flags: SnapshotFlags): void {\n if (claims === undefined) {\n return;\n }\n for (const name of FLAG_NAMES) {\n const claim = claims[name];\n if (claim !== undefined && claim !== flags[name]) {\n throw invariantViolation(\"I9\", `flag ${name} is claimed ${claim} but the arrays say ${flags[name]}`, {\n flag: name,\n found: claim,\n expected: flags[name],\n });\n }\n }\n}\n\n// ============================================================ rows and the rebuild\n\n/**\n * Whether every row satisfies invariant I4: colIdx non-decreasing within the row, and parallel arcs in\n * ascending arcToEdge order.\n * @param s - the candidate snapshot\n * @returns true when sorted\n */\nfunction rowsSorted(s: GraphSnapshot): boolean {\n const { rowPtr, colIdx, nodeCount } = s;\n const arcToEdge = s.flags.arcToEdgeIsIdentity ? null : s.arcToEdge;\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u] + 1; a < end; a++) {\n if (colIdx[a] < colIdx[a - 1]) {\n return false;\n }\n if (colIdx[a] === colIdx[a - 1] && arcToEdge !== null && arcToEdge[a] <= arcToEdge[a - 1]) {\n return false;\n }\n }\n }\n return true;\n}\n\n/**\n * The declared edge list of a candidate whose rows are unsorted: for every logical edge the arc\n * `edgeToArc[e]` gives the declared source (its row), target and weight.\n * @param s - the candidate snapshot\n * @returns the per-edge arrays\n */\nfunction declaredEdges(s: GraphSnapshot): { readonly src: U32; readonly dst: U32; readonly weights: F32 | null } {\n const { nodeCount, edgeCount, rowPtr, colIdx, weights } = s;\n const identity = s.flags.arcToEdgeIsIdentity;\n const src = new Uint32Array(edgeCount);\n const dst = new Uint32Array(edgeCount);\n const edgeWeights = weights === null ? null : new Float32Array(edgeCount);\n const arcToEdge = identity ? null : s.arcToEdge;\n const edgeToArc = identity ? null : s.edgeToArc;\n for (let u = 0; u < nodeCount; u++) {\n const end = rowPtr[u + 1];\n for (let a = rowPtr[u]; a < end; a++) {\n const e = arcToEdge === null ? a : arcToEdge[a];\n if (edgeToArc !== null && edgeToArc[e] !== a) {\n continue;\n }\n src[e] = u;\n dst[e] = colIdx[a];\n if (edgeWeights !== null && weights !== null) {\n edgeWeights[e] = weights[a];\n }\n }\n }\n return { src, dst, weights: edgeWeights };\n}\n\n/**\n * Compare the rebuilt sorted core with the unsorted input row by row as multisets of (target, edge,\n * weight) (the \"full\" level's pairing and weight checks of invariant I7 for an input that could not\n * be walked in sorted order): an arc without a mate, a mate on a different edge, or unequal mate\n * weights all leave the rebuilt rows different from the input rows.\n * @param input - the candidate over the caller's arrays\n * @param rebuilt - the rebuilt snapshot\n */\nfunction compareRows(input: GraphSnapshot, rebuilt: GraphSnapshot): void {\n const { nodeCount } = input;\n for (let u = 0; u <= nodeCount; u++) {\n if (input.rowPtr[u] !== rebuilt.rowPtr[u]) {\n throw invariantViolation(\"I7\", `row ${u - 1} holds arcs whose mates are missing from their rows`, {\n row: Math.max(0, u - 1),\n found: input.rowPtr[u],\n expected: rebuilt.rowPtr[u],\n });\n }\n }\n const inArcToEdge = input.arcToEdge;\n const outArcToEdge = rebuilt.arcToEdge;\n const inWeights = input.weights;\n const outWeights = rebuilt.weights;\n for (let u = 0; u < nodeCount; u++) {\n const start = input.rowPtr[u];\n const end = input.rowPtr[u + 1];\n const order = new Uint32Array(end - start);\n for (let i = 0; i < order.length; i++) {\n order[i] = start + i;\n }\n order.sort((x, y) => input.colIdx[x] - input.colIdx[y] || inArcToEdge[x] - inArcToEdge[y]);\n for (let i = 0; i < order.length; i++) {\n const a = order[i];\n const b = start + i;\n const sameArc = input.colIdx[a] === rebuilt.colIdx[b] && inArcToEdge[a] === outArcToEdge[b];\n const sameWeight = inWeights === null || outWeights === null || inWeights[a] === outWeights[b];\n if (!sameArc || !sameWeight) {\n throw invariantViolation(\"I7\", `arc ${a} in row ${u} has no matching mate`, {\n row: u,\n arc: a,\n target: input.colIdx[a],\n edge: inArcToEdge[a],\n });\n }\n }\n }\n}\n\n/**\n * Rebuild a sorted core from a candidate whose rows are unsorted through the freeze pipeline's\n * counting sorts (design section 6.3 steps 3-6 and 8) over the declared edge list, into a fresh arena\n * as `freeze()` would. Logical edge indices are preserved; the caller's arrays are not modified.\n * @param candidate - the candidate over the caller's arrays\n * @param parts - the candidate's parts (ids, tables, meta are reused)\n * @returns the rebuilt parts, with the truthful flags of the sorted core\n */\nfunction rebuildSorted(candidate: GraphSnapshot, parts: SnapshotParts): SnapshotParts {\n const edges = declaredEdges(candidate);\n const sorted = sortIntoCore(\n {\n directed: candidate.directed,\n nodeCount: candidate.nodeCount,\n edgeCount: candidate.edgeCount,\n src: edges.src,\n dst: edges.dst,\n weights: edges.weights,\n },\n true,\n );\n return {\n ...parts,\n arcCount: sorted.arcCount,\n selfLoopCount: sorted.selfLoopCount,\n rowPtr: sorted.core.rowPtr,\n colIdx: sorted.core.colIdx,\n weights: sorted.core.weights,\n arcToEdge: sorted.core.arcToEdge,\n edgeToArc: sorted.core.edgeToArc,\n flags: sorted.flags,\n arena: sorted.core.arena,\n };\n}\n\n/**\n * The order-independent checks of the \"full\" level over a candidate that is about to be rebuilt:\n * the permutation rules (I5 orientation, I6), NaN weights (I8), the id bijection (I11) and unique\n * columns. Sortedness (I4), pairing (I7) and the flags (I9) are established by the rebuild itself.\n * @param s - the candidate\n */\nfunction orderIndependentFullChecks(s: GraphSnapshot): void {\n checkI5Orientation(s);\n checkI6(s, true);\n checkI8NaN(s);\n checkI11Bijection(s);\n const tables: readonly [string, AttributeTable][] = [\n [\"nodes\", s.nodes],\n [\"edges\", s.edges],\n [\"graph\", s.graph],\n ];\n for (const [name, table] of tables) {\n for (const column of table) {\n checkUniqueColumn(name, column);\n }\n }\n}\n\n// ============================================================ the entry point\n\n/**\n * Resolve the options with their defaults, checking the validation level.\n * @param options - the caller's options\n * @returns the resolved values\n */\nfunction resolveOptions(options: FromCsrOptions): {\n readonly level: ValidationLevel;\n readonly copy: boolean;\n readonly sortRows: boolean;\n} {\n const level = options.validate ?? \"full\";\n if (!VALIDATION_LEVELS.has(level)) {\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unsupported validation level ${level}`, {\n field: \"validate\",\n found: level,\n reason: \"unsupported option\",\n });\n }\n return { level, copy: options.copy === true, sortRows: options.sortRows !== false };\n}\n\n/**\n * Build a snapshot from prebuilt CSR arrays (design section 8.1). The arrays are ADOPTED without\n * copying by default (`copy: false`): the caller transfers ownership and must not mutate them\n * afterwards; when they already share one plain ArrayBuffer at 256-byte-aligned offsets in arena\n * order that buffer becomes the snapshot's arena, otherwise `arena` is null. With `copy: true` (or\n * when an array is over a SharedArrayBuffer) the core is copied into a fresh arena. `validate`\n * defaults to \"full\" (design section 9.5), which computes the flags and verifies the caller's claims\n * (invariant I9); \"structure\" and \"none\" trust every claimed flag and compute only the unclaimed ones\n * (design section 8.1: \"structure\" skips the sortedness / multigraph / flag checks and trusts\n * `flags`). With `sortRows: true` (the default) invariant I4 is checked in O(m) and unsorted rows\n * are rebuilt through the freeze pipeline into a fresh arena; `sortRows: false` asserts sorted rows,\n * checked under \"full\". A directed input without `arcToEdge` (or with the identity) keeps identity\n * permutations lazy, so `edgeList().weights` aliases `weights`.\n * @param input - the arrays and counts; an undirected input must supply arcToEdge\n * @param options - validation level, copy and sortRows\n * @returns the snapshot; E_INVALID_SNAPSHOT (details.invariant, location) on every rejected input,\n * E_INVALID_ID / E_DUPLICATE_ID for bad ids, E_COLUMN_LENGTH for a column or id array of the wrong\n * length, E_TOO_LARGE for a node count above MAX_COUNT\n */\nexport function fromCsr(input: CsrInput, options: FromCsrOptions = {}): GraphSnapshot {\n const { level, copy, sortRows } = resolveOptions(options);\n checkShape(input);\n const resolved = resolveCore(input, level);\n const { directed, nodeCount } = input;\n const claims = input.flags;\n\n // adopt (detecting an arena) or copy\n let core: CoreArrays;\n if (copy || needsCopy(resolved)) {\n core = copyCoreIntoArena(coreArraysOf(resolved, null));\n } else {\n core = coreArraysOf(resolved, detectArena(resolved));\n }\n\n // flags (design sections 3.8, 8.1 and 9.5): \"full\" computes them and verifies the claims (I9);\n // \"structure\" and \"none\" trust every claimed flag and compute only the unclaimed ones\n const trustClaims = level !== \"full\";\n let flags: SnapshotFlags;\n if (trustClaims && fullyClaimed(claims)) {\n flags = applyClaims(\n {\n ...claims,\n weighted: core.weights !== null,\n arcToEdgeIsIdentity: directed && core.arcToEdge === null,\n },\n claims,\n );\n } else {\n const computed = flagsOf(directed, nodeCount, core, resolved.selfLoopCount);\n flags = trustClaims ? applyClaims(computed, claims) : computed;\n }\n\n const parts: SnapshotParts = {\n label: null,\n serial: null,\n directed,\n nodeCount,\n edgeCount: resolved.edgeCount,\n arcCount: resolved.arcCount,\n selfLoopCount: resolved.selfLoopCount,\n rowPtr: core.rowPtr,\n colIdx: core.colIdx,\n weights: core.weights,\n arcToEdge: core.arcToEdge,\n edgeToArc: core.edgeToArc,\n flags,\n ids: idMapOf(input, level, copy),\n nodes: tableOf(\"node\", nodeCount, input.nodeColumns, copy),\n edges: tableOf(\"edge\", resolved.edgeCount, input.edgeColumns, copy),\n graph: createTable(\"graph\", 1),\n extensions: new Map(),\n meta: resolveGraphMeta(input.meta),\n arena: core.arena,\n checksum: false,\n };\n const candidate = createSnapshot(parts);\n\n if (sortRows && !rowsSorted(candidate)) {\n // unsorted rows: check what can be checked without sorted rows, then rebuild\n if (level !== \"none\") {\n validateStructure(candidate);\n }\n if (level === \"full\") {\n orderIndependentFullChecks(candidate);\n }\n const rebuiltParts = rebuildSorted(candidate, parts);\n const rebuilt = createSnapshot({\n ...rebuiltParts,\n flags: trustClaims ? applyClaims(rebuiltParts.flags, claims) : rebuiltParts.flags,\n });\n if (level === \"full\") {\n if (!directed) {\n compareRows(candidate, rebuilt);\n }\n verifyClaims(claims, rebuilt.flags);\n }\n return rebuilt;\n }\n if (level === \"structure\") {\n validateStructure(candidate);\n } else if (level === \"full\") {\n validateFull(candidate);\n verifyClaims(claims, candidate.flags);\n }\n return candidate;\n}\n\n/** The flags that describe which arrays are PRESENT; they are never taken from a claim (I9 at every level). */\nconst PRESENCE_FLAGS: readonly (keyof SnapshotFlags)[] = [\"weighted\", \"arcToEdgeIsIdentity\"];\n\n/**\n * The trusted flags of a \"structure\" or \"none\" level construction: every claimed predicate flag as\n * given, every other one as computed. The two presence flags (`weighted`, `arcToEdgeIsIdentity`)\n * follow the arrays at every level, and a claim that contradicts them is I9 immediately: a claim\n * must never change which arrays the snapshot holds.\n * @param computed - the flags computed from the arrays\n * @param claims - the caller's claims, or undefined\n * @returns the flags to store\n */\nfunction applyClaims(computed: SnapshotFlags, claims: FlagClaims | undefined): SnapshotFlags {\n if (claims === undefined) {\n return computed;\n }\n const out: { -readonly [K in keyof SnapshotFlags]: boolean } = { ...computed };\n for (const name of FLAG_NAMES) {\n const value = claims[name];\n if (value === undefined) {\n continue;\n }\n if (PRESENCE_FLAGS.includes(name)) {\n if (value !== computed[name]) {\n throw invariantViolation(\n \"I9\",\n `flag ${name} is claimed ${value} but the arrays say ${computed[name]}`,\n {\n flag: name,\n found: value,\n expected: computed[name],\n },\n );\n }\n continue;\n }\n out[name] = value;\n }\n return out;\n}\n","/**\n * `fromEdgeArrays()` (design section 8.1, entry point 1): COO typed arrays with dense node indices,\n * the 20 ms path. The input goes through the builder's index-space fast path -- `addAnonymousNodes`\n * (no id Map unless `ids` is given) plus one `addEdges` call -- and then the freeze pipeline of design\n * section 6.3, so every builder policy (duplicate edges, self-loops, weight precision) and every\n * freeze option (label, prepare, arena, checksum) applies exactly as it does to a hand-built\n * builder. Attribute columns are staged in the builder too, so a merging duplicate policy or a\n * dropped self-loop gathers them through the same remaps as any other column (design section 5.11).\n *\n * The options object is the intersection of BuilderOptionsPatch and FreezeOptions; `splitOptions`\n * routes each field to the builder or to the freeze and is shared with `fromRecords`.\n */\n\nimport { GraphBuilder } from \"../builder/graph-builder.js\";\nimport { columnFromValues, metaToDecl } from \"../columns/column.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type GraphSnapshot } from \"../snapshot/graph-snapshot.js\";\nimport {\n type BuilderOptionsPatch,\n type ColumnDecl,\n type ColumnInput,\n type EdgeArraysInput,\n type FreezeOptions,\n type GraphBuilderOptions,\n type NodeId,\n type TypedArrayData,\n} from \"../types/index.js\";\n\n// ============================================================ options\n\n/** The builder half and the freeze half of a `BuilderOptionsPatch & FreezeOptions` object. */\ninterface SplitOptions {\n /** The builder options; `directed` is the caller's input value. */\n readonly builder: GraphBuilderOptions;\n /** The freeze options. */\n readonly freeze: FreezeOptions;\n}\n\n/**\n * Route the fields of a factory options object to the builder constructor and to `freeze()`.\n * `duplicateEdges` (a field of both) becomes the builder's default policy, which the freeze then\n * applies; an `options.directed` must agree with the input's own `directed` (E_DIRECTED otherwise; the input is\n * authoritative). Undefined fields are left to the builder's and the freeze's own defaults.\n * @param directed - the input's direction\n * @param options - the combined options\n * @returns the two halves\n */\nexport function splitOptions(directed: boolean, options: BuilderOptionsPatch & FreezeOptions): SplitOptions {\n if (options.directed !== undefined && options.directed !== directed) {\n throw new GraphFormatError(\n \"E_DIRECTED\",\n `options.directed (${String(options.directed)}) disagrees with the input's directed (${String(directed)})`,\n { reason: \"direction mismatch\", directed, found: options.directed },\n );\n }\n return {\n builder: {\n directed,\n weighted: options.weighted,\n weightDtype: options.weightDtype,\n duplicateEdges: options.duplicateEdges,\n selfLoops: options.selfLoops,\n addMissingNodes: options.addMissingNodes,\n expectedNodes: options.expectedNodes,\n expectedEdges: options.expectedEdges,\n },\n freeze: {\n label: options.label,\n prepare: options.prepare,\n arena: options.arena,\n release: options.release,\n profile: options.profile,\n checksum: options.checksum,\n },\n };\n}\n\n// ============================================================ columns\n\n/**\n * Whether a column value is a typed array (as opposed to a ColumnInput).\n * @param value - the column value\n * @returns true for a typed array\n */\nfunction isTypedArrayData(value: TypedArrayData | ColumnInput): value is TypedArrayData {\n return ArrayBuffer.isView(value);\n}\n\n/**\n * Stage one caller-supplied column in the builder (design section 8.1). A typed array (bare or\n * inside a ColumnInput) is bulk-set with its declaration; a JS array of values is resolved with the\n * same inference `AttributeTable.set()` applies (design section 5.1 widening, list detection) and\n * written row by row into a declared column, so a string / list / json column reaches the snapshot\n * through the same freeze step as every other column.\n * @param builder - the builder\n * @param domain - \"node\" or \"edge\"\n * @param rows - the table's row count (nodeCount or edge count); a JS array must have this many entries\n * @param name - the column name (the record key; a `decl.name` is ignored)\n * @param value - the typed array or ColumnInput\n */\nfunction stageColumn(\n builder: GraphBuilder,\n domain: \"node\" | \"edge\",\n rows: number,\n name: string,\n value: TypedArrayData | ColumnInput,\n): void {\n const data = isTypedArrayData(value) ? value : value.data;\n const decl = isTypedArrayData(value) ? {} : value.decl;\n if (ArrayBuffer.isView(data)) {\n if (domain === \"node\") {\n builder.setNodeColumn(name, data, decl);\n } else {\n builder.setEdgeColumn(name, data, decl);\n }\n return;\n }\n const column = columnFromValues(domain, rows, name, data, decl);\n const declaration: ColumnDecl = { ...metaToDecl(column.meta), name, dtype: column.dtype };\n const handle = domain === \"node\" ? builder.declareNodeColumn(declaration) : builder.declareEdgeColumn(declaration);\n for (let row = 0; row < rows; row++) {\n if (!column.isSet(row)) {\n continue;\n }\n const cell = column.value(row);\n if (domain === \"node\") {\n builder.setNodeValue(handle, row, cell);\n } else {\n builder.setEdgeValue(handle, row, cell);\n }\n }\n}\n\n// ============================================================ the entry point\n\n/**\n * The E_COLUMN_LENGTH error for two input arrays whose lengths disagree.\n * @param field - the array that is wrong\n * @param expected - the length it should have\n * @param found - the length it has\n * @returns the error\n */\nfunction lengthError(field: string, expected: number, found: number): GraphFormatError {\n return new GraphFormatError(\"E_COLUMN_LENGTH\", `${field} has ${found} entries, expected ${expected}`, {\n field,\n expected,\n found,\n });\n}\n\n/**\n * Resolve the node count of an EdgeArraysInput: `ids.length` when ids are given (and `nodeCount`,\n * when also given, must agree), else `nodeCount`, which is then required.\n * @param input - the input\n * @returns the node count\n */\nfunction resolveNodeCount(input: EdgeArraysInput): number {\n const { nodeCount, ids } = input;\n if (nodeCount !== undefined && (!Number.isInteger(nodeCount) || nodeCount < 0)) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", `nodeCount ${nodeCount} is not a non-negative integer`, {\n field: \"nodeCount\",\n found: nodeCount,\n });\n }\n if (ids !== undefined) {\n if (nodeCount !== undefined && nodeCount !== ids.length) {\n throw lengthError(\"ids\", nodeCount, ids.length);\n }\n return ids.length;\n }\n if (nodeCount === undefined) {\n throw new GraphFormatError(\"E_INDEX_RANGE\", \"nodeCount is required when no ids are given\", {\n field: \"nodeCount\",\n });\n }\n return nodeCount;\n}\n\n/**\n * Add the caller's ids to the builder in index order; every id must be distinct so that index i holds\n * ids[i] (E_DUPLICATE_ID otherwise, naming the id and both positions).\n * @param builder - the builder\n * @param ids - the ids in index order\n */\nfunction addIds(builder: GraphBuilder, ids: readonly NodeId[] | Float64Array): void {\n const indices = builder.addNodes(ids);\n for (let i = 0; i < indices.length; i++) {\n if (indices[i] !== i) {\n const id = ids[i];\n throw new GraphFormatError(\"E_DUPLICATE_ID\", `ids[${i}] repeats the id of index ${indices[i]}`, {\n id,\n index: indices[i],\n position: i,\n });\n }\n }\n}\n\n/**\n * Build a snapshot from COO typed arrays with dense node indices (design section 8.1): the builder's\n * index-space fast path (`addAnonymousNodes` + `addEdges`, no id Map unless `ids` is given) followed\n * by the freeze pipeline, so the result is exactly what a builder fed the same nodes, edges, columns\n * and meta would freeze to. Without `ids` the id map is `identity` with offset 0 and no storage;\n * with `ids` the kind is detected at freeze (design section 4.2). Float64 weights select the f64\n * staging precision unless `options.weightDtype` says otherwise, so the values are downcast to f32 in\n * the arc array and an f64 shadow column is kept only when some value is not f32-exact (design\n * section 3.7).\n * @param input - the arrays; `nodeCount` is required unless `ids` is given (E_INDEX_RANGE); `src`,\n * `dst` and `weights` must have one entry per edge (E_COLUMN_LENGTH); every index must be below the\n * node count (E_UNKNOWN_NODE); no weight may be NaN (E_INVALID_WEIGHT); ids must be distinct legal\n * ids (E_DUPLICATE_ID / E_INVALID_ID); columns must have the table's row count (E_COLUMN_LENGTH)\n * @param options - builder policies and freeze options; `duplicateEdges` and `selfLoops` apply at the\n * freeze (E_DUPLICATE_EDGE / E_SELF_LOOP under the \"error\" policies)\n * @returns the frozen snapshot\n */\nexport function fromEdgeArrays(\n input: EdgeArraysInput,\n options: BuilderOptionsPatch & FreezeOptions = {},\n): GraphSnapshot {\n const { src, dst, weights } = input;\n if (dst.length !== src.length) {\n throw lengthError(\"dst\", src.length, dst.length);\n }\n if (weights !== undefined && weights.length !== src.length) {\n throw lengthError(\"weights\", src.length, weights.length);\n }\n const nodeCount = resolveNodeCount(input);\n const edgeCount = src.length;\n const split = splitOptions(input.directed, options);\n const builderOptions: GraphBuilderOptions = {\n ...split.builder,\n weightDtype: options.weightDtype ?? (weights instanceof Float64Array ? \"f64\" : undefined),\n expectedNodes: options.expectedNodes ?? nodeCount,\n expectedEdges: options.expectedEdges ?? edgeCount,\n };\n const builder = new GraphBuilder(builderOptions);\n if (input.ids === undefined) {\n builder.addAnonymousNodes(nodeCount);\n } else {\n addIds(builder, input.ids);\n }\n builder.addEdges(src, dst, weights);\n if (input.nodeColumns !== undefined) {\n for (const name of Object.keys(input.nodeColumns)) {\n stageColumn(builder, \"node\", nodeCount, name, input.nodeColumns[name]);\n }\n }\n if (input.edgeColumns !== undefined) {\n for (const name of Object.keys(input.edgeColumns)) {\n stageColumn(builder, \"edge\", edgeCount, name, input.edgeColumns[name]);\n }\n }\n if (input.meta !== undefined) {\n builder.setMeta(input.meta);\n }\n return builder.freeze(split.freeze);\n}\n","/**\n * `fromRecords()` (design section 8.1, entry point 3): plain node-link records, the shape every JSON\n * dialect parses into and what graphty-element's data sources emit. Every record is pushed into a\n * GraphBuilder scalar by scalar -- the id, the endpoints and the weight through `addNode` / `addEdge`,\n * every other key through `setNodeValue` / `setEdgeValue` -- so attribute columns are inferred and\n * widened per column by the builder exactly as `addNodeRecord` / `addEdgeRecord` would (design\n * section 5.1), and the FreezeReport carries the widenings. The reserved keys (the node id, the edge\n * source / target and the weight) never become attribute columns: the id map and the arc array\n * already hold them.\n *\n * Id coercion (design section 4.1) is applied here, before an id reaches the builder: \"keep\" (the\n * default; JSON values are already typed), \"canonical\" (canonical integer text becomes a number,\n * everything else stays a string), \"string\" and \"number\".\n */\n\nimport { GraphBuilder } from \"../builder/graph-builder.js\";\nimport { GraphFormatError } from \"../errors.js\";\nimport { type GraphSnapshot } from \"../snapshot/graph-snapshot.js\";\nimport {\n type BuilderOptionsPatch,\n type ColumnDecl,\n type ColumnHandle,\n type FreezeOptions,\n type FreezeReport,\n type GraphBuilderOptions,\n type IdCoercion,\n type NodeId,\n type RecordsInput,\n} from \"../types/index.js\";\nimport { assertOneOf } from \"../util/options.js\";\nimport { splitOptions } from \"./from-edge-arrays.js\";\n\n/** A node or edge record. */\ntype RecordRow = Readonly<Record<string, unknown>>;\n\n/** The default source keys, tried in order when `edgeSource` is not given. */\nconst SOURCE_KEYS: readonly string[] = [\"source\", \"src\", \"from\"];\n\n/** The default target keys, tried in order when `edgeTarget` is not given. */\nconst TARGET_KEYS: readonly string[] = [\"target\", \"dst\", \"to\"];\n\n/** The canonical integer text of design section 4.1. */\nconst CANONICAL_INTEGER = /^-?(0|[1-9][0-9]*)$/;\n\n// ============================================================ ids\n\n/**\n * Whether a record has an own property (records may come from `JSON.parse`, so prototype lookups are\n * never consulted).\n * @param record - the record\n * @param key - the key\n * @returns true when the key is an own property\n */\nfunction hasKey(record: RecordRow, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(record, key);\n}\n\n/**\n * The E_INVALID_ID error for an id cell the coercion rule cannot turn into a NodeId.\n * @param field - which cell (id / source / target)\n * @param value - the value\n * @param rule - the coercion rule in force\n * @returns the error\n */\nfunction invalidId(field: string, value: unknown, rule: IdCoercion): GraphFormatError {\n return new GraphFormatError(\n \"E_INVALID_ID\",\n `${field} value of type ${typeof value} is not a legal id under \"${rule}\"`,\n {\n field,\n found: typeof value,\n rule,\n },\n );\n}\n\n/**\n * Apply an id coercion rule to one id cell (design section 4.1). The result still goes through the\n * builder's own id validation (E_INVALID_ID for anything that is not a finite number or a well-formed\n * string), so this function only converts; it rejects the shapes a rule cannot convert.\n * @param value - the cell value\n * @param rule - the coercion rule\n * @param field - which cell, for the error message\n * @returns the id to hand to the builder\n */\nexport function coerceId(value: unknown, rule: IdCoercion, field: string): NodeId {\n switch (rule) {\n case \"keep\":\n if (typeof value === \"string\" || typeof value === \"number\") {\n return value;\n }\n throw invalidId(field, value, rule);\n case \"canonical\":\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n // \"-0\" is excluded so the rule stays injective on text (-0 and 0 are one id)\n if (CANONICAL_INTEGER.test(value) && value !== \"-0\") {\n const n = Number(value);\n return Number.isSafeInteger(n) ? n : value;\n }\n return value;\n }\n throw invalidId(field, value, rule);\n case \"string\":\n if (typeof value === \"string\") {\n return value;\n }\n if (\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"bigint\" ||\n value === null\n ) {\n return String(value);\n }\n throw invalidId(field, value, rule);\n case \"number\":\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return Number(value);\n }\n throw invalidId(field, value, rule);\n default: {\n const name: string = rule;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id coercion \"${name}\"`, {\n field: \"ids\",\n found: name,\n reason: \"unsupported option\",\n });\n }\n }\n}\n\n/**\n * Read an endpoint cell: the explicit key when one was given, else the first of the default keys the\n * record has.\n * @param record - the edge record\n * @param explicit - the caller's key, or undefined\n * @param defaults - the default keys in order\n * @returns the key that was used and its value; the key is null when none is present\n */\nfunction endpointOf(\n record: RecordRow,\n explicit: string | undefined,\n defaults: readonly string[],\n): { readonly key: string | null; readonly value: unknown } {\n if (explicit !== undefined) {\n return { key: hasKey(record, explicit) ? explicit : null, value: record[explicit] };\n }\n for (const key of defaults) {\n if (hasKey(record, key)) {\n return { key, value: record[key] };\n }\n }\n return { key: null, value: undefined };\n}\n\n/**\n * The E_INVALID_ID error for an edge record without an endpoint.\n * @param field - \"source\" or \"target\"\n * @param keys - the keys that were tried\n * @param edge - the record's position in the edge iteration\n * @returns the error\n */\nfunction missingEndpoint(field: string, keys: readonly string[], edge: number): GraphFormatError {\n return new GraphFormatError(\n \"E_INVALID_ID\",\n `edge record ${edge} has no ${field} (keys tried: ${keys.join(\", \")})`,\n {\n field,\n keys: [...keys],\n edge,\n reason: \"missing endpoint\",\n },\n );\n}\n\n// ============================================================ attribute policy\n\n/**\n * How non-reserved record keys become columns: the builder's inference, one json column per key, no\n * columns at all, or only the declared columns.\n */\nclass AttributePolicy {\n private readonly mode: \"infer\" | \"json\" | \"none\" | \"declared\";\n\n private readonly declared: ReadonlyMap<string, ColumnDecl>;\n\n private readonly handles: { readonly node: Map<string, ColumnHandle>; readonly edge: Map<string, ColumnHandle> };\n\n /**\n * Resolve the `columns` option.\n * @param columns - the option value; default \"infer\"\n */\n constructor(columns: RecordsInput[\"columns\"]) {\n this.handles = { node: new Map(), edge: new Map() };\n if (columns === undefined || columns === \"infer\") {\n this.mode = \"infer\";\n this.declared = new Map();\n return;\n }\n if (columns === \"json\" || columns === \"none\") {\n this.mode = columns;\n this.declared = new Map();\n return;\n }\n if (typeof columns === \"string\") {\n // unreachable for typed callers; an unknown mode string from untyped JS lands here\n const found: string = columns;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unsupported columns option \"${found}\"`, {\n field: \"columns\",\n found,\n reason: \"unsupported option\",\n });\n }\n const declared = new Map<string, ColumnDecl>();\n const list: readonly ColumnDecl[] = columns;\n for (const decl of list) {\n if (typeof decl.name !== \"string\" || decl.name.length === 0) {\n throw new GraphFormatError(\"E_COLUMN_TYPE\", \"a column declaration needs a non-empty name\", {\n field: \"name\",\n found: decl.name,\n });\n }\n if (declared.has(decl.name)) {\n throw new GraphFormatError(\"E_COLUMN_EXISTS\", `column \"${decl.name}\" is declared twice`, {\n column: decl.name,\n });\n }\n declared.set(decl.name, decl);\n }\n this.mode = \"declared\";\n this.declared = declared;\n }\n\n /**\n * Whether any attribute key is read at all.\n * @returns false under \"none\"\n */\n get readsAttributes(): boolean {\n return this.mode !== \"none\";\n }\n\n /**\n * Write one attribute cell according to the policy.\n * @param builder - the builder\n * @param domain - \"node\" or \"edge\"\n * @param row - the node index or logical edge index\n * @param key - the record key\n * @param value - the cell value\n */\n write(builder: GraphBuilder, domain: \"node\" | \"edge\", row: number, key: string, value: unknown): void {\n switch (this.mode) {\n case \"none\":\n return;\n case \"infer\":\n if (domain === \"node\") {\n builder.setNodeValue(key, row, value);\n } else {\n builder.setEdgeValue(key, row, value);\n }\n return;\n case \"json\":\n case \"declared\": {\n const handle = this.handleOf(builder, domain, key);\n if (handle === null) {\n return;\n }\n if (domain === \"node\") {\n builder.setNodeValue(handle, row, value);\n } else {\n builder.setEdgeValue(handle, row, value);\n }\n return;\n }\n default: {\n const name: string = this.mode;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown attribute mode ${name}`, { found: name });\n }\n }\n }\n\n /**\n * The handle of a key's column in one table, declaring it on first use: a json column under\n * \"json\", the caller's declaration under \"declared\" (an undeclared key has no column).\n * @param builder - the builder\n * @param domain - \"node\" or \"edge\"\n * @param key - the record key\n * @returns the handle, or null when the key is not stored\n */\n private handleOf(builder: GraphBuilder, domain: \"node\" | \"edge\", key: string): ColumnHandle | null {\n const cache = this.handles[domain];\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n let decl: ColumnDecl;\n if (this.mode === \"json\") {\n decl = { name: key, dtype: \"json\" };\n } else {\n const declared = this.declared.get(key);\n if (declared === undefined) {\n return null;\n }\n decl = declared;\n }\n const handle = domain === \"node\" ? builder.declareNodeColumn(decl) : builder.declareEdgeColumn(decl);\n cache.set(key, handle);\n return handle;\n }\n}\n\n// ============================================================ the entry point\n\n/**\n * The resolved record keys and rules of one fromRecords call.\n */\ninterface RecordRules {\n /** The node id key, or null for positional nodes (d3 v3). */\n readonly nodeId: string | null;\n /** The explicit source key, or undefined for the default keys. */\n readonly edgeSource: string | undefined;\n /** The explicit target key, or undefined for the default keys. */\n readonly edgeTarget: string | undefined;\n /** The weight key, or null for unweighted. */\n readonly edgeWeight: string | null;\n /** The id coercion rule. */\n readonly ids: IdCoercion;\n /** The attribute policy. */\n readonly attributes: AttributePolicy;\n}\n\n/**\n * Resolve the keys and rules of a RecordsInput with their defaults.\n * @param input - the input\n * @returns the rules\n */\nfunction rulesOf(input: RecordsInput): RecordRules {\n return {\n nodeId: input.nodeId === undefined ? \"id\" : input.nodeId,\n edgeSource: input.edgeSource,\n edgeTarget: input.edgeTarget,\n edgeWeight: input.edgeWeight === undefined ? \"weight\" : input.edgeWeight,\n ids: assertOneOf(\"ids\", input.ids, [\"keep\", \"canonical\", \"string\", \"number\"] as const) ?? \"keep\",\n attributes: new AttributePolicy(input.columns),\n };\n}\n\n/**\n * Resolve a positional endpoint (nodeId null: endpoints are node indices, design section 8.1): a\n * non-negative integer below the builder's node bound, or -- under addMissingNodes -- one that\n * extends the anonymous node range.\n * @param builder - the builder\n * @param value - the cell value\n * @param field - \"source\" or \"target\"\n * @param edge - the record's position, for the error\n * @returns the node index\n */\nfunction positionalEndpoint(builder: GraphBuilder, value: unknown, field: string, edge: number): number {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n throw new GraphFormatError(\n \"E_INVALID_ID\",\n `edge record ${edge}: ${field} ${String(value)} is not a node index`,\n {\n field,\n found: value,\n edge,\n reason: \"not an index\",\n },\n );\n }\n const bound = builder.nodeBound;\n if (value >= bound) {\n if (!builder.options.addMissingNodes) {\n throw new GraphFormatError(\"E_UNKNOWN_NODE\", `edge record ${edge}: node index ${value} does not exist`, {\n index: value,\n field,\n edge,\n });\n }\n builder.addAnonymousNodes(value - bound + 1);\n }\n return value;\n}\n\n/**\n * Read the weight cell of an edge record: absent, undefined and null mean \"no weight\" (1 in a\n * weighted graph, design section 3.7); anything else must be a number.\n * @param record - the edge record\n * @param key - the weight key\n * @param edge - the record's position, for the error\n * @returns the weight, or undefined when omitted\n */\nfunction weightOf(record: RecordRow, key: string, edge: number): number | undefined {\n if (!hasKey(record, key)) {\n return undefined;\n }\n const raw = record[key];\n if (raw === undefined || raw === null) {\n return undefined;\n }\n if (typeof raw !== \"number\") {\n throw new GraphFormatError(\"E_INVALID_WEIGHT\", `edge record ${edge}: weight \"${key}\" is not a number`, {\n key,\n found: typeof raw,\n edge,\n });\n }\n return raw;\n}\n\n/**\n * Push the node records.\n * @param builder - the builder\n * @param rules - the resolved rules\n * @param nodes - the node records\n */\nfunction pushNodes(builder: GraphBuilder, rules: RecordRules, nodes: Iterable<RecordRow>): void {\n const { nodeId, attributes } = rules;\n let position = 0;\n for (const record of nodes) {\n let index: number;\n if (nodeId === null) {\n index = builder.addAnonymousNodes(1);\n } else {\n if (!hasKey(record, nodeId)) {\n throw new GraphFormatError(\"E_INVALID_ID\", `node record ${position} has no \"${nodeId}\" key`, {\n field: nodeId,\n node: position,\n reason: \"missing id\",\n });\n }\n index = builder.addNode(coerceId(record[nodeId], rules.ids, nodeId));\n }\n if (attributes.readsAttributes) {\n for (const key of Object.keys(record)) {\n if (key !== nodeId) {\n attributes.write(builder, \"node\", index, key, record[key]);\n }\n }\n }\n position++;\n }\n}\n\n/**\n * Push the edge records.\n * @param builder - the builder\n * @param rules - the resolved rules\n * @param edges - the edge records\n */\nfunction pushEdges(builder: GraphBuilder, rules: RecordRules, edges: Iterable<RecordRow>): void {\n const { nodeId, edgeWeight, attributes } = rules;\n let position = 0;\n for (const record of edges) {\n const source = endpointOf(record, rules.edgeSource, SOURCE_KEYS);\n const target = endpointOf(record, rules.edgeTarget, TARGET_KEYS);\n if (source.key === null) {\n throw missingEndpoint(\n \"source\",\n rules.edgeSource === undefined ? SOURCE_KEYS : [rules.edgeSource],\n position,\n );\n }\n if (target.key === null) {\n throw missingEndpoint(\n \"target\",\n rules.edgeTarget === undefined ? TARGET_KEYS : [rules.edgeTarget],\n position,\n );\n }\n const weight = edgeWeight === null ? undefined : weightOf(record, edgeWeight, position);\n let edge: number;\n if (nodeId === null) {\n const u = positionalEndpoint(builder, source.value, \"source\", position);\n const v = positionalEndpoint(builder, target.value, \"target\", position);\n edge = builder.addEdgeByIndex(u, v, weight);\n } else {\n edge = builder.addEdge(\n coerceId(source.value, rules.ids, \"source\"),\n coerceId(target.value, rules.ids, \"target\"),\n weight,\n );\n }\n if (attributes.readsAttributes) {\n for (const key of Object.keys(record)) {\n if (key !== source.key && key !== target.key && key !== edgeWeight) {\n attributes.write(builder, \"edge\", edge, key, record[key]);\n }\n }\n }\n position++;\n }\n}\n\n/**\n * Build a snapshot from node-link records (design section 8.1): node records (optional; every node\n * an edge names is created under addMissingNodes, the default) and edge records, pushed into a\n * GraphBuilder one scalar at a time and frozen. The node id comes from `nodeId` (\"id\" by default;\n * null makes the node index the record position and the endpoints indices, the d3 v3 shape), the\n * endpoints from `edgeSource` / `edgeTarget` (\"source\" / \"target\" by default, falling back to \"src\"\n * / \"from\" and \"dst\" / \"to\"), the weight from `edgeWeight` (\"weight\" by default; null = unweighted).\n * Every other key becomes an attribute column per `columns`: \"infer\" (default) lets the builder\n * infer and widen per column (design section 5.1), \"json\" stores each key as a json column, \"none\"\n * loads only the structure, and a ColumnDecl list stores only the declared keys. Ids are coerced per\n * `ids` (\"keep\" by default). The staging weight precision defaults to f64 so a JSON weight such as\n * 0.1 is never corrupted (the shadow column costs nothing when every value is f32-exact); pass\n * `weightDtype: \"f32\"` to opt out.\n * @param input - the records and keys; a record without its id or an endpoint, or with an id the\n * coercion rule cannot convert, is E_INVALID_ID; a non-numeric weight is E_INVALID_WEIGHT; an\n * unknown endpoint under addMissingNodes false is E_UNKNOWN_NODE\n * @param options - builder policies and freeze options\n * @returns the snapshot and the freeze report (its `widened` entries name the inferred columns that\n * widened while the records were read)\n */\nexport function fromRecords(\n input: RecordsInput,\n options: BuilderOptionsPatch & FreezeOptions = {},\n): { snapshot: GraphSnapshot; report: FreezeReport } {\n const rules = rulesOf(input);\n const split = splitOptions(input.directed, options);\n const builderOptions: GraphBuilderOptions = {\n ...split.builder,\n weightDtype: options.weightDtype ?? \"f64\",\n };\n const builder = new GraphBuilder(builderOptions);\n if (input.nodes !== undefined) {\n pushNodes(builder, rules, input.nodes);\n }\n pushEdges(builder, rules, input.edges);\n return builder.freezeWithReport(split.freeze);\n}\n"],"names":["fatalDecoder","unsupportedDtype","ALL_ONES","I32_MIN","I32_MAX","MAX_JSON_DEPTH","lengthError","out","ID_TYPES","TIME_FORMATS","TIME_REPRESENTATIONS","MODES","resolveGraphMeta","valueRemapFor","isTypedArrayData","a","NUM_TAG","ESC_TAG","decoder","fillCode","AttributeTableClass","i","_GraphSnapshot","idMapOf","tableOf","nodes","edges","resolveOptions","target","resolveSharedGraphMeta"],"mappings":"AAeO,MAAM,gBAAgB;AAMtB,MAAM,YA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