@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
@@ -4,7 +4,7 @@
4
4
  import { isOfficialLanguage } from "@mailwoman/codex/country"
5
5
  import { readUnquotedTSV } from "@mailwoman/core/fs/delimited"
6
6
  import { pathExists } from "@mailwoman/core/fs/readers/stat"
7
- import { GEONAMES_ID_BASE, GEONAMES_POSTAL_ID_BASE } from "@mailwoman/core/resolver/synthetic-id-ranges"
7
+ import { GEONAMES_ID_BASE, GEONAMES_POSTAL_ID_BASE, geonamesFoldID } from "@mailwoman/core/resolver/synthetic-id-ranges"
8
8
  import type { DatabaseClient, StatementSync } from "@mailwoman/sqlite/client"
9
9
  import { type PathBuilderLike, resolvePathBuilder } from "path-ts"
10
10
 
@@ -192,11 +192,9 @@ function foldAdminRows(
192
192
  clean: (s: string) => string | null
193
193
  existing: GeonamesFoldMatcher | undefined
194
194
  claim: (match: GeonamesFoldMatch, name: string) => void
195
- nextID: number
196
195
  }
197
- ): { countryID: number; adminMap: Map<string, number>; nextID: number } {
196
+ ): { countryID: number; adminMap: Map<string, number> } {
198
197
  const { rows, country: cc, clean, existing, claim } = input
199
- let id = input.nextID
200
198
  let countryID = -1
201
199
  const adminMap = new Map<string, number>()
202
200
  // The regions this fold wrote, as opposed to existing records a region matched.
@@ -221,7 +219,7 @@ function foldAdminRows(
221
219
  claim(matched, aname)
222
220
  }
223
221
 
224
- const rid = matched?.id ?? id++
222
+ const rid = matched?.id ?? geonamesFoldID(place.geonamesID)
225
223
 
226
224
  if (!matched) {
227
225
  statements.spr.run(rid, -1, aname, placetype, cc, lat, lon, lat, lon, lat, lon, 1, 0, 0, 0, 0, 0)
@@ -248,7 +246,7 @@ function foldAdminRows(
248
246
  }
249
247
  }
250
248
 
251
- return { countryID, adminMap, nextID: id }
249
+ return { countryID, adminMap }
252
250
  }
253
251
 
