@graphty/graph-io 0.0.0 → 0.2.1

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 (339) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +250 -28
  3. package/dist/chunks/children-CL3Cy0ez.js +238 -0
  4. package/dist/chunks/children-CL3Cy0ez.js.map +1 -0
  5. package/dist/chunks/escape-DyI8JofU.js +938 -0
  6. package/dist/chunks/escape-DyI8JofU.js.map +1 -0
  7. package/dist/chunks/importer-CQnJuWJw.js +2987 -0
  8. package/dist/chunks/importer-CQnJuWJw.js.map +1 -0
  9. package/dist/chunks/importer-CpCpfbxr.js +2015 -0
  10. package/dist/chunks/importer-CpCpfbxr.js.map +1 -0
  11. package/dist/chunks/importer-DbnGYr3_.js +2342 -0
  12. package/dist/chunks/importer-DbnGYr3_.js.map +1 -0
  13. package/dist/chunks/importer-GozH8DkN.js +3050 -0
  14. package/dist/chunks/importer-GozH8DkN.js.map +1 -0
  15. package/dist/chunks/records-CGpxszm1.js +605 -0
  16. package/dist/chunks/records-CGpxszm1.js.map +1 -0
  17. package/dist/chunks/text-CajMdVFy.js +189 -0
  18. package/dist/chunks/text-CajMdVFy.js.map +1 -0
  19. package/dist/chunks/writer-DxSKC7TL.js +2842 -0
  20. package/dist/chunks/writer-DxSKC7TL.js.map +1 -0
  21. package/dist/csv.d.ts +1 -0
  22. package/dist/csv.js +1702 -0
  23. package/dist/csv.js.map +1 -0
  24. package/dist/dot.d.ts +1 -0
  25. package/dist/dot.js +8 -0
  26. package/dist/dot.js.map +1 -0
  27. package/dist/gexf.d.ts +1 -0
  28. package/dist/gexf.js +3466 -0
  29. package/dist/gexf.js.map +1 -0
  30. package/dist/gml.d.ts +1 -0
  31. package/dist/gml.js +2647 -0
  32. package/dist/gml.js.map +1 -0
  33. package/dist/graph-io.d.ts +1 -0
  34. package/dist/graph-io.js +790 -0
  35. package/dist/graph-io.js.map +1 -0
  36. package/dist/graphml.d.ts +1 -0
  37. package/dist/graphml.js +8 -0
  38. package/dist/graphml.js.map +1 -0
  39. package/dist/json.d.ts +1 -0
  40. package/dist/json.js +11 -0
  41. package/dist/json.js.map +1 -0
  42. package/dist/neo4j.d.ts +1 -0
  43. package/dist/neo4j.js +2046 -0
  44. package/dist/neo4j.js.map +1 -0
  45. package/dist/pajek.d.ts +1 -0
  46. package/dist/pajek.js +8 -0
  47. package/dist/pajek.js.map +1 -0
  48. package/dist/src/children.d.ts +134 -0
  49. package/dist/src/children.d.ts.map +1 -0
  50. package/dist/src/children.js +274 -0
  51. package/dist/src/children.js.map +1 -0
  52. package/dist/src/common/attributes.d.ts +229 -0
  53. package/dist/src/common/attributes.d.ts.map +1 -0
  54. package/dist/src/common/attributes.js +368 -0
  55. package/dist/src/common/attributes.js.map +1 -0
  56. package/dist/src/common/codes.d.ts +105 -0
  57. package/dist/src/common/codes.d.ts.map +1 -0
  58. package/dist/src/common/codes.js +107 -0
  59. package/dist/src/common/codes.js.map +1 -0
  60. package/dist/src/common/declared-types.d.ts +84 -0
  61. package/dist/src/common/declared-types.d.ts.map +1 -0
  62. package/dist/src/common/declared-types.js +326 -0
  63. package/dist/src/common/declared-types.js.map +1 -0
  64. package/dist/src/common/direction.d.ts +206 -0
  65. package/dist/src/common/direction.d.ts.map +1 -0
  66. package/dist/src/common/direction.js +370 -0
  67. package/dist/src/common/direction.js.map +1 -0
  68. package/dist/src/common/escape.d.ts +92 -0
  69. package/dist/src/common/escape.d.ts.map +1 -0
  70. package/dist/src/common/escape.js +212 -0
  71. package/dist/src/common/escape.js.map +1 -0
  72. package/dist/src/common/export.d.ts +249 -0
  73. package/dist/src/common/export.d.ts.map +1 -0
  74. package/dist/src/common/export.js +594 -0
  75. package/dist/src/common/export.js.map +1 -0
  76. package/dist/src/common/format.d.ts +59 -0
  77. package/dist/src/common/format.d.ts.map +1 -0
  78. package/dist/src/common/format.js +106 -0
  79. package/dist/src/common/format.js.map +1 -0
  80. package/dist/src/common/ids.d.ts +83 -0
  81. package/dist/src/common/ids.d.ts.map +1 -0
  82. package/dist/src/common/ids.js +158 -0
  83. package/dist/src/common/ids.js.map +1 -0
  84. package/dist/src/common/input.d.ts +100 -0
  85. package/dist/src/common/input.d.ts.map +1 -0
  86. package/dist/src/common/input.js +335 -0
  87. package/dist/src/common/input.js.map +1 -0
  88. package/dist/src/common/lists.d.ts +34 -0
  89. package/dist/src/common/lists.d.ts.map +1 -0
  90. package/dist/src/common/lists.js +185 -0
  91. package/dist/src/common/lists.js.map +1 -0
  92. package/dist/src/common/options.d.ts +108 -0
  93. package/dist/src/common/options.d.ts.map +1 -0
  94. package/dist/src/common/options.js +265 -0
  95. package/dist/src/common/options.js.map +1 -0
  96. package/dist/src/common/report.d.ts +187 -0
  97. package/dist/src/common/report.d.ts.map +1 -0
  98. package/dist/src/common/report.js +274 -0
  99. package/dist/src/common/report.js.map +1 -0
  100. package/dist/src/common/temporal.d.ts +71 -0
  101. package/dist/src/common/temporal.d.ts.map +1 -0
  102. package/dist/src/common/temporal.js +266 -0
  103. package/dist/src/common/temporal.js.map +1 -0
  104. package/dist/src/common/text.d.ts +104 -0
  105. package/dist/src/common/text.d.ts.map +1 -0
  106. package/dist/src/common/text.js +255 -0
  107. package/dist/src/common/text.js.map +1 -0
  108. package/dist/src/common/weights.d.ts +77 -0
  109. package/dist/src/common/weights.d.ts.map +1 -0
  110. package/dist/src/common/weights.js +156 -0
  111. package/dist/src/common/weights.js.map +1 -0
  112. package/dist/src/common/writer.d.ts +51 -0
  113. package/dist/src/common/writer.d.ts.map +1 -0
  114. package/dist/src/common/writer.js +108 -0
  115. package/dist/src/common/writer.js.map +1 -0
  116. package/dist/src/common/xml.d.ts +245 -0
  117. package/dist/src/common/xml.d.ts.map +1 -0
  118. package/dist/src/common/xml.js +942 -0
  119. package/dist/src/common/xml.js.map +1 -0
  120. package/dist/src/formats/csv/exporter.d.ts +70 -0
  121. package/dist/src/formats/csv/exporter.d.ts.map +1 -0
  122. package/dist/src/formats/csv/exporter.js +682 -0
  123. package/dist/src/formats/csv/exporter.js.map +1 -0
  124. package/dist/src/formats/csv/header.d.ts +66 -0
  125. package/dist/src/formats/csv/header.d.ts.map +1 -0
  126. package/dist/src/formats/csv/header.js +152 -0
  127. package/dist/src/formats/csv/header.js.map +1 -0
  128. package/dist/src/formats/csv/importer.d.ts +82 -0
  129. package/dist/src/formats/csv/importer.d.ts.map +1 -0
  130. package/dist/src/formats/csv/importer.js +849 -0
  131. package/dist/src/formats/csv/importer.js.map +1 -0
  132. package/dist/src/formats/csv/index.d.ts +60 -0
  133. package/dist/src/formats/csv/index.d.ts.map +1 -0
  134. package/dist/src/formats/csv/index.js +63 -0
  135. package/dist/src/formats/csv/index.js.map +1 -0
  136. package/dist/src/formats/csv/records.d.ts +188 -0
  137. package/dist/src/formats/csv/records.d.ts.map +1 -0
  138. package/dist/src/formats/csv/records.js +702 -0
  139. package/dist/src/formats/csv/records.js.map +1 -0
  140. package/dist/src/formats/csv/values.d.ts +105 -0
  141. package/dist/src/formats/csv/values.d.ts.map +1 -0
  142. package/dist/src/formats/csv/values.js +192 -0
  143. package/dist/src/formats/csv/values.js.map +1 -0
  144. package/dist/src/formats/dot/exporter.d.ts +52 -0
  145. package/dist/src/formats/dot/exporter.d.ts.map +1 -0
  146. package/dist/src/formats/dot/exporter.js +836 -0
  147. package/dist/src/formats/dot/exporter.js.map +1 -0
  148. package/dist/src/formats/dot/importer.d.ts +102 -0
  149. package/dist/src/formats/dot/importer.d.ts.map +1 -0
  150. package/dist/src/formats/dot/importer.js +1291 -0
  151. package/dist/src/formats/dot/importer.js.map +1 -0
  152. package/dist/src/formats/dot/index.d.ts +7 -0
  153. package/dist/src/formats/dot/index.d.ts.map +1 -0
  154. package/dist/src/formats/dot/index.js +7 -0
  155. package/dist/src/formats/dot/index.js.map +1 -0
  156. package/dist/src/formats/dot/names.d.ts +29 -0
  157. package/dist/src/formats/dot/names.d.ts.map +1 -0
  158. package/dist/src/formats/dot/names.js +28 -0
  159. package/dist/src/formats/dot/names.js.map +1 -0
  160. package/dist/src/formats/dot/tokenizer.d.ts +114 -0
  161. package/dist/src/formats/dot/tokenizer.d.ts.map +1 -0
  162. package/dist/src/formats/dot/tokenizer.js +341 -0
  163. package/dist/src/formats/dot/tokenizer.js.map +1 -0
  164. package/dist/src/formats/gexf/exporter.d.ts +56 -0
  165. package/dist/src/formats/gexf/exporter.d.ts.map +1 -0
  166. package/dist/src/formats/gexf/exporter.js +1395 -0
  167. package/dist/src/formats/gexf/exporter.js.map +1 -0
  168. package/dist/src/formats/gexf/importer.d.ts +73 -0
  169. package/dist/src/formats/gexf/importer.d.ts.map +1 -0
  170. package/dist/src/formats/gexf/importer.js +1880 -0
  171. package/dist/src/formats/gexf/importer.js.map +1 -0
  172. package/dist/src/formats/gexf/index.d.ts +96 -0
  173. package/dist/src/formats/gexf/index.d.ts.map +1 -0
  174. package/dist/src/formats/gexf/index.js +97 -0
  175. package/dist/src/formats/gexf/index.js.map +1 -0
  176. package/dist/src/formats/gexf/schema.d.ts +135 -0
  177. package/dist/src/formats/gexf/schema.d.ts.map +1 -0
  178. package/dist/src/formats/gexf/schema.js +323 -0
  179. package/dist/src/formats/gexf/schema.js.map +1 -0
  180. package/dist/src/formats/gml/exporter.d.ts +69 -0
  181. package/dist/src/formats/gml/exporter.d.ts.map +1 -0
  182. package/dist/src/formats/gml/exporter.js +1093 -0
  183. package/dist/src/formats/gml/exporter.js.map +1 -0
  184. package/dist/src/formats/gml/importer.d.ts +66 -0
  185. package/dist/src/formats/gml/importer.d.ts.map +1 -0
  186. package/dist/src/formats/gml/importer.js +1331 -0
  187. package/dist/src/formats/gml/importer.js.map +1 -0
  188. package/dist/src/formats/gml/index.d.ts +85 -0
  189. package/dist/src/formats/gml/index.d.ts.map +1 -0
  190. package/dist/src/formats/gml/index.js +88 -0
  191. package/dist/src/formats/gml/index.js.map +1 -0
  192. package/dist/src/formats/gml/syntax.d.ts +186 -0
  193. package/dist/src/formats/gml/syntax.d.ts.map +1 -0
  194. package/dist/src/formats/gml/syntax.js +467 -0
  195. package/dist/src/formats/gml/syntax.js.map +1 -0
  196. package/dist/src/formats/graphml/constants.d.ts +169 -0
  197. package/dist/src/formats/graphml/constants.d.ts.map +1 -0
  198. package/dist/src/formats/graphml/constants.js +165 -0
  199. package/dist/src/formats/graphml/constants.js.map +1 -0
  200. package/dist/src/formats/graphml/exporter.d.ts +34 -0
  201. package/dist/src/formats/graphml/exporter.d.ts.map +1 -0
  202. package/dist/src/formats/graphml/exporter.js +1176 -0
  203. package/dist/src/formats/graphml/exporter.js.map +1 -0
  204. package/dist/src/formats/graphml/importer.d.ts +31 -0
  205. package/dist/src/formats/graphml/importer.d.ts.map +1 -0
  206. package/dist/src/formats/graphml/importer.js +1607 -0
  207. package/dist/src/formats/graphml/importer.js.map +1 -0
  208. package/dist/src/formats/graphml/index.d.ts +8 -0
  209. package/dist/src/formats/graphml/index.d.ts.map +1 -0
  210. package/dist/src/formats/graphml/index.js +8 -0
  211. package/dist/src/formats/graphml/index.js.map +1 -0
  212. package/dist/src/formats/graphml/tree.d.ts +72 -0
  213. package/dist/src/formats/graphml/tree.d.ts.map +1 -0
  214. package/dist/src/formats/graphml/tree.js +290 -0
  215. package/dist/src/formats/graphml/tree.js.map +1 -0
  216. package/dist/src/formats/json/dialect.d.ts +125 -0
  217. package/dist/src/formats/json/dialect.d.ts.map +1 -0
  218. package/dist/src/formats/json/dialect.js +262 -0
  219. package/dist/src/formats/json/dialect.js.map +1 -0
  220. package/dist/src/formats/json/exporter.d.ts +89 -0
  221. package/dist/src/formats/json/exporter.d.ts.map +1 -0
  222. package/dist/src/formats/json/exporter.js +1358 -0
  223. package/dist/src/formats/json/exporter.js.map +1 -0
  224. package/dist/src/formats/json/importer.d.ts +108 -0
  225. package/dist/src/formats/json/importer.d.ts.map +1 -0
  226. package/dist/src/formats/json/importer.js +1838 -0
  227. package/dist/src/formats/json/importer.js.map +1 -0
  228. package/dist/src/formats/json/index.d.ts +8 -0
  229. package/dist/src/formats/json/index.d.ts.map +1 -0
  230. package/dist/src/formats/json/index.js +8 -0
  231. package/dist/src/formats/json/index.js.map +1 -0
  232. package/dist/src/formats/neo4j/exporter.d.ts +68 -0
  233. package/dist/src/formats/neo4j/exporter.d.ts.map +1 -0
  234. package/dist/src/formats/neo4j/exporter.js +1055 -0
  235. package/dist/src/formats/neo4j/exporter.js.map +1 -0
  236. package/dist/src/formats/neo4j/header.d.ts +52 -0
  237. package/dist/src/formats/neo4j/header.d.ts.map +1 -0
  238. package/dist/src/formats/neo4j/header.js +131 -0
  239. package/dist/src/formats/neo4j/header.js.map +1 -0
  240. package/dist/src/formats/neo4j/importer.d.ts +73 -0
  241. package/dist/src/formats/neo4j/importer.d.ts.map +1 -0
  242. package/dist/src/formats/neo4j/importer.js +932 -0
  243. package/dist/src/formats/neo4j/importer.js.map +1 -0
  244. package/dist/src/formats/neo4j/index.d.ts +79 -0
  245. package/dist/src/formats/neo4j/index.d.ts.map +1 -0
  246. package/dist/src/formats/neo4j/index.js +83 -0
  247. package/dist/src/formats/neo4j/index.js.map +1 -0
  248. package/dist/src/formats/pajek/exporter.d.ts +58 -0
  249. package/dist/src/formats/pajek/exporter.d.ts.map +1 -0
  250. package/dist/src/formats/pajek/exporter.js +825 -0
  251. package/dist/src/formats/pajek/exporter.js.map +1 -0
  252. package/dist/src/formats/pajek/importer.d.ts +88 -0
  253. package/dist/src/formats/pajek/importer.d.ts.map +1 -0
  254. package/dist/src/formats/pajek/importer.js +1047 -0
  255. package/dist/src/formats/pajek/importer.js.map +1 -0
  256. package/dist/src/formats/pajek/index.d.ts +7 -0
  257. package/dist/src/formats/pajek/index.d.ts.map +1 -0
  258. package/dist/src/formats/pajek/index.js +7 -0
  259. package/dist/src/formats/pajek/index.js.map +1 -0
  260. package/dist/src/formats/pajek/syntax.d.ts +112 -0
  261. package/dist/src/formats/pajek/syntax.d.ts.map +1 -0
  262. package/dist/src/formats/pajek/syntax.js +269 -0
  263. package/dist/src/formats/pajek/syntax.js.map +1 -0
  264. package/dist/src/index.d.ts +35 -0
  265. package/dist/src/index.d.ts.map +1 -0
  266. package/dist/src/index.js +39 -0
  267. package/dist/src/index.js.map +1 -0
  268. package/dist/src/registry.d.ts +207 -0
  269. package/dist/src/registry.d.ts.map +1 -0
  270. package/dist/src/registry.js +481 -0
  271. package/dist/src/registry.js.map +1 -0
  272. package/dist/src/sniff.d.ts +104 -0
  273. package/dist/src/sniff.d.ts.map +1 -0
  274. package/dist/src/sniff.js +357 -0
  275. package/dist/src/sniff.js.map +1 -0
  276. package/dist/src/types.d.ts +238 -0
  277. package/dist/src/types.d.ts.map +1 -0
  278. package/dist/src/types.js +29 -0
  279. package/dist/src/types.js.map +1 -0
  280. package/dist/tsconfig.build.tsbuildinfo +1 -0
  281. package/package.json +122 -7
  282. package/src/children.ts +335 -0
  283. package/src/common/attributes.ts +520 -0
  284. package/src/common/codes.ts +153 -0
  285. package/src/common/declared-types.ts +374 -0
  286. package/src/common/direction.ts +518 -0
  287. package/src/common/escape.ts +231 -0
  288. package/src/common/export.ts +817 -0
  289. package/src/common/format.ts +111 -0
  290. package/src/common/ids.ts +176 -0
  291. package/src/common/input.ts +378 -0
  292. package/src/common/lists.ts +196 -0
  293. package/src/common/options.ts +377 -0
  294. package/src/common/report.ts +352 -0
  295. package/src/common/temporal.ts +302 -0
  296. package/src/common/text.ts +294 -0
  297. package/src/common/weights.ts +202 -0
  298. package/src/common/writer.ts +123 -0
  299. package/src/common/xml.ts +1053 -0
  300. package/src/formats/csv/exporter.ts +894 -0
  301. package/src/formats/csv/header.ts +172 -0
  302. package/src/formats/csv/importer.ts +1104 -0
  303. package/src/formats/csv/index.ts +88 -0
  304. package/src/formats/csv/records.ts +813 -0
  305. package/src/formats/csv/values.ts +224 -0
  306. package/src/formats/dot/exporter.ts +1014 -0
  307. package/src/formats/dot/importer.ts +1549 -0
  308. package/src/formats/dot/index.ts +7 -0
  309. package/src/formats/dot/names.ts +40 -0
  310. package/src/formats/dot/tokenizer.ts +384 -0
  311. package/src/formats/gexf/exporter.ts +1696 -0
  312. package/src/formats/gexf/importer.ts +2333 -0
  313. package/src/formats/gexf/index.ts +142 -0
  314. package/src/formats/gexf/schema.ts +361 -0
  315. package/src/formats/gml/exporter.ts +1404 -0
  316. package/src/formats/gml/importer.ts +1591 -0
  317. package/src/formats/gml/index.ts +128 -0
  318. package/src/formats/gml/syntax.ts +545 -0
  319. package/src/formats/graphml/constants.ts +225 -0
  320. package/src/formats/graphml/exporter.ts +1458 -0
  321. package/src/formats/graphml/importer.ts +2027 -0
  322. package/src/formats/graphml/index.ts +8 -0
  323. package/src/formats/graphml/tree.ts +318 -0
  324. package/src/formats/json/dialect.ts +317 -0
  325. package/src/formats/json/exporter.ts +1616 -0
  326. package/src/formats/json/importer.ts +2271 -0
  327. package/src/formats/json/index.ts +8 -0
  328. package/src/formats/neo4j/exporter.ts +1287 -0
  329. package/src/formats/neo4j/header.ts +156 -0
  330. package/src/formats/neo4j/importer.ts +1220 -0
  331. package/src/formats/neo4j/index.ts +116 -0
  332. package/src/formats/pajek/exporter.ts +1000 -0
  333. package/src/formats/pajek/importer.ts +1311 -0
  334. package/src/formats/pajek/index.ts +7 -0
  335. package/src/formats/pajek/syntax.ts +307 -0
  336. package/src/index.ts +244 -0
  337. package/src/registry.ts +617 -0
  338. package/src/sniff.ts +397 -0
  339. package/src/types.ts +262 -0
