@mailwoman/resolver-wof-sqlite 11.1.0 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +5 -5
  2. package/lib/ancestry/backfill.ts +13 -43
  3. package/lib/build/candidate.ts +42 -2
  4. package/lib/candidate/alias-bags.ts +54 -14
  5. package/lib/candidate/importance.ts +4 -3
  6. package/lib/candidate/key-fold.ts +132 -0
  7. package/lib/candidate/lookup.ts +23 -13
  8. package/lib/candidate/nickname-namesakes.ts +140 -0
  9. package/lib/fst/binary-matcher.ts +26 -41
  10. package/lib/fst/format.ts +144 -7
  11. package/lib/fst/serialize.ts +92 -63
  12. package/lib/geonames/aliases.ts +8 -15
  13. package/lib/importance-source.ts +210 -0
  14. package/lib/primary-preference.ts +40 -2
  15. package/lib/street/normalize.ts +42 -0
  16. package/out/ancestry/backfill.d.ts +14 -9
  17. package/out/ancestry/backfill.d.ts.map +1 -1
  18. package/out/ancestry/backfill.js +4 -42
  19. package/out/ancestry/backfill.js.map +1 -1
  20. package/out/build/candidate.d.ts +20 -0
  21. package/out/build/candidate.d.ts.map +1 -1
  22. package/out/build/candidate.js +14 -2
  23. package/out/build/candidate.js.map +1 -1
  24. package/out/candidate/alias-bags.d.ts +8 -0
  25. package/out/candidate/alias-bags.d.ts.map +1 -1
  26. package/out/candidate/alias-bags.js +43 -12
  27. package/out/candidate/alias-bags.js.map +1 -1
  28. package/out/candidate/importance.d.ts.map +1 -1
  29. package/out/candidate/importance.js +4 -3
  30. package/out/candidate/importance.js.map +1 -1
  31. package/out/candidate/key-fold.d.ts +55 -0
  32. package/out/candidate/key-fold.d.ts.map +1 -0
  33. package/out/candidate/key-fold.js +80 -0
  34. package/out/candidate/key-fold.js.map +1 -0
  35. package/out/candidate/lookup.d.ts.map +1 -1
  36. package/out/candidate/lookup.js +22 -12
  37. package/out/candidate/lookup.js.map +1 -1
  38. package/out/candidate/nickname-namesakes.d.ts +32 -0
  39. package/out/candidate/nickname-namesakes.d.ts.map +1 -0
  40. package/out/candidate/nickname-namesakes.js +98 -0
  41. package/out/candidate/nickname-namesakes.js.map +1 -0
  42. package/out/fst/binary-matcher.d.ts.map +1 -1
  43. package/out/fst/binary-matcher.js +9 -30
  44. package/out/fst/binary-matcher.js.map +1 -1
  45. package/out/fst/format.d.ts +60 -9
  46. package/out/fst/format.d.ts.map +1 -1
  47. package/out/fst/format.js +97 -6
  48. package/out/fst/format.js.map +1 -1
  49. package/out/fst/serialize.d.ts.map +1 -1
  50. package/out/fst/serialize.js +66 -54
  51. package/out/fst/serialize.js.map +1 -1
  52. package/out/geonames/aliases.d.ts.map +1 -1
  53. package/out/geonames/aliases.js +7 -11
  54. package/out/geonames/aliases.js.map +1 -1
  55. package/out/importance-source.d.ts +90 -0
  56. package/out/importance-source.d.ts.map +1 -0
  57. package/out/importance-source.js +133 -0
  58. package/out/importance-source.js.map +1 -0
  59. package/out/primary-preference.d.ts +20 -1
  60. package/out/primary-preference.d.ts.map +1 -1
  61. package/out/primary-preference.js +31 -1
  62. package/out/primary-preference.js.map +1 -1
  63. package/out/street/normalize.d.ts +19 -0
  64. package/out/street/normalize.d.ts.map +1 -1
  65. package/out/street/normalize.js +38 -0
  66. package/out/street/normalize.js.map +1 -1
  67. package/package.json +12 -12
