@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.
Files changed (224) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +216 -43
  3. package/dist/graph-format.d.ts +1 -0
  4. package/dist/graph-format.d.ts.map +1 -0
  5. package/dist/graph-format.js +15798 -0
  6. package/dist/graph-format.js.map +1 -0
  7. package/dist/src/builder/arena.d.ts +85 -0
  8. package/dist/src/builder/arena.d.ts.map +1 -0
  9. package/dist/src/builder/arena.js +154 -0
  10. package/dist/src/builder/arena.js.map +1 -0
  11. package/dist/src/builder/compact.d.ts +515 -0
  12. package/dist/src/builder/compact.d.ts.map +1 -0
  13. package/dist/src/builder/compact.js +1553 -0
  14. package/dist/src/builder/compact.js.map +1 -0
  15. package/dist/src/builder/counting-sort.d.ts +96 -0
  16. package/dist/src/builder/counting-sort.d.ts.map +1 -0
  17. package/dist/src/builder/counting-sort.js +430 -0
  18. package/dist/src/builder/counting-sort.js.map +1 -0
  19. package/dist/src/builder/freeze.d.ts +72 -0
  20. package/dist/src/builder/freeze.d.ts.map +1 -0
  21. package/dist/src/builder/freeze.js +548 -0
  22. package/dist/src/builder/freeze.js.map +1 -0
  23. package/dist/src/builder/graph-builder.d.ts +602 -0
  24. package/dist/src/builder/graph-builder.d.ts.map +1 -0
  25. package/dist/src/builder/graph-builder.js +1940 -0
  26. package/dist/src/builder/graph-builder.js.map +1 -0
  27. package/dist/src/builder/options.d.ts +16 -0
  28. package/dist/src/builder/options.d.ts.map +1 -0
  29. package/dist/src/builder/options.js +21 -0
  30. package/dist/src/builder/options.js.map +1 -0
  31. package/dist/src/columns/bitmap.d.ts +96 -0
  32. package/dist/src/columns/bitmap.d.ts.map +1 -0
  33. package/dist/src/columns/bitmap.js +184 -0
  34. package/dist/src/columns/bitmap.js.map +1 -0
  35. package/dist/src/columns/column.d.ts +220 -0
  36. package/dist/src/columns/column.d.ts.map +1 -0
  37. package/dist/src/columns/column.js +2109 -0
  38. package/dist/src/columns/column.js.map +1 -0
  39. package/dist/src/columns/dictionary.d.ts +60 -0
  40. package/dist/src/columns/dictionary.d.ts.map +1 -0
  41. package/dist/src/columns/dictionary.js +102 -0
  42. package/dist/src/columns/dictionary.js.map +1 -0
  43. package/dist/src/columns/growable.d.ts +198 -0
  44. package/dist/src/columns/growable.d.ts.map +1 -0
  45. package/dist/src/columns/growable.js +296 -0
  46. package/dist/src/columns/growable.js.map +1 -0
  47. package/dist/src/columns/infer.d.ts +121 -0
  48. package/dist/src/columns/infer.d.ts.map +1 -0
  49. package/dist/src/columns/infer.js +268 -0
  50. package/dist/src/columns/infer.js.map +1 -0
  51. package/dist/src/columns/remap.d.ts +143 -0
  52. package/dist/src/columns/remap.d.ts.map +1 -0
  53. package/dist/src/columns/remap.js +588 -0
  54. package/dist/src/columns/remap.js.map +1 -0
  55. package/dist/src/columns/table.d.ts +184 -0
  56. package/dist/src/columns/table.d.ts.map +1 -0
  57. package/dist/src/columns/table.js +485 -0
  58. package/dist/src/columns/table.js.map +1 -0
  59. package/dist/src/constants.d.ts +34 -0
  60. package/dist/src/constants.d.ts.map +1 -0
  61. package/dist/src/constants.js +79 -0
  62. package/dist/src/constants.js.map +1 -0
  63. package/dist/src/errors.d.ts +76 -0
  64. package/dist/src/errors.d.ts.map +1 -0
  65. package/dist/src/errors.js +32 -0
  66. package/dist/src/errors.js.map +1 -0
  67. package/dist/src/ids/edge-id-index.d.ts +77 -0
  68. package/dist/src/ids/edge-id-index.d.ts.map +1 -0
  69. package/dist/src/ids/edge-id-index.js +155 -0
  70. package/dist/src/ids/edge-id-index.js.map +1 -0
  71. package/dist/src/ids/node-id-map.d.ts +280 -0
  72. package/dist/src/ids/node-id-map.d.ts.map +1 -0
  73. package/dist/src/ids/node-id-map.js +1139 -0
  74. package/dist/src/ids/node-id-map.js.map +1 -0
  75. package/dist/src/ids/string-store.d.ts +219 -0
  76. package/dist/src/ids/string-store.d.ts.map +1 -0
  77. package/dist/src/ids/string-store.js +526 -0
  78. package/dist/src/ids/string-store.js.map +1 -0
  79. package/dist/src/index.d.ts +30 -0
  80. package/dist/src/index.d.ts.map +1 -0
  81. package/dist/src/index.js +29 -0
  82. package/dist/src/index.js.map +1 -0
  83. package/dist/src/populate/from-csr.d.ts +61 -0
  84. package/dist/src/populate/from-csr.d.ts.map +1 -0
  85. package/dist/src/populate/from-csr.js +706 -0
  86. package/dist/src/populate/from-csr.js.map +1 -0
  87. package/dist/src/populate/from-edge-arrays.d.ts +51 -0
  88. package/dist/src/populate/from-edge-arrays.d.ts.map +1 -0
  89. package/dist/src/populate/from-edge-arrays.js +217 -0
  90. package/dist/src/populate/from-edge-arrays.js.map +1 -0
  91. package/dist/src/populate/from-records.d.ts +51 -0
  92. package/dist/src/populate/from-records.d.ts.map +1 -0
  93. package/dist/src/populate/from-records.js +447 -0
  94. package/dist/src/populate/from-records.js.map +1 -0
  95. package/dist/src/snapshot/derived.d.ts +211 -0
  96. package/dist/src/snapshot/derived.d.ts.map +1 -0
  97. package/dist/src/snapshot/derived.js +1254 -0
  98. package/dist/src/snapshot/derived.js.map +1 -0
  99. package/dist/src/snapshot/graph-meta.d.ts +23 -0
  100. package/dist/src/snapshot/graph-meta.d.ts.map +1 -0
  101. package/dist/src/snapshot/graph-meta.js +159 -0
  102. package/dist/src/snapshot/graph-meta.js.map +1 -0
  103. package/dist/src/snapshot/graph-snapshot.d.ts +509 -0
  104. package/dist/src/snapshot/graph-snapshot.d.ts.map +1 -0
  105. package/dist/src/snapshot/graph-snapshot.js +1247 -0
  106. package/dist/src/snapshot/graph-snapshot.js.map +1 -0
  107. package/dist/src/snapshot/hash.d.ts +90 -0
  108. package/dist/src/snapshot/hash.d.ts.map +1 -0
  109. package/dist/src/snapshot/hash.js +228 -0
  110. package/dist/src/snapshot/hash.js.map +1 -0
  111. package/dist/src/snapshot/queries.d.ts +74 -0
  112. package/dist/src/snapshot/queries.d.ts.map +1 -0
  113. package/dist/src/snapshot/queries.js +131 -0
  114. package/dist/src/snapshot/queries.js.map +1 -0
  115. package/dist/src/snapshot/validate.d.ts +192 -0
  116. package/dist/src/snapshot/validate.d.ts.map +1 -0
  117. package/dist/src/snapshot/validate.js +990 -0
  118. package/dist/src/snapshot/validate.js.map +1 -0
  119. package/dist/src/snapshot/views.d.ts +274 -0
  120. package/dist/src/snapshot/views.d.ts.map +1 -0
  121. package/dist/src/snapshot/views.js +856 -0
  122. package/dist/src/snapshot/views.js.map +1 -0
  123. package/dist/src/types/builder.d.ts +456 -0
  124. package/dist/src/types/builder.d.ts.map +1 -0
  125. package/dist/src/types/builder.js +11 -0
  126. package/dist/src/types/builder.js.map +1 -0
  127. package/dist/src/types/columns.d.ts +615 -0
  128. package/dist/src/types/columns.d.ts.map +1 -0
  129. package/dist/src/types/columns.js +14 -0
  130. package/dist/src/types/columns.js.map +1 -0
  131. package/dist/src/types/index.d.ts +14 -0
  132. package/dist/src/types/index.d.ts.map +1 -0
  133. package/dist/src/types/index.js +11 -0
  134. package/dist/src/types/index.js.map +1 -0
  135. package/dist/src/types/internal.d.ts +172 -0
  136. package/dist/src/types/internal.d.ts.map +1 -0
  137. package/dist/src/types/internal.js +13 -0
  138. package/dist/src/types/internal.js.map +1 -0
  139. package/dist/src/types/snapshot.d.ts +801 -0
  140. package/dist/src/types/snapshot.d.ts.map +1 -0
  141. package/dist/src/types/snapshot.js +14 -0
  142. package/dist/src/types/snapshot.js.map +1 -0
  143. package/dist/src/types/wire.d.ts +196 -0
  144. package/dist/src/types/wire.d.ts.map +1 -0
  145. package/dist/src/types/wire.js +8 -0
  146. package/dist/src/types/wire.js.map +1 -0
  147. package/dist/src/util/mask.d.ts +55 -0
  148. package/dist/src/util/mask.d.ts.map +1 -0
  149. package/dist/src/util/mask.js +71 -0
  150. package/dist/src/util/mask.js.map +1 -0
  151. package/dist/src/util/options.d.ts +22 -0
  152. package/dist/src/util/options.d.ts.map +1 -0
  153. package/dist/src/util/options.js +49 -0
  154. package/dist/src/util/options.js.map +1 -0
  155. package/dist/src/util/shared-buffers.d.ts +42 -0
  156. package/dist/src/util/shared-buffers.d.ts.map +1 -0
  157. package/dist/src/util/shared-buffers.js +52 -0
  158. package/dist/src/util/shared-buffers.js.map +1 -0
  159. package/dist/src/util/typed-array.d.ts +205 -0
  160. package/dist/src/util/typed-array.d.ts.map +1 -0
  161. package/dist/src/util/typed-array.js +289 -0
  162. package/dist/src/util/typed-array.js.map +1 -0
  163. package/dist/src/wire/bytes.d.ts +69 -0
  164. package/dist/src/wire/bytes.d.ts.map +1 -0
  165. package/dist/src/wire/bytes.js +361 -0
  166. package/dist/src/wire/bytes.js.map +1 -0
  167. package/dist/src/wire/carried-views.d.ts +111 -0
  168. package/dist/src/wire/carried-views.d.ts.map +1 -0
  169. package/dist/src/wire/carried-views.js +286 -0
  170. package/dist/src/wire/carried-views.js.map +1 -0
  171. package/dist/src/wire/from-wire.d.ts +144 -0
  172. package/dist/src/wire/from-wire.d.ts.map +1 -0
  173. package/dist/src/wire/from-wire.js +1425 -0
  174. package/dist/src/wire/from-wire.js.map +1 -0
  175. package/dist/src/wire/to-wire.d.ts +171 -0
  176. package/dist/src/wire/to-wire.d.ts.map +1 -0
  177. package/dist/src/wire/to-wire.js +652 -0
  178. package/dist/src/wire/to-wire.js.map +1 -0
  179. package/dist/tsconfig.build.tsbuildinfo +1 -0
  180. package/package.json +72 -7
  181. package/src/builder/arena.ts +192 -0
  182. package/src/builder/compact.ts +1811 -0
  183. package/src/builder/counting-sort.ts +506 -0
  184. package/src/builder/freeze.ts +689 -0
  185. package/src/builder/graph-builder.ts +2264 -0
  186. package/src/builder/options.ts +29 -0
  187. package/src/columns/bitmap.ts +196 -0
  188. package/src/columns/column.ts +2574 -0
  189. package/src/columns/dictionary.ts +114 -0
  190. package/src/columns/growable.ts +350 -0
  191. package/src/columns/infer.ts +285 -0
  192. package/src/columns/remap.ts +663 -0
  193. package/src/columns/table.ts +568 -0
  194. package/src/constants.ts +89 -0
  195. package/src/errors.ts +115 -0
  196. package/src/ids/edge-id-index.ts +179 -0
  197. package/src/ids/node-id-map.ts +1340 -0
  198. package/src/ids/string-store.ts +589 -0
  199. package/src/index.ts +139 -0
  200. package/src/lib-resizable-array-buffer.d.ts +34 -0
  201. package/src/populate/from-csr.ts +802 -0
  202. package/src/populate/from-edge-arrays.ts +257 -0
  203. package/src/populate/from-records.ts +536 -0
  204. package/src/snapshot/derived.ts +1486 -0
  205. package/src/snapshot/graph-meta.ts +167 -0
  206. package/src/snapshot/graph-snapshot.ts +1503 -0
  207. package/src/snapshot/hash.ts +241 -0
  208. package/src/snapshot/queries.ts +136 -0
  209. package/src/snapshot/validate.ts +1108 -0
  210. package/src/snapshot/views.ts +943 -0
  211. package/src/types/builder.ts +480 -0
  212. package/src/types/columns.ts +727 -0
  213. package/src/types/index.ts +14 -0
  214. package/src/types/internal.ts +195 -0
  215. package/src/types/snapshot.ts +886 -0
  216. package/src/types/wire.ts +207 -0
  217. package/src/util/mask.ts +89 -0
  218. package/src/util/options.ts +57 -0
  219. package/src/util/shared-buffers.ts +56 -0
  220. package/src/util/typed-array.ts +371 -0
  221. package/src/wire/bytes.ts +440 -0
  222. package/src/wire/carried-views.ts +327 -0
  223. package/src/wire/from-wire.ts +1690 -0
  224. package/src/wire/to-wire.ts +755 -0