@@ -0,0 +1,1331 @@
1
+ /**
2
+ * The GML importer (design sections 8.4 and 8.5, research note 07 section 2.2): reads a whole GML
3
+ * text (GML awaits the whole text, 8.4), lexes it once into a typed token list, derives the column
4
+ * schema of every node, edge and graph key in a first walk (GML types are lexical per value, so
5
+ * the column dtype is the union of the value classes seen: `int` -> i32, `real` -> f64, `string`
6
+ * -> string, a nested `[ ]` record -> json, a repeated key -> list; the class is recorded in
7
+ * `origin.type` per column as 8.5 requires), then pushes scalars into the sink in a second walk:
8
+ * every node block first, then every edge block, so node indices follow the file's node order
9
+ * and forward edge references resolve.
10
+ *
11
+ * Conventions honoured: NetworkX's `_networkx_list_start` marker and `"[]"` empty lists, `&#NN;`
12
+ * character references in strings, `Creator` / `Version` top-level metadata, `directed 0|1` and
13
+ * `multigraph 0|1` graph flags, comments, keys and values on one line or split across lines, and
14
+ * a `graphics [ x y z ]` node record mapped to the `position` role (note 07 section 9) with the
15
+ * remaining graphics keys kept as a json column.
16
+ *
17
+ * Node ids are the integer `id` keys (the GML spec type; a non-integer id is a validation error,
18
+ * never a silent string) under `nodeIdFrom: "id"`, the `label` under `"label"`, and the node's
19
+ * ordinal under `"index"`; `source` / `target` always resolve through the integer ids. A node's
20
+ * `graphty_originalId` key written by the exporter's `sanitizeIds: "mangle"` restores the
21
+ * original id under `restoreMangledIds` (the default).
22
+ */
23
+ import { GraphFormatError, INVALID_INDEX, } from "@graphty/graph-format";
24
+ import { declareResolved, DictHeuristic, uniqueColumnName } from "../../common/attributes.js";
25
+ import { COLUMN_RENAMED_CODE, DUPLICATE_NODE_CODE as SHARED_DUPLICATE_NODE_CODE, MISSING_ENDPOINT_CODE as SHARED_MISSING_ENDPOINT_CODE, MISSING_ID_CODE as SHARED_MISSING_ID_CODE, NO_GRAPH_CODE as SHARED_NO_GRAPH_CODE, PRECISION_CODE as SHARED_PRECISION_CODE, ROLE_TAKEN_CODE as SHARED_ROLE_TAKEN_CODE, } from "../../common/codes.js";
26
+ import { DirectionResolver } from "../../common/direction.js";
27
+ import { IdCoercer } from "../../common/ids.js";
28
+ import { readText, throwIfAborted } from "../../common/input.js";
29
+ import { reportSinkOptions, reportUnusedOptions, resolveImportOptions, } from "../../common/options.js";
30
+ import { ImportReportBuilder } from "../../common/report.js";
31
+ import { parseWeightText, weightFromValue } from "../../common/weights.js";
32
+ import { EMPTY_LIST_TEXT, EMPTY_TUPLE_TEXT, GmlSyntaxError, LIST_START_MARKER, numberOfText, ORIGINAL_ID_KEY, parseRecord, scalarOrRecord, TOKEN_INT, TOKEN_OPEN, TOKEN_REAL, TOKEN_STRING, TOKEN_WORD, tokenizeGml, } from "./syntax.js";
33
+ /** Issue code: the text holds no `graph [ ... ]` block. */
34
+ export const NO_GRAPH_CODE = SHARED_NO_GRAPH_CODE;
35
+ /** Issue code: the text holds more than one `graph [ ... ]` block (fatal; one network per file). */
36
+ export const SECOND_GRAPH_CODE = "E_GML_SECOND_GRAPH";
37
+ /** Issue code: a node block has no `id` key. */
38
+ export const MISSING_ID_CODE = SHARED_MISSING_ID_CODE;
39
+ /** Issue code: a node block has no `label` key under `nodeIdFrom: "label"`. */
40
+ export const MISSING_LABEL_CODE = "E_GML_MISSING_LABEL";
41
+ /** Issue code: an edge block has no `source` or no `target` key. */
42
+ export const MISSING_ENDPOINT_CODE = SHARED_MISSING_ENDPOINT_CODE;
43
+ /** Issue code: an `id`, `source` or `target` value is not an integer. */
44
+ export const ID_TYPE_CODE = "E_GML_ID_TYPE";
45
+ /** Issue code: a node id (or label under `nodeIdFrom: "label"`) is declared twice; later keys overwrite. */
46
+ export const DUPLICATE_NODE_CODE = SHARED_DUPLICATE_NODE_CODE;
47
+ /** Issue code: a structural key (`id`, `source`, `target`) appears twice in one block. */
48
+ export const REPEATED_KEY_CODE = "E_GML_REPEATED_KEY";
49
+ /** Issue code: a `node` or `edge` key whose value is not a `[ ... ]` block. */
50
+ export const ELEMENT_TYPE_CODE = "E_GML_ELEMENT_TYPE";
51
+ /** Issue code: a `directed` or `multigraph` flag that is not an integer. */
52
+ export const FLAG_TYPE_CODE = "E_GML_FLAG_TYPE";
53
+ /** Issue code: a `directed` / `multigraph` flag that is not 0 or 1 (read as its truth value), or one repeated. */
54
+ export const FLAG_VALUE_CODE = "W_GML_FLAG_VALUE";
55
+ /** Issue code: an integer beyond 2^53 stored as the nearest f64 (design section 5.1). */
56
+ export const PRECISION_CODE = SHARED_PRECISION_CODE;
57
+ /** Issue code: the sink already holds a column of the name with another declaration; renamed `<name>#<key>`. */
58
+ export const COLUMN_RENAMED_CODE_GML = COLUMN_RENAMED_CODE;
59
+ /** Issue code: the sink already holds a column with the role; the column is declared without it. */
60
+ export const ROLE_TAKEN_CODE = SHARED_ROLE_TAKEN_CODE;
61
+ /** Loss code: under `nodeIdFrom` "label" / "index" the integer `id` keys are not kept. */
62
+ export const ID_DROPPED_CODE = "W_GML_ID_DROPPED";
63
+ const FORMAT_DEFAULTS = { ids: "canonical", defaultDirected: false, weightFrom: "value" };
64
+ const KIND_INT = 1;
65
+ const KIND_REAL = 2;
66
+ const KIND_STRING = 4;
67
+ const KIND_RECORD = 8;
68
+ const I32_MIN = -2147483648;
69
+ const I32_MAX = 2147483647;
70
+ /** How many elements are pushed between abort-signal checks. */
71
+ const ABORT_CHECK_INTERVAL = 64;
72
+ /** The common options the GML importer reads (the rest is reported by reportUnusedOptions). */
73
+ const USED_OPTIONS = new Set([
74
+ "ids",
75
+ "nodeIdFrom",
76
+ "addMissingNodes",
77
+ "duplicateEdges",
78
+ "selfLoops",
79
+ "onMixedDirection",
80
+ "defaultDirected",
81
+ "weightFrom",
82
+ "weightDtype",
83
+ "restoreMangledIds",
84
+ "errorLimit",
85
+ "signal",
86
+ "onProgress",
87
+ ]);
88
+ /** The element sequence number of the graph block's own keys. */
89
+ const GRAPH_SEQ = -1;
90
+ /** The element sequence number of the top-level keys. */
91
+ const TOP_SEQ = -2;
92
+ /**
93
+ * Whether a key gets a role in its table (design section 5.6 applied to GML keys).
94
+ * @param domain - the table
95
+ * @param key - the key
96
+ * @returns the role, or null
97
+ */
98
+ function roleOf(domain, key) {
99
+ if (key === "label" && domain !== "graph") {
100
+ return "label";
101
+ }
102
+ if (domain === "edge") {
103
+ if (key === "id") {
104
+ return "id";
105
+ }
106
+ if (key === "key") {
107
+ return "key";
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+ /** One import call. */
113
+ class GmlImport {
114
+ /**
115
+ * Create one import.
116
+ * @param sink - the sink
117
+ * @param report - the report
118
+ * @param options - the resolved common options
119
+ * @param format - the format-specific options
120
+ */
121
+ constructor(sink, report, options, format) {
122
+ this.tokens = null;
123
+ this.resolver = null;
124
+ this.nodeSchema = new Map();
125
+ this.edgeSchema = new Map();
126
+ this.graphSchema = new Map();
127
+ this.topSchema = new Map();
128
+ this.nodePlans = new Map();
129
+ this.edgePlans = new Map();
130
+ this.graphPlans = new Map();
131
+ this.topPlans = new Map();
132
+ this.graphNames = new Set();
133
+ this.graphOpen = -1;
134
+ this.directedToken = -1;
135
+ this.multigraphToken = -1;
136
+ this.creatorToken = -1;
137
+ this.versionToken = -1;
138
+ this.nodeCount = 0;
139
+ this.edgeCount = 0;
140
+ this.weightKinds = 0;
141
+ this.hasOriginalId = false;
142
+ this.headerDirected = false;
143
+ this.seq = 0;
144
+ this.nodeOrdinal = 0;
145
+ this.elementsSinceCheck = 0;
146
+ /** The sink id every file id maps to when they differ (label / index / restored ids), else null. */
147
+ this.idMap = null;
148
+ /** Node indices declared by a node block of this import, for duplicate detection. */
149
+ this.declared = new Uint32Array(64);
150
+ /** The list plans touched by the current node or edge. */
151
+ this.touched = [];
152
+ /** The list plans touched by the graph table's keys. */
153
+ this.graphTouched = [];
154
+ /** The sequence number of the current node or edge, which its list items belong to. */
155
+ this.seqNow = 0;
156
+ this.sink = sink;
157
+ this.report = report;
158
+ this.options = options;
159
+ this.positions = format?.positions ?? true;
160
+ this.dictionaries = format?.dictionaries ?? true;
161
+ this.coercer = new IdCoercer(options.ids);
162
+ }
163
+ /**
164
+ * Run the import over a text.
165
+ * @param text - the whole GML text
166
+ */
167
+ run(text) {
168
+ const { report } = this;
169
+ try {
170
+ this.tokens = tokenizeGml(text);
171
+ }
172
+ catch (err) {
173
+ if (err instanceof GmlSyntaxError) {
174
+ report.fail(err.code, err.message, { line: err.line });
175
+ }
176
+ throw err;
177
+ }
178
+ this.scan();
179
+ this.push();
180
+ }
181
+ // ============================================================ pass 1: the schema
182
+ /**
183
+ * Walk the top level: find the graph block, the metadata keys and the top-level attributes,
184
+ * and derive every table's schema.
185
+ */
186
+ scan() {
187
+ const t = this.requireTokens();
188
+ for (let p = 0; p < t.count; p = t.nextPair(p)) {
189
+ const key = t.textOf(p);
190
+ const v = p + 1;
191
+ const record = t.kind[v] === TOKEN_OPEN;
192
+ if (key === "graph" && record) {
193
+ if (this.graphOpen >= 0) {
194
+ this.report.fail(SECOND_GRAPH_CODE, "the input contains more than one graph", {
195
+ line: t.line[p],
196
+ });
197
+ }
198
+ this.graphOpen = v;
199
+ this.scanGraph(v);
200
+ }
201
+ else if (key === "Creator" && !record && this.creatorToken < 0) {
202
+ this.creatorToken = v;
203
+ }
204
+ else if (key === "Version" && !record && this.versionToken < 0) {
205
+ this.versionToken = v;
206
+ }
207
+ else {
208
+ this.observe(this.topSchema, "graph", key, v, TOP_SEQ);
209
+ }
210
+ }
211
+ if (this.graphOpen < 0) {
212
+ this.report.fail(NO_GRAPH_CODE, "the input contains no graph [ ... ] block", { line: null });
213
+ }
214
+ }
215
+ /**
216
+ * Walk the graph block for the schema.
217
+ * @param open - the index of the block's `[`
218
+ */
219
+ scanGraph(open) {
220
+ const t = this.requireTokens();
221
+ const close = t.match[open];
222
+ for (let p = open + 1; p < close; p = t.nextPair(p)) {
223
+ const key = t.textOf(p);
224
+ const v = p + 1;
225
+ switch (key) {
226
+ case "node":
227
+ if (t.kind[v] === TOKEN_OPEN) {
228
+ this.nodeCount++;
229
+ this.scanElement("node", v);
230
+ }
231
+ break;
232
+ case "edge":
233
+ if (t.kind[v] === TOKEN_OPEN) {
234
+ this.edgeCount++;
235
+ this.scanElement("edge", v);
236
+ }
237
+ break;
238
+ case "directed":
239
+ if (this.directedToken < 0) {
240
+ this.directedToken = v;
241
+ }
242
+ break;
243
+ case "multigraph":
244
+ if (this.multigraphToken < 0) {
245
+ this.multigraphToken = v;
246
+ }
247
+ break;
248
+ default:
249
+ this.observe(this.graphSchema, "graph", key, v, GRAPH_SEQ);
250
+ }
251
+ }
252
+ }
253
+ /**
254
+ * Walk one node or edge block for the schema.
255
+ * @param domain - node or edge
256
+ * @param open - the block's `[`
257
+ */
258
+ scanElement(domain, open) {
259
+ const t = this.requireTokens();
260
+ const close = t.match[open];
261
+ const seq = this.seq++;
262
+ const schema = domain === "node" ? this.nodeSchema : this.edgeSchema;
263
+ const { weightFrom, restoreMangledIds } = this.options;
264
+ for (let p = open + 1; p < close; p = t.nextPair(p)) {
265
+ const key = t.textOf(p);
266
+ const v = p + 1;
267
+ if (domain === "node") {
268
+ if (key === "id") {
269
+ continue;
270
+ }
271
+ if (key === ORIGINAL_ID_KEY && restoreMangledIds) {
272
+ this.hasOriginalId = true;
273
+ continue;
274
+ }
275
+ }
276
+ else {
277
+ if (key === "source" || key === "target") {
278
+ continue;
279
+ }
280
+ if (key === weightFrom) {
281
+ this.weightKinds |= kindBit(t, v);
282
+ continue;
283
+ }
284
+ }
285
+ this.observe(schema, domain, key, v, seq);
286
+ }
287
+ }
288
+ /**
289
+ * Record one value of one key in a table's schema.
290
+ * @param schema - the table's schema
291
+ * @param domain - the table
292
+ * @param key - the key
293
+ * @param v - the value token
294
+ * @param seq - the element sequence number
295
+ */
296
+ observe(schema, domain, key, v, seq) {
297
+ const t = this.requireTokens();
298
+ let entry = schema.get(key);
299
+ if (entry === undefined) {
300
+ entry = {
301
+ key,
302
+ kinds: 0,
303
+ list: false,
304
+ lastSeq: seq,
305
+ wide: false,
306
+ unsafe: false,
307
+ dict: this.dictionaries && roleOf(domain, key) === null ? new DictHeuristic() : null,
308
+ position: false,
309
+ rest: false,
310
+ };
311
+ schema.set(key, entry);
312
+ }
313
+ else if (entry.lastSeq === seq) {
314
+ entry.list = true;
315
+ }
316
+ else {
317
+ entry.lastSeq = seq;
318
+ }
319
+ switch (t.kind[v]) {
320
+ case TOKEN_STRING: {
321
+ const raw = t.textOf(v);
322
+ if (raw === LIST_START_MARKER || raw === EMPTY_LIST_TEXT || raw === EMPTY_TUPLE_TEXT) {
323
+ entry.list = true;
324
+ return;
325
+ }
326
+ entry.kinds |= KIND_STRING;
327
+ if (entry.dict !== null && !entry.dict.decided) {
328
+ entry.dict.observe(raw);
329
+ }
330
+ return;
331
+ }
332
+ case TOKEN_INT: {
333
+ entry.kinds |= KIND_INT;
334
+ const n = Number(t.textOf(v));
335
+ if (n < I32_MIN || n > I32_MAX) {
336
+ entry.wide = true;
337
+ if (!Number.isSafeInteger(n)) {
338
+ entry.unsafe = true;
339
+ }
340
+ }
341
+ return;
342
+ }
343
+ case TOKEN_OPEN:
344
+ entry.kinds |= KIND_RECORD;
345
+ if (domain === "node" && key === "graphics" && this.positions) {
346
+ this.inspectGraphics(entry, v);
347
+ }
348
+ return;
349
+ default:
350
+ entry.kinds |= KIND_REAL;
351
+ }
352
+ }
353
+ /**
354
+ * Note whether a node's graphics record carries a position (numeric x and y) and whether
355
+ * anything besides the position remains.
356
+ * @param entry - the graphics schema entry
357
+ * @param open - the record's `[`
358
+ */
359
+ inspectGraphics(entry, open) {
360
+ const t = this.requireTokens();
361
+ const close = t.match[open];
362
+ let x = false;
363
+ let y = false;
364
+ let other = false;
365
+ for (let p = open + 1; p < close; p = t.nextPair(p)) {
366
+ const key = t.textOf(p);
367
+ const numeric = t.kind[p + 1] === TOKEN_INT || t.kind[p + 1] === TOKEN_REAL;
368
+ if (key === "x" && numeric && !x) {
369
+ x = true;
370
+ }
371
+ else if (key === "y" && numeric && !y) {
372
+ y = true;
373
+ }
374
+ else if (!(key === "z" && numeric)) {
375
+ other = true;
376
+ }
377
+ }
378
+ const positioned = x && y;
379
+ entry.position || (entry.position = positioned);
380
+ entry.rest || (entry.rest = positioned ? other : true);
381
+ }
382
+ // ============================================================ pass 2: the push
383
+ /** Declare what the schema needs, set the header and push every element. */
384
+ push() {
385
+ const { sink, report, options } = this;
386
+ const t = this.requireTokens();
387
+ sink.reserve(this.nodeCount, this.edgeCount);
388
+ this.buildPlans();
389
+ this.setMetadata();
390
+ this.headerDirected = this.readFlag(this.directedToken, "directed") ?? options.defaultDirected;
391
+ const resolver = new DirectionResolver(sink, report, options.onMixedDirection);
392
+ resolver.setHeader(this.headerDirected, {
393
+ line: this.directedToken >= 0 ? t.line[this.directedToken] : t.line[this.graphOpen],
394
+ });
395
+ this.resolver = resolver;
396
+ if (options.nodeIdFrom !== "id" || this.hasOriginalId) {
397
+ this.idMap = new Map();
398
+ }
399
+ if (options.nodeIdFrom !== "id") {
400
+ report.loss(ID_DROPPED_CODE, `node ids taken from the ${options.nodeIdFrom}; the integer id keys are not kept as a column`, null, this.nodeCount);
401
+ }
402
+ this.pushTopLevel();
403
+ this.pushNodes();
404
+ this.pushEdges();
405
+ }
406
+ /** Turn every schema entry into a column plan. */
407
+ buildPlans() {
408
+ for (const [key, entry] of this.nodeSchema) {
409
+ this.nodePlans.set(key, this.planOf("node", entry));
410
+ }
411
+ for (const [key, entry] of this.edgeSchema) {
412
+ this.edgePlans.set(key, this.planOf("edge", entry));
413
+ }
414
+ for (const [key, entry] of this.graphSchema) {
415
+ this.graphPlans.set(key, this.planOf("graph", entry));
416
+ }
417
+ for (const [key, entry] of this.topSchema) {
418
+ this.topPlans.set(key, this.planOf("graph", entry, true));
419
+ }
420
+ }
421
+ /**
422
+ * The plan of one schema entry.
423
+ * @param domain - the table
424
+ * @param entry - the schema entry
425
+ * @param top - whether the key is a top-level one (graph table)
426
+ * @returns the plan
427
+ */
428
+ planOf(domain, entry, top = false) {
429
+ const kind = kindOf(entry);
430
+ let scalar = dtypeOfKind(kind, entry);
431
+ if (scalar === "string" &&
432
+ !entry.list &&
433
+ entry.dict !== null &&
434
+ entry.kinds === KIND_STRING &&
435
+ entry.dict.decide() === "dict") {
436
+ scalar = "dict";
437
+ }
438
+ if (entry.unsafe) {
439
+ this.report.warnOnce("precision", PRECISION_CODE, `${domain} key "${entry.key}" holds integers beyond 2^53; they are stored as the nearest f64`, { element: entry.key }, `${PRECISION_CODE}:${domain}:${entry.key}`);
440
+ }
441
+ const name = domain === "graph" ? this.uniqueGraphName(entry.key) : entry.key;
442
+ let itemDtype = null;
443
+ if (entry.list) {
444
+ itemDtype = scalar === "dict" ? "string" : scalar;
445
+ }
446
+ const plan = {
447
+ key: entry.key,
448
+ name,
449
+ dtype: entry.list ? "list" : scalar,
450
+ itemDtype,
451
+ kind,
452
+ list: entry.list,
453
+ role: roleOf(domain, entry.key),
454
+ top,
455
+ position: null,
456
+ rest: null,
457
+ handle: INVALID_INDEX,
458
+ declared: false,
459
+ items: null,
460
+ seq: Number.NEGATIVE_INFINITY,
461
+ };
462
+ if (domain === "node" &&
463
+ entry.key === "graphics" &&
464
+ entry.position &&
465
+ entry.kinds === KIND_RECORD &&
466
+ !entry.list) {
467
+ const taken = (candidate) => this.nodeSchema.has(candidate) || this.sink.nodeColumn(candidate) !== INVALID_INDEX;
468
+ const position = {
469
+ ...plan,
470
+ name: uniqueColumnName("position", "graphics", taken),
471
+ dtype: "f64",
472
+ itemDtype: null,
473
+ kind: "real",
474
+ role: "position",
475
+ };
476
+ const rest = entry.rest ? { ...plan } : null;
477
+ return { ...plan, position, rest };
478
+ }
479
+ return plan;
480
+ }
481
+ /**
482
+ * A graph column name not yet used by this import (top-level and in-graph keys share the table).
483
+ * @param key - the key
484
+ * @returns the name
485
+ */
486
+ uniqueGraphName(key) {
487
+ const name = uniqueColumnName(key, key, (candidate) => this.graphNames.has(candidate));
488
+ this.graphNames.add(name);
489
+ return name;
490
+ }
491
+ /** Set the graph metadata: source format, creator, version, multigraph flag, weight origin. */
492
+ setMetadata() {
493
+ const t = this.requireTokens();
494
+ const { sink, options } = this;
495
+ const textOf = (v) => (t.kind[v] === TOKEN_STRING ? t.stringOf(v) : t.textOf(v));
496
+ const multigraph = this.readFlag(this.multigraphToken, "multigraph");
497
+ sink.setMeta({
498
+ sourceFormat: "gml",
499
+ creator: this.creatorToken >= 0 ? textOf(this.creatorToken) : undefined,
500
+ sourceVersion: this.versionToken >= 0 ? textOf(this.versionToken) : undefined,
501
+ declaredMultigraph: multigraph ?? undefined,
502
+ weightOrigin: this.weightKinds !== 0 && options.weightFrom !== null
503
+ ? {
504
+ format: "gml",
505
+ id: options.weightFrom,
506
+ title: null,
507
+ type: this.weightKinds === KIND_INT ? "int" : "real",
508
+ namespace: null,
509
+ }
510
+ : undefined,
511
+ });
512
+ }
513
+ /**
514
+ * Read a `directed` / `multigraph` flag token.
515
+ * @param v - the value token, or -1 when absent
516
+ * @param name - the flag name, for issues
517
+ * @returns the flag, or null when absent or not an integer
518
+ */
519
+ readFlag(v, name) {
520
+ if (v < 0) {
521
+ return null;
522
+ }
523
+ const t = this.requireTokens();
524
+ if (t.kind[v] !== TOKEN_INT) {
525
+ this.report.error("validation-error", FLAG_TYPE_CODE, `graph flag "${name}" must be the integer 0 or 1, found ${describeValue(t, v)}`, { line: t.line[v], element: name });
526
+ return null;
527
+ }
528
+ const n = Number(t.textOf(v));
529
+ if (n !== 0 && n !== 1) {
530
+ this.report.warning("validation-error", FLAG_VALUE_CODE, `graph flag "${name}" is ${n}; read as ${n !== 0 ? "1" : "0"}`, { line: t.line[v], element: name });
531
+ }
532
+ return n !== 0;
533
+ }
534
+ /** Push the top-level attributes (every top-level key but graph, Creator and Version). */
535
+ pushTopLevel() {
536
+ const t = this.requireTokens();
537
+ for (let p = 0; p < t.count; p = t.nextPair(p)) {
538
+ const v = p + 1;
539
+ if (v === this.graphOpen || v === this.creatorToken || v === this.versionToken) {
540
+ continue;
541
+ }
542
+ const plan = this.topPlans.get(t.textOf(p));
543
+ if (plan !== undefined) {
544
+ this.writeGraph(plan, v, TOP_SEQ);
545
+ }
546
+ }
547
+ this.flushGraphLists();
548
+ }
549
+ /** Push every node block and the graph block's own attributes, in file order. */
550
+ pushNodes() {
551
+ const t = this.requireTokens();
552
+ const close = t.match[this.graphOpen];
553
+ for (let p = this.graphOpen + 1; p < close; p = t.nextPair(p)) {
554
+ const key = t.textOf(p);
555
+ const v = p + 1;
556
+ switch (key) {
557
+ case "node":
558
+ if (t.kind[v] === TOKEN_OPEN) {
559
+ this.importNode(v);
560
+ }
561
+ else {
562
+ this.badElement("node", p);
563
+ this.report.counts.skippedNodes++;
564
+ }
565
+ break;
566
+ case "edge":
567
+ break;
568
+ case "directed":
569
+ case "multigraph":
570
+ if (v !== this.directedToken && v !== this.multigraphToken) {
571
+ this.report.warning("validation-error", FLAG_VALUE_CODE, `graph flag "${key}" repeated; the first value stands`, { line: t.line[p], element: key });
572
+ }
573
+ break;
574
+ default: {
575
+ const plan = this.graphPlans.get(key);
576
+ if (plan !== undefined) {
577
+ this.writeGraph(plan, v, GRAPH_SEQ);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ this.flushGraphLists();
583
+ }
584
+ /** Push every edge block, in file order. */
585
+ pushEdges() {
586
+ const t = this.requireTokens();
587
+ const close = t.match[this.graphOpen];
588
+ let ordinal = 0;
589
+ for (let p = this.graphOpen + 1; p < close; p = t.nextPair(p)) {
590
+ if (t.textOf(p) !== "edge") {
591
+ continue;
592
+ }
593
+ const v = p + 1;
594
+ if (t.kind[v] === TOKEN_OPEN) {
595
+ this.importEdge(v, ordinal);
596
+ }
597
+ else {
598
+ this.badElement("edge", p);
599
+ this.report.counts.skippedEdges++;
600
+ }
601
+ ordinal++;
602
+ }
603
+ }
604
+ /**
605
+ * Record a `node` / `edge` key whose value is not a block.
606
+ * @param what - node or edge
607
+ * @param p - the key token
608
+ */
609
+ badElement(what, p) {
610
+ const t = this.requireTokens();
611
+ this.report.error("validation-error", ELEMENT_TYPE_CODE, `${what} must be a [ ... ] block, found ${describeValue(t, p + 1)}`, { line: t.line[p], element: what });
612
+ }
613
+ /**
614
+ * Push one node block.
615
+ * @param open - the block's `[`
616
+ */
617
+ importNode(open) {
618
+ const t = this.requireTokens();
619
+ const { sink, report, options } = this;
620
+ const close = t.match[open];
621
+ const line = t.line[open];
622
+ const ordinal = this.nodeOrdinal++;
623
+ this.checkAbort();
624
+ let index;
625
+ let sinkId;
626
+ try {
627
+ let idTok = -1;
628
+ let labelTok = -1;
629
+ let originalTok = -1;
630
+ for (let p = open + 1; p < close; p = t.nextPair(p)) {
631
+ const key = t.textOf(p);
632
+ if (key === "id") {
633
+ idTok = this.structuralToken(idTok, p, "id");
634
+ }
635
+ else if (key === "label") {
636
+ labelTok = labelTok < 0 ? p + 1 : labelTok;
637
+ }
638
+ else if (key === ORIGINAL_ID_KEY && options.restoreMangledIds) {
639
+ originalTok = originalTok < 0 ? p + 1 : originalTok;
640
+ }
641
+ }
642
+ if (idTok < 0) {
643
+ throw new GraphFormatError("E_INVALID_ID", "node has no id", { reason: "missing id" });
644
+ }
645
+ const fileId = this.integerOf(idTok, "id");
646
+ if (originalTok >= 0) {
647
+ sinkId = this.restoredId(originalTok);
648
+ }
649
+ else {
650
+ switch (options.nodeIdFrom) {
651
+ case "label":
652
+ if (labelTok < 0) {
653
+ throw new GraphFormatError("E_INVALID_ID", "node has no label", {
654
+ reason: "missing label",
655
+ });
656
+ }
657
+ sinkId = this.coerceValueToken(labelTok);
658
+ break;
659
+ case "index":
660
+ sinkId = ordinal;
661
+ break;
662
+ default:
663
+ sinkId = this.coerceInteger(idTok, fileId);
664
+ }
665
+ }
666
+ if (this.idMap !== null) {
667
+ this.idMap.set(fileId, sinkId);
668
+ }
669
+ index = sink.addNode(sinkId);
670
+ }
671
+ catch (err) {
672
+ this.recordNodeError(err, line);
673
+ report.counts.skippedNodes++;
674
+ return;
675
+ }
676
+ if (this.isDeclared(index)) {
677
+ report.warning("merged", DUPLICATE_NODE_CODE, `node ${JSON.stringify(sinkId)} is declared twice; later keys overwrite`, { line, element: String(sinkId) });
678
+ }
679
+ else {
680
+ this.markDeclared(index);
681
+ report.counts.nodes++;
682
+ }
683
+ this.beginElement(this.seq++);
684
+ try {
685
+ for (let p = open + 1; p < close; p = t.nextPair(p)) {
686
+ const key = t.textOf(p);
687
+ if (key === "id" || (key === ORIGINAL_ID_KEY && options.restoreMangledIds)) {
688
+ continue;
689
+ }
690
+ const plan = this.nodePlans.get(key);
691
+ if (plan !== undefined) {
692
+ this.writeNode(plan, index, p + 1);
693
+ }
694
+ }
695
+ this.flushLists("node", index);
696
+ }
697
+ catch (err) {
698
+ this.touched.length = 0;
699
+ report.recordError(err, { line, element: String(sinkId) });
700
+ }
701
+ }
702
+ /**
703
+ * Push one edge block.
704
+ * @param open - the block's `[`
705
+ * @param ordinal - the edge's ordinal among edge blocks, for messages
706
+ */
707
+ importEdge(open, ordinal) {
708
+ const t = this.requireTokens();
709
+ const { sink, report, options } = this;
710
+ const close = t.match[open];
711
+ const line = t.line[open];
712
+ const element = `edge #${ordinal}`;
713
+ this.checkAbort();
714
+ let edge;
715
+ try {
716
+ let sourceTok = -1;
717
+ let targetTok = -1;
718
+ let weightTok = -1;
719
+ for (let p = open + 1; p < close; p = t.nextPair(p)) {
720
+ const key = t.textOf(p);
721
+ if (key === "source") {
722
+ sourceTok = this.structuralToken(sourceTok, p, "source");
723
+ }
724
+ else if (key === "target") {
725
+ targetTok = this.structuralToken(targetTok, p, "target");
726
+ }
727
+ else if (key === options.weightFrom) {
728
+ weightTok = p + 1;
729
+ }
730
+ }
731
+ if (sourceTok < 0 || targetTok < 0) {
732
+ throw new GraphFormatError("E_UNKNOWN_NODE", `edge has no ${sourceTok < 0 ? "source" : "target"}`, {
733
+ reason: "missing endpoint",
734
+ });
735
+ }
736
+ const source = this.endpoint(sourceTok, "source");
737
+ const target = this.endpoint(targetTok, "target");
738
+ const weight = weightTok >= 0 ? this.weightOf(weightTok) : undefined;
739
+ const before = sink.edgeCount;
740
+ const sourceNew = sink.indexOf(source) === INVALID_INDEX;
741
+ const targetNew = source !== target && sink.indexOf(target) === INVALID_INDEX;
742
+ edge = this.requireResolver().addEdge(source, target, this.headerDirected ? "directed" : "undirected", weight, { line, element });
743
+ report.counts.edges += sink.edgeCount - before;
744
+ // endpoints the file never declares (addMissingNodes) are nodes of the sink too
745
+ report.counts.nodes += (sourceNew ? 1 : 0) + (targetNew ? 1 : 0);
746
+ }
747
+ catch (err) {
748
+ this.recordEdgeError(err, line, element);
749
+ report.counts.skippedEdges++;
750
+ return;
751
+ }
752
+ this.beginElement(this.seq++);
753
+ try {
754
+ for (let p = open + 1; p < close; p = t.nextPair(p)) {
755
+ const key = t.textOf(p);
756
+ if (key === "source" || key === "target" || key === options.weightFrom) {
757
+ continue;
758
+ }
759
+ const plan = this.edgePlans.get(key);
760
+ if (plan !== undefined) {
761
+ this.writeEdge(plan, edge, p + 1);
762
+ }
763
+ }
764
+ this.flushLists("edge", edge);
765
+ }
766
+ catch (err) {
767
+ this.touched.length = 0;
768
+ report.recordError(err, { line, element });
769
+ }
770
+ }
771
+ // ============================================================ ids and weights
772
+ /**
773
+ * Note a structural key token, refusing a repeat.
774
+ * @param previous - the token seen before, or -1
775
+ * @param p - the key token
776
+ * @param key - the key name
777
+ * @returns the value token
778
+ */
779
+ structuralToken(previous, p, key) {
780
+ if (previous >= 0) {
781
+ throw new GraphFormatError("E_INVALID_ID", `key "${key}" appears twice in one block`, {
782
+ reason: "duplicate key",
783
+ key,
784
+ });
785
+ }
786
+ return p + 1;
787
+ }
788
+ /**
789
+ * The integer value of an id / source / target token (the GML grammar's integer ids; a string
790
+ * id is refused, as the malformed corpus pins, although NetworkX would accept it).
791
+ * @param v - the value token
792
+ * @param key - the key name, for the error
793
+ * @returns the number
794
+ */
795
+ integerOf(v, key) {
796
+ const t = this.requireTokens();
797
+ if (t.kind[v] !== TOKEN_INT) {
798
+ throw new GraphFormatError("E_INVALID_ID", `${key} must be an integer, found ${describeValue(t, v)}`, {
799
+ reason: "not an integer",
800
+ key,
801
+ value: t.kind[v] === TOKEN_OPEN ? "[...]" : t.textOf(v),
802
+ });
803
+ }
804
+ return Number(t.textOf(v));
805
+ }
806
+ /**
807
+ * Coerce an integer id token under the `ids` rule: a safe integer passes as a typed number
808
+ * (so `01` is 1 and `-0` is 0), a larger one goes through the text rule (a string under
809
+ * "canonical"), and "string" keeps the text as written.
810
+ * @param v - the value token
811
+ * @param n - its numeric value
812
+ * @returns the id
813
+ */
814
+ coerceInteger(v, n) {
815
+ if (Number.isSafeInteger(n) && this.coercer.mode !== "string") {
816
+ return this.coercer.value(n);
817
+ }
818
+ return this.coercer.text(this.requireTokens().textOf(v));
819
+ }
820
+ /**
821
+ * Coerce a label token under the `ids` rule: a string by its text, a number as a typed value.
822
+ * @param v - the value token
823
+ * @returns the id
824
+ */
825
+ coerceValueToken(v) {
826
+ const t = this.requireTokens();
827
+ switch (t.kind[v]) {
828
+ case TOKEN_STRING:
829
+ return this.coercer.text(t.stringOf(v));
830
+ case TOKEN_INT:
831
+ return this.coerceInteger(v, Number(t.textOf(v)));
832
+ case TOKEN_OPEN:
833
+ throw new GraphFormatError("E_INVALID_ID", "label must be a string or a number, found a record", {
834
+ reason: "record label",
835
+ });
836
+ default:
837
+ return this.coercer.value(numberOfText(t.textOf(v)));
838
+ }
839
+ }
840
+ /**
841
+ * The id a `graphty_originalId` key restores: typed, never coerced (the exporter wrote it exactly).
842
+ * @param v - the value token
843
+ * @returns the original id
844
+ */
845
+ restoredId(v) {
846
+ const t = this.requireTokens();
847
+ switch (t.kind[v]) {
848
+ case TOKEN_STRING:
849
+ return t.stringOf(v);
850
+ case TOKEN_OPEN:
851
+ throw new GraphFormatError("E_INVALID_ID", `${ORIGINAL_ID_KEY} must be a string or a number`, {
852
+ reason: "record original id",
853
+ });
854
+ default:
855
+ return numberOfText(t.textOf(v));
856
+ }
857
+ }
858
+ /**
859
+ * Resolve a source / target token to a sink id.
860
+ * @param v - the value token
861
+ * @param key - source or target
862
+ * @returns the id
863
+ */
864
+ endpoint(v, key) {
865
+ const n = this.integerOf(v, key);
866
+ if (this.idMap !== null) {
867
+ const mapped = this.idMap.get(n);
868
+ if (mapped !== undefined) {
869
+ return mapped;
870
+ }
871
+ }
872
+ return this.coerceInteger(v, n);
873
+ }
874
+ /**
875
+ * The weight of an edge from its weight token.
876
+ * @param v - the value token
877
+ * @returns the weight; E_INVALID_WEIGHT for a record or non-numeric text
878
+ */
879
+ weightOf(v) {
880
+ const t = this.requireTokens();
881
+ switch (t.kind[v]) {
882
+ case TOKEN_STRING:
883
+ return parseWeightText(t.stringOf(v));
884
+ case TOKEN_OPEN:
885
+ throw new GraphFormatError("E_INVALID_WEIGHT", "edge weight is a record", { value: "[...]" });
886
+ default:
887
+ return weightFromValue(numberOfText(t.textOf(v)));
888
+ }
889
+ }
890
+ /**
891
+ * Record a node-level error under the GML code it implies.
892
+ * @param err - the thrown value
893
+ * @param line - the block's line
894
+ */
895
+ recordNodeError(err, line) {
896
+ const { report } = this;
897
+ if (err instanceof GraphFormatError && err.code === "E_INVALID_ID") {
898
+ const { reason } = err.details;
899
+ switch (reason) {
900
+ case "missing id":
901
+ report.error("missing-value", MISSING_ID_CODE, err.message, { line, element: "node" });
902
+ return;
903
+ case "missing label":
904
+ report.error("missing-value", MISSING_LABEL_CODE, err.message, { line, element: "node" });
905
+ return;
906
+ case "duplicate key":
907
+ report.error("validation-error", REPEATED_KEY_CODE, err.message, { line, element: "node" });
908
+ return;
909
+ case "not an integer":
910
+ report.error("validation-error", ID_TYPE_CODE, err.message, { line, element: "node" });
911
+ return;
912
+ default:
913
+ break;
914
+ }
915
+ }
916
+ report.recordError(err, { line, element: "node" });
917
+ }
918
+ /**
919
+ * Record an edge-level error under the GML code it implies.
920
+ * @param err - the thrown value
921
+ * @param line - the block's line
922
+ * @param element - the edge description
923
+ */
924
+ recordEdgeError(err, line, element) {
925
+ const { report } = this;
926
+ if (err instanceof GraphFormatError) {
927
+ const { reason } = err.details;
928
+ if (err.code === "E_UNKNOWN_NODE" && reason === "missing endpoint") {
929
+ report.error("missing-value", MISSING_ENDPOINT_CODE, err.message, { line, element });
930
+ return;
931
+ }
932
+ if (err.code === "E_INVALID_ID" && reason === "duplicate key") {
933
+ report.error("validation-error", REPEATED_KEY_CODE, err.message, { line, element });
934
+ return;
935
+ }
936
+ if (err.code === "E_INVALID_ID" && reason === "not an integer") {
937
+ report.error("validation-error", ID_TYPE_CODE, err.message, { line, element });
938
+ return;
939
+ }
940
+ }
941
+ report.recordError(err, { line, element });
942
+ }
943
+ // ============================================================ values
944
+ /**
945
+ * Write one node value.
946
+ * @param plan - the key's plan
947
+ * @param index - the node index
948
+ * @param v - the value token
949
+ */
950
+ writeNode(plan, index, v) {
951
+ if (plan.position !== null) {
952
+ this.writeGraphics(plan, index, v);
953
+ return;
954
+ }
955
+ if (plan.list) {
956
+ this.collectItem(plan, v, this.seqNow, this.touched);
957
+ return;
958
+ }
959
+ this.sink.setNodeValue(this.handleOf(plan, "node"), index, this.scalarOf(plan, v));
960
+ }
961
+ /**
962
+ * Write one edge value.
963
+ * @param plan - the key's plan
964
+ * @param edge - the edge index
965
+ * @param v - the value token
966
+ */
967
+ writeEdge(plan, edge, v) {
968
+ if (plan.list) {
969
+ this.collectItem(plan, v, this.seqNow, this.touched);
970
+ return;
971
+ }
972
+ this.sink.setEdgeValue(this.handleOf(plan, "edge"), edge, this.scalarOf(plan, v));
973
+ }
974
+ /**
975
+ * Write one graph value.
976
+ * @param plan - the key's plan
977
+ * @param v - the value token
978
+ * @param seq - TOP_SEQ or GRAPH_SEQ
979
+ */
980
+ writeGraph(plan, v, seq) {
981
+ if (plan.list) {
982
+ this.collectItem(plan, v, seq, this.graphTouched);
983
+ return;
984
+ }
985
+ this.sink.setGraphValue(plan.name, this.scalarOf(plan, v), graphDecl(plan));
986
+ }
987
+ /**
988
+ * Write a node's graphics record: the position column from x / y / z, the remaining keys to
989
+ * the json column.
990
+ * @param plan - the graphics plan
991
+ * @param index - the node index
992
+ * @param v - the value token (a record)
993
+ */
994
+ writeGraphics(plan, index, v) {
995
+ const t = this.requireTokens();
996
+ const { sink } = this;
997
+ const record = parseRecord(t, v);
998
+ const { x, y, z } = record;
999
+ const positionPlan = plan.position;
1000
+ if (positionPlan !== null && typeof x === "number" && typeof y === "number") {
1001
+ sink.setNodeValue(this.handleOf(positionPlan, "node"), index, [x, y, typeof z === "number" ? z : 0]);
1002
+ delete record.x;
1003
+ delete record.y;
1004
+ if (typeof z === "number") {
1005
+ delete record.z;
1006
+ }
1007
+ if (plan.rest !== null && Object.keys(record).length > 0) {
1008
+ sink.setNodeValue(this.handleOf(plan.rest, "node"), index, record);
1009
+ }
1010
+ return;
1011
+ }
1012
+ if (plan.rest !== null) {
1013
+ sink.setNodeValue(this.handleOf(plan.rest, "node"), index, record);
1014
+ }
1015
+ }
1016
+ /**
1017
+ * Collect one list item.
1018
+ * @param plan - the list plan
1019
+ * @param v - the value token
1020
+ * @param seq - the sequence number of the element the item belongs to
1021
+ * @param touched - the plans touched by that element
1022
+ */
1023
+ collectItem(plan, v, seq, touched) {
1024
+ const t = this.requireTokens();
1025
+ if (plan.seq !== seq) {
1026
+ plan.seq = seq;
1027
+ plan.items = [];
1028
+ touched.push(plan);
1029
+ }
1030
+ if (t.kind[v] === TOKEN_STRING) {
1031
+ const raw = t.textOf(v);
1032
+ if (raw === LIST_START_MARKER || raw === EMPTY_LIST_TEXT || raw === EMPTY_TUPLE_TEXT) {
1033
+ return;
1034
+ }
1035
+ }
1036
+ plan.items.push(this.scalarOf(plan, v));
1037
+ }
1038
+ /**
1039
+ * Start a node or edge: later list items belong to it.
1040
+ * @param seq - the element's sequence number
1041
+ */
1042
+ beginElement(seq) {
1043
+ this.seqNow = seq;
1044
+ this.touched.length = 0;
1045
+ }
1046
+ /**
1047
+ * Write the lists collected for the current node or edge.
1048
+ * @param domain - node or edge
1049
+ * @param row - the row
1050
+ */
1051
+ flushLists(domain, row) {
1052
+ const { sink, touched } = this;
1053
+ for (const plan of touched) {
1054
+ const handle = this.handleOf(plan, domain);
1055
+ if (domain === "node") {
1056
+ sink.setNodeValue(handle, row, plan.items);
1057
+ }
1058
+ else {
1059
+ sink.setEdgeValue(handle, row, plan.items);
1060
+ }
1061
+ plan.items = null;
1062
+ }
1063
+ touched.length = 0;
1064
+ }
1065
+ /** Write the lists collected for the graph table. */
1066
+ flushGraphLists() {
1067
+ const { sink, graphTouched } = this;
1068
+ for (const plan of graphTouched) {
1069
+ sink.setGraphValue(plan.name, plan.items, graphDecl(plan));
1070
+ plan.items = null;
1071
+ }
1072
+ graphTouched.length = 0;
1073
+ }
1074
+ /**
1075
+ * The JS value of a scalar value token (or list item) under a plan's storage class.
1076
+ * @param plan - the plan
1077
+ * @param v - the value token
1078
+ * @returns the value to push
1079
+ */
1080
+ scalarOf(plan, v) {
1081
+ const t = this.requireTokens();
1082
+ const kind = t.kind[v];
1083
+ switch (plan.kind) {
1084
+ case "int":
1085
+ return Number(t.textOf(v));
1086
+ case "real":
1087
+ return numberOfText(t.textOf(v));
1088
+ case "string":
1089
+ return kind === TOKEN_STRING ? t.stringOf(v) : t.textOf(v);
1090
+ default:
1091
+ return kind === TOKEN_STRING ? t.stringOf(v) : scalarOrRecord(t, v);
1092
+ }
1093
+ }
1094
+ /**
1095
+ * The handle of a plan's column, declaring it on first use. A declaration the sink refuses
1096
+ * because a column of the name exists with another declaration falls back to that column
1097
+ * (reported once); a taken role is dropped (reported once).
1098
+ * @param plan - the plan
1099
+ * @param domain - node or edge
1100
+ * @returns the handle
1101
+ */
1102
+ handleOf(plan, domain) {
1103
+ if (plan.declared) {
1104
+ return plan.handle;
1105
+ }
1106
+ plan.declared = true;
1107
+ const { sink, report } = this;
1108
+ const decl = {
1109
+ name: plan.name,
1110
+ dtype: plan.dtype,
1111
+ nullable: true,
1112
+ origin: { format: "gml", id: plan.key, title: null, type: originTypeOf(plan), namespace: null },
1113
+ };
1114
+ if (plan.list) {
1115
+ decl.itemDtype = plan.itemDtype ?? "string";
1116
+ }
1117
+ if (plan.role === "position") {
1118
+ decl.components = 3;
1119
+ }
1120
+ if (plan.role !== null) {
1121
+ decl.role = plan.role;
1122
+ }
1123
+ const resolved = declareResolved(sink, domain, decl, report, { element: plan.name });
1124
+ plan.handle = resolved.handle;
1125
+ if (resolved.renamed) {
1126
+ plan.name = resolved.decl.name;
1127
+ }
1128
+ return plan.handle;
1129
+ }
1130
+ // ============================================================ bookkeeping
1131
+ /**
1132
+ * Whether a node index was declared by a node block of this import.
1133
+ * @param index - the node index
1134
+ * @returns true when declared
1135
+ */
1136
+ isDeclared(index) {
1137
+ const word = index >>> 5;
1138
+ return word < this.declared.length && ((this.declared[word] >>> (index & 31)) & 1) === 1;
1139
+ }
1140
+ /**
1141
+ * Mark a node index as declared.
1142
+ * @param index - the node index
1143
+ */
1144
+ markDeclared(index) {
1145
+ const word = index >>> 5;
1146
+ if (word >= this.declared.length) {
1147
+ const grown = new Uint32Array(Math.max(word + 1, this.declared.length * 2));
1148
+ grown.set(this.declared);
1149
+ this.declared = grown;
1150
+ }
1151
+ this.declared[word] |= 1 << (index & 31);
1152
+ }
1153
+ /** Check the abort signal every ABORT_CHECK_INTERVAL elements. */
1154
+ checkAbort() {
1155
+ if (++this.elementsSinceCheck >= ABORT_CHECK_INTERVAL) {
1156
+ this.elementsSinceCheck = 0;
1157
+ throwIfAborted(this.options.signal);
1158
+ }
1159
+ }
1160
+ /**
1161
+ * The tokens, which exist after run() lexed the text.
1162
+ * @returns the tokens
1163
+ */
1164
+ requireTokens() {
1165
+ if (this.tokens === null) {
1166
+ throw new GraphFormatError("E_UNSUPPORTED", "the GML text was not lexed", { reason: "no tokens" });
1167
+ }
1168
+ return this.tokens;
1169
+ }
1170
+ /**
1171
+ * The direction resolver, which exists once the header was set.
1172
+ * @returns the resolver
1173
+ */
1174
+ requireResolver() {
1175
+ if (this.resolver === null) {
1176
+ throw new GraphFormatError("E_DIRECTED", "the header was not set", { reason: "no resolver" });
1177
+ }
1178
+ return this.resolver;
1179
+ }
1180
+ }
1181
+ /**
1182
+ * The KIND_* bit of a value token.
1183
+ * @param t - the tokens
1184
+ * @param v - the value token
1185
+ * @returns the bit
1186
+ */
1187
+ function kindBit(t, v) {
1188
+ switch (t.kind[v]) {
1189
+ case TOKEN_INT:
1190
+ return KIND_INT;
1191
+ case TOKEN_STRING:
1192
+ return KIND_STRING;
1193
+ case TOKEN_OPEN:
1194
+ return KIND_RECORD;
1195
+ default:
1196
+ return KIND_REAL;
1197
+ }
1198
+ }
1199
+ /**
1200
+ * The storage class of a schema entry: the widest value class seen.
1201
+ * @param entry - the entry
1202
+ * @returns the class
1203
+ */
1204
+ function kindOf(entry) {
1205
+ if ((entry.kinds & KIND_RECORD) !== 0) {
1206
+ return "record";
1207
+ }
1208
+ if ((entry.kinds & KIND_STRING) !== 0) {
1209
+ return "string";
1210
+ }
1211
+ if ((entry.kinds & KIND_REAL) !== 0) {
1212
+ return "real";
1213
+ }
1214
+ return "int";
1215
+ }
1216
+ /**
1217
+ * The scalar dtype of a storage class.
1218
+ * @param kind - the class
1219
+ * @param entry - the entry (a wide int keeps origin int but stores f64)
1220
+ * @returns the dtype
1221
+ */
1222
+ function dtypeOfKind(kind, entry) {
1223
+ switch (kind) {
1224
+ case "int":
1225
+ return entry.wide ? "f64" : "i32";
1226
+ case "real":
1227
+ return "f64";
1228
+ case "string":
1229
+ return "string";
1230
+ default:
1231
+ return "json";
1232
+ }
1233
+ }
1234
+ /**
1235
+ * The origin.type text of a plan: the GML value class of its values (`int` for wide integers
1236
+ * stored as f64 too, so the exporter writes them without a decimal point).
1237
+ * @param plan - the plan
1238
+ * @returns the type text
1239
+ */
1240
+ function originTypeOf(plan) {
1241
+ return plan.kind;
1242
+ }
1243
+ /**
1244
+ * The declaration patch of a graph column.
1245
+ * @param plan - the plan
1246
+ * @returns the decl for setGraphValue
1247
+ */
1248
+ function graphDecl(plan) {
1249
+ const decl = {
1250
+ name: plan.name,
1251
+ dtype: plan.dtype,
1252
+ nullable: true,
1253
+ origin: { format: "gml", id: plan.key, title: null, type: originTypeOf(plan), namespace: null },
1254
+ };
1255
+ if (plan.list) {
1256
+ decl.itemDtype = plan.itemDtype ?? "string";
1257
+ }
1258
+ if (plan.top) {
1259
+ decl.extra = { gmlTopLevel: true };
1260
+ }
1261
+ return decl;
1262
+ }
1263
+ /**
1264
+ * A short description of a value token for messages.
1265
+ * @param t - the tokens
1266
+ * @param v - the value token
1267
+ * @returns the description
1268
+ */
1269
+ function describeValue(t, v) {
1270
+ switch (t.kind[v]) {
1271
+ case TOKEN_OPEN:
1272
+ return "a record";
1273
+ case TOKEN_STRING:
1274
+ return `the string "${t.textOf(v)}"`;
1275
+ case TOKEN_REAL:
1276
+ return `the real ${t.textOf(v)}`;
1277
+ case TOKEN_WORD:
1278
+ return `the word ${t.textOf(v)}`;
1279
+ default:
1280
+ return t.textOf(v);
1281
+ }
1282
+ }
1283
+ const SNIFF_GRAPH_START = /^(?:\s|#[^\n]*\n)*graph\s*\[/;
1284
+ const SNIFF_GRAPH_ANYWHERE = /(?:^|\s)graph\s*\[/;
1285
+ const SNIFF_KEY_START = /^(?:\s|#[^\n]*\n)*[A-Za-z_][0-9A-Za-z_]*\s+(?:"|[+-]?[0-9.]|\[)/;
1286
+ /**
1287
+ * Confidence that a head of bytes is GML: a `graph [` opener, or key-value text with a `graph [`
1288
+ * somewhere in the head.
1289
+ * @param head - the first bytes of the input
1290
+ * @returns 0.95 for a leading `graph [`, 0.85 for key-value text containing one, 0.4 for key-value text, 0 otherwise
1291
+ */
1292
+ function sniffGml(head) {
1293
+ let text = new TextDecoder("utf-8", { fatal: false }).decode(head);
1294
+ if (text.charCodeAt(0) === 0xfeff) {
1295
+ text = text.slice(1);
1296
+ }
1297
+ if (SNIFF_GRAPH_START.test(text)) {
1298
+ return 0.95;
1299
+ }
1300
+ if (SNIFF_KEY_START.test(text)) {
1301
+ return SNIFF_GRAPH_ANYWHERE.test(text) ? 0.85 : 0.4;
1302
+ }
1303
+ return 0;
1304
+ }
1305
+ /** The GML importer plugin. */
1306
+ export const gmlImporter = Object.freeze({
1307
+ format: "gml",
1308
+ extensions: Object.freeze([".gml"]),
1309
+ mimeTypes: Object.freeze(["text/x-gml", "text/plain"]),
1310
+ sniff: sniffGml,
1311
+ /**
1312
+ * Read a GML text into a sink.
1313
+ * @param input - the text, bytes or stream
1314
+ * @param sink - the sink
1315
+ * @param options - format-specific and common options
1316
+ * @returns the report
1317
+ */
1318
+ async import(input, sink, options) {
1319
+ const resolved = resolveImportOptions(options, FORMAT_DEFAULTS);
1320
+ const report = new ImportReportBuilder("gml", resolved.errorLimit);
1321
+ reportSinkOptions(sink, options, report);
1322
+ reportUnusedOptions(options, report, USED_OPTIONS);
1323
+ const text = await readText(input, report, resolved);
1324
+ throwIfAborted(resolved.signal);
1325
+ new GmlImport(sink, report, resolved, options).run(text);
1326
+ // an abort raised during the last few elements (after the last periodic check) still rejects
1327
+ throwIfAborted(resolved.signal);
1328
+ return report.finish();
1329
+ },
1330
+ });
1331
+ //# sourceMappingURL=importer.js.map