@@ -0,0 +1,140 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file The candidate build's nickname refusal: a colloquial or unclassified name doesn't become an
6
+ * alias row when a populated place holds the same key by a real name.
7
+ */
8
+
9
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
10
+ import { tableExists } from "@mailwoman/sqlite/introspection"
11
+
12
+ import type { PlaceAttrs } from "#candidate/place-attrs"
13
+ import type { CandidateDatabase } from "#candidate/schema"
14
+ import type { WOFDatabase } from "#schema"
15
+ import { normalizeLocalityForKey, withoutApostropheLikeMarks } from "#street/normalize"
16
+
17
+ /**
18
+ * The WOF name kinds that name a place without being its name: a colloquial name
19
+ * (`Motor City`, `T.O.`) and an unclassified one.
20
+ * An unclassified name is mostly a code (`DE`, `AP`, `GTA`).
21
+ */
22
+ const NICKNAME_KINDS: readonly string[] = ["colloquial", "unknown"]
23
+
24
+ /**
25
+ * The keys a name stages as alias rows: its key, and its mark-free form when that differs.
26
+ */
27
+ function stagedKeys(name: string): string[] {
28
+ const k = normalizeLocalityForKey(name)
29
+
30
+ if (!k) return []
31
+ const free = withoutApostropheLikeMarks(k)
32
+
33
+ return free && free !== k ? [k, free] : [k]
34
+ }
35
+
36
+ /**
37
+ * Deletes the alias rows a place holds only through a colloquial or unclassified name,
38
+ * when another place with a population holds the same key by any other name.
39
+ *
40
+ * The candidate ranks a key's rows by population, so a nickname of a large place outranks
41
+ * every smaller place whose own name the nickname spells: `T.O.` and `To.`
42
+ * (Toronto) over Tó, `Garden City` (Victoria) over each Garden City, `DE` (Germany) over Delaware's `DE`.
43
+ *
44
+ * A namesake without a population ranks last under any populated holder, so a nickname whose
45
+ * only namesakes are unpopulated stays: `Motor City` keeps Detroit over Motor City, California.
46
+ * A nickname that several places share also stays when no other place holds its key
47
+ * by a real name (`The Windy City` for Chicago and Wellington).
48
+ *
49
+ * Runs on `cand_stage` after the primaries, aliases and abbreviations are staged,
50
+ * and before the postcode extracts.
51
+ * A postcode row stores no population.
52
+ *
53
+ * @returns The count of alias rows deleted, and of distinct keys they held.
54
+ */
55
+ export function refuseNicknamesOfNamesakes(
56
+ src: DatabaseClient<WOFDatabase>,
57
+ out: DatabaseClient<CandidateDatabase>,
58
+ attrs: Map<number, PlaceAttrs>
59
+ ): { rows: number; keys: number } {
60
+ if (!tableExists(src, "names")) return { rows: 0, keys: 0 }
61
+
62
+ const kinds = NICKNAME_KINDS.map(() => "?").join(", ")
63
+ const nicknameKeys = new Map<number, Set<string>>()
64
+
65
+ for (const r of src.prepare(`SELECT id, name FROM names WHERE privateuse IN (${kinds})`).iterate(...NICKNAME_KINDS)) {
66
+ const id = Number(r.id)
67
+
68
+ if (!attrs.has(id)) continue
69
+ let keys = nicknameKeys.get(id)
70
+
71
+ if (!keys) {
72
+ keys = new Set()
73
+ nicknameKeys.set(id, keys)
74
+ }
75
+
76
+ for (const k of stagedKeys(String(r.name ?? ""))) {
77
+ keys.add(k)
78
+ }
79
+ }
80
+
81
+ if (!nicknameKeys.size) return { rows: 0, keys: 0 }
82
+
83
+ // A key the place also holds by a real name belongs to that name's row and is never refused.
84
+ const realNames = src.prepare(`SELECT name FROM names WHERE id = ? AND privateuse NOT IN (${kinds})`)
85
+ const abbrs = tableExists(src, "place_abbr") ? src.prepare("SELECT abbr FROM place_abbr WHERE id = ?") : null
86
+
87
+ const ownKeys = (id: number): string[] => [
88
+ ...stagedKeys(attrs.get(id)?.name ?? ""),
89
+ ...realNames.all(id, ...NICKNAME_KINDS).flatMap((r) => stagedKeys(String(r.name ?? ""))),
90
+ ...(abbrs?.all(id).flatMap((r) => stagedKeys(String(r.abbr ?? ""))) ?? []),
91
+ ]
92
+
93
+ out.exec(
94
+ "CREATE TEMP TABLE nickname_key (spr_id INTEGER NOT NULL, name_key TEXT NOT NULL, PRIMARY KEY (spr_id, name_key)) WITHOUT ROWID"
95
+ )
96
+
97
+ const insNickname = out.prepare("INSERT OR IGNORE INTO nickname_key VALUES (?, ?)")
98
+ out.exec("BEGIN")
99
+
100
+ for (const [id, keys] of nicknameKeys) {
101
+ for (const k of ownKeys(id)) {
102
+ keys.delete(k)
103
+ }
104
+
105
+ for (const k of keys) {
106
+ insNickname.run(id, k)
107
+ }
108
+ }
109
+
110
+ out.exec("COMMIT")
111
+
112
+ out.exec("CREATE INDEX temp.nickname_key_by_key ON nickname_key (name_key)")
113
+ out.exec("CREATE TEMP TABLE namesake_key (name_key TEXT PRIMARY KEY) WITHOUT ROWID")
114
+
115
+ out.exec(
116
+ `INSERT OR IGNORE INTO namesake_key
117
+ SELECT cs.name_key FROM cand_stage cs
118
+ WHERE cs.population > 0
119
+ AND cs.name_key IN (SELECT name_key FROM nickname_key)
120
+ AND NOT EXISTS (SELECT 1 FROM nickname_key nk WHERE nk.spr_id = cs.spr_id AND nk.name_key = cs.name_key)`
121
+ )
122
+
123
+ const keys = Number(out.prepare("SELECT count(*) AS n FROM namesake_key").get()!["n"])
124
+
125
+ const rows = Number(
126
+ out
127
+ .prepare(
128
+ `DELETE FROM cand_stage
129
+ WHERE is_primary = 0
130
+ AND name_key IN (SELECT name_key FROM namesake_key)
131
+ AND EXISTS (SELECT 1 FROM nickname_key nk WHERE nk.spr_id = cand_stage.spr_id AND nk.name_key = cand_stage.name_key)`
132
+ )
133
+ .run().changes
134
+ )
135
+
136
+ out.exec("DROP TABLE namesake_key")
137
+ out.exec("DROP TABLE nickname_key")
138
+
139
+ return { rows, keys }
140
+ }
@@ -16,17 +16,16 @@ import type { AncestrieMatch } from "@mailwoman/ancestrie"
16
16
  import { hashFNV1a } from "@mailwoman/core/coarse-placer/fnv-hash"
