@graphty/graph-io 0.3.18 → 0.3.19

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 (118) hide show
  1. package/README.md +37 -2
  2. package/dist/chunks/{escape-D-gZWO26.js → escape-CWExcecC.js} +3 -3
  3. package/dist/chunks/{escape-D-gZWO26.js.map → escape-CWExcecC.js.map} +1 -1
  4. package/dist/chunks/exporter-CbMZyVt-.js +735 -0
  5. package/dist/chunks/exporter-CbMZyVt-.js.map +1 -0
  6. package/dist/chunks/importer-BAP4PrxR.js +2194 -0
  7. package/dist/chunks/importer-BAP4PrxR.js.map +1 -0
  8. package/dist/chunks/{importer-Br_QeAeE.js → importer-BNFuV1-K.js} +5 -4
  9. package/dist/chunks/{importer-Br_QeAeE.js.map → importer-BNFuV1-K.js.map} +1 -1
  10. package/dist/chunks/{importer-d0uQxFp6.js → importer-BVGtU1NA.js} +5 -4
  11. package/dist/chunks/{importer-d0uQxFp6.js.map → importer-BVGtU1NA.js.map} +1 -1
  12. package/dist/chunks/{importer-DHagxvDD.js → importer-BW-Ft2ps.js} +5 -4
  13. package/dist/chunks/{importer-DHagxvDD.js.map → importer-BW-Ft2ps.js.map} +1 -1
  14. package/dist/chunks/{importer-Du5crN9l.js → importer-Bm1_5vPS.js} +275 -82
  15. package/dist/chunks/importer-Bm1_5vPS.js.map +1 -0
  16. package/dist/chunks/{importer-aNJfe0qu.js → importer-ByPGO-09.js} +2 -2
  17. package/dist/chunks/{importer-aNJfe0qu.js.map → importer-ByPGO-09.js.map} +1 -1
  18. package/dist/chunks/importer-DOepkgnG.js +1713 -0
  19. package/dist/chunks/importer-DOepkgnG.js.map +1 -0
  20. package/dist/chunks/json-elements-CZY1wiZh.js +779 -0
  21. package/dist/chunks/json-elements-CZY1wiZh.js.map +1 -0
  22. package/dist/chunks/{records-Bk9jgodz.js → records-BzNicMsf.js} +2 -2
  23. package/dist/chunks/{records-Bk9jgodz.js.map → records-BzNicMsf.js.map} +1 -1
  24. package/dist/chunks/{report-BOk0p5y8.js → report-BcWboivV.js} +95 -95
  25. package/dist/chunks/{report-BOk0p5y8.js.map → report-BcWboivV.js.map} +1 -1
  26. package/dist/chunks/weights-CwISIpCP.js +176 -0
  27. package/dist/chunks/weights-CwISIpCP.js.map +1 -0
  28. package/dist/chunks/{writer-GAdltGmC.js → writer-DQiKgQJc.js} +8 -179
  29. package/dist/chunks/writer-DQiKgQJc.js.map +1 -0
  30. package/dist/csv.js +5 -4
  31. package/dist/csv.js.map +1 -1
  32. package/dist/cx.d.ts +1 -0
  33. package/dist/cx.js +6 -0
  34. package/dist/cx.js.map +1 -0
  35. package/dist/cx2.d.ts +1 -0
  36. package/dist/cx2.js +10 -0
  37. package/dist/cx2.js.map +1 -0
  38. package/dist/dot.js +1 -1
  39. package/dist/gexf.js +15 -4
  40. package/dist/gexf.js.map +1 -1
  41. package/dist/gml.js +5 -4
  42. package/dist/gml.js.map +1 -1
  43. package/dist/graph-io.js +145 -389
  44. package/dist/graph-io.js.map +1 -1
  45. package/dist/graphml.js +1 -1
  46. package/dist/json.js +1 -1
  47. package/dist/neo4j.js +5 -4
  48. package/dist/neo4j.js.map +1 -1
  49. package/dist/obo.js +1 -1
  50. package/dist/pajek.js +1 -1
  51. package/dist/src/common/json-elements.d.ts +286 -0
  52. package/dist/src/common/json-elements.d.ts.map +1 -0
  53. package/dist/src/common/json-elements.js +926 -0
  54. package/dist/src/common/json-elements.js.map +1 -0
  55. package/dist/src/formats/cx/importer.d.ts +133 -0
  56. package/dist/src/formats/cx/importer.d.ts.map +1 -0
  57. package/dist/src/formats/cx/importer.js +2220 -0
  58. package/dist/src/formats/cx/importer.js.map +1 -0
  59. package/dist/src/formats/cx/index.d.ts +7 -0
  60. package/dist/src/formats/cx/index.d.ts.map +1 -0
  61. package/dist/src/formats/cx/index.js +7 -0
  62. package/dist/src/formats/cx/index.js.map +1 -0
  63. package/dist/src/formats/cx2/exporter.d.ts +59 -0
  64. package/dist/src/formats/cx2/exporter.d.ts.map +1 -0
  65. package/dist/src/formats/cx2/exporter.js +864 -0
  66. package/dist/src/formats/cx2/exporter.js.map +1 -0
  67. package/dist/src/formats/cx2/importer.d.ts +169 -0
  68. package/dist/src/formats/cx2/importer.d.ts.map +1 -0
  69. package/dist/src/formats/cx2/importer.js +1652 -0
  70. package/dist/src/formats/cx2/importer.js.map +1 -0
  71. package/dist/src/formats/cx2/index.d.ts +7 -0
  72. package/dist/src/formats/cx2/index.d.ts.map +1 -0
  73. package/dist/src/formats/cx2/index.js +7 -0
  74. package/dist/src/formats/cx2/index.js.map +1 -0
  75. package/dist/src/formats/gexf/exporter.d.ts +2 -0
  76. package/dist/src/formats/gexf/exporter.d.ts.map +1 -1
  77. package/dist/src/formats/gexf/exporter.js +6 -0
  78. package/dist/src/formats/gexf/exporter.js.map +1 -1
  79. package/dist/src/formats/gexf/importer.d.ts +2 -4
  80. package/dist/src/formats/gexf/importer.d.ts.map +1 -1
  81. package/dist/src/formats/gexf/importer.js +2 -4
  82. package/dist/src/formats/gexf/importer.js.map +1 -1
  83. package/dist/src/formats/gexf/index.d.ts +1 -1
  84. package/dist/src/formats/gexf/index.js +2 -2
  85. package/dist/src/formats/gexf/index.js.map +1 -1
  86. package/dist/src/formats/gml/exporter.js +1 -1
  87. package/dist/src/formats/gml/exporter.js.map +1 -1
  88. package/dist/src/formats/json/importer.d.ts.map +1 -1
  89. package/dist/src/formats/json/importer.js +6 -104
  90. package/dist/src/formats/json/importer.js.map +1 -1
  91. package/dist/src/index.d.ts +2 -0
  92. package/dist/src/index.d.ts.map +1 -1
  93. package/dist/src/index.js +2 -0
  94. package/dist/src/index.js.map +1 -1
  95. package/dist/src/registry.d.ts.map +1 -1
  96. package/dist/src/registry.js +5 -0
  97. package/dist/src/registry.js.map +1 -1
  98. package/dist/src/sniff.d.ts +1 -1
  99. package/dist/src/sniff.d.ts.map +1 -1
  100. package/dist/src/sniff.js +2 -0
  101. package/dist/src/sniff.js.map +1 -1
  102. package/package.json +11 -1
  103. package/src/common/json-elements.ts +1147 -0
  104. package/src/formats/cx/importer.ts +2733 -0
  105. package/src/formats/cx/index.ts +7 -0
  106. package/src/formats/cx2/exporter.ts +1036 -0
  107. package/src/formats/cx2/importer.ts +2187 -0
  108. package/src/formats/cx2/index.ts +7 -0
  109. package/src/formats/gexf/exporter.ts +11 -0
  110. package/src/formats/gexf/importer.ts +2 -2
  111. package/src/formats/gexf/index.ts +1 -1
  112. package/src/formats/gml/exporter.ts +1 -1
  113. package/src/formats/json/importer.ts +6 -105
  114. package/src/index.ts +10 -0
  115. package/src/registry.ts +5 -0
  116. package/src/sniff.ts +14 -1
  117. package/dist/chunks/importer-Du5crN9l.js.map +0 -1
  118. package/dist/chunks/writer-GAdltGmC.js.map +0 -1