@@ -0,0 +1,1553 @@
1
+ /**
2
+ * The builder's staging representation and its compaction (design sections 6.2 and 6.3 step 1).
3
+ *
4
+ * Staging is structure-of-arrays typed storage that grows by doubling: the node side (`ids`,
5
+ * `idToIndex`, `nodeAlive`, the incidence-list heads `firstOut` / `firstIn`), the edge side (`src`,
6
+ * `dst`, `weight`, `weightSet`, `edgeAlive`, the incidence-list links `nextOut` / `nextIn`), the live
7
+ * counts, and one `StagingColumn` per declared node / edge / extension column (a growable typed array,
8
+ * packed bitmap or JS array plus an optional validity bitmap and, for dict columns, an interning
9
+ * dictionary). No per-node or per-edge object is ever allocated.
10
+ *
11
+ * Compaction (`compactStaging`) gathers a NEW staging object through node and edge remaps assigned in
12
+ * index order (invariant I14): tombstoned nodes and edges disappear, `refersTo` column values are
13
+ * rewritten (dangling references become INVALID_INDEX with the row unset), fresh `ids` / `idToIndex`
14
+ * objects are built so the previous snapshot keeps the ones it shares (design section 4.2), and the
15
+ * incidence lists are rebuilt. The source staging is never modified, so a freeze that throws after
16
+ * compacting leaves the builder exactly as it was (design section 11.1); the builder commits the new
17
+ * staging only when the freeze succeeds.
18
+ */
19
+ import { bitmapClear, bitmapGet, bitmapWordCount, makeBitmap } from "../columns/bitmap.js";
20
+ import { allocNumeric, assertJsonValue, columnOfValues, createColumn, isArrayLikeNumbers, metaToDecl, representableNumber, resolveColumnMeta, seedDictionary, } from "../columns/column.js";
21
+ import { assertWellFormedString } from "../columns/dictionary.js";
22
+ import { GrowableBitmap, GrowableTypedArray } from "../columns/growable.js";
23
+ import { coerceValue, DtypeInferrer, inferValueDtype } from "../columns/infer.js";
24
+ import { INVALID_INDEX } from "../constants.js";
25
+ import { GraphFormatError } from "../errors.js";
26
+ import { detachString } from "../ids/string-store.js";
27
+ // ============================================================ small helpers
28
+ /** The shared, frozen empty list every unset / unwritten list row points at. */
29
+ const EMPTY_LIST = Object.freeze([]);
30
+ /**
31
+ * The E_COLUMN_TYPE error for a value a column cannot hold.
32
+ * @param meta - the column
33
+ * @param row - the row
34
+ * @param message - what is wrong
35
+ * @param found - the offending value's type or shape
36
+ * @returns the error
37
+ */
38
+ function cellError(meta, row, message, found) {
39
+ return new GraphFormatError("E_COLUMN_TYPE", `row ${row} of ${meta.dtype} column "${meta.name}": ${message}`, {
40
+ column: meta.name,
41
+ domain: meta.domain,
42
+ row,
43
+ found,
44
+ });
45
+ }
46
+ /**
47
+ * The dtype an inferred (auto-declared) column starts with for a value (design section 5.1).
48
+ * @param value - the first set value
49
+ * @returns the inferred dtype; E_COLUMN_TYPE for a value no column can hold
50
+ */
51
+ export function inferInitialDtype(value) {
52
+ const dtype = inferValueDtype(value);
53
+ if (dtype === null) {
54
+ throw new GraphFormatError("E_COLUMN_TYPE", "an unset value cannot start an inferred column", {
55
+ reason: "unset",
56
+ });
57
+ }
58
+ return dtype;
59
+ }
60
+ /**
61
+ * The position of a dtype in the widening order of design section 5.1, for the union rule of
62
+ * `addGraph()` (design section 6.6): the dtypes outside the inference order map to the narrowest
63
+ * inferred dtype that can hold every value of theirs.
64
+ * @param dtype - any dtype
65
+ * @returns the inferred dtype the column widens to when it must hold values of `dtype`
66
+ */
67
+ export function inferredEquivalent(dtype) {
68
+ switch (dtype) {
69
+ case "bool":
70
+ return "bool";
71
+ case "i32":
72
+ case "u8":
73
+ return "i32";
74
+ case "u32":
75
+ case "f32":
76
+ case "f64":
77
+ return "f64";
78
+ case "dict":
79
+ case "string":
80
+ return "string";
81
+ case "list":
82
+ case "json":
83
+ return "json";
84
+ default: {
85
+ const name = dtype;
86
+ throw new GraphFormatError("E_COLUMN_TYPE", `unknown dtype ${name}`, { dtype: name });
87
+ }
88
+ }
89
+ }
90
+ /**
91
+ * Check one list item against the child dtype of a list column at write time, so a bad item fails
92
+ * at the call that supplied it rather than at freeze.
93
+ * @param meta - the list column
94
+ * @param row - the row
95
+ * @param item - the item
96
+ */
97
+ function checkListItem(meta, row, item) {
98
+ const itemDtype = meta.itemDtype;
99
+ const components = meta.itemComponents ?? 1;
100
+ switch (itemDtype) {
101
+ case "f32":
102
+ case "f64":
103
+ case "i32":
104
+ case "u32":
105
+ case "u8": {
106
+ if (components === 1) {
107
+ if (typeof item !== "number" || !representableNumber(itemDtype, item)) {
108
+ throw cellError(meta, row, `list item is not a representable ${itemDtype}`, typeof item);
109
+ }
110
+ return;
111
+ }
112
+ if (!Array.isArray(item) || item.length !== components) {
113
+ throw cellError(meta, row, `list item is not ${components} numbers`, typeof item);
114
+ }
115
+ for (const k of item) {
116
+ if (typeof k !== "number" || !representableNumber(itemDtype, k)) {
117
+ throw cellError(meta, row, `list item component is not a representable ${itemDtype}`, typeof k);
118
+ }
119
+ }
120
+ return;
121
+ }
122
+ case "bool":
123
+ if (typeof item !== "boolean") {
124
+ throw cellError(meta, row, "list item is not a boolean", typeof item);
125
+ }
126
+ return;
127
+ case "dict":
128
+ case "string":
129
+ if (typeof item !== "string") {
130
+ throw cellError(meta, row, "list item is not a string", typeof item);
131
+ }
132
+ assertWellFormedString(item, { column: meta.name, row });
133
+ return;
134
+ case "json":
135
+ assertJsonValue(item, meta.name);
136
+ return;
137
+ default: {
138
+ const name = itemDtype;
139
+ throw new GraphFormatError("E_COLUMN_TYPE", `unknown dtype ${name}`, { dtype: name });
140
+ }
141
+ }
142
+ }
143
+ /**
144
+ * One growable column of the builder (design section 6.2).
145
+ *
146
+ * A DECLARED column stores values in the storage of its dtype (a growable typed array for the numeric
147
+ * dtypes and dict codes, a growable bitmap for bool, a JS array for string / list / json) plus an
148
+ * optional validity bitmap and, for dict columns, the interning dictionary; rows are materialised
149
+ * lazily up to `length` and unset rows physically hold the fill (design section 5.3). It never widens
150
+ * and rejects values it cannot hold with E_COLUMN_TYPE at the write.
151
+ *
152
+ * An INFERRED column (auto-declared by a string column name in `setNodeValue` / `addNodeRecord`, or
153
+ * a declared column widened by the union rule of `addGraph`) keeps the values exactly as written in a
154
+ * JS array and widens its dtype monotonically per design section 5.1 as wider values arrive; the
155
+ * values are coerced ONCE, at freeze, to the final dtype (bool -> 1 / 0 in a number column, number or
156
+ * boolean -> its canonical text in a string column), exactly as `fromRecords` would.
157
+ */
158
+ export class StagingColumn {
159
+ /**
160
+ * Create an empty column.
161
+ * @param meta - the resolved metadata
162
+ * @param inferred - whether the column stages raw values and may widen
163
+ * @param resizable - the staging buffer kind (tests pass false); undefined = engine default
164
+ * @param dictionary - an existing dictionary to share (compaction); a fresh one when omitted
165
+ */
166
+ constructor(meta, inferred, resizable, dictionary) {
167
+ /** Rows materialised so far. */
168
+ this.length = 0;
169
+ /** Declared numeric data (rows * components) or dict codes. */
170
+ this.typed = null;
171
+ /** Declared bool data. */
172
+ this.bits = null;
173
+ /** Declared string / list / json rows, or the raw values of an inferred column. */
174
+ this.values = null;
175
+ /** dict only: the interning dictionary. */
176
+ this.dictionary = null;
177
+ /** The validity bitmap; null for a non-nullable column. */
178
+ this.validity = null;
179
+ this.meta = meta;
180
+ this.resizable = resizable;
181
+ if (inferred) {
182
+ this.inferrer = new DtypeInferrer();
183
+ this.inferrer.widenTo(inferredEquivalent(meta.dtype));
184
+ }
185
+ else {
186
+ this.inferrer = null;
187
+ }
188
+ this.allocate(dictionary);
189
+ }
190
+ /**
191
+ * Whether the column stages raw values and may widen.
192
+ * @returns true for an inferred column
193
+ */
194
+ get inferred() {
195
+ return this.inferrer !== null;
196
+ }
197
+ /**
198
+ * The inferred dtype of an inferred column, or null.
199
+ * @returns the current inferred dtype
200
+ */
201
+ get inferredDtype() {
202
+ return this.inferrer === null ? null : this.inferrer.dtype;
203
+ }
204
+ /**
205
+ * Make at least `rows` rows exist, unset (when nullable) and holding the fill.
206
+ * @param rows - the row count to reach
207
+ */
208
+ ensureLength(rows) {
209
+ if (rows <= this.length) {
210
+ return;
211
+ }
212
+ const { meta } = this;
213
+ if (this.typed !== null) {
214
+ this.typed.resize(rows * meta.components, this.fillNumber());
215
+ }
216
+ else if (this.bits !== null) {
217
+ this.bits.resize(rows, meta.fill === true);
218
+ }
219
+ else if (this.values !== null) {
220
+ const fill = this.fillValue();
221
+ for (let row = this.length; row < rows; row++) {
222
+ this.values.push(fill);
223
+ }
224
+ }
225
+ if (this.validity !== null) {
226
+ this.validity.resize(rows, false);
227
+ }
228
+ this.length = rows;
229
+ }
230
+ /**
231
+ * Whether a row holds a value.
232
+ * @param row - the row
233
+ * @returns true when set (non-nullable columns: when materialised)
234
+ */
235
+ isSet(row) {
236
+ if (row >= this.length) {
237
+ return false;
238
+ }
239
+ return this.validity === null || this.validity.get(row);
240
+ }
241
+ /**
242
+ * Set one cell (design sections 5.1 and 6.6). `undefined` unsets the row, and so does `null`
243
+ * except on a declared json column (JSON null imports as unset, design section 5.3). An inferred
244
+ * column widens when the value is wider than its dtype; the widening is returned so the builder
245
+ * can report it.
246
+ * @param row - the row; rows below it are materialised
247
+ * @param value - the value
248
+ * @returns the widening that took place, or null
249
+ */
250
+ write(row, value) {
251
+ this.ensureLength(row + 1);
252
+ if (value === undefined || (value === null && (this.inferrer !== null || this.meta.dtype !== "json"))) {
253
+ this.unset(row);
254
+ return null;
255
+ }
256
+ let widened = null;
257
+ if (this.inferrer !== null) {
258
+ const before = this.meta.dtype;
259
+ if (this.inferrer.observeValue(value)) {
260
+ const next = this.inferrer.dtype;
261
+ this.widenTo(next);
262
+ widened = { from: before, to: next };
263
+ }
264
+ this.storeRaw(row, value);
265
+ }
266
+ else {
267
+ this.store(row, value);
268
+ }
269
+ if (this.validity !== null) {
270
+ this.validity.set(row, true);
271
+ }
272
+ return widened;
273
+ }
274
+ /**
275
+ * Validate a value exactly as `write` would, without writing anything: the same E_COLUMN_TYPE
276
+ * errors for a value the column cannot hold (a non-representable number, a lone surrogate, a
277
+ * non-JSON object, an unset value on a non-nullable column). The record methods of the builder
278
+ * validate every attribute before they apply anything (design section 11.1).
279
+ * @param row - the row the value is meant for (error details only)
280
+ * @param value - the value
281
+ */
282
+ checkValue(row, value) {
283
+ if (value === undefined || (value === null && (this.inferrer !== null || this.meta.dtype !== "json"))) {
284
+ if (this.validity === null) {
285
+ throw this.unsetError(row);
286
+ }
287
+ return;
288
+ }
289
+ if (this.inferrer !== null) {
290
+ inferValueDtype(value);
291
+ this.checkRaw(row, value);
292
+ return;
293
+ }
294
+ this.coerce(row, value);
295
+ }
296
+ /**
297
+ * Unset one cell: the validity bit is cleared and the fill is written back (design section 5.3).
298
+ * @param row - the row; E_COLUMN_TYPE on a non-nullable column
299
+ */
300
+ unset(row) {
301
+ this.ensureLength(row + 1);
302
+ if (this.validity === null) {
303
+ throw this.unsetError(row);
304
+ }
305
+ this.validity.set(row, false);
306
+ this.writeFill(row);
307
+ }
308
+ /**
309
+ * The E_COLUMN_TYPE error for unsetting a row of a non-nullable column.
310
+ * @param row - the row
311
+ * @returns the error
312
+ */
313
+ unsetError(row) {
314
+ return new GraphFormatError("E_COLUMN_TYPE", `row ${row} of non-nullable column "${this.meta.name}" cannot be unset`, { column: this.meta.name, row, field: "nullable" });
315
+ }
316
+ /**
317
+ * The JS value of one cell as the frozen column would hold it: a number (or an array of
318
+ * `components` numbers), a boolean, a string, a list or a json value; undefined for an unset or
319
+ * unmaterialised row. An inferred column's raw value is coerced to its current dtype.
320
+ * @param row - the row
321
+ * @returns the value
322
+ */
323
+ read(row) {
324
+ if (!this.isSet(row)) {
325
+ return undefined;
326
+ }
327
+ if (this.inferrer !== null) {
328
+ return coerceValue(this.values[row], this.inferrer.dtype);
329
+ }
330
+ const { meta } = this;
331
+ const { dtype, components } = meta;
332
+ switch (dtype) {
333
+ case "f32":
334
+ case "f64":
335
+ case "i32":
336
+ case "u32":
337
+ case "u8": {
338
+ const typed = this.typed;
339
+ if (components === 1) {
340
+ return typed.get(row);
341
+ }
342
+ const out = new Array(components);
343
+ for (let k = 0; k < components; k++) {
344
+ out[k] = typed.get(row * components + k);
345
+ }
346
+ return out;
347
+ }
348
+ case "bool":
349
+ return this.bits.get(row);
350
+ case "dict": {
351
+ const code = this.typed.get(row);
352
+ return this.dictionary.values[code];
353
+ }
354
+ case "string":
355
+ case "list":
356
+ case "json":
357
+ return this.values[row];
358
+ default: {
359
+ const name = dtype;
360
+ throw new GraphFormatError("E_COLUMN_TYPE", `unknown dtype ${name}`, { dtype: name });
361
+ }
362
+ }
363
+ }
364
+ /**
365
+ * Widen the column to a wider dtype of the design section 5.1 order. An inferred column only
366
+ * changes its dtype (its raw values are coerced at freeze); a declared column becomes inferred:
367
+ * its current values are read out and kept as raw values from then on.
368
+ * @param next - the dtype to widen to
369
+ */
370
+ widenTo(next) {
371
+ const { meta } = this;
372
+ const nextMeta = resolveColumnMeta(meta.name, meta.domain, {
373
+ dtype: next,
374
+ nullable: true,
375
+ role: meta.role ?? undefined,
376
+ extra: meta.extra,
377
+ });
378
+ if (this.inferrer !== null) {
379
+ this.inferrer.widenTo(next);
380
+ this.meta = nextMeta;
381
+ return;
382
+ }
383
+ const rows = this.length;
384
+ const raw = new Array(rows);
385
+ const validity = new GrowableBitmap({ capacity: rows, resizable: this.resizable });
386
+ validity.resize(rows, false);
387
+ for (let row = 0; row < rows; row++) {
388
+ if (this.isSet(row)) {
389
+ raw[row] = this.read(row);
390
+ validity.set(row, true);
391
+ }
392
+ }
393
+ this.meta = nextMeta;
394
+ this.inferrer = new DtypeInferrer();
395
+ this.inferrer.widenTo(next);
396
+ this.typed = null;
397
+ this.bits = null;
398
+ this.dictionary = null;
399
+ this.values = raw;
400
+ this.validity = validity;
401
+ }
402
+ /**
403
+ * A new column of the same shape holding the rows `indexMap` selects (`out[i] = this[indexMap[i]]`),
404
+ * or every row in order when `indexMap` is null, with `refersTo` values rewritten through
405
+ * `valueRemap` when given: an in-range value maps to its new index and a dangling reference
406
+ * becomes INVALID_INDEX with the row unset (for a list, dangling items are dropped and a row whose
407
+ * every item dangled becomes unset and empty). The dictionary of a dict column is shared.
408
+ * @param indexMap - new row -> old row, or null to keep every row
409
+ * @param valueRemap - the remap of the space the values reference, or null
410
+ * @returns the gathered column
411
+ */
412
+ gather(indexMap, valueRemap) {
413
+ const rows = indexMap === null ? this.length : indexMap.length;
414
+ const out = new StagingColumn(this.meta, this.inferred, this.resizable, this.dictionary ?? undefined);
415
+ out.ensureLength(rows);
416
+ const { components } = this.meta;
417
+ const rewrite = valueRemap !== null && this.meta.refersTo !== null;
418
+ for (let i = 0; i < rows; i++) {
419
+ const old = indexMap === null ? i : indexMap[i];
420
+ if (!this.isSet(old)) {
421
+ continue;
422
+ }
423
+ if (out.typed !== null && this.typed !== null) {
424
+ if (rewrite) {
425
+ const mapped = remapIndex(this.typed.get(old), valueRemap);
426
+ if (mapped === INVALID_INDEX) {
427
+ // dangling reference: INVALID_INDEX (the fill of a refersTo column) with the row unset
428
+ out.unsetDangling(i);
429
+ continue;
430
+ }
431
+ out.typed.set(i, mapped);
432
+ }
433
+ else {
434
+ for (let k = 0; k < components; k++) {
435
+ out.typed.set(i * components + k, this.typed.get(old * components + k));
436
+ }
437
+ }
438
+ }
439
+ else if (out.bits !== null && this.bits !== null) {
440
+ out.bits.set(i, this.bits.get(old));
441
+ }
442
+ else if (out.values !== null && this.values !== null) {
443
+ let value = this.values[old];
444
+ if (rewrite) {
445
+ const items = value;
446
+ const kept = [];
447
+ for (const item of items) {
448
+ const mapped = remapIndex(item, valueRemap);
449
+ if (mapped !== INVALID_INDEX) {
450
+ kept.push(mapped);
451
+ }
452
+ }
453
+ if (kept.length === 0 && items.length > 0) {
454
+ out.unsetDangling(i);
455
+ continue;
456
+ }
457
+ value = kept;
458
+ }
459
+ out.values[i] = value;
460
+ }
461
+ if (out.validity !== null) {
462
+ out.validity.set(i, true);
463
+ }
464
+ }
465
+ return out;
466
+ }
467
+ /**
468
+ * Leave row `i` of a gathered column unset because its reference dangled (design section 5.11).
469
+ * A non-nullable column gains a validity bitmap and becomes nullable (invariant I12 forbids a set
470
+ * row holding INVALID_INDEX; `remapColumn` flips `nullable` the same way): every earlier row is
471
+ * marked set except a scalar reference row still holding the INVALID_INDEX fill.
472
+ * @param i - the row being gathered; rows below it are already gathered
473
+ */
474
+ unsetDangling(i) {
475
+ if (this.validity !== null) {
476
+ return;
477
+ }
478
+ const { meta } = this;
479
+ this.meta = resolveColumnMeta(meta.name, meta.domain, { ...metaToDecl(meta), nullable: true });
480
+ const validity = new GrowableBitmap({ capacity: this.length, resizable: this.resizable });
481
+ validity.resize(this.length, false);
482
+ const { typed } = this;
483
+ for (let row = 0; row < i; row++) {
484
+ if (typed === null || typed.get(row) !== INVALID_INDEX) {
485
+ validity.set(row, true);
486
+ }
487
+ }
488
+ this.validity = validity;
489
+ }
490
+ /**
491
+ * Freeze the column into `rows` rows (design section 6.3 step 10): typed data is copied out of
492
+ * staging into exact-length buffers (invariant I18), the validity bitmap is copied (and dropped when
493
+ * every row is set), a dict dictionary is copied so the snapshot's column never changes (I17), and
494
+ * string / list / json rows and the raw values of an inferred column go through the column factory,
495
+ * which coerces them to the final dtype.
496
+ * @param rows - the row count of the table
497
+ * @returns the frozen column
498
+ */
499
+ toColumn(rows) {
500
+ this.ensureLength(rows);
501
+ const { meta } = this;
502
+ const { dtype, components } = meta;
503
+ if (this.inferrer !== null) {
504
+ const source = this.values;
505
+ const entries = new Array(rows);
506
+ for (let row = 0; row < rows; row++) {
507
+ entries[row] = this.isSet(row) ? source[row] : undefined;
508
+ }
509
+ return columnOfValues(meta, entries);
510
+ }
511
+ let validity = null;
512
+ if (this.validity !== null && this.validity.count() !== rows) {
513
+ validity = this.validity.trim();
514
+ }
515
+ const parts = {
516
+ meta,
517
+ length: rows,
518
+ data: null,
519
+ validity,
520
+ nullCount: validity === null ? 0 : rows - this.validity.count(),
521
+ dictionary: null,
522
+ offsets: null,
523
+ utf8: null,
524
+ strings: null,
525
+ child: null,
526
+ values: null,
527
+ };
528
+ switch (dtype) {
529
+ case "f32":
530
+ case "f64":
531
+ case "i32":
532
+ case "u32":
533
+ case "u8": {
534
+ const data = allocNumeric(dtype, rows * components);
535
+ data.set(this.typed.view().subarray(0, rows * components));
536
+ parts.data = data;
537
+ if (meta.refersTo !== null && this.validity === null) {
538
+ unsetFillReferences(parts, data, rows);
539
+ }
540
+ return createColumn(parts);
541
+ }
542
+ case "bool":
543
+ parts.data = this.bits.trim();
544
+ return createColumn(parts);
545
+ case "dict": {
546
+ const codes = new Uint32Array(rows);
547
+ codes.set(this.typed.view().subarray(0, rows));
548
+ parts.data = codes;
549
+ parts.dictionary = [...this.dictionary.values];
550
+ return createColumn(parts);
551
+ }
552
+ case "string":
553
+ case "list":
554
+ case "json": {
555
+ const source = this.values;
556
+ const entries = new Array(rows);
557
+ for (let row = 0; row < rows; row++) {
558
+ const value = this.isSet(row) ? source[row] : undefined;
559
+ entries[row] = value === undefined ? this.unsetEntry() : value;
560
+ }
561
+ return columnOfValues(meta, entries);
562
+ }
563
+ default: {
564
+ const name = dtype;
565
+ throw new GraphFormatError("E_COLUMN_TYPE", `unknown dtype ${name}`, { dtype: name });
566
+ }
567
+ }
568
+ }
569
+ /**
570
+ * Bytes of typed staging held by the column (JS arrays are not counted).
571
+ * @returns the byte count
572
+ */
573
+ byteLength() {
574
+ let bytes = 0;
575
+ if (this.typed !== null) {
576
+ bytes += this.typed.array.byteLength;
577
+ }
578
+ if (this.bits !== null) {
579
+ bytes += bitmapWordCount(this.bits.length) * 4;
580
+ }
581
+ if (this.validity !== null) {
582
+ bytes += bitmapWordCount(this.validity.length) * 4;
583
+ }
584
+ return bytes;
585
+ }
586
+ /**
587
+ * Allocate the storage of the current dtype (raw values for an inferred column).
588
+ * @param dictionary - a dictionary to share, or undefined for a fresh seeded one
589
+ */
590
+ allocate(dictionary) {
591
+ const { meta } = this;
592
+ const { dtype } = meta;
593
+ const options = { resizable: this.resizable };
594
+ if (this.inferrer !== null) {
595
+ this.values = [];
596
+ this.validity = new GrowableBitmap(options);
597
+ return;
598
+ }
599
+ switch (dtype) {
600
+ case "f32":
601
+ this.typed = new GrowableTypedArray(Float32Array, options);
602
+ break;
603
+ case "f64":
604
+ this.typed = new GrowableTypedArray(Float64Array, options);
605
+ break;
606
+ case "i32":
607
+ this.typed = new GrowableTypedArray(Int32Array, options);
608
+ break;
609
+ case "u32":
610
+ this.typed = new GrowableTypedArray(Uint32Array, options);
611
+ break;
612
+ case "u8":
613
+ this.typed = new GrowableTypedArray(Uint8Array, options);
614
+ break;
615
+ case "bool":
616
+ this.bits = new GrowableBitmap(options);
617
+ break;
618
+ case "dict": {
619
+ this.typed = new GrowableTypedArray(Uint32Array, options);
620
+ this.dictionary = dictionary ?? seedDictionary(meta);
621
+ break;
622
+ }
623
+ case "string":
624
+ case "list":
625
+ case "json":
626
+ this.values = [];
627
+ break;
628
+ default: {
629
+ const name = dtype;
630
+ throw new GraphFormatError("E_COLUMN_TYPE", `unknown dtype ${name}`, { dtype: name });
631
+ }
632
+ }
633
+ this.validity = meta.nullable ? new GrowableBitmap(options) : null;
634
+ }
635
+ /**
636
+ * The number written into unset numeric rows (the dict fill code for dict columns).
637
+ * @returns the fill
638
+ */
639
+ fillNumber() {
640
+ const { meta } = this;
641
+ if (meta.dtype === "dict") {
642
+ const dictionary = this.dictionary;
643
+ const text = typeof meta.fill === "string" ? meta.fill : "";
644
+ if (this.validity === null) {
645
+ // a set row holding the fill needs a member's code: the nominal "" is interned on demand
646
+ return dictionary.intern(text);
647
+ }
648
+ const code = dictionary.codeOf(text);
649
+ return code === INVALID_INDEX ? 0 : code;
650
+ }
651
+ return typeof meta.fill === "number" ? meta.fill : 0;
652
+ }
653
+ /**
654
+ * The JS value stored in unset rows of a JS-array column (undefined for an inferred column).
655
+ * @returns the fill
656
+ */
657
+ fillValue() {
658
+ if (this.inferrer !== null) {
659
+ return undefined;
660
+ }
661
+ switch (this.meta.dtype) {
662
+ case "string":
663
+ return typeof this.meta.fill === "string" ? this.meta.fill : "";
664
+ case "list":
665
+ return EMPTY_LIST;
666
+ default:
667
+ return undefined;
668
+ }
669
+ }
670
+ /**
671
+ * The entry handed to the column factory for an unset row of a declared JS-array column:
672
+ * undefined for a nullable column, the fill for a non-nullable one (json: null, the one JSON value
673
+ * that means "nothing").
674
+ * @returns the entry
675
+ */
676
+ unsetEntry() {
677
+ if (this.meta.nullable) {
678
+ return undefined;
679
+ }
680
+ return this.meta.dtype === "json" ? null : this.fillValue();
681
+ }
682
+ writeFill(row) {
683
+ const { components } = this.meta;
684
+ if (this.typed !== null) {
685
+ const fill = this.fillNumber();
686
+ for (let k = 0; k < components; k++) {
687
+ this.typed.set(row * components + k, fill);
688
+ }
689
+ }
690
+ else if (this.bits !== null) {
691
+ this.bits.set(row, this.meta.fill === true);
692
+ }
693
+ else if (this.values !== null) {
694
+ this.values[row] = this.fillValue();
695
+ }
696
+ }
697
+ /**
698
+ * Keep a raw value on an inferred column after checking it is storable at all (a json value must
699
+ * be JSON; a string must be well-formed).
700
+ * @param row - the row
701
+ * @param value - the value as written
702
+ */
703
+ storeRaw(row, value) {
704
+ this.checkRaw(row, value);
705
+ this.values[row] = typeof value === "string" ? detachString(value) : value;
706
+ }
707
+ /**
708
+ * The checks of storeRaw: a string must be well-formed, an object must be JSON.
709
+ * @param row - the row
710
+ * @param value - the value as written
711
+ */
712
+ checkRaw(row, value) {
713
+ const { meta } = this;
714
+ if (typeof value === "string") {
715
+ assertWellFormedString(value, { column: meta.name, row });
716
+ }
717
+ else if (typeof value === "object") {
718
+ assertJsonValue(value, `${meta.name}[${row}]`);
719
+ }
720
+ }
721
+ /**
722
+ * Store a value on a declared column: validate and normalise it (E_COLUMN_TYPE when the column
723
+ * cannot hold it), then write the normalised form.
724
+ * @param row - the row
725
+ * @param value - the value
726
+ */
727
+ store(row, value) {
728
+ this.put(row, this.coerce(row, value));
729
+ }
730
+ /**
731
+ * Validate a value against a declared column's dtype and return the form `put` writes: a number
732
+ * or an array of `components` numbers, a boolean, a string, a copied list, or a JSON value.
733
+ * @param row - the row (error details only)
734
+ * @param value - the value
735
+ * @returns the normalised value
736
+ */
737
+ coerce(row, value) {
738
+ const { meta } = this;
739
+ const { dtype, components } = meta;
740
+ switch (dtype) {
741
+ case "f32":
742
+ case "f64":
743
+ case "i32":
744
+ case "u32":
745
+ case "u8": {
746
+ const scalar = typeof value === "boolean" ? Number(value) : value;
747
+ if (typeof scalar === "number") {
748
+ if (!representableNumber(dtype, scalar)) {
749
+ throw cellError(meta, row, `${scalar} is not representable`, scalar);
750
+ }
751
+ return scalar;
752
+ }
753
+ if (components === 1 || !isArrayLikeNumbers(scalar, components)) {
754
+ throw cellError(meta, row, `not ${components} number(s)`, typeof scalar);
755
+ }
756
+ for (let k = 0; k < components; k++) {
757
+ if (!representableNumber(dtype, scalar[k])) {
758
+ throw cellError(meta, row, `${scalar[k]} is not representable`, scalar[k]);
759
+ }
760
+ }
761
+ return scalar;
762
+ }
763
+ case "bool":
764
+ return coerceValue(value, "bool") === true;
765
+ case "dict":
766
+ case "string": {
767
+ const text = coerceValue(value, "string");
768
+ if (typeof text !== "string") {
769
+ throw cellError(meta, row, "not a string", typeof value);
770
+ }
771
+ assertWellFormedString(text, { column: meta.name, row });
772
+ return detachString(text);
773
+ }
774
+ case "list": {
775
+ if (!Array.isArray(value)) {
776
+ throw cellError(meta, row, "not an array", typeof value);
777
+ }
778
+ for (const item of value) {
779
+ checkListItem(meta, row, item);
780
+ }
781
+ return value.map((item) => (typeof item === "string" ? detachString(item) : item));
782
+ }
783
+ case "json":
784
+ assertJsonValue(value, `${meta.name}[${row}]`);
785
+ return value;
786
+ default: {
787
+ const name = dtype;
788
+ throw new GraphFormatError("E_COLUMN_TYPE", `unknown dtype ${name}`, { dtype: name });
789
+ }
790
+ }
791
+ }
792
+ /**
793
+ * Write a value `coerce` returned.
794
+ * @param row - the row
795
+ * @param value - the normalised value
796
+ */
797
+ put(row, value) {
798
+ const { dtype, components } = this.meta;
799
+ switch (dtype) {
800
+ case "f32":
801
+ case "f64":
802
+ case "i32":
803
+ case "u32":
804
+ case "u8": {
805
+ const typed = this.typed;
806
+ if (typeof value === "number") {
807
+ if (components === 1) {
808
+ typed.set(row, value);
809
+ }
810
+ else {
811
+ for (let k = 0; k < components; k++) {
812
+ typed.set(row * components + k, value);
813
+ }
814
+ }
815
+ return;
816
+ }
817
+ const vector = value;
818
+ for (let k = 0; k < components; k++) {
819
+ typed.set(row * components + k, vector[k]);
820
+ }
821
+ return;
822
+ }
823
+ case "bool":
824
+ this.bits.set(row, value === true);
825
+ return;
826
+ case "dict":
827
+ this.typed.set(row, this.dictionary.intern(value));
828
+ return;
829
+ case "string":
830
+ case "list":
831
+ case "json":
832
+ this.values[row] = value;
833
+ return;
834
+ default: {
835
+ const name = dtype;
836
+ throw new GraphFormatError("E_COLUMN_TYPE", `unknown dtype ${name}`, { dtype: name });
837
+ }
838
+ }
839
+ }
840
+ }
841
+ /**
842
+ * Map an index-valued cell through a remap: in range and alive -> the new index; otherwise INVALID_INDEX.
843
+ * @param value - the old index
844
+ * @param remap - old -> new or INVALID_INDEX
845
+ * @returns the new index or INVALID_INDEX
846
+ */
847
+ function remapIndex(value, remap) {
848
+ return value < remap.length ? remap[value] : INVALID_INDEX;
849
+ }
850
+ /**
851
+ * The frozen form of a non-nullable scalar `refersTo` column whose rows were never all written: the
852
+ * unwritten rows still hold the INVALID_INDEX fill, and a SET row holding INVALID_INDEX violates
853
+ * invariant I12, so the frozen column becomes nullable with exactly those rows unset (the rule of
854
+ * `gather` for a dangling reference and of `remapColumn`; design sections 5.11 and 6.3, the builder
855
+ * establishes I1-I13 by construction). The builder's own declaration is left alone. A column whose
856
+ * every row holds an index is returned as declared.
857
+ * @param parts - the parts being assembled; `meta`, `validity` and `nullCount` are replaced when needed
858
+ * @param data - the frozen u32 data (stride 1: refersTo requires a scalar u32)
859
+ * @param rows - the row count
860
+ */
861
+ function unsetFillReferences(parts, data, rows) {
862
+ let validity = null;
863
+ for (let row = 0; row < rows; row++) {
864
+ if (data[row] === INVALID_INDEX) {
865
+ validity ?? (validity = makeBitmap(rows, true));
866
+ bitmapClear(validity, row);
867
+ parts.nullCount++;
868
+ }
869
+ }
870
+ if (validity !== null) {
871
+ const { meta } = parts;
872
+ parts.meta = resolveColumnMeta(meta.name, meta.domain, { ...metaToDecl(meta), nullable: true });
873
+ parts.validity = validity;
874
+ }
875
+ }
876
+ /**
877
+ * Create a staging column from a declaration patch.
878
+ * @param name - the column name
879
+ * @param domain - the table
880
+ * @param decl - the declaration; dtype required
881
+ * @param inferred - whether the column may widen
882
+ * @param resizable - the staging buffer kind
883
+ * @returns the column
884
+ */
885
+ export function createStagingColumn(name, domain, decl, inferred, resizable) {
886
+ return new StagingColumn(resolveColumnMeta(name, domain, decl), inferred, resizable);
887
+ }
888
+ /**
889
+ * The staging of one builder (design section 6.2). Plain growable storage plus the push and link
890
+ * primitives; every rule (id validation, policies, error codes) lives in the builder.
891
+ */
892
+ export class Staging {
893
+ /**
894
+ * Create empty staging.
895
+ * @param options - precision, capacity hints and buffer kind
896
+ */
897
+ constructor(options) {
898
+ /** The ids in index order, or null while every node is anonymous (id === index). */
899
+ this.ids = null;
900
+ /** id -> index, shared by reference with frozen snapshots; null while every node is anonymous. */
901
+ this.idToIndex = null;
902
+ /** Per-edge weights (f32 or f64 per weightDtype), or null while unweighted. */
903
+ this.weight = null;
904
+ /** Bit e set: edge e's weight was supplied explicitly; null while every edge agrees. */
905
+ this.weightSet = null;
906
+ /** Whether edges so far supplied, omitted, or disagreed about their weight. */
907
+ this.weightMode = "none";
908
+ /** Live node count. */
909
+ this.liveNodeCount = 0;
910
+ /** Live edge count. */
911
+ this.liveEdgeCount = 0;
912
+ /** Live self-loop count. */
913
+ this.selfLoopCount = 0;
914
+ /** Node columns in handle order. */
915
+ this.nodeColumns = [];
916
+ /** Edge columns in handle order. */
917
+ this.edgeColumns = [];
918
+ /** Extension tables in handle order. */
919
+ this.extensions = [];
920
+ this.options = options;
921
+ const { resizable } = options;
922
+ const nodes = options.expectedNodes ?? 0;
923
+ const edges = options.expectedEdges ?? 0;
924
+ this.nodeAlive = new GrowableBitmap({ capacity: nodes, resizable });
925
+ this.firstOut = new GrowableTypedArray(Uint32Array, { capacity: nodes, resizable });
926
+ this.firstIn = new GrowableTypedArray(Uint32Array, { capacity: nodes, resizable });
927
+ this.src = new GrowableTypedArray(Uint32Array, { capacity: edges, resizable });
928
+ this.dst = new GrowableTypedArray(Uint32Array, { capacity: edges, resizable });
929
+ this.edgeAlive = new GrowableBitmap({ capacity: edges, resizable });
930
+ this.nextOut = new GrowableTypedArray(Uint32Array, { capacity: edges, resizable });
931
+ this.nextIn = new GrowableTypedArray(Uint32Array, { capacity: edges, resizable });
932
+ if (options.weighted) {
933
+ this.weight = this.allocateWeights(edges);
934
+ }
935
+ }
936
+ /**
937
+ * The next node index to be assigned.
938
+ * @returns the node bound
939
+ */
940
+ get nodeBound() {
941
+ return this.nodeAlive.length;
942
+ }
943
+ /**
944
+ * The next edge index to be assigned.
945
+ * @returns the edge bound
946
+ */
947
+ get edgeBound() {
948
+ return this.edgeAlive.length;
949
+ }
950
+ /**
951
+ * Whether tombstoned nodes or edges exist.
952
+ * @returns true when compaction is needed
953
+ */
954
+ get hasTombstones() {
955
+ return this.liveNodeCount < this.nodeBound || this.liveEdgeCount < this.edgeBound;
956
+ }
957
+ /**
958
+ * Grow capacity ahead of a bulk push.
959
+ * @param nodes - the node count to fit
960
+ * @param edges - the edge count to fit
961
+ */
962
+ reserve(nodes, edges) {
963
+ if (nodes > 0) {
964
+ this.firstOut.ensureCapacity(nodes);
965
+ this.firstIn.ensureCapacity(nodes);
966
+ }
967
+ if (edges > 0) {
968
+ this.src.ensureCapacity(edges);
969
+ this.dst.ensureCapacity(edges);
970
+ this.nextOut.ensureCapacity(edges);
971
+ this.nextIn.ensureCapacity(edges);
972
+ if (this.weight !== null) {
973
+ this.weight.ensureCapacity(edges);
974
+ }
975
+ }
976
+ }
977
+ /**
978
+ * Materialise `ids` and `idToIndex` from the anonymous prefix (every node so far has id === index).
979
+ */
980
+ materialiseIds() {
981
+ if (this.ids !== null && this.idToIndex !== null) {
982
+ return;
983
+ }
984
+ const bound = this.nodeBound;
985
+ const ids = new Array(bound);
986
+ const map = new Map();
987
+ for (let i = 0; i < bound; i++) {
988
+ ids[i] = i;
989
+ map.set(i, i);
990
+ }
991
+ this.ids = ids;
992
+ this.idToIndex = map;
993
+ }
994
+ /**
995
+ * Append a live node; the id is recorded only when the id structures exist.
996
+ * @param id - the id, or null for an anonymous node (id === index)
997
+ * @returns the new index
998
+ */
999
+ pushNode(id) {
1000
+ const index = this.nodeAlive.push(true);
1001
+ this.firstOut.push(INVALID_INDEX);
1002
+ this.firstIn.push(INVALID_INDEX);
1003
+ if (this.ids !== null && this.idToIndex !== null) {
1004
+ const stored = id ?? index;
1005
+ this.ids.push(stored);
1006
+ this.idToIndex.set(stored, index);
1007
+ }
1008
+ this.liveNodeCount++;
1009
+ return index;
1010
+ }
1011
+ /**
1012
+ * The weight array, allocated on first use and back-filled with 1 for existing edges.
1013
+ * @returns the growable weight array
1014
+ */
1015
+ ensureWeights() {
1016
+ if (this.weight === null) {
1017
+ this.weight = this.allocateWeights(this.edgeBound);
1018
+ this.weight.resize(this.edgeBound, 1);
1019
+ }
1020
+ return this.weight;
1021
+ }
1022
+ /**
1023
+ * Record whether an edge's weight was explicit (design section 3.7): the `weightSet` bitmap is
1024
+ * allocated on the first edge that disagrees with every earlier one.
1025
+ * @param edge - the edge index (=== edgeBound - 1 when appending)
1026
+ * @param explicit - whether the weight was supplied
1027
+ */
1028
+ trackWeight(edge, explicit) {
1029
+ if (this.weightSet !== null) {
1030
+ if (edge >= this.weightSet.length) {
1031
+ this.weightSet.resize(edge + 1, false);
1032
+ }
1033
+ this.weightSet.set(edge, explicit);
1034
+ return;
1035
+ }
1036
+ switch (this.weightMode) {
1037
+ case "none":
1038
+ this.weightMode = explicit ? "explicit" : "omitted";
1039
+ return;
1040
+ case "explicit":
1041
+ if (!explicit) {
1042
+ this.allocateWeightSet(true, edge);
1043
+ }
1044
+ return;
1045
+ case "omitted":
1046
+ if (explicit) {
1047
+ this.allocateWeightSet(false, edge);
1048
+ }
1049
+ return;
1050
+ case "mixed":
1051
+ return;
1052
+ default: {
1053
+ const mode = this.weightMode;
1054
+ throw new GraphFormatError("E_UNSUPPORTED", `unknown weight mode ${mode}`, { mode });
1055
+ }
1056
+ }
1057
+ }
1058
+ /**
1059
+ * Whether an edge's weight was supplied explicitly (design section 3.7).
1060
+ * @param e - the edge index
1061
+ * @returns true when explicit
1062
+ */
1063
+ weightExplicit(e) {
1064
+ if (this.weightSet === null) {
1065
+ return this.weightMode === "explicit";
1066
+ }
1067
+ return e < this.weightSet.length && this.weightSet.get(e);
1068
+ }
1069
+ /**
1070
+ * Append a live edge and link it into both incidence lists. The caller has validated the
1071
+ * endpoints and the weight.
1072
+ * @param u - source index
1073
+ * @param v - target index
1074
+ * @param weight - the weight, or undefined when omitted (stored as 1 when the array exists)
1075
+ * @returns the new edge index
1076
+ */
1077
+ pushEdge(u, v, weight) {
1078
+ const e = this.src.push(u);
1079
+ this.dst.push(v);
1080
+ if (weight !== undefined) {
1081
+ this.ensureWeights().push(weight);
1082
+ }
1083
+ else if (this.weight !== null) {
1084
+ this.weight.push(1);
1085
+ }
1086
+ this.trackWeight(e, weight !== undefined);
1087
+ this.edgeAlive.push(true);
1088
+ this.nextOut.push(this.firstOut.get(u));
1089
+ this.firstOut.set(u, e);
1090
+ this.nextIn.push(this.firstIn.get(v));
1091
+ this.firstIn.set(v, e);
1092
+ this.liveEdgeCount++;
1093
+ if (u === v) {
1094
+ this.selfLoopCount++;
1095
+ }
1096
+ return e;
1097
+ }
1098
+ /**
1099
+ * Append `src.length` live edges at once (the bulk `addEdges` path): the same storage, weight
1100
+ * tracking and incidence-list linking as one pushEdge per edge in order, done as typed-array
1101
+ * passes. The caller has validated the endpoints and the weights.
1102
+ * @param src - source indices
1103
+ * @param dst - target indices, as many as `src`
1104
+ * @param weights - the explicit weight of every edge, or null when every weight is omitted
1105
+ * @returns the first new edge index
1106
+ */
1107
+ pushEdges(src, dst, weights) {
1108
+ const count = src.length;
1109
+ const first = this.edgeBound;
1110
+ const end = first + count;
1111
+ if (count === 0) {
1112
+ return first;
1113
+ }
1114
+ this.src.pushAll(src);
1115
+ this.dst.pushAll(dst);
1116
+ if (weights !== null) {
1117
+ this.ensureWeights().pushAll(weights);
1118
+ }
1119
+ else if (this.weight !== null) {
1120
+ this.weight.resize(end, 1);
1121
+ }
1122
+ this.trackWeights(first, count, weights !== null);
1123
+ this.edgeAlive.resize(end, true);
1124
+ this.nextOut.resize(end);
1125
+ this.nextIn.resize(end);
1126
+ this.selfLoopCount += linkEdgeRange(this.src.array, this.dst.array, first, end, this.firstOut.array, this.firstIn.array, this.nextOut.array, this.nextIn.array);
1127
+ this.liveEdgeCount += count;
1128
+ return first;
1129
+ }
1130
+ /**
1131
+ * trackWeight for a batch of `count` edges from `first` that all supplied or all omitted their
1132
+ * weight: the same mode transitions and bitmap contents as `count` calls in order.
1133
+ * @param first - the first edge of the batch
1134
+ * @param count - the batch size, at least 1
1135
+ * @param explicit - whether the batch supplied its weights
1136
+ */
1137
+ trackWeights(first, count, explicit) {
1138
+ const end = first + count;
1139
+ let bitmap = this.weightSet;
1140
+ if (bitmap === null) {
1141
+ switch (this.weightMode) {
1142
+ case "none":
1143
+ this.weightMode = explicit ? "explicit" : "omitted";
1144
+ return;
1145
+ case "explicit":
1146
+ if (explicit) {
1147
+ return;
1148
+ }
1149
+ bitmap = this.allocateWeightSet(true, first);
1150
+ break;
1151
+ case "omitted":
1152
+ if (!explicit) {
1153
+ return;
1154
+ }
1155
+ bitmap = this.allocateWeightSet(false, first);
1156
+ break;
1157
+ case "mixed":
1158
+ return;
1159
+ default: {
1160
+ const mode = this.weightMode;
1161
+ throw new GraphFormatError("E_UNSUPPORTED", `unknown weight mode ${mode}`, { mode });
1162
+ }
1163
+ }
1164
+ }
1165
+ if (bitmap.length < first) {
1166
+ bitmap.resize(first, false);
1167
+ }
1168
+ bitmap.resize(end, explicit);
1169
+ }
1170
+ /**
1171
+ * Tombstone a live edge (O(1)).
1172
+ * @param e - a live edge index
1173
+ */
1174
+ killEdge(e) {
1175
+ this.edgeAlive.set(e, false);
1176
+ this.liveEdgeCount--;
1177
+ if (this.src.get(e) === this.dst.get(e)) {
1178
+ this.selfLoopCount--;
1179
+ }
1180
+ }
1181
+ /**
1182
+ * Live edges leaving a node, walked from the out-list (O(degree)).
1183
+ * @param u - the node index
1184
+ * @returns the live edge indices in ascending order
1185
+ */
1186
+ outEdges(u) {
1187
+ const out = [];
1188
+ for (let e = this.firstOut.get(u); e !== INVALID_INDEX; e = this.nextOut.get(e)) {
1189
+ if (this.edgeAlive.get(e)) {
1190
+ out.push(e);
1191
+ }
1192
+ }
1193
+ return Uint32Array.from(out).sort();
1194
+ }
1195
+ /**
1196
+ * Live edges entering a node, walked from the in-list (O(degree)).
1197
+ * @param v - the node index
1198
+ * @returns the live edge indices in ascending order
1199
+ */
1200
+ inEdges(v) {
1201
+ const out = [];
1202
+ for (let e = this.firstIn.get(v); e !== INVALID_INDEX; e = this.nextIn.get(e)) {
1203
+ if (this.edgeAlive.get(e)) {
1204
+ out.push(e);
1205
+ }
1206
+ }
1207
+ return Uint32Array.from(out).sort();
1208
+ }
1209
+ /**
1210
+ * Live edges incident to a node in either orientation (the undirected outEdgesOf / inEdgesOf,
1211
+ * design section 6.6 and invariant I7): both lists walked, a self-loop listed once (O(degree)).
1212
+ * @param u - the node index
1213
+ * @returns the live edge indices in ascending order
1214
+ */
1215
+ incidentEdges(u) {
1216
+ const out = [];
1217
+ for (let e = this.firstOut.get(u); e !== INVALID_INDEX; e = this.nextOut.get(e)) {
1218
+ if (this.edgeAlive.get(e)) {
1219
+ out.push(e);
1220
+ }
1221
+ }
1222
+ for (let e = this.firstIn.get(u); e !== INVALID_INDEX; e = this.nextIn.get(e)) {
1223
+ if (this.edgeAlive.get(e) && this.src.get(e) !== u) {
1224
+ out.push(e);
1225
+ }
1226
+ }
1227
+ return Uint32Array.from(out).sort();
1228
+ }
1229
+ /**
1230
+ * Bytes of typed staging held (capacity, not length), for `byteLength()`.
1231
+ * @returns the byte count
1232
+ */
1233
+ byteLength() {
1234
+ let bytes = this.firstOut.array.byteLength +
1235
+ this.firstIn.array.byteLength +
1236
+ this.src.array.byteLength +
1237
+ this.dst.array.byteLength +
1238
+ this.nextOut.array.byteLength +
1239
+ this.nextIn.array.byteLength +
1240
+ bitmapWordCount(this.nodeAlive.length) * 4 +
1241
+ bitmapWordCount(this.edgeAlive.length) * 4;
1242
+ if (this.weight !== null) {
1243
+ bytes += this.weight.array.byteLength;
1244
+ }
1245
+ if (this.weightSet !== null) {
1246
+ bytes += bitmapWordCount(this.weightSet.length) * 4;
1247
+ }
1248
+ for (const column of this.nodeColumns) {
1249
+ bytes += column.byteLength();
1250
+ }
1251
+ for (const column of this.edgeColumns) {
1252
+ bytes += column.byteLength();
1253
+ }
1254
+ for (const table of this.extensions) {
1255
+ for (const column of table.columns) {
1256
+ bytes += column.byteLength();
1257
+ }
1258
+ }
1259
+ return bytes;
1260
+ }
1261
+ allocateWeights(capacity) {
1262
+ const { resizable } = this.options;
1263
+ return this.options.weightDtype === "f64"
1264
+ ? new GrowableTypedArray(Float64Array, { capacity, resizable })
1265
+ : new GrowableTypedArray(Float32Array, { capacity, resizable });
1266
+ }
1267
+ /**
1268
+ * Allocate the weightSet bitmap over `edge + 1` bits: every earlier edge gets `earlier`, `edge`
1269
+ * itself the opposite.
1270
+ * @param earlier - the value of every edge before `edge`
1271
+ * @param edge - the first disagreeing edge
1272
+ * @returns the new bitmap
1273
+ */
1274
+ allocateWeightSet(earlier, edge) {
1275
+ const bitmap = new GrowableBitmap({ capacity: edge + 1, resizable: this.options.resizable });
1276
+ bitmap.resize(edge, earlier);
1277
+ bitmap.push(!earlier);
1278
+ this.weightSet = bitmap;
1279
+ this.weightMode = "mixed";
1280
+ return bitmap;
1281
+ }
1282
+ }
1283
+ /**
1284
+ * The remap that drops every index whose `keep(i)` is false, assigning new indices in index order
1285
+ * (invariant I14).
1286
+ * @param bound - the old index space size
1287
+ * @param keep - whether an old index survives
1288
+ * @returns the remap, its inverse and the new count
1289
+ */
1290
+ export function remapDropping(bound, keep) {
1291
+ const remap = new Uint32Array(bound);
1292
+ let count = 0;
1293
+ for (let i = 0; i < bound; i++) {
1294
+ remap[i] = keep(i) ? count++ : INVALID_INDEX;
1295
+ }
1296
+ const origin = new Uint32Array(count);
1297
+ for (let i = 0; i < bound; i++) {
1298
+ if (remap[i] !== INVALID_INDEX) {
1299
+ origin[remap[i]] = i;
1300
+ }
1301
+ }
1302
+ return { remap, origin, count };
1303
+ }
1304
+ /**
1305
+ * The remap that keeps exactly the indices whose bit is set in `keep` (a bitmap over `bound` bits),
1306
+ * assigning new indices in index order (invariant I14): `remapDropping` over the builder's alive
1307
+ * bitmaps without a call per index.
1308
+ * @param bound - the old index space size
1309
+ * @param keep - a bitmap of at least `bound` bits; bit i set = old index i survives
1310
+ * @returns the remap, its inverse and the new count
1311
+ */
1312
+ export function remapKeepingBits(bound, keep) {
1313
+ const remap = new Uint32Array(bound);
1314
+ let count = 0;
1315
+ for (let i = 0; i < bound; i++) {
1316
+ if (((keep[i >>> 5] >>> (i & 31)) & 1) === 1) {
1317
+ remap[i] = count++;
1318
+ }
1319
+ else {
1320
+ remap[i] = INVALID_INDEX;
1321
+ }
1322
+ }
1323
+ const origin = new Uint32Array(count);
1324
+ for (let i = 0; i < bound; i++) {
1325
+ const mapped = remap[i];
1326
+ if (mapped !== INVALID_INDEX) {
1327
+ origin[mapped] = i;
1328
+ }
1329
+ }
1330
+ return { remap, origin, count };
1331
+ }
1332
+ /**
1333
+ * The remap that keeps exactly the survivors of a merge walk (the indices with `survivorOf[e] === e`),
1334
+ * assigning new indices in index order (invariant I14): `remapDropping` for design section 6.5's
1335
+ * step-7 repeat without a call per edge.
1336
+ * @param survivorOf - old edge -> its survivor (itself for a survivor)
1337
+ * @returns the remap, its inverse and the new count
1338
+ */
1339
+ export function remapSurvivors(survivorOf) {
1340
+ const bound = survivorOf.length;
1341
+ const remap = new Uint32Array(bound);
1342
+ let count = 0;
1343
+ for (let e = 0; e < bound; e++) {
1344
+ if (survivorOf[e] === e) {
1345
+ remap[e] = count++;
1346
+ }
1347
+ else {
1348
+ remap[e] = INVALID_INDEX;
1349
+ }
1350
+ }
1351
+ const origin = new Uint32Array(count);
1352
+ for (let e = 0; e < bound; e++) {
1353
+ const mapped = remap[e];
1354
+ if (mapped !== INVALID_INDEX) {
1355
+ origin[mapped] = e;
1356
+ }
1357
+ }
1358
+ return { remap, origin, count };
1359
+ }
1360
+ /**
1361
+ * Link the edges [first, end) into both incidence lists in index order, exactly as pushEdge does one
1362
+ * at a time (every list head becomes the highest linked index).
1363
+ * @param src - sources (backing view)
1364
+ * @param dst - targets (backing view)
1365
+ * @param first - the first edge to link
1366
+ * @param end - one past the last edge to link
1367
+ * @param firstOut - out-list heads
1368
+ * @param firstIn - in-list heads
1369
+ * @param nextOut - receives the out-list links
1370
+ * @param nextIn - receives the in-list links
1371
+ * @returns the number of self-loops among the linked edges
1372
+ */
1373
+ function linkEdgeRange(src, dst, first, end, firstOut, firstIn, nextOut, nextIn) {
1374
+ let loops = 0;
1375
+ for (let e = first; e < end; e++) {
1376
+ const u = src[e];
1377
+ const v = dst[e];
1378
+ nextOut[e] = firstOut[u];
1379
+ firstOut[u] = e;
1380
+ nextIn[e] = firstIn[v];
1381
+ firstIn[v] = e;
1382
+ if (u === v) {
1383
+ loops++;
1384
+ }
1385
+ }
1386
+ return loops;
1387
+ }
1388
+ /**
1389
+ * The edge gather of a compaction: endpoints through the node remap, in new-index order, with both
1390
+ * incidence lists rebuilt (every list head is the highest edge index, as after pushEdge in order).
1391
+ * @param src - the source staging's sources (backing view)
1392
+ * @param dst - the source staging's targets (backing view)
1393
+ * @param origin - new edge index -> old edge index
1394
+ * @param nodeRemap - old node index -> new node index
1395
+ * @param outSrc - receives the remapped sources
1396
+ * @param outDst - receives the remapped targets
1397
+ * @param firstOut - out-list heads, INVALID_INDEX on entry
1398
+ * @param firstIn - in-list heads, INVALID_INDEX on entry
1399
+ * @param nextOut - receives the out-list links
1400
+ * @param nextIn - receives the in-list links
1401
+ * @returns the self-loop count
1402
+ */
1403
+ function gatherEdges(src, dst, origin, nodeRemap, outSrc, outDst, firstOut, firstIn, nextOut, nextIn) {
1404
+ const edgeCount = origin.length;
1405
+ let loops = 0;
1406
+ for (let e = 0; e < edgeCount; e++) {
1407
+ const old = origin[e];
1408
+ const u = nodeRemap[src[old]];
1409
+ const v = nodeRemap[dst[old]];
1410
+ outSrc[e] = u;
1411
+ outDst[e] = v;
1412
+ nextOut[e] = firstOut[u];
1413
+ firstOut[u] = e;
1414
+ nextIn[e] = firstIn[v];
1415
+ firstIn[v] = e;
1416
+ if (u === v) {
1417
+ loops++;
1418
+ }
1419
+ }
1420
+ return loops;
1421
+ }
1422
+ /**
1423
+ * `out[i] = values[origin[i]]` for every new index; the element conversion is the target array's
1424
+ * (an f64 source into f32 staging rounds exactly as a push would).
1425
+ * @param values - the old values (backing view)
1426
+ * @param origin - new index -> old index
1427
+ * @param out - receives the gathered values
1428
+ */
1429
+ function gatherValues(values, origin, out) {
1430
+ const count = origin.length;
1431
+ for (let i = 0; i < count; i++) {
1432
+ out[i] = values[origin[i]];
1433
+ }
1434
+ }
1435
+ /**
1436
+ * Store the reduced weight of every merged group on its survivor (design section 6.5).
1437
+ * @param merged - per new edge, the reduced weight where `stored` is set
1438
+ * @param stored - per new edge, bit set when a reduced weight is to be stored
1439
+ * @param weights - the new staging weights
1440
+ * @param edgeCount - the new edge count
1441
+ */
1442
+ function applyMergedWeights(merged, stored, weights, edgeCount) {
1443
+ for (let e = 0; e < edgeCount; e++) {
1444
+ if (bitmapGet(stored, e)) {
1445
+ weights[e] = merged[e];
1446
+ }
1447
+ }
1448
+ }
1449
+ /**
1450
+ * Gather a new staging through a compaction plan (design section 6.3 step 1). The source is left
1451
+ * untouched; the result has no tombstones, fresh `ids` / `idToIndex` objects (or none when every node
1452
+ * is anonymous), rebuilt incidence lists, gathered columns with `refersTo` values rewritten, and
1453
+ * extension tables with their `refersTo` values rewritten.
1454
+ * @param source - the staging to compact
1455
+ * @param plan - the remaps and merge overrides
1456
+ * @returns the compacted staging
1457
+ */
1458
+ export function compactStaging(source, plan) {
1459
+ const { nodes, edges } = plan;
1460
+ const out = new Staging({
1461
+ ...source.options,
1462
+ weighted: source.weight !== null || plan.mergedWeights !== null,
1463
+ expectedNodes: nodes.count,
1464
+ expectedEdges: edges.count,
1465
+ });
1466
+ // nodes: every new node is live with empty incidence lists (what pushNode(null) does, in bulk); ids
1467
+ // and map are fresh objects; anonymous nodes stay anonymous (their ids are their new indices)
1468
+ out.nodeAlive.resize(nodes.count, true);
1469
+ out.firstOut.resize(nodes.count, INVALID_INDEX);
1470
+ out.firstIn.resize(nodes.count, INVALID_INDEX);
1471
+ out.liveNodeCount = nodes.count;
1472
+ if (source.ids !== null) {
1473
+ const ids = new Array(nodes.count);
1474
+ const map = new Map();
1475
+ for (let i = 0; i < nodes.count; i++) {
1476
+ const id = source.ids[nodes.origin[i]];
1477
+ ids[i] = id;
1478
+ map.set(id, i);
1479
+ }
1480
+ out.ids = ids;
1481
+ out.idToIndex = map;
1482
+ }
1483
+ // edges: gathered in new-index order through the backing views (one typed-array pass, design
1484
+ // section 6.3 step 1), weights and explicit-weight bits carried, lists rebuilt by pushing every
1485
+ // edge in index order exactly as pushEdge does (head of each list = highest index)
1486
+ const { remap: nodeRemap } = nodes;
1487
+ const edgeCount = edges.count;
1488
+ const { origin } = edges;
1489
+ out.weightMode = source.weightMode;
1490
+ if (source.weightSet !== null || plan.mergedWeightSet !== null) {
1491
+ out.weightSet = new GrowableBitmap({ capacity: edgeCount, resizable: source.options.resizable });
1492
+ out.weightMode = "mixed";
1493
+ }
1494
+ out.src.resize(edgeCount);
1495
+ out.dst.resize(edgeCount);
1496
+ out.nextOut.resize(edgeCount);
1497
+ out.nextIn.resize(edgeCount);
1498
+ out.edgeAlive.resize(edgeCount, true);
1499
+ out.liveEdgeCount = edgeCount;
1500
+ out.selfLoopCount = gatherEdges(source.src.array, source.dst.array, origin, nodeRemap, out.src.array, out.dst.array, out.firstOut.array, out.firstIn.array, out.nextOut.array, out.nextIn.array);
1501
+ if (out.weight !== null) {
1502
+ out.weight.resize(edgeCount);
1503
+ const weights = out.weight.array;
1504
+ if (source.weight === null) {
1505
+ weights.fill(1, 0, edgeCount);
1506
+ }
1507
+ else {
1508
+ gatherValues(source.weight.array, origin, weights);
1509
+ }
1510
+ if (plan.mergedWeights !== null && plan.mergedWeightStored !== null) {
1511
+ applyMergedWeights(plan.mergedWeights, plan.mergedWeightStored, weights, edgeCount);
1512
+ }
1513
+ }
1514
+ if (out.weightSet !== null) {
1515
+ out.weightSet.resize(edgeCount, false);
1516
+ for (let e = 0; e < edgeCount; e++) {
1517
+ let explicit = source.weightExplicit(origin[e]);
1518
+ if (plan.mergedWeightSet !== null && bitmapGet(plan.mergedWeightSet, e)) {
1519
+ explicit = true;
1520
+ }
1521
+ if (explicit) {
1522
+ out.weightSet.set(e, true);
1523
+ }
1524
+ }
1525
+ }
1526
+ // columns
1527
+ const refs = { node: nodeRemap, edge: plan.edgeValues ?? edges.remap };
1528
+ out.nodeColumns = source.nodeColumns.map((column) => column.gather(nodes.origin, valueRemapFor(column, refs)));
1529
+ out.edgeColumns = source.edgeColumns.map((column) => column.gather(edges.origin, valueRemapFor(column, refs)));
1530
+ out.extensions = source.extensions.map((table) => ({
1531
+ name: table.name,
1532
+ rowCount: table.rowCount,
1533
+ columns: table.columns.map((column) => column.gather(null, valueRemapFor(column, refs))),
1534
+ }));
1535
+ return out;
1536
+ }
1537
+ /**
1538
+ * The value remap that applies to a column's `refersTo`, if any.
1539
+ * @param column - the column
1540
+ * @param refs - the node and edge remaps
1541
+ * @returns the remap of the referenced space, or null
1542
+ */
1543
+ function valueRemapFor(column, refs) {
1544
+ switch (column.meta.refersTo) {
1545
+ case "node":
1546
+ return refs.node;
1547
+ case "edge":
1548
+ return refs.edge;
1549
+ default:
1550
+ return null;
1551
+ }
1552
+ }
1553
+ //# sourceMappingURL=compact.js.map