17
17
 
18
18
  import {
19
+ decodePlaceEntry,
20
+ idTableOffset,
21
+ loadIDTable,
19
22
  EDGE_ENTRY_SIZE,
20
- ENCYCLOPEDIC_OFFSET,
21
23
  FST_FORMAT_VERSION,
22
24
  FST_MAGIC_BYTES,
23
25
  HEADER_SIZE,
24
- LEGACY_PLACE_ENTRY_SIZE,
25
26
  NARROW_STATE_ENTRY_SIZE,
26
- PLACE_FLAG_HAS_ENCYCLOPEDIC,
27
- PLACETYPE_ORDER,
28
- SPLIT_PLACE_ENTRY_SIZE,
29
- VERSION_TWO_SCORE_SPLIT,
27
+ placeEntryLayout,
28
+ type PlaceEntryLayout,
30
29
  VERSION_WIDE_STATE_COUNTERS,
31
30
  WIDE_STATE_ENTRY_SIZE,
32
31
  } from "#fst/format"
@@ -71,10 +70,13 @@ export class BinaryFSTMatcher {
71
70
  readonly #decoder = new TextDecoder("utf-8")
72
71
  readonly #version: number
73
72
  readonly #isWide: boolean
74
- readonly #isSplit: boolean
75
73
  readonly #hasAmbiguity: boolean
76
74
  readonly #stateEntrySize: number
77
- readonly #placeEntrySize: number
75
+ readonly #placeLayout: PlaceEntryLayout
76
+ /**
77
+ * The file's id table, or `null` for a file that stores WOF ids in its place entries.
78
+ */
79
+ readonly #ids: Float64Array | null
78
80
  readonly #stringDataStart: number
79
81
  readonly #stateTableStart: number
80
82
  readonly #edgeTableStart: number
@@ -106,12 +108,10 @@ export class BinaryFSTMatcher {
106
108
  this.#view = view
107
109
  this.#version = version
108
110
  this.#isWide = version >= VERSION_WIDE_STATE_COUNTERS
109
- this.#isSplit = version >= VERSION_TWO_SCORE_SPLIT
110
111
  // Flags bit 0, as `serializeFST` writes it: place rows include surface-ambiguity data.
111
112
  this.#hasAmbiguity = (view.getUint16(6, true) & 1) === 1
112
113
  this.#stateEntrySize = this.#isWide ? WIDE_STATE_ENTRY_SIZE : NARROW_STATE_ENTRY_SIZE
113
- // Version 5 grew the place entry by the encyclopedic float.
114
- this.#placeEntrySize = this.#isSplit ? SPLIT_PLACE_ENTRY_SIZE : LEGACY_PLACE_ENTRY_SIZE
114
+ this.#placeLayout = placeEntryLayout(version)
115
115
 
116
116
  const stateCount = view.getUint32(8, true)
117
117
  const edgeCount = view.getUint32(12, true)
@@ -130,6 +130,12 @@ export class BinaryFSTMatcher {
130
130
  this.#edgeTableStart = this.#stateTableStart + stateCount * this.#stateEntrySize
131
131
  this.#placeTableStart = this.#edgeTableStart + edgeCount * EDGE_ENTRY_SIZE
132
132
 
133
+ this.#ids = loadIDTable(
134
+ view,
135
+ idTableOffset(this.#placeTableStart, view.getUint32(16, true), this.#placeLayout),
136
+ this.#placeLayout
137
+ )
138
+
133
139
  this.#tokenSlots = new Int32Array(tableCapacity(stringCount)).fill(EMPTY_SLOT)
134
140
 
135
141
  const edgeCapacity = tableCapacity(edgeCount)
@@ -346,35 +352,14 @@ export class BinaryFSTMatcher {
346
352
  }
347
353
 
348
354
  #placeAt(placeIndex: number): PlaceEntry {
349
- const view = this.#view
350
- const entry = this.#placeTableStart + placeIndex * this.#placeEntrySize
351
- const chainLength = view.getUint8(entry + 5)
352
- const parentChain: number[] = new Array(chainLength)
353
-
354
- for (let index = 0; index < chainLength; index++) {
355
- parentChain[index] = view.getUint32(entry + 24 + index * 4, true)
356
- }
357
-
358
- // Version 1 stored a raw population u32 here, and later versions store the referential score.
359
- // `deserializeFST` explains why a version 1 value converts to the referential score this way.
360
- const referential =
361
- this.#version >= 2
362
- ? view.getFloat32(entry + 12, true)
363
- : Math.min(1, Math.log2(1 + view.getUint32(entry + 12, true) / 1000) / 14)
364
-
365
- const hasEncyclopedic =
366
- this.#isSplit && (view.getUint8(entry + 7) & PLACE_FLAG_HAS_ENCYCLOPEDIC) === PLACE_FLAG_HAS_ENCYCLOPEDIC
367
-
368
- return {
369
- wofID: view.getUint32(entry, true),
370
- placetype: PLACETYPE_ORDER[view.getUint8(entry + 4)] ?? "locality",
371
- name: this.#string(view.getUint32(entry + 8, true)),
372
- referential,
373
- lat: view.getFloat32(entry + 16, true),
374
- lon: view.getFloat32(entry + 20, true),
375
- parentChain,
376
- crossCountryBranches: this.#hasAmbiguity ? view.getUint8(entry + 6) : null,
377
- encyclopedic: hasEncyclopedic ? view.getFloat32(entry + ENCYCLOPEDIC_OFFSET, true) : null,
378
- }
355
+ return decodePlaceEntry(
356
+ this.#view,
357
+ this.#placeTableStart + placeIndex * this.#placeLayout.size,
358
+ this.#version,
359
+ this.#placeLayout,
360
+ this.#hasAmbiguity,
361
+ (index) => this.#string(index),
362
+ this.#ids
363
+ )
379
364
  }
380
365
  }
package/lib/fst/format.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  * Both runtimes convert {@link FST_MAGIC_BYTES} themselves.
11
11
  */
12
12
 
13
- import type { PlacetypeID } from "#fst/types"
13
+ import type { PlaceEntry, PlacetypeID } from "#fst/types"
14
14
 
15
15
  /**
16
16
  * Format version this tree writes and the maximum either deserializer accepts, published
@@ -27,7 +27,7 @@ import type { PlacetypeID } from "#fst/types"
27
27
  *
28
28
  * A check that's the writer's version cannot drift from it.
29
29
  */
30
- export const FST_FORMAT_VERSION = 5
30
+ export const FST_FORMAT_VERSION = 6
31
31
 
32
32
  /**
33
33
  * Fixed header size in bytes.
@@ -75,18 +75,155 @@ export const VERSION_TWO_SCORE_SPLIT = 5
75
75
  /**
76
76
  * Place-entry size in bytes at or above {@link VERSION_TWO_SCORE_SPLIT}.
77
77
  */
78
- export const SPLIT_PLACE_ENTRY_SIZE = 60
78
+ const SPLIT_PLACE_ENTRY_SIZE = 60
79
79
 
80
80
  /**
81
81
  * Place-entry size in bytes below {@link VERSION_TWO_SCORE_SPLIT}.
82
82
  */
83
- export const LEGACY_PLACE_ENTRY_SIZE = 56
83
+ const LEGACY_PLACE_ENTRY_SIZE = 56
84
84
 
85
85
  /**
86
- * Byte offset of the encyclopedic float inside a v5 place entry — immediately
87
- * after the 8-slot parent chain.
86
+ * Format version that moved WOF ids into an id table.
87
+ *
88
+ * A place entry's id and its parent ids are u32 indices into the table.
89
+ * The table follows the place table as a u32 count and one f64 per distinct id in ascending order.
90
+ *
91
+ * The `mailwoman` fork's WOF records take ids from 9,895,000,000, above the u32 maximum of 4,294,967,295.
92
+ *
93
+ * An f64 holds every integer up to 2^53 exactly.
94
+ * Each distinct id is stored once, so a file grows by 8 bytes per distinct id
95
+ * rather than by 36 bytes per place entry.
96
+ */
97
+ export const VERSION_ID_TABLE = 6
98
+
99
+ /**
100
+ * The number of parent-id slots in every place entry.
101
+ */
102
+ export const PARENT_CHAIN_SLOTS = 8
103
+
104
+ /**
105
+ * Where each field of a place entry sits, in bytes from the entry's start, for one format version.
106
+ */
107
+ export interface PlaceEntryLayout {
108
+ size: number
109
+ /**
110
+ * Whether the id fields hold indices into the id table ({@link VERSION_ID_TABLE}) rather than WOF ids.
111
+ */
112
+ idTable: boolean
113
+ placetype: number
114
+ chainLength: number
115
+ crossCountryBranches: number
116
+ flags: number
117
+ name: number
118
+ referential: number
119
+ latitude: number
120
+ longitude: number
121
+ chain: number
122
+ /**
123
+ * `null` before {@link VERSION_TWO_SCORE_SPLIT}, which had no encyclopedic score.
124
+ */
125
+ encyclopedic: number | null
126
+ }
127
+
128
+ /**
129
+ * The place-entry layout of format `version`.
88
130
  */
89
- export const ENCYCLOPEDIC_OFFSET = 56
131
+ export function placeEntryLayout(version: number): PlaceEntryLayout {
132
+ return {
133
+ size: version >= VERSION_TWO_SCORE_SPLIT ? SPLIT_PLACE_ENTRY_SIZE : LEGACY_PLACE_ENTRY_SIZE,
134
+ idTable: version >= VERSION_ID_TABLE,
135
+ placetype: 4,
136
+ chainLength: 5,
137
+ crossCountryBranches: 6,
138
+ flags: 7,
139
+ name: 8,
140
+ referential: 12,
141
+ latitude: 16,
142
+ longitude: 20,
143
+ chain: 24,
144
+ encyclopedic: version >= VERSION_TWO_SCORE_SPLIT ? 24 + PARENT_CHAIN_SLOTS * 4 : null,
145
+ }
146
+ }
147
+
148
+ /**
149
+ * The byte offset of the id table.
150
+ * The table starts where the place table ends.
151
+ */
152
+ export function idTableOffset(placeTableStart: number, placeCount: number, layout: PlaceEntryLayout): number {
153
+ return placeTableStart + placeCount * layout.size
154
+ }
155
+
156
+ /**
157
+ * The WOF ids an id-table file stores, in table order, or `null` for a file
158
+ * before {@link VERSION_ID_TABLE}.
159
+ */
160
+ export function loadIDTable(view: DataView, offset: number, layout: PlaceEntryLayout): Float64Array | null {
161
+ if (!layout.idTable) return null
162
+ const count = view.getUint32(offset, true)
163
+ const ids = new Float64Array(count)
164
+
165
+ for (let index = 0; index < count; index++) {
166
+ ids[index] = view.getFloat64(offset + 4 + index * 8, true)
167
+ }
168
+
169
+ return ids
170
+ }
171
+
172
+ /**
173
+ * Decodes the place entry at byte `entry` of a format-`version` file.
174
+ *
175
+ * Both deserializers call this, so a layout change reaches the Node and the browser readers together.
176
+ * `string` resolves a string-table index.
177
+ *
178
+ * `ids` is the file's id table, `null` before {@link VERSION_ID_TABLE}.
179
+ * `hasAmbiguity` is the header's flag bit 0.
180
+ */
181
+ export function decodePlaceEntry(
182
+ view: DataView,
183
+ entry: number,
184
+ version: number,
185
+ layout: PlaceEntryLayout,
186
+ hasAmbiguity: boolean,
187
+ string: (index: number) => string,
188
+ ids: Float64Array | null
189
+ ): PlaceEntry {
190
+ const readID = (offset: number) => {
191
+ const value = view.getUint32(entry + offset, true)
192
+
193
+ return ids ? ids[value]! : value
194
+ }
195
+
196
+ const chainLength = view.getUint8(entry + layout.chainLength)
197
+ const parentChain: number[] = new Array(chainLength)
198
+
199
+ for (let index = 0; index < chainLength; index++) {
200
+ parentChain[index] = readID(layout.chain + index * 4)
201
+ }
202
+
203
+ // Version 1 stored a raw population u32 where later versions store the referential score.
204
+ // It maps through the `referentialFromPopulation` curve.
205
+ const referential =
206
+ version >= 2
207
+ ? view.getFloat32(entry + layout.referential, true)
208
+ : Math.min(1, Math.log2(1 + view.getUint32(entry + layout.referential, true) / 1000) / 14)
209
+
210
+ // Files before version 5 have no encyclopedic score, so their reserved flag byte isn't read.
211
+ const hasEncyclopedic =
212
+ layout.encyclopedic !== null &&
213
+ (view.getUint8(entry + layout.flags) & PLACE_FLAG_HAS_ENCYCLOPEDIC) === PLACE_FLAG_HAS_ENCYCLOPEDIC
214
+
215
+ return {
216
+ wofID: readID(0),
217
+ placetype: PLACETYPE_ORDER[view.getUint8(entry + layout.placetype)] ?? "locality",
218
+ name: string(view.getUint32(entry + layout.name, true)),
219
+ referential,
220
+ lat: view.getFloat32(entry + layout.latitude, true),
221
+ lon: view.getFloat32(entry + layout.longitude, true),
222
+ parentChain,
223
+ crossCountryBranches: hasAmbiguity ? view.getUint8(entry + layout.crossCountryBranches) : null,
224
+ encyclopedic: hasEncyclopedic ? view.getFloat32(entry + layout.encyclopedic!, true) : null,
225
+ }
226
+ }
90
227
 
91
228
  /**
92
229
  * `placeFlags` bit 0 (byte `pp+7`, v5+): this place has an encyclopedic score.
@@ -14,9 +14,10 @@
14
14
  * 4 the entry is 12 bytes with u16 counts.
15
15
  * - Edge table, 8 bytes per edge: stringIdx u32, targetState u32.
16
16
  * - Place table, 60 bytes per place: wofID u32, placetypeIdx u8, chainLen u8, crossCountryBranches u8,
17
- * placeFlags u8 (bit 0 means `encyclopedic` is present), nameIdx u32, referential f32, lat f32, lon f32.
18
- * Each entry then stores eight u32 parent ids. Version 5 added encyclopedic f32. Earlier entries contain 56 bytes.
19
- * Those entries have no encyclopedic score.
17
+ * placeFlags u8 (bit 0 means `encyclopedic` is present), nameIdx u32, referential f32, lat f32, lon f32,
18
+ * eight u32 parent ids, encyclopedic f32. From version 6 the wofID and parent-id fields are indices into
19
+ * the id table. Before version 5 the entry is 56 bytes with no encyclopedic score.
20
+ * - Id table, from version 6: a u32 count, then one f64 WOF id per distinct id, ascending.
20
21
  * - Provenance trailer: a u32 length followed by JSON.
21
22
  *
22
23
  * Presence bits keep a missing value distinct from a stored zero.
@@ -25,17 +26,18 @@
25
26
  import { tryParsingJSON, stringifyJSON } from "@mailwoman/core/json"
26
27
 
27
28
  import {
29
+ decodePlaceEntry,
30
+ idTableOffset,
31
+ loadIDTable,
28
32
  EDGE_ENTRY_SIZE,
29
- ENCYCLOPEDIC_OFFSET,
30
33
  FST_FORMAT_VERSION,
31
34
  FST_MAGIC_BYTES,
32
35
  HEADER_SIZE,
33
- LEGACY_PLACE_ENTRY_SIZE,
34
36
  NARROW_STATE_ENTRY_SIZE,
37
+ PARENT_CHAIN_SLOTS,
35
38
  PLACE_FLAG_HAS_ENCYCLOPEDIC,
36
39
  PLACETYPE_ORDER,
37
- SPLIT_PLACE_ENTRY_SIZE,
38
- VERSION_TWO_SCORE_SPLIT,
40
+ placeEntryLayout,
39
41
  VERSION_WIDE_STATE_COUNTERS,
40
42
  VERSION_WITH_METADATA,
41
43
  WIDE_STATE_ENTRY_SIZE,
@@ -47,11 +49,46 @@ import type { FSTProvenance, PlaceEntry } from "#fst/types"
47
49
  const MAGIC = Buffer.from(FST_MAGIC_BYTES)
48
50
 
49
51
  /**
50
- * The longest parent chain stored per place.
52
+ * The place-entry layout this writer emits.
53
+ */
54
+ const PLACE_LAYOUT = placeEntryLayout(FST_FORMAT_VERSION)
55
+
56
+ /**
57
+ * The id table for `nodes`: every place's id and its first {@link PARENT_CHAIN_SLOTS}
58
+ * valid parent ids, distinct and ascending, with each id's index.
51
59
  *
52
- * The writer keeps the first eight valid parent ids and drops the rest.
60
+ * @throws When an id isn't a safe integer.
61
+ * An f64 holds only safe integers exactly.
53
62
  */
54
- const MAX_CHAIN_LEN = 8
63
+ function buildIDTable(nodes: readonly FSTNode[]): { ids: number[]; indexOf: Map<number, number> } {
64
+ const distinct = new Set<number>()
65
+
66
+ for (const node of nodes) {
67
+ for (const place of node.places) {
68
+ distinct.add(place.wofID)
69
+
70
+ for (const id of validParentChain(place.parentChain)) {
71
+ distinct.add(id)
72
+ }
73
+ }
74
+ }
75
+
76
+ const ids = [...distinct].toSorted((a, b) => a - b)
77
+
78
+ for (const id of ids) {
79
+ if (!Number.isSafeInteger(id)) throw new RangeError(`serializeFST: WOF id ${id} is not a safe integer`)
80
+ }
81
+
82
+ return { ids, indexOf: new Map(ids.map((id, index) => [id, index])) }
83
+ }
84
+
85
+ /**
86
+ * The parent ids a place entry stores: the first eight positive ids,
87
+ * since WOF uses negative ids such as -1 as sentinels.
88
+ */
89
+ function validParentChain(chain: readonly number[]): number[] {
90
+ return chain.filter((id) => id > 0).slice(0, PARENT_CHAIN_SLOTS)
91
+ }
55
92
 
56
93
  const placetypeToIdx = new Map<string, number>(PLACETYPE_ORDER.map((placetype, index) => [placetype, index]))
57
94
 
@@ -100,10 +137,12 @@ export function serializeFST(matcher: FSTMatcher, provenance?: FSTProvenance): B
100
137
  const stringTableSize = (strings.length + 1) * 4 + stringBytes
101
138
  const stateTableSize = nodes.length * WIDE_STATE_ENTRY_SIZE
102
139
  const edgeTableSize = totalEdges * EDGE_ENTRY_SIZE
103
- const placeTableSize = totalPlaces * SPLIT_PLACE_ENTRY_SIZE
140
+ const placeTableSize = totalPlaces * PLACE_LAYOUT.size
141
+ const idTable = buildIDTable(nodes)
142
+ const idTableSize = 4 + idTable.ids.length * 8
104
143
  const provenanceJson = provenance ? Buffer.from(stringifyJSON(provenance), "utf8") : null
105
144
  const provenanceSize = provenanceJson ? 4 + provenanceJson.length : 0
106
- const binarySize = HEADER_SIZE + stringTableSize + stateTableSize + edgeTableSize + placeTableSize
145
+ const binarySize = HEADER_SIZE + stringTableSize + stateTableSize + edgeTableSize + placeTableSize + idTableSize
107
146
  const totalSize = binarySize + provenanceSize
108
147
  const buf = Buffer.alloc(totalSize)
109
148
  let pos = 0
@@ -172,33 +211,44 @@ export function serializeFST(matcher: FSTMatcher, provenance?: FSTProvenance): B
172
211
  }