@@ -0,0 +1,176 @@
1
+ import { GraphFormatError } from "@graphty/graph-format";
2
+ import { aF as parseDecimalText } from "./report-BcWboivV.js";
3
+ function formatF32(value) {
4
+ if (!Number.isFinite(value)) {
5
+ return String(value);
6
+ }
7
+ if (value === 0) {
8
+ return Object.is(value, -0) ? "-0" : "0";
9
+ }
10
+ for (let digits = 1; digits <= 9; digits++) {
11
+ const text = value.toPrecision(digits);
12
+ if (Math.fround(Number(text)) === value) {
13
+ return String(Number(text));
14
+ }
15
+ }
16
+ return String(value);
17
+ }
18
+ function formatF64(value) {
19
+ return Object.is(value, -0) ? "-0" : String(value);
20
+ }
21
+ function formatDecimal(value, dtype = "f64") {
22
+ if (!Number.isFinite(value)) {
23
+ return String(value);
24
+ }
25
+ if (Object.is(value, -0)) {
26
+ return "-0.0";
27
+ }
28
+ const text = formatNumber(value, dtype);
29
+ return text.includes(".") || text.includes("e") ? text : `${text}.0`;
30
+ }
31
+ function formatGmlReal(value, dtype = "f64") {
32
+ if (Number.isNaN(value)) {
33
+ return "NAN";
34
+ }
35
+ if (!Number.isFinite(value)) {
36
+ return value > 0 ? "+INF" : "-INF";
37
+ }
38
+ const text = formatDecimal(value, dtype);
39
+ if (text.includes(".")) {
40
+ return text;
41
+ }
42
+ const e = text.indexOf("e");
43
+ return `${text.slice(0, e)}.0${text.slice(e)}`;
44
+ }
45
+ function formatInteger(value) {
46
+ if (Number.isSafeInteger(value) || !Number.isFinite(value)) {
47
+ return String(value);
48
+ }
49
+ return BigInt(value).toString();
50
+ }
51
+ function formatNumber(value, dtype) {
52
+ return dtype === "f32" ? formatF32(value) : formatF64(value);
53
+ }
54
+ const DEFAULT_WEIGHT = 1;
55
+ function isWeightField(name, weightFrom) {
56
+ return weightFrom !== null && name === weightFrom;
57
+ }
58
+ function parseWeightText(text) {
59
+ const trimmed = text.trim();
60
+ if (trimmed.length === 0) {
61
+ return void 0;
62
+ }
63
+ let value;
64
+ try {
65
+ value = parseDecimalText(trimmed);
66
+ } catch (err) {
67
+ throw invalidWeight(text, err);
68
+ }
69
+ if (Number.isNaN(value)) {
70
+ throw invalidWeight(text, null);
71
+ }
72
+ return value;
73
+ }
74
+ function weightFromValue(value) {
75
+ if (value === void 0 || value === null) {
76
+ return void 0;
77
+ }
78
+ if (typeof value === "number") {
79
+ if (Number.isNaN(value)) {
80
+ throw invalidWeight(value, null);
81
+ }
82
+ return value;
83
+ }
84
+ if (typeof value === "string") {
85
+ return parseWeightText(value);
86
+ }
87
+ throw invalidWeight(value, null);
88
+ }
89
+ function invalidWeight(value, cause) {
90
+ let shown;
91
+ switch (typeof value) {
92
+ case "string":
93
+ shown = JSON.stringify(value);
94
+ break;
95
+ case "number":
96
+ shown = String(value);
97
+ break;
98
+ default:
99
+ shown = typeof value;
100
+ }
101
+ return new GraphFormatError("E_INVALID_WEIGHT", `invalid edge weight ${shown}`, {
102
+ value: typeof value === "object" ? typeof value : value,
103
+ cause: cause instanceof Error ? cause.message : null
104
+ });
105
+ }
106
+ const NEGATIVE_ZERO_TEXT = "-0";
107
+ const NUMERIC_DTYPES = /* @__PURE__ */ new Set(["f32", "f64", "i32", "u32", "u8"]);
108
+ function weightFormatter(dtype) {
109
+ switch (dtype) {
110
+ case "f32":
111
+ return formatF32;
112
+ case "f64":
113
+ return formatF64;
114
+ default:
115
+ return formatInteger;
116
+ }
117
+ }
118
+ function explicitWeights(snapshot) {
119
+ const shadowColumn = snapshot.edges.byRole("weight");
120
+ const shadow = shadowColumn !== null && NUMERIC_DTYPES.has(shadowColumn.dtype) ? shadowColumn : null;
121
+ if (shadow !== null) {
122
+ const dtype = shadow.dtype === "f32" ? "f32" : "f64";
123
+ const format = weightFormatter(shadow.dtype);
124
+ return {
125
+ weighted: true,
126
+ dtype,
127
+ isExplicit: (e) => shadow.isSet(e),
128
+ value: (e) => shadow.value(e),
129
+ text: (e, integral = false) => {
130
+ if (!shadow.isSet(e)) {
131
+ return null;
132
+ }
133
+ const value = shadow.value(e);
134
+ if (Object.is(value, -0)) {
135
+ return NEGATIVE_ZERO_TEXT;
136
+ }
137
+ return integral && Number.isInteger(value) ? formatInteger(value) : format(value);
138
+ }
139
+ };
140
+ }
141
+ const { weights } = snapshot.edgeList();
142
+ if (weights === null || !snapshot.flags.weighted) {
143
+ return {
144
+ weighted: false,
145
+ dtype: "f32",
146
+ isExplicit: () => false,
147
+ value: () => DEFAULT_WEIGHT,
148
+ text: () => null
149
+ };
150
+ }
151
+ return {
152
+ weighted: true,
153
+ dtype: "f32",
154
+ isExplicit: () => true,
155
+ value: (e) => weights[e],
156
+ text: (e, integral = false) => {
157
+ const value = weights[e];
158
+ if (Object.is(value, -0)) {
159
+ return NEGATIVE_ZERO_TEXT;
160
+ }
161
+ return integral && Number.isInteger(value) ? formatInteger(value) : formatF32(value);
162
+ }
163
+ };
164
+ }
165
+ export {
166
+ formatF32 as a,
167
+ formatF64 as b,
168
+ formatGmlReal as c,
169
+ formatInteger as d,
170
+ explicitWeights as e,
171
+ formatDecimal as f,
172
+ isWeightField as i,
173
+ parseWeightText as p,
174
+ weightFromValue as w
175
+ };
176
+ //# sourceMappingURL=weights-CwISIpCP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"weights-CwISIpCP.js","sources":["../../src/common/format.ts","../../src/common/weights.ts"],"sourcesContent":["/**\n * Number formatting for exporters (design section 3.7): an f32 weight is written as the shortest\n * decimal that round-trips through Math.fround (never `String(x)`, which prints\n * 0.10000000149011612 for a stored 0.1); an f64 value as its shortest JS text; a GML real always\n * with a decimal point so the dtype survives (design section 8.5); non-finite values as the\n * spelling the target syntax accepts.\n */\n\n/**\n * The shortest decimal text that reads back to the same f32 value through Math.fround.\n * @param value - an f32 value (a JS number holding one)\n * @returns the text; \"Infinity\" / \"-Infinity\" / \"NaN\" for the non-finite values, \"-0\" for negative zero\n */\nexport function formatF32(value: number): string {\n if (!Number.isFinite(value)) {\n return String(value);\n }\n if (value === 0) {\n return Object.is(value, -0) ? \"-0\" : \"0\";\n }\n for (let digits = 1; digits <= 9; digits++) {\n const text = value.toPrecision(digits);\n if (Math.fround(Number(text)) === value) {\n return String(Number(text));\n }\n }\n return String(value);\n}\n\n/**\n * The shortest text of an f64 value: `String(x)`, which is already the shortest round-tripping\n * decimal in JS, except for negative zero, which `String()` writes as \"0\".\n * @param value - the value\n * @returns the text; \"Infinity\" / \"-Infinity\" / \"NaN\" for the non-finite values, \"-0\" for negative zero\n */\nexport function formatF64(value: number): string {\n return Object.is(value, -0) ? \"-0\" : String(value);\n}\n\n/**\n * A decimal text with a decimal point or an exponent guaranteed for a finite value (`2.0`,\n * `1e+21`, `1.5e-7`), so an\n * untyped re-import keeps the column f64 rather than i32 (design section 8.5); negative zero is\n * written `-0.0` so it reads back as -0; non-finite values are the JS spellings (`Infinity`,\n * `-Infinity`, `NaN`), which the CSV / DOT / Pajek importers read back as text. The one\n * implementation of the \"decimal point guaranteed\" rule for every text format; GML has its own\n * spellings of the non-finite values in formatGmlReal().\n * @param value - the value\n * @param dtype - the column dtype the value comes from; f32 values use the shortest fround-round-trip text\n * @returns the text\n */\nexport function formatDecimal(value: number, dtype: \"f32\" | \"f64\" | \"i32\" | \"u32\" | \"u8\" = \"f64\"): string {\n if (!Number.isFinite(value)) {\n return String(value);\n }\n if (Object.is(value, -0)) {\n return \"-0.0\";\n }\n const text = formatNumber(value, dtype);\n // an exponent form (`1e+21`, `1.5e-7`) is already f64 text under the 5.1 grammar\n return text.includes(\".\") || text.includes(\"e\") ? text : `${text}.0`;\n}\n\n/**\n * A GML real: the shortest text with a decimal point guaranteed (`2.0`, `1.0e-7`), so a re-import\n * keeps the column real rather than int. Non-finite values have no GML spelling and are written\n * as the texts NetworkX's writer emits and its reader accepts, `+INF`, `-INF` and `NAN` (the\n * lowercase `inf` / `nan` would lex as keys there).\n * @param value - the value\n * @param dtype - the column dtype the value comes from; f32 values use the shortest fround-round-trip text\n * @returns the text\n */\nexport function formatGmlReal(value: number, dtype: \"f32\" | \"f64\" | \"i32\" | \"u32\" | \"u8\" = \"f64\"): string {\n if (Number.isNaN(value)) {\n return \"NAN\";\n }\n if (!Number.isFinite(value)) {\n return value > 0 ? \"+INF\" : \"-INF\";\n }\n const text = formatDecimal(value, dtype);\n if (text.includes(\".\")) {\n return text;\n }\n // NetworkX's real pattern requires a decimal point even in the exponent form (`1.0e-7`)\n const e = text.indexOf(\"e\");\n return `${text.slice(0, e)}.0${text.slice(e)}`;\n}\n\n/**\n * An integer text for a value known to be integral (an i32 / u32 / u8 cell, an f64 that holds an\n * integer), avoiding the exponent form `String()` uses above 1e21.\n * @param value - an integral value\n * @returns the digits\n */\nexport function formatInteger(value: number): string {\n if (Number.isSafeInteger(value) || !Number.isFinite(value)) {\n return String(value);\n }\n return BigInt(value).toString();\n}\n\n/**\n * The text of a numeric cell of any numeric dtype, dispatching on the dtype: f32 through\n * formatF32, everything else through formatF64.\n * @param value - the value\n * @param dtype - the column dtype the value came from\n * @returns the text\n */\nexport function formatNumber(value: number, dtype: \"f32\" | \"f64\" | \"i32\" | \"u32\" | \"u8\"): string {\n return dtype === \"f32\" ? formatF32(value) : formatF64(value);\n}\n","/**\n * Weight resolution shared by every importer (design sections 3.7 and 8.4): which source field is\n * THE weight (`weightFrom`, per-format default, null = unweighted), how its text or JSON value\n * becomes the number passed to `addEdge`, and the E_INVALID_WEIGHT boundary.\n *\n * An edge whose weight field is absent or blank is pushed WITHOUT a weight argument, never with an\n * explicit 1: the builder's weightSet bitmap then records that the weight was defaulted, and the\n * exporter re-emits no weight for it (decision D-WSET). NaN and non-numeric text are\n * E_INVALID_WEIGHT before the sink is touched, so the importer records the issue and skips the edge\n * with the sink unchanged; Infinity and negative values are legal weights (design section 3.7).\n */\n\nimport { type Column, GraphFormatError, type GraphSnapshot } from \"@graphty/graph-format\";\n\nimport { parseDecimalText } from \"./declared-types.js\";\nimport { formatF32, formatF64, formatInteger } from \"./format.js\";\n\n/** The weight of an edge added without one (design section 3.7). */\nexport const DEFAULT_WEIGHT = 1;\n\n/**\n * Whether a source field is the weight field under the resolved `weightFrom` option.\n * @param name - the field name (attribute title, CSV header, JSON key)\n * @param weightFrom - the resolved option; null means unweighted\n * @returns true when the field is THE weight\n */\nexport function isWeightField(name: string, weightFrom: string | null): boolean {\n return weightFrom !== null && name === weightFrom;\n}\n\n/**\n * The weight argument of addEdge from a text cell: undefined for a blank cell (the weight is\n * omitted), the number otherwise.\n * @param text - the cell text\n * @returns the weight, or undefined when blank; E_INVALID_WEIGHT for NaN or non-numeric text\n */\nexport function parseWeightText(text: string): number | undefined {\n const trimmed = text.trim();\n if (trimmed.length === 0) {\n return undefined;\n }\n let value: number;\n try {\n value = parseDecimalText(trimmed);\n } catch (err) {\n throw invalidWeight(text, err);\n }\n if (Number.isNaN(value)) {\n throw invalidWeight(text, null);\n }\n return value;\n}\n\n/**\n * The weight argument of addEdge from a typed value (JSON, a record field): undefined for null /\n * undefined, the number for a finite or infinite number, the parsed number for numeric text.\n * @param value - the field value\n * @returns the weight, or undefined when absent; E_INVALID_WEIGHT for NaN, a boolean, an object or non-numeric text\n */\nexport function weightFromValue(value: unknown): number | undefined {\n if (value === undefined || value === null) {\n return undefined;\n }\n if (typeof value === \"number\") {\n if (Number.isNaN(value)) {\n throw invalidWeight(value, null);\n }\n return value;\n }\n if (typeof value === \"string\") {\n return parseWeightText(value);\n }\n throw invalidWeight(value, null);\n}\n\n/**\n * The E_INVALID_WEIGHT error of a rejected value.\n * @param value - the rejected value\n * @param cause - the parse error, or null\n * @returns the error\n */\nfunction invalidWeight(value: unknown, cause: unknown): GraphFormatError {\n let shown: string;\n switch (typeof value) {\n case \"string\":\n shown = JSON.stringify(value);\n break;\n case \"number\":\n shown = String(value);\n break;\n default:\n shown = typeof value;\n }\n return new GraphFormatError(\"E_INVALID_WEIGHT\", `invalid edge weight ${shown}`, {\n value: typeof value === \"object\" ? typeof value : value,\n cause: cause instanceof Error ? cause.message : null,\n });\n}\n\n// ============================================================ the exporter side\n\n/**\n * The explicit weights of a snapshot for exporters (design sections 3.7 and 8.5): the weight\n * role column when present (its validity says which edges had an explicit weight, its dtype how\n * the value is written), else `edgeList().weights` as f32 for every edge of a weighted snapshot;\n * nothing for an unweighted one. One implementation for every exporter.\n * Consumed by the per-format exporters under src/formats.\n * @public\n */\nexport interface ExplicitWeights {\n /** Whether any edge can have an explicit weight (the snapshot is weighted). */\n readonly weighted: boolean;\n /** The dtype the values are read from: the shadow column's, or f32 for the arc array. */\n readonly dtype: \"f32\" | \"f64\";\n /**\n * Whether an edge's weight was explicit in the source.\n * @param e - the logical edge index\n * @returns true when the exporter must write it\n */\n isExplicit(e: number): boolean;\n /**\n * The weight value of an edge (meaningful when explicit).\n * @param e - the logical edge index\n * @returns the value\n */\n value(e: number): number;\n /**\n * The weight text of an edge: the shortest round-tripping decimal for its dtype, or the\n * integer digits when `integral` is requested and the value is an integer; null when the\n * weight was defaulted.\n * @param e - the logical edge index\n * @param integral - write an integral value without a decimal part (formats declaring an int weight)\n * @returns the text, or null\n */\n text(e: number, integral?: boolean): string | null;\n}\n\n/** A weight of -0 keeps its sign: every importer's weight grammar reads \"-0\" back as -0. */\nconst NEGATIVE_ZERO_TEXT = \"-0\";\n\n/** The dtypes a weight role column may have (an integer column declared by a caller included). */\nconst NUMERIC_DTYPES: ReadonlySet<string> = new Set([\"f32\", \"f64\", \"i32\", \"u32\", \"u8\"]);\n\n/**\n * The shortest round-tripping text of a weight by the shadow column's dtype.\n * @param dtype - the shadow column's dtype\n * @returns the formatter\n */\nfunction weightFormatter(dtype: string): (value: number) => string {\n switch (dtype) {\n case \"f32\":\n return formatF32;\n case \"f64\":\n return formatF64;\n default:\n return formatInteger;\n }\n}\n\n/**\n * Build the explicit-weight view of a snapshot.\n * @param snapshot - the snapshot\n * @returns the view\n */\nexport function explicitWeights(snapshot: GraphSnapshot): ExplicitWeights {\n const shadowColumn = snapshot.edges.byRole(\"weight\");\n const shadow: Column | null = shadowColumn !== null && NUMERIC_DTYPES.has(shadowColumn.dtype) ? shadowColumn : null;\n if (shadow !== null) {\n const dtype = shadow.dtype === \"f32\" ? \"f32\" : \"f64\";\n const format = weightFormatter(shadow.dtype);\n return {\n weighted: true,\n dtype,\n isExplicit: (e: number): boolean => shadow.isSet(e),\n value: (e: number): number => shadow.value(e) as number,\n text: (e: number, integral = false): string | null => {\n if (!shadow.isSet(e)) {\n return null;\n }\n const value = shadow.value(e) as number;\n if (Object.is(value, -0)) {\n return NEGATIVE_ZERO_TEXT;\n }\n return integral && Number.isInteger(value) ? formatInteger(value) : format(value);\n },\n };\n }\n const { weights } = snapshot.edgeList();\n if (weights === null || !snapshot.flags.weighted) {\n return {\n weighted: false,\n dtype: \"f32\",\n isExplicit: (): boolean => false,\n value: (): number => DEFAULT_WEIGHT,\n text: (): string | null => null,\n };\n }\n return {\n weighted: true,\n dtype: \"f32\",\n isExplicit: (): boolean => true,\n value: (e: number): number => weights[e],\n text: (e: number, integral = false): string => {\n const value = weights[e];\n if (Object.is(value, -0)) {\n return NEGATIVE_ZERO_TEXT;\n }\n return integral && Number.isInteger(value) ? formatInteger(value) : formatF32(value);\n },\n };\n}\n"],"names":[],"mappings":";;AAaO,SAAS,UAAU,OAAuB;AAC7C,MAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AACzB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AACA,SAAO;AAAA,IACH,UAAU;AAAA,IACV,OAAO;AAAA,IACP,YAAY,MAAe;AAAA,IAC3B,OAAO,CAAC,MAAsB,QAAQ,CAAC;AAAA,IACvC,MAAM,CAAC,GAAW,WAAW,UAAkB;AAC3C,YAAM,QAAQ,QAAQ,CAAC;AACvB,UAAI,OAAO,GAAG,OAAO,EAAE,GAAG;AACtB,eAAO;AAAA,MACX;AACA,aAAO,YAAY,OAAO,UAAU,KAAK,IAAI,cAAc,KAAK,IAAI,UAAU,KAAK;AAAA,IACvF;AAAA,EAAA;AAER;"}
@@ -1,167 +1,5 @@
1
1
  import { GraphFormatError, INVALID_INDEX } from "@graphty/graph-format";