254
252
  /**
@@ -320,7 +318,6 @@ export async function ingestGeonamesAliases(
320
318
  }
321
319
  }
322
320
 
323
- let id = GEONAMES_ID_BASE
324
321
  let total = 0
325
322
  db.exec("BEGIN")
326
323
 
@@ -373,16 +370,12 @@ export async function ingestGeonamesAliases(
373
370
  }
374
371
  }
375
372
 
376
- const admin = addAdmin
373
+ const { countryID, adminMap } = addAdmin
377
374
  ? foldAdminRows(
378
375
  { db, spr: sprInsert, names: namesInsert, ancestors: ancestorInsert },
379
- { rows: adminRows, country: cc, clean, existing: opts?.existing, claim, nextID: id }
376
+ { rows: adminRows, country: cc, clean, existing: opts?.existing, claim }
380
377
  )
381
- : { countryID: -1, adminMap: new Map<string, number>(), nextID: id }
382
-
383
- const { countryID, adminMap } = admin
384
-
385
- id = admin.nextID
378
+ : { countryID: -1, adminMap: new Map<string, number>() }
386
379
 
387
380
  for await (const f of readUnquotedTSV(file)) {
388
381
  if (f[6] !== "P") continue
@@ -430,7 +423,7 @@ export async function ingestGeonamesAliases(
430
423
  continue
431
424
  }
432
425
 
433
- const nid = id++
426
+ const nid = geonamesFoldID(place.geonamesID)
434
427
 
435
428
  opts?.existing?.onGap({ ...place, id: nid })
436
429
 
@@ -0,0 +1,210 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * Which admin database an importance build was made from.
6
+ *
7
+ * `mailwoman gazetteer importance` copies an admin database and adds `place_importance` to the copy.
8
+ * It stamps the admin file's md5 and size into the copy's `importance_source` table, the same
9
+ * identity an FST stamps as `sourceDBMD5` and `sourceDBBytes` ({@linkcode readWOFSourceIdentity}).
10
+ *
11
+ * The copy is written beside the admin database at {@linkcode importanceDatabasePath},
12
+ * a name derived from the admin md5, so the candidate build finds the importance build for
13
+ * its admin database by hashing that database, and checks the stamp before reading a score.
14
+ */
15
+
16
+ import { pathExists } from "@mailwoman/core/fs/readers/stat"
17
+ import { DatabaseClient } from "@mailwoman/sqlite/client"
18
+ import { tableExists } from "@mailwoman/sqlite/introspection"
19
+ import type { Kysely } from "kysely"
20
+ import { basename, dirname, resolvePathBuilder, type PathBuilderLike } from "path-ts"
21
+
22
+ import { type FSTSourceIdentity, readWOFSourceIdentity } from "#fst/freshness"
23
+
24
+ /**
25
+ * The one row of `importance_source`: the admin database the importance build copied.
26
+ */
27
+ export interface ImportanceSourceTable {
28
+ /**
29
+ * The admin path as the importance build was given it.
30
+ */
31
+ admin_path: string
32
+ /**
33
+ * The admin file's md5 as lowercase hex.
34
+ */
35
+ admin_md5: string
36
+ /**
37
+ * The admin file's size in bytes.
38
+ */
39
+ admin_bytes: number
40
+ }
41
+
42
+ export interface ImportanceSourceDatabase {
43
+ importance_source: ImportanceSourceTable
44
+ }
45
+
46
+ /**
47
+ * The admin database an importance build records, read back from its stamp.
48
+ */
49
+ export interface ImportanceAdminSource extends FSTSourceIdentity {
50
+ path: string
51
+ }
52
+
53
+ /**
54
+ * The count of md5 hex characters in the importance file name.
55
+ * The stamp inside the file holds the whole digest.
56
+ */
57
+ const NAME_DIGEST_LENGTH = 12
58
+
59
+ /**
60
+ * Where the importance build for an admin database lives: beside it,
61
+ * under a name built from the admin's md5.
62
+ *
63
+ * `admin-global-priority.db` with md5 `6a0c2736…` gives `admin-global-priority-importance-6a0c2736xxxx.db`.
64
+ */
65
+ export function importanceDatabasePath(adminDB: PathBuilderLike, adminMD5: string): string {
66
+ const name = basename(adminDB.toString(), ".db")
67
+
68
+ return resolvePathBuilder(dirname(adminDB.toString()))(
69
+ `${name}-importance-${adminMD5.slice(0, NAME_DIGEST_LENGTH)}.db`
70
+ ).toString()
71
+ }
72
+
73
+ /**
74
+ * Create `importance_source` and write the admin identity into it, replacing any earlier row.
75
+ */
76
+ export async function writeImportanceSource(
77
+ db: Kysely<ImportanceSourceDatabase>,
78
+ source: ImportanceAdminSource
79
+ ): Promise<void> {
80
+ await db.schema.dropTable("importance_source").ifExists().execute()
81
+
82
+ await db.schema
83
+ .createTable("importance_source")
84
+ .addColumn("admin_path", "text", (c) => c.notNull())
85
+ .addColumn("admin_md5", "text", (c) => c.notNull())
86
+ .addColumn("admin_bytes", "integer", (c) => c.notNull())
87
+ .execute()
88
+
89
+ await db
90
+ .insertInto("importance_source")
91
+ .values({ admin_path: source.path, admin_md5: source.md5, admin_bytes: source.bytes })
92
+ .execute()
93
+ }
94
+
95
+ /**
96
+ * Read the admin identity an importance build stamped.
97
+ *
98
+ * Returns `null` only when the file has no `importance_source` table.
99
+ * Such a file is an importance build that predates the stamp.
100
+ *
101
+ * @throws When the file is missing, or when the table holds other than one row.
102
+ */
103
+ export async function readImportanceSource(importanceDB: PathBuilderLike): Promise<ImportanceAdminSource | null> {
104
+ if (!(await pathExists(importanceDB))) {
105
+ throw new Error(`importance source: ${importanceDB} not found`)
106
+ }
107
+
108
+ using db = new DatabaseClient<ImportanceSourceDatabase>(importanceDB, { readOnly: true })
109
+
110
+ if (!tableExists(db, "importance_source")) return null
111
+
112
+ const rows = await db.selectFrom("importance_source").selectAll().execute()
113
+
114
+ if (rows.length !== 1) {
115
+ throw new Error(`importance source: ${importanceDB} holds ${rows.length} importance_source rows, expected 1`)
116
+ }
117
+
118
+ const [row] = rows
119
+
120
+ return { path: row!.admin_path, md5: row!.admin_md5, bytes: Number(row!.admin_bytes) }
121
+ }
122
+
123
+ /**
124
+ * The importance build a reader uses, with its own md5 for a manifest or a report.
125
+ */
126
+ export interface ResolvedImportance {
127
+ path: string
128
+ md5: string
129
+ }
130
+
131
+ /**
132
+ * A refusal from {@linkcode resolveImportanceForAdmin}.
133
+ * Its message gives the admin path and the importance path.
134
+ */
135
+ export class ImportanceSourceError extends Error {
136
+ constructor(message: string) {
137
+ super(message)
138
+
139
+ this.name = "ImportanceSourceError"
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Find the importance build that belongs with `adminDB` and check its stamp.
145
+ *
146
+ * Every reader of importance scores finds its file here, from the admin database it reads.
147
+ * Without `importanceDB` the file is the one {@linkcode importanceDatabasePath} gives for the admin md5.
148
+ * A given `importanceDB` is checked the same way.
149
+ *
150
+ * @throws {ImportanceSourceError} When no importance build exists for the admin database,
151
+ * when the file has no `importance_source` stamp, or when its stamp records another admin database.
152
+ */
153
+ export async function resolveImportanceForAdmin(
154
+ adminDB: PathBuilderLike,
155
+ importanceDB?: PathBuilderLike
156
+ ): Promise<ResolvedImportance> {
157
+ if (!(await pathExists(adminDB))) {
158
+ throw new ImportanceSourceError(`admin ${adminDB} does not exist, so no importance build can be matched to it.`)
159
+ }
160
+
161
+ const admin = await readWOFSourceIdentity(adminDB)
162
+ const path = (importanceDB ?? importanceDatabasePath(adminDB, admin.md5)).toString()
163
+ const rebuild = `mailwoman gazetteer importance --admin ${adminDB}`
164
+
165
+ if (!(await pathExists(path))) {
166
+ throw new ImportanceSourceError(
167
+ `no importance build for admin ${adminDB} (md5 ${admin.md5}): ${path} does not exist. ` +
168
+ `Build it with \`${rebuild}\`.`
169
+ )
170
+ }
171
+
172
+ const stamped = await readImportanceSource(path)
173
+
174
+ if (!stamped) {
175
+ throw new ImportanceSourceError(
176
+ `importance ${path} records no admin database (no importance_source table), so it cannot be ` +
177
+ `matched to admin ${adminDB} (md5 ${admin.md5}). Rebuild it with \`${rebuild}\`.`
178
+ )
179
+ }
180
+
181
+ if (stamped.md5 !== admin.md5 || stamped.bytes !== admin.bytes) {
182
+ throw new ImportanceSourceError(
183
+ `importance ${path} was built from admin ${stamped.path} (md5 ${stamped.md5}, ` +
184
+ `${stamped.bytes} bytes), not admin ${adminDB} (md5 ${admin.md5}, ${admin.bytes} bytes). ` +
185
+ `Rebuild it with \`${rebuild}\`.`
186
+ )
187
+ }
188
+
189
+ return { path, md5: (await readWOFSourceIdentity(path)).md5 }
190
+ }
191
+
192
+ /**
193
+ * {@linkcode resolveImportanceForAdmin} for a report that goes on without scores.
194
+ *
195
+ * A refusal comes back as its message, and the message gives both paths.
196
+ * The report states that message as the reason it read no scores.
197
+ *
198
+ * @throws Any error other than an {@linkcode ImportanceSourceError}.
199
+ */
200
+ export async function resolveImportanceOrRefusal(
201
+ adminDB: PathBuilderLike
202
+ ): Promise<(ResolvedImportance & { refusal: null }) | { path: null; md5: null; refusal: string }> {
203
+ try {
204
+ return { ...(await resolveImportanceForAdmin(adminDB)), refusal: null }
205
+ } catch (error) {
206
+ if (error instanceof ImportanceSourceError) return { path: null, md5: null, refusal: error.message }
207
+
208
+ throw error
209
+ }
210
+ }
@@ -1,6 +1,8 @@
1
1
  // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
3
 
4
+ import { latLonBoundsContain } from "@mailwoman/spatial/bbox"
5
+
4
6
  import type { CandidateTable } from "#candidate/schema"
5
7
 
6
8
  /**
@@ -20,6 +22,40 @@ export type PrimaryPreferenceRow = Pick<CandidateTable, "neg_rank"> &
20
22
  */
21
23
  export const PRIMARY_PREFERENCE_LOG10 = 1
22
24
 
25
+ /**
26
+ * The alias penalty inside a stated region, larger than any log10 population gap.
27
+ *
28
+ * A query that states the region (`Junction, IL`) has already chosen among the world's namesakes,
29
+ * so a place whose primary name equals the query outranks a different place that lists it as an alias.
30
+ * WOF `und` variant names include former names of absorbed communities, such as `Junction` on West
31
+ * Chicago, and a population gap between the two places is no evidence of which one the query means.
32
+ */
33
+ export const REGION_PRIMARY_PREFERENCE_LOG10 = 100
34
+
35
+ /**
36
+ * The alias penalty inside a stated region for one alias row against the top primary row.
37
+ *
38
+ * A primary row inside the alias row's extent records the same place twice,
39
+ * as the Setauket hamlet inside the Setauket-East Setauket census place,
40
+ * so the worldwide margin applies and population decides.
41
+ * A primary row outside it is a different place, and the region margin applies.
42
+ */
43
+ export function regionAliasMargin(
44
+ alias: Partial<Pick<CandidateTable, "min_lat" | "min_lon" | "max_lat" | "max_lon">>,
45
+ primary: Partial<Pick<CandidateTable, "latitude" | "longitude">>
46
+ ): number {
47
+ const { min_lat: minLat, min_lon: minLon, max_lat: maxLat, max_lon: maxLon } = alias
48
+ const { latitude, longitude } = primary
49
+
50
+ if (minLat == null || minLon == null || maxLat == null || maxLon == null || latitude == null || longitude == null) {
51
+ return REGION_PRIMARY_PREFERENCE_LOG10
52
+ }
53
+
54
+ return latLonBoundsContain({ minLat, minLon, maxLat, maxLon }, latitude, longitude)
55
+ ? PRIMARY_PREFERENCE_LOG10
56
+ : REGION_PRIMARY_PREFERENCE_LOG10
57
+ }
58
+
23
59
  const SEAT_PLACETYPE = "locality"
24
60
 
25
61
  /**
@@ -80,6 +116,7 @@ export type RankedRow<R> = R & {
80
116
  * Re-ranks population-ordered candidate rows.
81
117
  *
82
118
  * An alias must beat the top primary by `delta` in log10 population, in any country.
119
+ * A `delta` function returns the margin for one alias row against the top primary row.
83
120
  * The function returns the top `limit` rows.
84
121
  *
85
122
  * When `placetypes` is given, an exact tie prefers a populated `locality`.
@@ -88,7 +125,7 @@ export type RankedRow<R> = R & {
88
125
  export function rankByPrimaryPreference<R extends PrimaryPreferenceRow>(
89
126
  rows: readonly R[],
90
127
  limit: number,
91
- delta = PRIMARY_PREFERENCE_LOG10,
128
+ delta: number | ((alias: R, primary: R) => number) = PRIMARY_PREFERENCE_LOG10,
92
129
  placetypes?: ReadonlyMap<number, string>,
93
130
  exemptVariantAliases = false
94
131
  ): Array<RankedRow<R>> {
@@ -105,7 +142,8 @@ export function rankByPrimaryPreference<R extends PrimaryPreferenceRow>(
105
142
  const annotate = (r: R): RankedRow<R> => {
106
143
  const exempted = exemptVariantAliases && r.name_role === "variant" && isAliasOfPrimary(r)
107
144
  const penalized = isAliasOfPrimary(r) && !exempted
108
- const effectiveNegRank = r.neg_rank + (penalized ? delta : 0)
145
+ const margin = penalized ? (typeof delta === "number" ? delta : delta(r, topPrimary!)) : 0
146
+ const effectiveNegRank = r.neg_rank + margin
109
147
 
110
148
  return {
111
149
  ...r,
@@ -347,6 +347,48 @@ export function normalizeLocalityForKey(locality: string): NameKey {
347
347
  return fold(locality) as NameKey
348
348
  }
349
349
 
350
+ /**
351
+ * Apostrophe-like marks that romanized names contain and {@link normalizeLocalityForKey} keeps.
352
+ *
353
+ * The set holds the Hawaiian, Tongan and Uzbek ʻokina (U+02BB), the modifier
354
+ * apostrophe (U+02BC), the reversed comma above (U+02BD), the prime (U+02B9),
355
+ * the ʾalif and ʿayn half rings (U+02BE, U+02BF), and the left quotation mark (U+2018)
356
+ * and backtick (U+0060) that romanized Arabic, Persian and Pashto names write for ʿayn.
357
+ * A writer typing in ASCII leaves them out or types `'`, which the key drops.
358
+ */
359
+ const APOSTROPHE_LIKE_MARKS = /[ʹʻ-ʿ‘`]/gu
360
+
361
+ /**
362
+ * The key with every apostrophe-like mark removed, so `Hawaiʻi` and `` `Ajman ``
363
+ * are also found as `hawaii` and `ajman`.
364
+ *
365
+ * The candidate build stages it as one more alias of the place.
366
+ * The query-side key is unchanged, so a query written with the mark still matches the source spelling.
367
+ */
368
+ export function withoutApostropheLikeMarks(key: NameKey): NameKey {
369
+ return key.replaceAll(APOSTROPHE_LIKE_MARKS, "").replaceAll(/\s+/g, " ").trim() as NameKey
370
+ }
371
+
372
+ /**
373
+ * The tatweel (U+0640), the short-vowel and shadda marks (U+064B–U+065F) and the superscript
374
+ * alef (U+0670), with the hamza and madda that NFKD splits off `أ`, `إ`, `آ`, `ؤ` and `ئ`.
375
+ */
376
+ const ARABIC_MARKS = /[ـً-ٰٟ]/gu
377
+
378
+ /**
379
+ * The key with the Arabic letters that writers interchange folded together, so `الاسماعيليه`
380
+ * and `الإسماعيلية`, or `الوادى الجديد` and `الوادي الجديد`, meet at one key.
381
+ *
382
+ * It removes {@link ARABIC_MARKS}, which leaves a hamza-carrying alef as a bare `ا`,
383
+ * and writes `ى` (alef maqsura) as `ي` (yeh) and `ة` (taa marbuta) as `ه` (heh).
384
+ * {@link normalizeLocalityForKey} doesn't apply it, so the columns keyed by that fold are unchanged.
385
+ * A candidate build applies it to `name_key` only under the `arabic-letter-variants` key fold
386
+ * (`#candidate/key-fold`), which the artifact records so its reader folds query keys too.
387
+ */
388
+ export function withArabicLetterVariantsFolded(key: NameKey): NameKey {
389
+ return key.normalize("NFKD").replaceAll(ARABIC_MARKS, "").replaceAll("ى", "ي").replaceAll("ة", "ه") as NameKey
390
+ }
391
+
350
392
  /**
351
393
  * Folds a locality name into a {@link NameKey} with the Han fold for `zh`
352
394
  * and {@link normalizeLocalityForKey} otherwise.
@@ -1,27 +1,32 @@
1
+ /**
2
+ * Repair the truncated ancestry left by the `parent_id` closure.
3
+ *
4
+ * Must run after `populateAncestors` and before the build freezes.
5
+ */
6
+ import type { WOFFeature } from "@mailwoman/gazetteer/whosonfirst";
1
7
  import type { DatabaseClient } from "@mailwoman/sqlite/client";
2
- import { PathBuilder, type PathBuilderLike } from "path-ts";
3
8
  import type { WOFDatabase } from "#schema";
9
+ /**
10
+ * Reads the WOF record with an id, such as a primary-key read of the WOF record store, or returns `null`.
11
+ */
12
+ export type WOFFeatureReader = (id: number) => Pick<WOFFeature, "properties"> | null | Promise<Pick<WOFFeature, "properties"> | null>;
4
13
  export interface AncestryBackfillResult {
5
14
  placesFixed: number;
6
15
  rowsAdded: number;
7
16
  /**
8
- * Candidates whose source geojson was not found (non-WOF backfilled places or absent repos),
17
+ * Candidates the reader returned no record for (non-WOF backfilled places or absent repos),
9
18
  * skipped rather than treated as an error.
10
19
  */
11
20
  noGeojson: number;
12
21
  }
13
- /**
14
- * Discover the `data` directories under a WOF repos root that hold attached geojson,
15
- * accepting both the nested lab layout and a flat layout at most two directory levels deep.
16
- */
17
- export declare function discoverAdminDataRoots(reposRoot: PathBuilderLike): Promise<PathBuilder[]>;
18
22
  /**
19
23
  * Insert missing ancestor rows for places whose ancestry chain ended before reaching a country.
20
24
  *
21
- * The function reads `wof:hierarchy` and runs in one transaction under the caller's connection.
25
+ * The function reads each candidate's `wof:hierarchy` through `readFeature`
26
+ * and runs in one transaction under the caller's connection.
22
27
  * `opts.maxID` bounds the scan to avoid probing synthetic-id Overture and GeoNames rows.
23
28
  */
24
- export declare function backfillAncestorsFromHierarchy(db: DatabaseClient<WOFDatabase>, geojsonRoots: readonly PathBuilderLike[], opts?: {
29
+ export declare function backfillAncestorsFromHierarchy(db: DatabaseClient<WOFDatabase>, readFeature: WOFFeatureReader, opts?: {
25
30
  maxID?: number;
26
31
  }): Promise<AncestryBackfillResult>;
27
32
  //# sourceMappingURL=backfill.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"backfill.d.ts","sourceRoot":"","sources":["../../lib/ancestry/backfill.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAA;AAC9D,OAAO,EAAE,WAAW,EAAE,KAAK,eAAe,EAAE,MAAM,SAAS,CAAA;AAG3D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAI1C,M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OAAO,CAAC,sBAAsB,CAAC,CA2FjC"}
@@ -1,53 +1,15 @@
1
1
  // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
2
  // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
- /**
4
- * Repair the truncated ancestry left by the `parent_id` closure.
5
- *
6
- * Must run after `populateAncestors` and before the build freezes.
7
- */
8
- import { readWOFFeature } from "@mailwoman/gazetteer/whosonfirst";
9
3
  import { hierarchyAncestorsInAnyBranch } from "@mailwoman/gazetteer/whosonfirst/hierarchy";
10
- import { PathBuilder } from "path-ts";
11
- import { Globerator } from "spliterator/node/fs";
12
4
  const TOP_PLACETYPES = new Set(["country", "continent", "empire", "ocean", "marinearea", "planet"]);
13
- /**
14
- * Discover the `data` directories under a WOF repos root that hold attached geojson,
15
- * accepting both the nested lab layout and a flat layout at most two directory levels deep.
16
- */
17
- export async function discoverAdminDataRoots(reposRoot) {
18
- const roots = [];
19
- const visit = async (dir, depth) => {
20
- if (depth > 2)
21
- return;
22
- let names;
23
- try {
24
- names = (await Globerator.from("*", { cwd: dir, withFileTypes: true, onlyFiles: false }).toArray())
25
- .filter((entry) => entry.isDirectory())
26
- .map((entry) => entry.name);
27
- }
28
- catch {
29
- return;
30
- }
31
- for (const name of names) {
32
- const child = dir(name);
33
- if (name === "data") {
34
- roots.push(child);
35
- }
36
- else if (name.startsWith("whosonfirst-data")) {
37
- await visit(child, depth + 1);
38
- }
39
- }
40
- };
41
- await visit(PathBuilder.from(reposRoot), 0);
42
- return roots;
43
- }
44
5
  /**
45
6
  * Insert missing ancestor rows for places whose ancestry chain ended before reaching a country.
46
7
  *
47
- * The function reads `wof:hierarchy` and runs in one transaction under the caller's connection.
8
+ * The function reads each candidate's `wof:hierarchy` through `readFeature`
9
+ * and runs in one transaction under the caller's connection.
48
10
  * `opts.maxID` bounds the scan to avoid probing synthetic-id Overture and GeoNames rows.
49
11
  */
50
- export async function backfillAncestorsFromHierarchy(db, geojsonRoots, opts = {}) {
12
+ export async function backfillAncestorsFromHierarchy(db, readFeature, opts = {}) {
51
13
  const maxID = opts.maxID ?? Number.MAX_SAFE_INTEGER;
52
14
  // The id bound is stated first so SQLite prunes by the PK index before the not-exists runs.
53
15
  const candidateBase = db
@@ -82,7 +44,7 @@ export async function backfillAncestorsFromHierarchy(db, geojsonRoots, opts = {}
82
44
  for (const { id, placetype } of candidates) {
83
45
  if (placetype && TOP_PLACETYPES.has(placetype))
84
46
  continue;
85
- const gj = await readWOFFeature(id, geojsonRoots);
47
+ const gj = await readFeature(id);
86
48
  const hierarchy = gj?.properties?.["wof:hierarchy"];
87
49
  if (!hierarchy || !hierarchy.length) {
88
50
  if (!gj) {
@@ -1 +1 @@
1
- {"version":3,"file":"backfill.js","sourceRoot":"","sources":["../../lib/ancestry/backfill.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,kEAAkE;AAElE;;;;GAIG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,kCAAkC,CAAA;AACjE,OAAO,EAAE,6BAA6B,EAAE,MAAM,4CAA4C,CAAA;AAE1F,OAAO,EAAE,WAAW,EAAwB,MAAM,SAAS,CAAA;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAIhD,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAA;AAYnG;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,SAA0B;IACtE,MAAM,KAAK,GAAkB,EAAE,CAAA;IAE/B,MAAM,KAAK,GAAG,KAAK,EAAE,GAAgB,EAAE,KAAa,EAAiB,EAAE;QACtE,IAAI,KAAK,GAAG,CAAC;YAAE,OAAM;QAErB,IAAI,KAAe,CAAA;QAEnB,IAAI,CAAC;YACJ,KAAK,GAAG,CAAC,MAAM,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,EAA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CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;QAEpC,IAAI,CAAC,OAAO,EAAE,CAAC;YACd,OAAO,GAAG,IAAI,GAAG,EAAE,CAAA;YACnB,cAAc,CAAC,GAAG,CAAC,EAAE,EAAE,OAAO,CAAC,CAAA;QAChC,CAAC;QAED,IAAI,KAAK,GAAG,CAAC,CAAA;QAEb,KAAK,MAAM,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,IAAI,EAAE,CAAC;YAC9B,IAAI,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC;gBAAE,SAAQ;YAE9B,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,EAAE,EAAE,CAAC,CAAA;YACvB,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;YAEhB,KAAK,EAAE,CAAA;QACR,CAAC;QAED,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACf,WAAW,EAAE,CAAA;YACb,SAAS,IAAI,KAAK,CAAA;QACnB,CAAC;IACF,CAAC;IAED,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;IAEjB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,CAAA;AAC7C,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import type { PathBuilderLike } from "path-ts";
2
+ import { type CandidateKeyFold } from "#candidate/key-fold";
2
3
  import type { CapitalPoint } from "#capitals";
3
4
  /**
4
5
  * Options for {@link buildCandidateTable}.
@@ -59,6 +60,13 @@ export interface BuildCandidateOptions {
59
60
  * @defaultValue {@linkcode GLOSS_KEY_THRESHOLD}
60
61
  */
61
62
  glossKeyThreshold?: number;
63
+ /**
64
+ * Folds applied to every `name_key` after `normalizeLocalityForKey`, recorded in
65
+ * the artifact so its reader folds query keys the same way.
66
+ *
67
+ * @defaultValue none
68
+ */
69
+ keyFolds?: readonly CandidateKeyFold[];
62
70
  }
63
71
  /**
64
72
  * Row and place counts from each stage of {@link buildCandidateTable}.
@@ -68,6 +76,11 @@ export interface BuildCandidateResult {
68
76
  places: number;
69
77
  primaries: number;
70
78
  aliases: number;
79
+ /**
80
+ * The count of alias rows staged as a name's key with its apostrophe-like marks
81
+ * removed (`hawaii` for `Hawaiʻi`), which `aliases` excludes.
82
+ */
83
+ markFreeAliases: number;
71
84
  /**
72
85
  * The count of region aliases dropped because another region in the same
73
86
  * country uses the name as its official name.
@@ -75,6 +88,13 @@ export interface BuildCandidateResult {
75
88
  * The count is always zero for a source without a `names` table.
76
89
  */
77
90
  regionOfficialRefused: number;
91
+ /**
92
+ * The count of alias rows from a colloquial or unclassified name dropped
93
+ * because a populated place holds the same key by a real name.
94
+ *
95
+ * The count is always zero for a source without a `names` table.
96
+ */
97
+ nicknameRefused: number;
78
98
  abbrevs: number;
79
99
  postcodes: number;
80
100
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"candidate.d.ts","sourceRoot":"","sources":["../../lib/build/candidate.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAmB9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA;AAI7C;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACrC;;;;OAIG;IACH,KAAK,EAAE,eAAe,CAAA;IAEtB;;OAEG;IACH,MAAM,EAAE,eAAe,CAAA;IAEvB;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,SAAS,YAAY,EAAE,CAAA;IAElC;;;;OAIG;IACH,SAAS,CAAC,EAAE,SAAS,eAAe,EAAE,CAAA;IAEtC;;;;;;;;OAQG;IACH,UAAU,CAAC,EAAE,SAAS,eAAe,EAAE,CAAA;IAEvC;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,eAAe,CAAA;IAE5B;;OAEG;IACH,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;IAErD;;;;;;OAMG;IACH,iBAAiB,CAAC,EAAE,MAAM,CA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A;IAEhB;;;OAGG;IACH,aAAa,EAAE,MAAM,CAAA;IAErB;;OAEG;IACH,eAAe,EAAE,MAAM,CAAA;CACvB;AAED;;;GAGG;AAGH,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA+YpG"}
@@ -14,7 +14,9 @@ import { stageCountryDisplayNames } from "#candidate/country-display-names";
14
14
  import { foldExtract } from "#candidate/extract-fold";
15
15
  import { createCandidateFTS } from "#candidate/fts";
16
16
  import { IMPORTANCE_JOIN_RADIUS_KM, loadImportanceIndex } from "#candidate/importance";
17
+ import { applyCandidateKeyFold } from "#candidate/key-fold";
17
18
  import { GLOSS_KEY_THRESHOLD, stampNameRoles } from "#candidate/name-roles";
19
+ import { refuseNicknamesOfNamesakes } from "#candidate/nickname-namesakes";
18
20
  import { CANDIDATE_COLUMNS, createCandidateStagingTables, createCandidateTable, } from "#candidate/schema";
19
21
  import { createCapitalTable } from "#capital-schema";
20
22
  import { normalizeLocalityForKey } from "#street/normalize";
@@ -148,12 +150,13 @@ export async function buildCandidateTable(opts) {
148
150
  }).toLocaleString()} bare admin names`);
149
151
  progress("aliases", "exploding alias bags");
150
152
  const iso2ByCountryID = new Map([...ccodes].map(([code, id]) => [id, code]));
151
- const { nAlias, nBare, keyCounts, regionOfficialRefused } = explodeAliasBags(src, kdb, attrs, stageRow, {
153
+ const { nAlias, nBare, nMarkFree, keyCounts, regionOfficialRefused } = explodeAliasBags(src, kdb, attrs, stageRow, {
152
154
  regionPlacetypeID: ptID("region"),
153
155
  ccID,
154
156
  bareName: (countryID, alias) => bareAdminName(iso2ByCountryID.get(countryID) ?? "", alias),
155
157
  });
156
- progress("aliases", `${nAlias.toLocaleString()} aliases; ${nBare.toLocaleString()} bare admin aliases` +
158
+ progress("aliases", `${nAlias.toLocaleString()} aliases; ${nBare.toLocaleString()} bare admin aliases; ` +
159
+ `${nMarkFree.toLocaleString()} mark-free aliases` +
157
160
  (regionOfficialRefused
158
161
  ? `; ${regionOfficialRefused.toLocaleString()} region aliases refused as another region's official name`
159
162
  : ""));
@@ -171,6 +174,9 @@ export async function buildCandidateTable(opts) {
171
174
  }
172
175
  kdb.exec("COMMIT");
173
176
  progress("abbrevs", `${nAbbr.toLocaleString()} abbrevs`);
177
+ const nicknames = refuseNicknamesOfNamesakes(src, kdb, attrs);
178
+ progress("nicknames", `${nicknames.rows.toLocaleString()} colloquial or unclassified alias rows refused on ` +
179
+ `${nicknames.keys.toLocaleString()} keys a populated place holds by a real name`);
174
180
  const roles = stampNameRoles({
175
181
  src,
176
182
  out: kdb,
@@ -256,6 +262,10 @@ export async function buildCandidateTable(opts) {
256
262
  await createCandidateTable(kdb);
257
263
  kdb.exec(`INSERT OR IGNORE INTO candidate (${cols}) SELECT ${cols} FROM cand_stage ORDER BY ${keyOrder};`);
258
264
  await kdb.schema.dropTable("cand_stage").execute();
265
+ for (const fold of opts.keyFolds ?? []) {
266
+ const { rekeyed, merged } = await applyCandidateKeyFold(kdb, fold);
267
+ progress("key-fold", `${fold}: ${rekeyed.toLocaleString()} rows rekeyed, ${merged.toLocaleString()} merged`);
268
+ }
259
269
  progress("fts", "building FTS5-trigram fuzzy index");
260
270
  createCandidateFTS(kdb);
261
271
  kdb.exec("PRAGMA page_size=8192");
@@ -269,7 +279,9 @@ export async function buildCandidateTable(opts) {
269
279
  places: attrs.size,
270
280
  primaries: nPrim,
271
281
  aliases: nAlias,
282
+ markFreeAliases: nMarkFree,
272
283
  regionOfficialRefused,
284
+ nicknameRefused: nicknames.rows,
273
285
  abbrevs: nAbbr,
274
286
  postcodes: nPostcode,
275
287
  postcodeAliases: nPostcodeAlias,