173
212
 
174
213
  for (const place of node.places) {
175
- const pp = placeTableStart + placeIdx * SPLIT_PLACE_ENTRY_SIZE
176
- // WOF uses negative parent ids such as -1 as sentinels.
177
- const validChain = place.parentChain.filter((id) => id > 0)
178
- const chainLen = Math.min(validChain.length, MAX_CHAIN_LEN)
179
- buf.writeUInt32LE(place.wofID, pp)
180
- buf.writeUInt8(placetypeToIdx.get(place.placetype) ?? 0, pp + 4)
181
- buf.writeUInt8(chainLen, pp + 5)
182
- buf.writeUInt8(hasAmbiguity ? Math.min(place.crossCountryBranches ?? 0, 255) : 0, pp + 6)
214
+ const pp = placeTableStart + placeIdx * PLACE_LAYOUT.size
215
+ const validChain = validParentChain(place.parentChain)
216
+ const chainLen = validChain.length
217
+ buf.writeUInt32LE(idTable.indexOf.get(place.wofID)!, pp)
218
+ buf.writeUInt8(placetypeToIdx.get(place.placetype) ?? 0, pp + PLACE_LAYOUT.placetype)
219
+ buf.writeUInt8(chainLen, pp + PLACE_LAYOUT.chainLength)
220
+
221
+ buf.writeUInt8(
222
+ hasAmbiguity ? Math.min(place.crossCountryBranches ?? 0, 255) : 0,
223
+ pp + PLACE_LAYOUT.crossCountryBranches
224
+ )
225
+
183
226
  // An absent encyclopedic score writes flag 0 and a 0.0 float.
184
227
  // Readers skip the float when the flag is 0.
185
228
  const hasEncyclopedic = place.encyclopedic != null
186
- buf.writeUInt8(hasEncyclopedic ? PLACE_FLAG_HAS_ENCYCLOPEDIC : 0, pp + 7)
187
- buf.writeUInt32LE(intern(place.name), pp + 8)
188
- buf.writeFloatLE(place.referential, pp + 12)
189
- buf.writeFloatLE(place.lat, pp + 16)
190
- buf.writeFloatLE(place.lon, pp + 20)
191
-
192
- for (let ci = 0; ci < MAX_CHAIN_LEN; ci++) {
193
- buf.writeUInt32LE(ci < chainLen ? validChain[ci]! : 0, pp + 24 + ci * 4)
229
+ buf.writeUInt8(hasEncyclopedic ? PLACE_FLAG_HAS_ENCYCLOPEDIC : 0, pp + PLACE_LAYOUT.flags)
230
+ buf.writeUInt32LE(intern(place.name), pp + PLACE_LAYOUT.name)
231
+ buf.writeFloatLE(place.referential, pp + PLACE_LAYOUT.referential)
232
+ buf.writeFloatLE(place.lat, pp + PLACE_LAYOUT.latitude)
233
+ buf.writeFloatLE(place.lon, pp + PLACE_LAYOUT.longitude)
234
+
235
+ for (let ci = 0; ci < PARENT_CHAIN_SLOTS; ci++) {
236
+ buf.writeUInt32LE(ci < chainLen ? idTable.indexOf.get(validChain[ci]!)! : 0, pp + PLACE_LAYOUT.chain + ci * 4)
194
237
  }
195
238
 
196
- buf.writeFloatLE(place.encyclopedic ?? 0, pp + ENCYCLOPEDIC_OFFSET)
239
+ buf.writeFloatLE(place.encyclopedic ?? 0, pp + PLACE_LAYOUT.encyclopedic!)
197
240
 
198
241
  placeIdx++
199
242
  }
200
243
  }