2
- import { aO as parseDecimalText, U as OPTIONS_GAINED_CODE, al as XML_ILLEGAL_CHAR_CODE, ac as TEXT_INFERRED_CODE, y as INTEGRAL_F64_CODE, a6 as STORAGE_CLASS_CODE, E as EMPTY_COLUMN_DROPPED_CODE, f as COLUMN_RENAMED_LOSS_CODE, a0 as ROLE_ASSUMED_CODE, aj as WEIGHT_KEY_CLASH_CODE, w as ID_TEXT_COLLISION_CODE, x as ID_TEXT_TYPE_CODE, Q as MUTUAL_AS_UNDIRECTED_CODE, S as MUTUAL_EXPANDED_CODE, X as PARENTS_DROPPED_CODE, a1 as ROLE_DROPPED_CODE, ab as TEMPORAL_TEXT_DROPPED_CODE, aa as TEMPORAL_DROPPED_CODE, O as MIXED_DIRECTION_CODE } from "./report-BOk0p5y8.js";
3
- function formatF32(value) {
4
- if (!Number.isFinite(value)) {
5
- return String(value);
6
- }
7
- if (value === 0) {
8
- return Object.is(value, -0) ? "-0" : "0";
9
- }
10
- for (let digits = 1; digits <= 9; digits++) {
11
- const text = value.toPrecision(digits);
12
- if (Math.fround(Number(text)) === value) {
13
- return String(Number(text));
14
- }
15
- }
16
- return String(value);
17
- }
18
- function formatF64(value) {
19
- return Object.is(value, -0) ? "-0" : String(value);
20
- }
21
- function formatDecimal(value, dtype = "f64") {
22
- if (!Number.isFinite(value)) {
23
- return String(value);
24
- }
25
- if (Object.is(value, -0)) {
26
- return "-0.0";
27
- }
28
- const text = formatNumber(value, dtype);
29
- return text.includes(".") || text.includes("e") ? text : `${text}.0`;
30
- }
31
- function formatGmlReal(value, dtype = "f64") {
32
- if (Number.isNaN(value)) {
33
- return "NAN";
34
- }
35
- if (!Number.isFinite(value)) {
36
- return value > 0 ? "+INF" : "-INF";
37
- }
38
- const text = formatDecimal(value, dtype);
39
- if (text.includes(".")) {
40
- return text;
41
- }
42
- const e = text.indexOf("e");
43
- return `${text.slice(0, e)}.0${text.slice(e)}`;
44
- }
45
- function formatInteger(value) {
46
- if (Number.isSafeInteger(value) || !Number.isFinite(value)) {
47
- return String(value);
48
- }
49
- return BigInt(value).toString();
50
- }
51
- function formatNumber(value, dtype) {
52
- return dtype === "f32" ? formatF32(value) : formatF64(value);
53
- }
54
- const DEFAULT_WEIGHT = 1;
55
- function isWeightField(name, weightFrom) {
56
- return weightFrom !== null && name === weightFrom;
57
- }
58
- function parseWeightText(text) {
59
- const trimmed = text.trim();
60
- if (trimmed.length === 0) {
61
- return void 0;
62
- }
63
- let value;
64
- try {
65
- value = parseDecimalText(trimmed);
66
- } catch (err) {
67
- throw invalidWeight(text, err);
68
- }
69
- if (Number.isNaN(value)) {
70
- throw invalidWeight(text, null);
71
- }
72
- return value;
73
- }
74
- function weightFromValue(value) {
75
- if (value === void 0 || value === null) {
76
- return void 0;
77
- }
78
- if (typeof value === "number") {
79
- if (Number.isNaN(value)) {
80
- throw invalidWeight(value, null);
81
- }
82
- return value;
83
- }
84
- if (typeof value === "string") {
85
- return parseWeightText(value);
86
- }
87
- throw invalidWeight(value, null);
88
- }
89
- function invalidWeight(value, cause) {
90
- let shown;
91
- switch (typeof value) {
92
- case "string":
93
- shown = JSON.stringify(value);
94
- break;
95
- case "number":
96
- shown = String(value);
97
- break;
98
- default:
99
- shown = typeof value;
100
- }
101
- return new GraphFormatError("E_INVALID_WEIGHT", `invalid edge weight ${shown}`, {
102
- value: typeof value === "object" ? typeof value : value,
103
- cause: cause instanceof Error ? cause.message : null
104
- });
105
- }
106
- const NEGATIVE_ZERO_TEXT = "-0";
107
- const NUMERIC_DTYPES = /* @__PURE__ */ new Set(["f32", "f64", "i32", "u32", "u8"]);
108
- function weightFormatter(dtype) {
109
- switch (dtype) {
110
- case "f32":
111
- return formatF32;
112
- case "f64":
113
- return formatF64;
114
- default:
115
- return formatInteger;
116
- }
117
- }
118
- function explicitWeights(snapshot) {
119
- const shadowColumn = snapshot.edges.byRole("weight");
120
- const shadow = shadowColumn !== null && NUMERIC_DTYPES.has(shadowColumn.dtype) ? shadowColumn : null;
121
- if (shadow !== null) {
122
- const dtype = shadow.dtype === "f32" ? "f32" : "f64";
123
- const format = weightFormatter(shadow.dtype);
124
- return {
125
- weighted: true,
126
- dtype,
127
- isExplicit: (e) => shadow.isSet(e),
128
- value: (e) => shadow.value(e),
129
- text: (e, integral = false) => {
130
- if (!shadow.isSet(e)) {
131
- return null;
132
- }
133
- const value = shadow.value(e);
134
- if (Object.is(value, -0)) {
135
- return NEGATIVE_ZERO_TEXT;
136
- }
137
- return integral && Number.isInteger(value) ? formatInteger(value) : format(value);
138
- }
139
- };
140
- }
141
- const { weights } = snapshot.edgeList();
142
- if (weights === null || !snapshot.flags.weighted) {
143
- return {
144
- weighted: false,
145
- dtype: "f32",
146
- isExplicit: () => false,
147
- value: () => DEFAULT_WEIGHT,
148
- text: () => null
149
- };
150
- }
151
- return {
152
- weighted: true,
153
- dtype: "f32",
154
- isExplicit: () => true,
155
- value: (e) => weights[e],
156
- text: (e, integral = false) => {
157
- const value = weights[e];
158
- if (Object.is(value, -0)) {
159
- return NEGATIVE_ZERO_TEXT;
160
- }
161
- return integral && Number.isInteger(value) ? formatInteger(value) : formatF32(value);
162
- }
163
- };
164
- }
2
+ import { T as OPTIONS_GAINED_CODE, ak as XML_ILLEGAL_CHAR_CODE, ab as TEXT_INFERRED_CODE, x as INTEGRAL_F64_CODE, a5 as STORAGE_CLASS_CODE, E as EMPTY_COLUMN_DROPPED_CODE, e as COLUMN_RENAMED_LOSS_CODE, $ as ROLE_ASSUMED_CODE, ai as WEIGHT_KEY_CLASH_CODE, v as ID_TEXT_COLLISION_CODE, w as ID_TEXT_TYPE_CODE, P as MUTUAL_AS_UNDIRECTED_CODE, R as MUTUAL_EXPANDED_CODE, W as PARENTS_DROPPED_CODE, a0 as ROLE_DROPPED_CODE, aa as TEMPORAL_TEXT_DROPPED_CODE, a9 as TEMPORAL_DROPPED_CODE, N as MIXED_DIRECTION_CODE } from "./report-BcWboivV.js";
165
3
  const LOSS = Object.freeze({
166
4
  /** The format has no mixed direction; expanded pairs are written per onMixedDirection. */
167
5
  MIXED_DIRECTION: "W_MIXED_DIRECTION",
@@ -807,21 +645,12 @@ export {
807
645
  capabilities as c,
808
646
  decodeChunks as d,
809
647
  encodeChunks as e,
810
- explicitWeights as f,
811
- formatDecimal as g,
812
- formatF32 as h,
813
- formatF64 as i,
814
- formatGmlReal as j,
815
- formatInteger as k,
816
- isNmtoken as l,
817
- isWeightField as m,
818
- joinText as n,
819
- mangleNmtoken as o,
820
- parseWeightText as p,
821
- isNameChar as q,
822
- countMixedEdges as r,
648
+ isNameChar as f,
649
+ countMixedEdges as g,
650
+ isNmtoken as i,
651
+ joinText as j,
652
+ mangleNmtoken as m,
823
653
  sanitizeIds as s,
824
- toReadableStream as t,
825
- weightFromValue as w
654
+ toReadableStream as t
826
655
  };
827
- //# sourceMappingURL=writer-GAdltGmC.js.map
656
+ //# sourceMappingURL=writer-DQiKgQJc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"writer-DQiKgQJc.js","sources":["../../src/common/export.ts","../../src/common/writer.ts"],"sourcesContent":["/**\n * The exporter-side machinery of design section 8.5: the ExportCapabilities table helper, the\n * generic check() that turns capability gaps into LossNotes with shared codes, and id sanitising\n * (`sanitizeIds: \"error\"` by default; an exporter never silently renames a node; \"mangle\" rewrites\n * the ids the format cannot hold and hands the exporter the originals to write into its\n * `graphty:originalId` attribute).\n *\n * Every exporter's check() calls checkCapabilities() first and appends its format-specific notes\n * (design section 8.5 names W_GML_RECORD_NUMBER_TYPE and W_OPEN_INTERVAL); export() calls\n * sanitizeIds() before writing anything.\n */\n\nimport {\n type Column,\n type Dtype,\n GraphFormatError,\n type GraphSnapshot,\n INVALID_INDEX,\n type NodeId,\n} from \"@graphty/graph-format\";\n\nimport { type ExportCapabilities, type LossNote } from \"../types.js\";\nimport {\n COLUMN_RENAMED_LOSS_CODE,\n EMPTY_COLUMN_DROPPED_CODE,\n ID_TEXT_COLLISION_CODE,\n ID_TEXT_TYPE_CODE,\n INTEGRAL_F64_CODE,\n MIXED_DIRECTION_CODE,\n MUTUAL_AS_UNDIRECTED_CODE,\n MUTUAL_EXPANDED_CODE,\n OPTIONS_GAINED_CODE,\n PARENTS_DROPPED_CODE,\n ROLE_ASSUMED_CODE,\n ROLE_DROPPED_CODE,\n STORAGE_CLASS_CODE,\n TEMPORAL_DROPPED_CODE,\n TEMPORAL_TEXT_DROPPED_CODE,\n TEXT_INFERRED_CODE,\n WEIGHT_KEY_CLASH_CODE,\n XML_ILLEGAL_CHAR_CODE,\n} from \"./codes.js\";\nimport { type ResolvedExportOptions } from \"./options.js\";\n\n/** The shared LossNote codes of checkCapabilities(). */\nexport const LOSS = Object.freeze({\n /** The format has no mixed direction; expanded pairs are written per onMixedDirection. */\n MIXED_DIRECTION: \"W_MIXED_DIRECTION\",\n /** The format has no mixed direction and onMixedDirection is \"error\": export() will throw E_DIRECTED. */\n MIXED_DIRECTION_ERROR: MIXED_DIRECTION_CODE,\n /** Parallel edges in a format without them. */\n MULTI_EDGES: \"W_MULTI_EDGES\",\n /** Self-loops in a format without them. */\n SELF_LOOPS: \"W_SELF_LOOPS\",\n /** The format requires edge ids and the snapshot has none; canonical e0..e{E-1} are generated. */\n EDGE_IDS_GENERATED: \"W_EDGE_IDS_GENERATED\",\n /** The snapshot has an edge id column and the format cannot write one. */\n EDGE_IDS_DROPPED: \"W_EDGE_IDS_DROPPED\",\n /** Ids outside the format's charset are rewritten (sanitizeIds \"mangle\"). */\n ID_MANGLED: \"W_ID_MANGLED\",\n /** Ids outside the format's charset and sanitizeIds \"error\": export() will throw E_INVALID_ID. */\n ID_CHARSET: \"E_ID_CHARSET\",\n /** The format numbers nodes 1..N; ids that are not their 1-based index are kept as labels only. */\n ID_RENUMBERED: \"W_ID_RENUMBERED\",\n /** A column dtype the format does not keep as declared. */\n DTYPE: \"W_DTYPE_UNSUPPORTED\",\n /** A multi-component column in a format without strides. */\n COMPONENTS: \"W_COMPONENTS_FLATTENED\",\n /** A list column in a format without lists. */\n LIST: \"W_LIST_UNSUPPORTED\",\n /** A json column in a format without nested values. */\n JSON: \"W_JSON_UNSUPPORTED\",\n /** A declared default in a format without defaults. */\n DEFAULT: \"W_DEFAULT_DROPPED\",\n /** Declared options in a format without enumerations. */\n OPTIONS: \"W_OPTIONS_DROPPED\",\n /** A parent / parents column in a format without containment. */\n HIERARCHY: \"W_HIERARCHY_DROPPED\",\n /** A start / end / timestamp column in a format without temporal support. */\n TEMPORAL: TEMPORAL_DROPPED_CODE,\n /** A `<column>.text` companion (design section 5.1) the format cannot carry. */\n TEMPORAL_TEXT: TEMPORAL_TEXT_DROPPED_CODE,\n /** A role column the format has no slot for; written as a plain attribute, the role lost. */\n ROLE: ROLE_DROPPED_CODE,\n /** A parents (multi-parent) column in a format with single containment only. */\n PARENTS: PARENTS_DROPPED_CODE,\n /** A mutual pair written as two directed edges without the mutual mark. */\n MUTUAL_EXPANDED: MUTUAL_EXPANDED_CODE,\n /** A mutual pair written as one undirected edge; the mark is lost and the pair reads back undirected. */\n MUTUAL_AS_UNDIRECTED: MUTUAL_AS_UNDIRECTED_CODE,\n /** Node ids whose written text reads back as the other type under the importer's id rule. */\n ID_TEXT_TYPE: ID_TEXT_TYPE_CODE,\n /** Two node ids share one written text; export() throws E_INVALID_ID. */\n ID_TEXT_COLLISION: ID_TEXT_COLLISION_CODE,\n /** A plain column named like the importer's weight key reads back as THE weight. */\n WEIGHT_KEY_CLASH: WEIGHT_KEY_CLASH_CODE,\n /** A role-less column whose written name the importer maps to a role. */\n ROLE_ASSUMED: ROLE_ASSUMED_CODE,\n /** A role column written into the format's slot reads back under the importer's fixed name. */\n COLUMN_NAME_CHANGED: COLUMN_RENAMED_LOSS_CODE,\n /** A declared column whose every row is unset vanishes through a format without declarations. */\n EMPTY_COLUMN: EMPTY_COLUMN_DROPPED_CODE,\n /** A string / dict column that reads back as the other storage class (the dictionary heuristic). */\n STORAGE_CLASS: STORAGE_CLASS_CODE,\n /** An f64 column whose set values are all integral reads back as i32 through an untyped format. */\n INTEGRAL_F64: INTEGRAL_F64_CODE,\n /** Text cells that read back as numbers or booleans under the 5.1 grammar. */\n TEXT_INFERRED: TEXT_INFERRED_CODE,\n /** A string cell holding a character XML 1.0 forbids; export() throws E_COLUMN_TYPE. */\n XML_ILLEGAL_CHAR: XML_ILLEGAL_CHAR_CODE,\n /** A dict column without declared options gains one on re-import. */\n OPTIONS_GAINED: OPTIONS_GAINED_CODE,\n /** A spells column in a format without spells. */\n SPELLS: \"W_SPELLS_DROPPED\",\n /** Dynamic attribute values (extension tables) in a format without them. */\n DYNAMIC_VALUES: \"W_DYNAMIC_VALUES_DROPPED\",\n /** An open-interval column in a format without open intervals (design section 5.1). */\n OPEN_INTERVAL: \"W_OPEN_INTERVAL\",\n /** Graph-level attributes in a format without them. */\n GRAPH_ATTRIBUTES: \"W_GRAPH_ATTRIBUTES_DROPPED\",\n /** A position column in a format without positions. */\n POSITIONS: \"W_POSITIONS_DROPPED\",\n /** Visual columns in a format without them. */\n VIZ: \"W_VIZ_DROPPED\",\n /** An extension table the format cannot carry. */\n EXTENSION_TABLE: \"W_EXTENSION_TABLE_DROPPED\",\n});\n\n/** The capabilities of a format that keeps nothing beyond plain topology; the base every exporter overrides. */\nexport const NO_CAPABILITIES: ExportCapabilities = Object.freeze({\n mixedDirection: false,\n multiEdges: false,\n selfLoops: false,\n edgeIds: \"none\",\n idCharset: \"any\",\n dtypes: Object.freeze([]),\n components: false,\n lists: false,\n json: false,\n defaults: false,\n options: false,\n hierarchy: false,\n temporal: \"none\",\n graphAttributes: false,\n positions: false,\n viz: false,\n});\n\n/**\n * Build a capabilities table from the fields a format supports; every field left out is the\n * conservative NO_CAPABILITIES value, so an exporter states what it keeps and nothing is assumed.\n * @param supported - the fields the format supports\n * @returns a frozen table\n */\nexport function capabilities(supported: Partial<ExportCapabilities>): ExportCapabilities {\n return Object.freeze({ ...NO_CAPABILITIES, ...supported, dtypes: Object.freeze([...(supported.dtypes ?? [])]) });\n}\n\n/**\n * Format facts checkCapabilities() needs that the 12.4 table does not carry.\n * Consumed by the per-format importers and exporters under src/formats.\n * @public\n */\nexport interface CheckExtras {\n /** Whether the format can write open intervals (GEXF 1.2 startopen / endopen); default false. */\n readonly openIntervals?: boolean | undefined;\n /**\n * Whether the format carries the `<column>.text` companions of design section 5.1 (the lexical\n * form of a temporal value); default false, and every companion is then reported as\n * W_TEMPORAL_TEXT_DROPPED.\n */\n readonly temporalText?: boolean | undefined;\n /**\n * The dtype the format's importer gives a position column; an f32 / f64 position of the other\n * dtype is reported as W_DTYPE_UNSUPPORTED because its values differ at the other precision.\n * Undefined skips the check.\n */\n readonly positionDtype?: Dtype | undefined;\n /**\n * The roles beyond the structural, position, viz, hierarchy and temporal ones that the format\n * has a slot for (`label`, `kind`, `labels`, `idSpace`, `sourcePort`, `targetPort`, ...); a\n * column with any other role is written as a plain attribute and reported as W_ROLE_DROPPED.\n * Defaults to none.\n */\n readonly roles?: ReadonlySet<string> | undefined;\n /**\n * Roles the format writes into a fixed slot whose importer reads them back under a fixed name;\n * a role column named otherwise is reported as W_COLUMN_NAME_CHANGED (role -> the name the\n * importer gives it). Defaults to none.\n */\n readonly roleNames?: Readonly<Record<string, string>> | undefined;\n}\n\n/** The roles checkCapabilities() treats structurally rather than as attribute columns. */\nconst STRUCTURAL_ROLES: ReadonlySet<string> = new Set([\"directed\", \"pair\", \"mutual\", \"weight\", \"originalId\"]);\nconst VIZ_ROLES: ReadonlySet<string> = new Set([\"color\", \"size\", \"shape\", \"thickness\"]);\nconst TEMPORAL_ROLES: ReadonlySet<string> = new Set([\"start\", \"end\", \"timestamp\", \"timestamps\"]);\nconst HIERARCHY_ROLES: ReadonlySet<string> = new Set([\"parent\", \"parents\"]);\n\n/**\n * The generic pre-flight of design section 8.5: compare a snapshot with a format's capabilities\n * and return one LossNote per gap, with the shared codes of LOSS. Format-specific notes are the\n * exporter's to append.\n * @param snapshot - the snapshot about to be exported\n * @param caps - the exporter's capabilities\n * @param options - the resolved common export options\n * @param extras - format facts the capabilities table does not carry\n * @returns the notes, empty when the export is exact\n */\nexport function checkCapabilities(\n snapshot: GraphSnapshot,\n caps: ExportCapabilities,\n options: ResolvedExportOptions,\n extras: CheckExtras = {},\n): LossNote[] {\n const notes: LossNote[] = [];\n const note = (code: string, message: string, column: string | null = null, count: number | null = null): void => {\n notes.push(Object.freeze({ code, message, column, count }));\n };\n\n // mixed direction (design section 3.6): an expanded snapshot carries the pair / directed roles\n const mixed = countMixedEdges(snapshot);\n if (mixed > 0 && !caps.mixedDirection) {\n if (options.onMixedDirection === \"error\") {\n note(\n LOSS.MIXED_DIRECTION_ERROR,\n `${mixed} undirected edge(s) in a directed graph; the format has no mixed direction and onMixedDirection is \"error\"`,\n null,\n mixed,\n );\n } else {\n note(\n LOSS.MIXED_DIRECTION,\n `${mixed} undirected edge(s) in a directed graph written as ${options.onMixedDirection}`,\n null,\n mixed,\n );\n }\n }\n\n if (snapshot.flags.multigraph && !caps.multiEdges) {\n const parallel = countParallelArcs(snapshot);\n note(LOSS.MULTI_EDGES, `${parallel} parallel edge(s); the format has no parallel edges`, null, parallel);\n }\n if (snapshot.selfLoopCount > 0 && !caps.selfLoops) {\n note(\n LOSS.SELF_LOOPS,\n `${snapshot.selfLoopCount} self-loop(s); the format has no self-loops`,\n null,\n snapshot.selfLoopCount,\n );\n }\n\n const edgeIds = snapshot.edges.byRole(\"id\");\n if (caps.edgeIds === \"required\" && edgeIds === null && snapshot.edgeCount > 0) {\n note(\n LOSS.EDGE_IDS_GENERATED,\n \"the format requires edge ids; canonical e0..e{E-1} are generated and not written back\",\n null,\n snapshot.edgeCount,\n );\n } else if (caps.edgeIds === \"none\" && edgeIds !== null) {\n note(\n LOSS.EDGE_IDS_DROPPED,\n `edge id column \"${edgeIds.meta.name}\" cannot be written`,\n edgeIds.meta.name,\n snapshot.edgeCount,\n );\n }\n\n const unrepresentable = countUnrepresentableIds(snapshot, caps.idCharset);\n if (unrepresentable > 0) {\n if (caps.idCharset === \"dense-1-based\") {\n note(\n LOSS.ID_RENUMBERED,\n options.sanitizeIds === \"mangle\"\n ? `${unrepresentable} node id(s) are not their 1-based index; nodes are numbered 1..N, the originals kept in the exporter's originalId attribute (restored by restoreMangledIds) and as labels of the nodes without a label value`\n : `${unrepresentable} node id(s) are not their 1-based index; nodes are numbered 1..N and ids kept as labels of the nodes without a label value (a node with one loses its id)`,\n null,\n unrepresentable,\n );\n } else if (options.sanitizeIds === \"mangle\") {\n note(\n LOSS.ID_MANGLED,\n `${unrepresentable} node id(s) outside the ${caps.idCharset} charset are rewritten; originals kept in the originalId attribute`,\n null,\n unrepresentable,\n );\n } else {\n note(\n LOSS.ID_CHARSET,\n `${unrepresentable} node id(s) outside the ${caps.idCharset} charset; export() will throw unless sanitizeIds is \"mangle\"`,\n null,\n unrepresentable,\n );\n }\n }\n\n checkColumns(snapshot.nodes, \"node\", caps, extras, note);\n checkColumns(snapshot.edges, \"edge\", caps, extras, note);\n const graphColumns = snapshot.graph.names();\n if (graphColumns.length > 0) {\n if (caps.graphAttributes) {\n checkColumns(snapshot.graph, \"graph\", caps, extras, note);\n } else {\n note(\n LOSS.GRAPH_ATTRIBUTES,\n `${graphColumns.length} graph attribute(s) cannot be written`,\n null,\n graphColumns.length,\n );\n }\n }\n\n for (const [name, table] of snapshot.extensions) {\n if (name.startsWith(\"temporal:\")) {\n if (caps.temporal !== \"dynamic-values\") {\n note(\n LOSS.DYNAMIC_VALUES,\n `dynamic values of \"${name}\" (${table.rowCount} row(s)) cannot be written`,\n name,\n table.rowCount,\n );\n }\n } else {\n note(\n LOSS.EXTENSION_TABLE,\n `extension table \"${name}\" (${table.rowCount} row(s)) cannot be written`,\n name,\n table.rowCount,\n );\n }\n }\n return notes;\n}\n\n/** A note-recording callback. */\ntype NoteFn = (code: string, message: string, column?: string | null, count?: number | null) => void;\n\n/**\n * The per-column checks of checkCapabilities().\n * @param table - the table\n * @param domain - the domain, for messages\n * @param caps - the capabilities\n * @param extras - format extras\n * @param note - the recorder\n */\nfunction checkColumns(\n table: Iterable<Column>,\n domain: string,\n caps: ExportCapabilities,\n extras: CheckExtras,\n note: NoteFn,\n): void {\n for (const column of table) {\n const { meta } = column;\n const { name, role } = meta;\n if (role !== null && STRUCTURAL_ROLES.has(role)) {\n continue;\n }\n const label = `${domain} column \"${name}\"`;\n if (role !== null && extras.roleNames !== undefined) {\n const fixed = extras.roleNames[role];\n if (fixed !== undefined && fixed !== name) {\n note(\n LOSS.COLUMN_NAME_CHANGED,\n `${label} (${role}) is written into the format's ${role} slot and reads back as \"${fixed}\"`,\n name,\n column.length - column.nullCount,\n );\n }\n }\n if (domain === \"edge\" && role === \"id\") {\n continue;\n }\n if (role === \"timeText\") {\n if (extras.temporalText !== true) {\n note(\n LOSS.TEMPORAL_TEXT,\n `${label} (the lexical form of a temporal column, design section 5.1) cannot be written`,\n name,\n column.length - column.nullCount,\n );\n }\n continue;\n }\n if (role === \"position\") {\n if (!caps.positions) {\n note(LOSS.POSITIONS, `${label} (positions) cannot be written`, name, column.length - column.nullCount);\n } else if (extras.positionDtype !== undefined && meta.dtype !== extras.positionDtype) {\n note(\n LOSS.DTYPE,\n `${label} (positions) is ${meta.dtype}; the format reads positions back as ${extras.positionDtype}`,\n name,\n column.length - column.nullCount,\n );\n }\n continue;\n }\n if (role !== null && VIZ_ROLES.has(role)) {\n if (!caps.viz) {\n note(LOSS.VIZ, `${label} (${role}) cannot be written`, name, column.length - column.nullCount);\n }\n continue;\n }\n if (role !== null && HIERARCHY_ROLES.has(role)) {\n if (!caps.hierarchy) {\n note(LOSS.HIERARCHY, `${label} (${role}) cannot be written`, name, column.length - column.nullCount);\n }\n continue;\n }\n if (role !== null && TEMPORAL_ROLES.has(role)) {\n if (caps.temporal === \"none\") {\n note(LOSS.TEMPORAL, `${label} (${role}) cannot be written`, name, column.length - column.nullCount);\n }\n continue;\n }\n if (role === \"spells\") {\n if (caps.temporal !== \"spells\" && caps.temporal !== \"dynamic-values\") {\n note(LOSS.SPELLS, `${label} (spells) cannot be written`, name, column.length - column.nullCount);\n }\n continue;\n }\n if (role === \"open\" || role === \"spellsOpen\") {\n // The open bits are written by the format's own temporal syntax when it has one; the\n // column's u8 storage is never an attribute dtype, so no dtype note either way.\n if (extras.openIntervals !== true) {\n note(\n LOSS.OPEN_INTERVAL,\n `${label} (open intervals) cannot be written`,\n name,\n column.length - column.nullCount,\n );\n }\n continue;\n }\n if (role !== null && !(extras.roles?.has(role) ?? false)) {\n note(\n LOSS.ROLE,\n `${label} (${role}) is written as a plain attribute; the format has no ${role} slot and the role is lost`,\n name,\n column.length - column.nullCount,\n );\n }\n if (meta.dynamic && caps.temporal !== \"dynamic-values\") {\n note(LOSS.DYNAMIC_VALUES, `${label} is dynamic; only its static value can be written`, name, null);\n }\n checkDtype(column, label, caps, note);\n if (meta.default !== undefined && !caps.defaults) {\n note(LOSS.DEFAULT, `${label} declares a default; the format has no defaults`, name, null);\n }\n if (meta.options !== null && !caps.options) {\n note(LOSS.OPTIONS, `${label} declares options; the format has no enumerations`, name, null);\n }\n }\n}\n\n/**\n * The dtype checks of one attribute column: lists, nested values, scalar dtypes and strides\n * against the capability table.\n * @param column - the column\n * @param label - the column's label for messages\n * @param caps - the capabilities\n * @param note - the recorder\n */\nfunction checkDtype(column: Column, label: string, caps: ExportCapabilities, note: NoteFn): void {\n const { meta } = column;\n const { name } = meta;\n const set = column.length - column.nullCount;\n switch (meta.dtype) {\n case \"list\":\n if (!caps.lists) {\n note(LOSS.LIST, `${label} is a list; the format has no lists`, name, set);\n } else if (meta.itemDtype !== null && !caps.dtypes.includes(meta.itemDtype)) {\n note(\n LOSS.DTYPE,\n `${label} holds ${meta.itemDtype} items; the format cannot keep that dtype`,\n name,\n set,\n );\n } else if (meta.itemDtype === \"dict\") {\n // no format declares an enumeration for list items: they read back as strings\n note(LOSS.DTYPE, `${label} holds dict items; list items read back as string`, name, set);\n }\n break;\n case \"json\":\n if (!caps.json) {\n note(LOSS.JSON, `${label} holds nested values; the format has no nested values`, name, set);\n }\n break;\n default:\n if (!caps.dtypes.includes(meta.dtype)) {\n note(LOSS.DTYPE, `${label} is ${meta.dtype}; the format cannot keep that dtype`, name, set);\n }\n if (meta.components > 1 && !caps.components) {\n note(\n LOSS.COMPONENTS,\n `${label} has ${meta.components} components; the format has no strides`,\n name,\n set,\n );\n }\n break;\n }\n}\n\n/**\n * The number of source edges that were undirected in a directed snapshot (the halves of an\n * expanded pair count once; an expanded self-loop has no mirror and counts once).\n * @param snapshot - the snapshot\n * @returns the count; 0 for an undirected snapshot or one without the directed role\n */\nexport function countMixedEdges(snapshot: GraphSnapshot): number {\n if (!snapshot.directed) {\n return 0;\n }\n const directed = snapshot.edges.byRole(\"directed\");\n if (directed === null || directed.dtype !== \"bool\") {\n return 0;\n }\n const pair = snapshot.edges.byRole(\"pair\");\n let undirectedRows = 0;\n let paired = 0;\n for (let e = 0; e < snapshot.edgeCount; e++) {\n if (directed.isSet(e) && directed.value(e) === false) {\n undirectedRows++;\n if (pair !== null && pair.dtype === \"u32\" && pair.isSet(e) && pair.data[e] !== INVALID_INDEX) {\n paired++;\n }\n }\n }\n return paired / 2 + (undirectedRows - paired);\n}\n\n/**\n * The number of arcs that repeat the previous arc's target within a row (parallel edges), counted\n * over the forward CSR; an undirected parallel edge is counted in both rows.\n * @param snapshot - the snapshot\n * @returns the count\n */\nexport function countParallelArcs(snapshot: GraphSnapshot): number {\n const { rowPtr, colIdx, nodeCount } = snapshot;\n let count = 0;\n for (let u = 0; u < nodeCount; u++) {\n for (let a = rowPtr[u] + 1; a < rowPtr[u + 1]; a++) {\n if (colIdx[a] === colIdx[a - 1]) {\n count++;\n }\n }\n }\n return snapshot.directed ? count : Math.ceil(count / 2);\n}\n\n// ============================================================ id sanitising\n\n/**\n * The id charsets of ExportCapabilities.\n * Consumed by the per-format importers and exporters under src/formats.\n * @public\n */\nexport type IdCharset = ExportCapabilities[\"idCharset\"];\n\n/**\n * The ids to write for every node after sanitising (design section 8.5).\n * Consumed by the per-format importers and exporters under src/formats.\n * @public\n */\nexport interface SanitizedIds {\n /** The charset applied. */\n readonly charset: IdCharset;\n /** How many ids differ from the snapshot's. */\n readonly changed: number;\n /**\n * The id to write for a node.\n * @param index - the node index\n * @returns the id as the format will read it back\n */\n idAt(index: number): NodeId;\n /**\n * Whether a node's written id differs from its original.\n * @param index - the node index\n * @returns true when the exporter must record the original\n */\n isChanged(index: number): boolean;\n /**\n * The original id of a node.\n * @param index - the node index\n * @returns the snapshot's id\n */\n originalAt(index: number): NodeId;\n}\n\n/** XML NameChar ranges (XML 1.0 fifth edition), as inclusive code point pairs. */\nconst NAME_CHAR_RANGES: readonly (readonly [number, number])[] = [\n [0x2d, 0x2e],\n [0x30, 0x3a],\n [0x41, 0x5a],\n [0x5f, 0x5f],\n [0x61, 0x7a],\n [0xb7, 0xb7],\n [0xc0, 0xd6],\n [0xd8, 0xf6],\n [0xf8, 0x37d],\n [0x37f, 0x1fff],\n [0x200c, 0x200d],\n [0x203f, 0x2040],\n [0x2070, 0x218f],\n [0x2c00, 0x2fef],\n [0x3001, 0xd7ff],\n [0xf900, 0xfdcf],\n [0xfdf0, 0xfffd],\n [0x10000, 0xeffff],\n];\n\n/**\n * Whether a code point is an XML NameChar.\n * @param cp - the code point\n * @returns true when it may appear in an NMTOKEN\n */\nexport function isNameChar(cp: number): boolean {\n for (const [lo, hi] of NAME_CHAR_RANGES) {\n if (cp < lo) {\n return false;\n }\n if (cp <= hi) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Whether a text is an XML NMTOKEN (one or more NameChars; GraphML node and edge ids).\n * @param text - the text\n * @returns true for a non-empty text of NameChars\n */\nexport function isNmtoken(text: string): boolean {\n if (text.length === 0) {\n return false;\n }\n for (const ch of text) {\n const cp = ch.codePointAt(0);\n if (cp === undefined || !isNameChar(cp)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Whether an id can be written unchanged under a charset.\n * @param id - the id\n * @param charset - the charset\n * @returns true when the id needs no rewriting (\"dense-1-based\" is never true: see sanitizeIds)\n */\nexport function isRepresentableId(id: NodeId, charset: IdCharset): boolean {\n switch (charset) {\n case \"any\":\n return true;\n case \"nmtoken\":\n return isNmtoken(String(id));\n case \"integer\":\n return typeof id === \"number\" && Number.isSafeInteger(id);\n case \"dense-1-based\":\n return false;\n default: {\n const name: string = charset;\n throw new GraphFormatError(\"E_UNSUPPORTED\", `unknown id charset ${name}`, { charset: name });\n }\n }\n}\n\n/**\n * How many node ids a charset cannot hold as they are (for check()); under \"dense-1-based\" the\n * ids that are not their own 1-based index.\n * @param snapshot - the snapshot\n * @param charset - the charset\n * @returns the count\n */\nexport function countUnrepresentableIds(snapshot: GraphSnapshot, charset: IdCharset): number {\n const { ids } = snapshot;\n if (charset === \"any\") {\n return 0;\n }\n if (charset === \"dense-1-based\") {\n if (ids.kind === \"identity\" && ids.offset === 1) {\n return 0;\n }\n let changed = 0;\n for (let i = 0; i < ids.size; i++) {\n if (ids.idOf(i) !== i + 1) {\n changed++;\n }\n }\n return changed;\n }\n let count = 0;\n for (let i = 0; i < ids.size; i++) {\n if (!isRepresentableId(ids.idOf(i), charset)) {\n count++;\n }\n }\n return count;\n}\n\n/**\n * Sanitise the node ids for a charset (design section 8.5). Under \"error\" any id the charset\n * cannot hold is E_INVALID_ID (details.reason \"charset\") and nothing is written; under \"mangle\"\n * such ids are rewritten deterministically and uniquely: NMTOKEN by replacing every other\n * character with `_` (an empty result becomes `_`) and suffixing `_2`, `_3`... on collision;\n * integer by the smallest unused non-negative integers in index order. \"dense-1-based\" always\n * writes the 1-based index (Pajek numbers vertices; the exporter writes the original id as the\n * label), which is a renumbering rather than a mangling, so it never throws under \"error\"; under\n * \"mangle\" the exporter also writes the original id under its originalId attribute.\n * @param snapshot - the snapshot\n * @param charset - the charset\n * @param mode - the resolved sanitizeIds option\n * @returns the ids to write\n */\nexport function sanitizeIds(snapshot: GraphSnapshot, charset: IdCharset, mode: \"error\" | \"mangle\"): SanitizedIds {\n const { ids } = snapshot;\n const n = ids.size;\n if (charset === \"dense-1-based\") {\n const changed = countUnrepresentableIds(snapshot, charset);\n return {\n charset,\n changed,\n idAt: (i: number): NodeId => i + 1,\n isChanged: (i: number): boolean => ids.idOf(i) !== i + 1,\n originalAt: (i: number): NodeId => ids.idOf(i),\n };\n }\n const unchanged: SanitizedIds = {\n charset,\n changed: 0,\n idAt: (i: number): NodeId => ids.idOf(i),\n isChanged: (): boolean => false,\n originalAt: (i: number): NodeId => ids.idOf(i),\n };\n if (charset === \"any\") {\n return unchanged;\n }\n const bad: number[] = [];\n for (let i = 0; i < n; i++) {\n if (!isRepresentableId(ids.idOf(i), charset)) {\n bad.push(i);\n }\n }\n if (bad.length === 0) {\n return unchanged;\n }\n if (mode === \"error\") {\n const first = ids.idOf(bad[0]);\n throw new GraphFormatError(\n \"E_INVALID_ID\",\n `${bad.length} node id(s) cannot be written as ${charset} (first: ${JSON.stringify(first)} at index ${bad[0]}); pass sanitizeIds: \"mangle\" to rewrite them`,\n { reason: \"charset\", charset, count: bad.length, id: first, index: bad[0] },\n );\n }\n const written = new Map<number, NodeId>();\n if (charset === \"nmtoken\") {\n const used = new Set<string>();\n for (let i = 0; i < n; i++) {\n const id = ids.idOf(i);\n if (isRepresentableId(id, charset)) {\n used.add(String(id));\n }\n }\n for (const i of bad) {\n const base = mangleNmtoken(String(ids.idOf(i)));\n let candidate = base;\n for (let k = 2; used.has(candidate); k++) {\n candidate = `${base}_${k}`;\n }\n used.add(candidate);\n written.set(i, candidate);\n }\n } else {\n const used = new Set<number>();\n for (let i = 0; i < n; i++) {\n const id = ids.idOf(i);\n if (typeof id === \"number\" && Number.isSafeInteger(id)) {\n used.add(id);\n }\n }\n let next = 0;\n for (const i of bad) {\n while (used.has(next)) {\n next++;\n }\n used.add(next);\n written.set(i, next);\n next++;\n }\n }\n return {\n charset,\n changed: bad.length,\n idAt: (i: number): NodeId => written.get(i) ?? ids.idOf(i),\n isChanged: (i: number): boolean => written.has(i),\n originalAt: (i: number): NodeId => ids.idOf(i),\n };\n}\n\n/**\n * Rewrite a text as an NMTOKEN: every character that is not a NameChar becomes `_`.\n * @param text - the text\n * @returns a non-empty NMTOKEN\n */\nexport function mangleNmtoken(text: string): string {\n let out = \"\";\n for (const ch of text) {\n const cp = ch.codePointAt(0);\n out += cp !== undefined && isNameChar(cp) ? ch : \"_\";\n }\n return out.length === 0 ? \"_\" : out;\n}\n","/**\n * The output side of the exporter contract (design sections 8.5 and 12.4): an exporter produces\n * its document as a sequence of text parts (a sync or async generator of strings, one per line or\n * element); these helpers turn that sequence into `export()`'s `AsyncIterable<Uint8Array>` of\n * UTF-8 chunks of a bounded size, into `exportToString()`'s one string, or into a\n * `ReadableStream<Uint8Array>` for a caller that wants a stream.\n */\n\n/**\n * Text parts an exporter produces.\n * Consumed by the per-format importers and exporters under src/formats.\n * @public\n */\nexport type TextParts = Iterable<string> | AsyncIterable<string>;\n\n/** The target size of one encoded chunk; parts are coalesced up to it and never split. */\nexport const DEFAULT_CHUNK_BYTES = 64 * 1024;\n\n/**\n * Encode text parts as UTF-8 chunks of about `chunkBytes` each. Small parts are coalesced; a part\n * larger than the chunk size is emitted whole. The last chunk may be short; nothing is emitted for\n * an empty document.\n * @param parts - the text parts\n * @param chunkBytes - the target chunk size in bytes\n * @yields UTF-8 chunks\n * @returns nothing\n */\nexport async function* encodeChunks(\n parts: TextParts,\n chunkBytes: number = DEFAULT_CHUNK_BYTES,\n): AsyncGenerator<Uint8Array, void, undefined> {\n const encoder = new TextEncoder();\n let pending: string[] = [];\n let pendingUnits = 0;\n for await (const part of parts) {\n if (part.length === 0) {\n continue;\n }\n pending.push(part);\n pendingUnits += part.length;\n // UTF-16 code units are a lower bound on the UTF-8 byte count; flush when the lower bound reaches the target\n if (pendingUnits >= chunkBytes) {\n yield encoder.encode(pending.length === 1 ? pending[0] : pending.join(\"\"));\n pending = [];\n pendingUnits = 0;\n }\n }\n if (pending.length > 0) {\n yield encoder.encode(pending.length === 1 ? pending[0] : pending.join(\"\"));\n }\n}\n\n/**\n * Join text parts into one string.\n * @param parts - the text parts\n * @returns the whole document\n */\nexport async function joinText(parts: TextParts): Promise<string> {\n const collected: string[] = [];\n for await (const part of parts) {\n collected.push(part);\n }\n return collected.join(\"\");\n}\n\n/**\n * Decode UTF-8 chunks back into one string (for tests and for callers holding an export() result).\n * @param chunks - the chunks\n * @returns the decoded text\n */\nexport async function decodeChunks(chunks: AsyncIterable<Uint8Array>): Promise<string> {\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n const parts: string[] = [];\n for await (const chunk of chunks) {\n parts.push(decoder.decode(chunk, { stream: true }));\n }\n parts.push(decoder.decode());\n return parts.join(\"\");\n}\n\n/**\n * Collect UTF-8 chunks into one Uint8Array.\n * @param chunks - the chunks\n * @returns the concatenated bytes\n */\nexport async function collectBytes(chunks: AsyncIterable<Uint8Array>): Promise<Uint8Array> {\n const parts: Uint8Array[] = [];\n let total = 0;\n for await (const chunk of chunks) {\n parts.push(chunk);\n total += chunk.byteLength;\n }\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.byteLength;\n }\n return out;\n}\n\n/**\n * Wrap an async iterable of chunks as a ReadableStream, pulling one chunk per read and cancelling\n * the iterable when the stream is cancelled.\n * @param chunks - the chunks\n * @returns a byte stream\n */\nexport function toReadableStream(chunks: AsyncIterable<Uint8Array>): ReadableStream<Uint8Array> {\n const iterator = chunks[Symbol.asyncIterator]();\n return new ReadableStream<Uint8Array>({\n async pull(controller): Promise<void> {\n const { done, value } = await iterator.next();\n if (done) {\n controller.close();\n return;\n }\n controller.enqueue(value);\n },\n async cancel(): Promise<void> {\n await iterator.return?.(undefined);\n },\n });\n}\n"],"names":[],"mappings":";;AA6CO,MAAM,OAAO,OAAO,OAAO;AAAA;AAAA,EAE9B,iBAAiB;AAAA;AAAA,EAEjB,uBAAuB;AAAA;AAAA,EAEvB,aAAa;AAAA;AAAA,EAEb,YAAY;AAAA;AAAA,EAEZ,oBAAoB;AAAA;AAAA,EAEpB,kBAAkB;AAAA;AAAA,EAElB,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA,EAEZ,eAAe;AAAA;AAAA,EAEf,OAAO;AAAA;AAAA,EAEP,YAAY;AAAA;AAAA,EAEZ,MAAM;AAAA;AAAA,EAEN,MAAM;AAAA;AAAA,EAEN,SAAS;AAAA;AAAA,EAET,SAAS;AAAA;AAAA,EAET,WAAW;AAAA;AAAA,EAEX,UAAU;AAAA;AAAA,EAEV,eAAe;AAAA;AAAA,EAEf,MAAM;AAAA;AAAA,EAEN,SAAS;AAAA;AAAA,EAET,iBAAiB;AAAA;AAAA,EAEjB,sBAAsB;AAAA;AAAA,EAEtB,cAAc;AAAA;AAAA,EAEd,mBAAmB;AAAA;AAAA,EAEnB,kBAAkB;AAAA;AAAA,EAElB,cAAc;AAAA;AAAA,EAEd,qBAAqB;AAAA;AAAA,EAErB,cAAc;AAAA;AAAA,EAEd,eAAe;AAAA;AAAA,EAEf,cAAc;AAAA;AAAA,EAEd,eAAe;AAAA;AAAA,EAEf,kBAAkB;AAAA;AAAA,EAElB,gBAAgB;AAAA;AAAA,EAEhB,QAAQ;AAAA;AAAA,EAER,gBAAgB;AAAA;AAAA,EAEhB,eAAe;AAAA;AAAA,EAEf,kBAAkB;AAAA;AAAA,EAElB,WAAW;AAAA;AAAA,EAEX,KAAK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,IAAI,WAAW,KAAK;AAChC,MAAI,SAAS;AACb,aAAW,QAAQ,OAAO;AACtB,QAAI,IAAI,MAAM,MAAM;AACpB,cAAU,KAAK;AAAA,EACnB;AACA,SAAO;AACX;AAQO,SAAS,iBAAiB,QAA+D;AAC5F,QAAM,WAAW,OAAO,OAAO,aAAa,EAAA;AAC5C,SAAO,IAAI,eAA2B;AAAA,IAClC,MAAM,KAAK,YAA2B;AAClC,YAAM,EAAE,MAAM,MAAA,IAAU,MAAM,SAAS,KAAA;AACvC,UAAI,MAAM;AACN,mBAAW,MAAA;AACX;AAAA,MACJ;AACA,iBAAW,QAAQ,KAAK;AAAA,IAC5B;AAAA,IACA,MAAM,SAAwB;AAC1B,YAAM,SAAS,SAAS,MAAS;AAAA,IACrC;AAAA,EAAA,CACH;AACL;"}
package/dist/csv.js CHANGED
@@ -1,9 +1,10 @@
1
- import { aU as DICT_SAMPLE_ROWS, aT as DictHeuristic, a2 as ROLE_TAKEN_CODE$1, v as ID_MERGED_CODE$1, n as DUPLICATE_EDGE_ID_CODE$1, p as DUPLICATE_NODE_CODE$1, N as MISSING_ID_CODE$1, M as MISSING_ENDPOINT_CODE$1, r as EMPTY_INPUT_CODE$1, aD as resolveImportOptions, I as ImportReportBuilder, aA as reportSinkOptions, aB as reportUnusedOptions, q as DirectionResolver, J as IdCoercer, a as throwIfAborted, aE as uniqueColumnName, $ as RENAMED_CODE, as as declareResolved, aC as resolveExportOptions, ay as pairFolding, aR as joinListText, an as canonicalId, O as MIXED_DIRECTION_CODE, k as DIRECTION_FORCED_CODE, l as DIRECTION_REFUSED_CODE, a3 as SINK_OPTION_CODE, V as OPTION_IGNORED_CODE, C as COLUMN_RENAMED_CODE, ag as UNKNOWN_ENCODING_CODE, s as ENCODING_FALLBACK_CODE, z as INVALID_ENCODING_CODE, F as INVALID_UTF8_CODE } from "./chunks/report-BOk0p5y8.js";
1
+ import { aU as DICT_SAMPLE_ROWS, aT as DictHeuristic, a1 as ROLE_TAKEN_CODE$1, u as ID_MERGED_CODE$1, m as DUPLICATE_EDGE_ID_CODE$1, o as DUPLICATE_NODE_CODE$1, K as MISSING_ID_CODE$1, M as MISSING_ENDPOINT_CODE$1, q as EMPTY_INPUT_CODE$1, aC as resolveImportOptions, I as ImportReportBuilder, az as reportSinkOptions, aA as reportUnusedOptions, p as DirectionResolver, F as IdCoercer, t as throwIfAborted, aE as uniqueColumnName, _ as RENAMED_CODE, ar as declareResolved, aB as resolveExportOptions, ax as pairFolding, aR as joinListText, am as canonicalId, N as MIXED_DIRECTION_CODE, j as DIRECTION_FORCED_CODE, k as DIRECTION_REFUSED_CODE, a2 as SINK_OPTION_CODE, U as OPTION_IGNORED_CODE, C as COLUMN_RENAMED_CODE, af as UNKNOWN_ENCODING_CODE, r as ENCODING_FALLBACK_CODE, y as INVALID_ENCODING_CODE, z as INVALID_UTF8_CODE } from "./chunks/report-BcWboivV.js";
2
2
  import { i as inferTextDtype, T as TextCellWriter, p as parseTextCell, W as WIDENING_UNSUPPORTED_CODE } from "./chunks/text-Dr0Ifpag.js";
3
3
  import { GraphFormatError, INVALID_INDEX } from "@graphty/graph-format";
4
- import { p as parseWeightText, c as capabilities, L as LOSS, n as joinText, e as encodeChunks, a as checkCapabilities, r as countMixedEdges, f as explicitWeights, k as formatInteger, g as formatDecimal } from "./chunks/writer-GAdltGmC.js";
5
- import { s as sniffNewline, a as sniffDelimiter, C as CsvRecordReader, D as DELIMITER_CANDIDATES, B as BAD_QUOTE_CODE, U as UNCLOSED_QUOTE_CODE } from "./chunks/records-Bk9jgodz.js";
6
- import { m as quoteCsvCell } from "./chunks/escape-D-gZWO26.js";
4
+ import { p as parseWeightText, e as explicitWeights, d as formatInteger, f as formatDecimal } from "./chunks/weights-CwISIpCP.js";
5
+ import { s as sniffNewline, a as sniffDelimiter, C as CsvRecordReader, D as DELIMITER_CANDIDATES, B as BAD_QUOTE_CODE, U as UNCLOSED_QUOTE_CODE } from "./chunks/records-BzNicMsf.js";
6
+ import { m as quoteCsvCell } from "./chunks/escape-CWExcecC.js";
7
+ import { c as capabilities, L as LOSS, j as joinText, e as encodeChunks, a as checkCapabilities, g as countMixedEdges } from "./chunks/writer-DQiKgQJc.js";
7
8
  const SOURCE_NAMES = Object.freeze([
8
9
  "source",
9
10
  "src",