201
244
 
245
+ const idTableStart = idTableOffset(placeTableStart, totalPlaces, PLACE_LAYOUT)
246
+ buf.writeUInt32LE(idTable.ids.length, idTableStart)
247
+
248
+ for (const [index, id] of idTable.ids.entries()) {
249
+ buf.writeDoubleLE(id, idTableStart + 4 + index * 8)
250
+ }
251
+
202
252
  if (provenanceJson) {
203
253
  const trailerStart = binarySize
204
254
  buf.writeUInt32LE(provenanceJson.length, trailerStart)
@@ -223,13 +273,13 @@ export function deserializeFST(buf: Buffer): FSTMatcher {
223
273
  throw new Error(`FST version ${version} unsupported (expected 1..${FST_FORMAT_VERSION})`)
224
274
  }
225
275
 
226
- const isV2 = version >= 2
227
- const isSplit = version >= VERSION_TWO_SCORE_SPLIT
228
276
  const hasAmbiguity = (buf.readUInt16LE(6) & 1) === 1
277
+ const placeLayout = placeEntryLayout(version)
278
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength)
229
279
 
230
280
  const stateCount = buf.readUInt32LE(8)
231
281
  const edgeCount = buf.readUInt32LE(12)
232
- const _placeCount = buf.readUInt32LE(16)
282
+ const placeCount = buf.readUInt32LE(16)
233
283
  const stringCount = buf.readUInt32LE(20)
234
284
  const stringBytes = buf.readUInt32LE(24)
235
285
 
@@ -254,10 +304,10 @@ export function deserializeFST(buf: Buffer): FSTMatcher {
254
304
  pos += stringBytes
255
305
 
256
306
  const stateEntrySize = version >= VERSION_WIDE_STATE_COUNTERS ? WIDE_STATE_ENTRY_SIZE : NARROW_STATE_ENTRY_SIZE
257
- const placeEntrySize = version >= VERSION_TWO_SCORE_SPLIT ? SPLIT_PLACE_ENTRY_SIZE : LEGACY_PLACE_ENTRY_SIZE
258
307
  const stateTableStart = pos
259
308
  const edgeTableStart = stateTableStart + stateCount * stateEntrySize
260
309
  const placeTableStart = edgeTableStart + edgeCount * EDGE_ENTRY_SIZE
310
+ const ids = loadIDTable(view, idTableOffset(placeTableStart, placeCount, placeLayout), placeLayout)
261
311
 
262
312
  const nodes: FSTNode[] = new Array(stateCount)
263
313
 
@@ -284,36 +334,15 @@ export function deserializeFST(buf: Buffer): FSTMatcher {
284
334
  const places: PlaceEntry[] = new Array(placeCountForState)
285
335
 
286
336
  for (let pi = 0; pi < placeCountForState; pi++) {
287
- const pp = placeTableStart + (placeStart + pi) * placeEntrySize
288
- const chainLen = buf.readUInt8(pp + 5)
289
- const parentChain: number[] = []
290
-
291
- for (let ci = 0; ci < chainLen; ci++) {
292
- parentChain.push(buf.readUInt32LE(pp + 24 + ci * 4))
293
- }
294
-
295
- // Version 1 stored a raw population u32 here.
296
- // This version maps it through the `referentialFromPopulation` curve.
297
- // Later versions store an f32 score.
298
- const referential = isV2
299
- ? buf.readFloatLE(pp + 12)
300
- : Math.min(1, Math.log2(1 + buf.readUInt32LE(pp + 12) / 1000) / 14)
301
-
302
- // Files before version 5 have no encyclopedic score, so their reserved byte isn't read as a flag.
303
- const hasEncyclopedic =
304
- isSplit && (buf.readUInt8(pp + 7) & PLACE_FLAG_HAS_ENCYCLOPEDIC) === PLACE_FLAG_HAS_ENCYCLOPEDIC
305
-
306
- places[pi] = {
307
- wofID: buf.readUInt32LE(pp),
308
- placetype: PLACETYPE_ORDER[buf.readUInt8(pp + 4)] ?? "locality",
309
- name: strings[buf.readUInt32LE(pp + 8)]!,
310
- referential,
311
- lat: buf.readFloatLE(pp + 16),
312
- lon: buf.readFloatLE(pp + 20),
313
- parentChain,
314
- crossCountryBranches: hasAmbiguity ? buf.readUInt8(pp + 6) : null,
315
- encyclopedic: hasEncyclopedic ? buf.readFloatLE(pp + ENCYCLOPEDIC_OFFSET) : null,
316
- }
337
+ places[pi] = decodePlaceEntry(
338
+ view,
339
+ placeTableStart + (placeStart + pi) * placeLayout.size,
340
+ version,
341
+ placeLayout,
342
+ hasAmbiguity,
343
+ (index) => strings[index]!,
344
+ ids
345
+ )
317
346
  }
318
347
 
319
348
  nodes[si] = { edges, places }