@mailwoman/resolver-wof-wasm 7.2.0 → 7.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.
- package/index.ts +18 -0
- package/loader.ts +103 -0
- package/lookup.ts +352 -0
- package/package.json +23 -9
package/index.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export { loadSlimWOFDatabase, type LoadSlimOpts } from "./loader.ts"
|
|
8
|
+
export { WOFWasmPlaceLookup, type WOFWasmPlaceLookupOpts } from "./lookup.ts"
|
|
9
|
+
|
|
10
|
+
// Re-export the shared interface types so callers don't need both packages on the typed path.
|
|
11
|
+
export type {
|
|
12
|
+
FindPlaceQuery,
|
|
13
|
+
GeoBbox,
|
|
14
|
+
GeoPoint,
|
|
15
|
+
PlaceCandidate,
|
|
16
|
+
PlaceLookup,
|
|
17
|
+
WOFPlacetype,
|
|
18
|
+
} from "@mailwoman/resolver-wof-sqlite"
|
package/loader.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Loads a slim WOF SQLite distribution into an in-memory `@sqlite.org/sqlite-wasm` database.
|
|
7
|
+
*
|
|
8
|
+
* V1 strategy: fetch the whole file (~35 MB for the default top-1k US slim) and open it via the OO1
|
|
9
|
+
* API's "OPFS"-flavored constructor in transient mode. The full-fetch approach is fine for a
|
|
10
|
+
* bundle this size — the slim DB is what the browser holds in RAM for the duration of the session
|
|
11
|
+
* anyway, and HTTP/2 + gzip make the 35 MB transfer pay one RTT + transfer time, not the
|
|
12
|
+
* "hundreds of byte-range requests" cost a HTTP-VFS approach would incur.
|
|
13
|
+
*
|
|
14
|
+
* When we eventually want incremental loading (Phase B.x), this is the seam to swap — keep
|
|
15
|
+
* `WOFWasmPlaceLookup` unchanged and replace the loader with a `sql.js-httpvfs`-style VFS.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import sqlite3InitModule, { type Database, type Sqlite3Static } from "@sqlite.org/sqlite-wasm"
|
|
19
|
+
|
|
20
|
+
export interface LoadSlimOpts {
|
|
21
|
+
/**
|
|
22
|
+
* Either a URL to fetch the slim .db from, or a raw Uint8Array containing the file bytes.
|
|
23
|
+
*
|
|
24
|
+
* URL form is the public-demo path (load over HTTP). Uint8Array form is what tests use to skip the network entirely
|
|
25
|
+
* and is also useful if a caller wants to embed the DB in their own bundler output (Vite's `?url` / `?arraybuffer`
|
|
26
|
+
* imports both produce things that fit here).
|
|
27
|
+
*/
|
|
28
|
+
source: string | Uint8Array
|
|
29
|
+
/**
|
|
30
|
+
* Where the sqlite-wasm runtime can find its .wasm asset. Required in browser builds because the default URL is
|
|
31
|
+
* resolved relative to the worker script, which bundlers usually rewrite.
|
|
32
|
+
*
|
|
33
|
+
* Most bundlers will let you do `new URL("../node_modules/@sqlite.org/sqlite-wasm/sqlite-wasm/jswasm/sqlite3.wasm",
|
|
34
|
+
* import.meta.url).href`.
|
|
35
|
+
*
|
|
36
|
+
* Leave unset to use the runtime's defaults (works in Node + worker contexts where the path is resolvable directly).
|
|
37
|
+
*/
|
|
38
|
+
wasmURL?: string
|
|
39
|
+
/**
|
|
40
|
+
* Optional fetch implementation override. Defaults to `globalThis.fetch`. Useful in test harnesses that want to
|
|
41
|
+
* short-circuit network calls.
|
|
42
|
+
*/
|
|
43
|
+
fetchImpl?: typeof fetch
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Loads + opens the slim WOF DB. Returns `{ db, sqlite3 }` — `db` is the open Database; `sqlite3` is the runtime handle
|
|
48
|
+
* (in case the caller wants to call other OO1 APIs on it).
|
|
49
|
+
*
|
|
50
|
+
* Caller is responsible for `db.close()` when done.
|
|
51
|
+
*/
|
|
52
|
+
export async function loadSlimWOFDatabase(opts: LoadSlimOpts): Promise<{ db: Database; sqlite3: Sqlite3Static }> {
|
|
53
|
+
const bytes = typeof opts.source === "string" ? await fetchBytes(opts.source, opts.fetchImpl) : opts.source
|
|
54
|
+
|
|
55
|
+
// sqlite3InitModule's TS signature lies about its options bag — the runtime DOES accept the
|
|
56
|
+
// Emscripten-style {print, printErr, locateFile} options shown in the upstream docs. Cast to
|
|
57
|
+
// `any` for the call site rather than shadowing the typed wrapper for the entire file.
|
|
58
|
+
const sqlite3 = await (sqlite3InitModule as unknown as (opts: Record<string, unknown>) => Promise<Sqlite3Static>)({
|
|
59
|
+
print: () => {}, // suppress stdout from the WASM runtime
|
|
60
|
+
printErr: (msg: string) => console.error("[sqlite-wasm]", msg),
|
|
61
|
+
...(opts.wasmURL ? { locateFile: (name: string) => (name.endsWith(".wasm") ? opts.wasmURL! : name) } : {}),
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
// OO1 transient-DB constructor: opens an in-memory DB then we restore the file bytes into it
|
|
65
|
+
// via `sqlite3.capi.sqlite3_deserialize`. This is the official way to "open a Uint8Array as a
|
|
66
|
+
// database" — `new DB(":memory:")` followed by deserialize is faster than CREATE TABLE +
|
|
67
|
+
// INSERT-from-dump and preserves the on-disk b-tree pages directly.
|
|
68
|
+
const db = new sqlite3.oo1.DB(":memory:", "ct")
|
|
69
|
+
|
|
70
|
+
// `allocFromTypedArray` has shape constraints across sqlite-wasm versions; the
|
|
71
|
+
// explicit alloc + HEAPU8.set pattern is the lowest-common-denominator path and
|
|
72
|
+
// avoids the "expecting 8/16/32/64" heap-shape mismatch seen on Node builds.
|
|
73
|
+
const p = sqlite3.wasm.alloc(bytes.byteLength)
|
|
74
|
+
const heap = sqlite3.wasm.heap8u()
|
|
75
|
+
heap.set(bytes, p)
|
|
76
|
+
const rc = sqlite3.capi.sqlite3_deserialize(
|
|
77
|
+
db.pointer!,
|
|
78
|
+
"main",
|
|
79
|
+
p,
|
|
80
|
+
bytes.byteLength,
|
|
81
|
+
bytes.byteLength,
|
|
82
|
+
sqlite3.capi.SQLITE_DESERIALIZE_FREEONCLOSE | sqlite3.capi.SQLITE_DESERIALIZE_RESIZEABLE
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if (rc !== sqlite3.capi.SQLITE_OK) {
|
|
86
|
+
sqlite3.wasm.dealloc(p)
|
|
87
|
+
db.close()
|
|
88
|
+
throw new Error(`sqlite3_deserialize failed: rc=${rc}`)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return { db, sqlite3 }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function fetchBytes(url: string, fetchImpl?: typeof fetch): Promise<Uint8Array> {
|
|
95
|
+
const f = fetchImpl ?? globalThis.fetch
|
|
96
|
+
|
|
97
|
+
if (!f) throw new Error("no fetch implementation available — pass fetchImpl in non-fetch environments")
|
|
98
|
+
const res = await f(url)
|
|
99
|
+
|
|
100
|
+
if (!res.ok) throw new Error(`fetch ${url} failed: ${res.status} ${res.statusText}`)
|
|
101
|
+
|
|
102
|
+
return new Uint8Array(await res.arrayBuffer())
|
|
103
|
+
}
|
package/lookup.ts
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* `WOFWasmPlaceLookup` — browser-side `PlaceLookup` backed by `@sqlite.org/sqlite-wasm`.
|
|
7
|
+
*
|
|
8
|
+
* V1 scope: text + placetype + limit + country. The full ranking surface from
|
|
9
|
+
* `WOFSqlitePlaceLookup` (parentID descendant filter, near-proximity boost, bbox hard filter,
|
|
10
|
+
* population-weighted ordering) is queued for v2 in the same PR series — see Phase B tracking
|
|
11
|
+
* issue #98. The v1 scope is the minimum that lets the public demo answer "type a US city /
|
|
12
|
+
* postcode, get a hit".
|
|
13
|
+
*
|
|
14
|
+
* Internally this is a thin facade over the OO1 DB returned by `loadSlimWOFDatabase`. The SQL we
|
|
15
|
+
* issue is the same SQLite dialect the Node implementation uses — once we extract the SQL
|
|
16
|
+
* building into a shared helper (planned: `@mailwoman/resolver-wof-sqlite/query-builder`), both
|
|
17
|
+
* implementations will call into the same builder and the parity guarantee becomes mechanical
|
|
18
|
+
* rather than convention-driven.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { expandPlacetypeFilter, type CoincidentLocality } from "@mailwoman/resolver"
|
|
22
|
+
import type { FindPlaceQuery, PlaceCandidate, PlaceLookup, WOFPlacetype } from "@mailwoman/resolver-wof-sqlite"
|
|
23
|
+
// Browser-safe subpath import (fts.ts's only node:sqlite import is type-only) — the shared
|
|
24
|
+
// alias-bag parser keeps this backend's exact tier byte-identical to the Node resolver's.
|
|
25
|
+
import { aliasBagExactMatch } from "@mailwoman/resolver-wof-sqlite/fts"
|
|
26
|
+
import type { Database } from "@sqlite.org/sqlite-wasm"
|
|
27
|
+
|
|
28
|
+
export interface WOFWasmPlaceLookupOpts {
|
|
29
|
+
/** Open `@sqlite.org/sqlite-wasm` Database (from `loadSlimWOFDatabase`). */
|
|
30
|
+
db: Database
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Population-boost tunables, mirroring `resolver-wof-sqlite/lookup.ts` defaults. The boost is `POPULATION_BOOST *
|
|
35
|
+
* min(1, log10(1 + pop) / POPULATION_SCALE_LOG10)`, subtracted from bm25 (lower = better, matching SQLite's
|
|
36
|
+
* convention). A 1M-population city earns the full boost — enough to surface the famous same-name place ("New York"
|
|
37
|
+
* over "West New York") without steamrolling a clearly-better text match, because exact-name tiering is consulted
|
|
38
|
+
* FIRST.
|
|
39
|
+
*/
|
|
40
|
+
const POPULATION_BOOST = 4.0
|
|
41
|
+
const POPULATION_SCALE_LOG10 = 6.0
|
|
42
|
+
|
|
43
|
+
/** Normalize a name/query for exact-match tiering: lowercase, trim, collapse internal whitespace. */
|
|
44
|
+
function normalizeName(s: string): string {
|
|
45
|
+
return s.toLowerCase().trim().replace(/\s+/g, " ")
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class WOFWasmPlaceLookup implements PlaceLookup {
|
|
49
|
+
readonly #db: Database
|
|
50
|
+
#hasPopulationCache?: boolean
|
|
51
|
+
#hasPlaceAbbrCache?: boolean
|
|
52
|
+
/**
|
|
53
|
+
* Lazily-built `admin_id → coincident localities` map from the #403 relation (the slim DB carries it).
|
|
54
|
+
*/
|
|
55
|
+
#coincidentRolesCache?: Map<number, CoincidentLocality[]>
|
|
56
|
+
|
|
57
|
+
constructor(opts: WOFWasmPlaceLookupOpts) {
|
|
58
|
+
this.#db = opts.db
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Lazily probe (once) whether the slim DB carries the `place_population` aux table. */
|
|
62
|
+
#hasPopulation(): boolean {
|
|
63
|
+
if (this.#hasPopulationCache === undefined) {
|
|
64
|
+
const r = this.#db.selectObjects(
|
|
65
|
+
`SELECT 1 FROM sqlite_master WHERE type='table' AND name='place_population' LIMIT 1`
|
|
66
|
+
)
|
|
67
|
+
this.#hasPopulationCache = r.length > 0
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return this.#hasPopulationCache
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Lazily probe (once) whether the slim DB carries the `place_abbr` aux table (build-slim ≥ #189). */
|
|
74
|
+
#hasPlaceAbbr(): boolean {
|
|
75
|
+
if (this.#hasPlaceAbbrCache === undefined) {
|
|
76
|
+
const r = this.#db.selectObjects(`SELECT 1 FROM sqlite_master WHERE type='table' AND name='place_abbr' LIMIT 1`)
|
|
77
|
+
this.#hasPlaceAbbrCache = r.length > 0
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return this.#hasPlaceAbbrCache
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Ids whose region abbreviation exactly equals `text` (case-insensitive), from `place_abbr`. The exact-abbrev tier
|
|
85
|
+
* signal — see the `findPlace` call site. Empty on slim DBs without the table.
|
|
86
|
+
*/
|
|
87
|
+
#abbrExactIds(text: string): Set<number> {
|
|
88
|
+
const t = text.trim()
|
|
89
|
+
|
|
90
|
+
if (!t || !this.#hasPlaceAbbr()) return new Set()
|
|
91
|
+
const rows = this.#db.selectObjects(`SELECT id FROM place_abbr WHERE abbr = ? COLLATE NOCASE`, [t]) as Array<{
|
|
92
|
+
id: number
|
|
93
|
+
}>
|
|
94
|
+
|
|
95
|
+
return new Set(rows.map((r) => Number(r.id)))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async findPlace(query: FindPlaceQuery): Promise<PlaceCandidate[]> {
|
|
99
|
+
const text = (query.text ?? "").trim()
|
|
100
|
+
|
|
101
|
+
if (!text) return []
|
|
102
|
+
|
|
103
|
+
// Postcode-typed queries keep the #920 fused name-law shape; everything else splits on
|
|
104
|
+
// intra-token punctuation so hyphenated names reach the FTS as their real terms (#945) —
|
|
105
|
+
// parity with the resolver-wof-sqlite implementation.
|
|
106
|
+
const ftsQuery = sanitizeFTSQuery(text, {
|
|
107
|
+
fuseTokens: normalizePlacetypes(query.placetype)?.includes("postalcode") ?? false,
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
if (!ftsQuery) return []
|
|
111
|
+
|
|
112
|
+
const limit = Math.max(1, query.limit ?? 10)
|
|
113
|
+
|
|
114
|
+
// FTS5 MATCH on place_search joined to spr. Placetype + country filters are pushed into the
|
|
115
|
+
// WHERE clause because they reduce candidate count cheaply.
|
|
116
|
+
const conditions: string[] = ["place_search MATCH ?", "spr.is_current != 0", "spr.is_deprecated = 0"]
|
|
117
|
+
const params: Array<string | number> = [ftsQuery]
|
|
118
|
+
|
|
119
|
+
// Shared placetype-equivalence expansion (core/resolver): a `locality` query must also reach
|
|
120
|
+
// `borough` / `localadmin` rows. Without it, Brooklyn-the-borough (pop 2.5M, an EXACT name
|
|
121
|
+
// match) was unreachable and the fuzzy "Brooklyn Park, MN" won. Same table the Node resolver
|
|
122
|
+
// uses — the two backends can't drift.
|
|
123
|
+
const placetypes = expandPlacetypeFilter(normalizePlacetypes(query.placetype)) as WOFPlacetype[] | null
|
|
124
|
+
|
|
125
|
+
if (placetypes && placetypes.length > 0) {
|
|
126
|
+
conditions.push(`spr.placetype IN (${placetypes.map(() => "?").join(",")})`)
|
|
127
|
+
params.push(...placetypes)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (query.country) {
|
|
131
|
+
conditions.push("spr.country = ?")
|
|
132
|
+
params.push(query.country.toUpperCase())
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Point-in-bbox filter. Used to constrain a locality lookup to a parsed region/state's bounds
|
|
136
|
+
// (e.g. "Roseville, Michigan" → only the Roseville whose centroid sits in Michigan's bbox),
|
|
137
|
+
// which the broken-in-the-slim-DB parent_id chain can't do via descendant filtering.
|
|
138
|
+
if (query.bbox) {
|
|
139
|
+
conditions.push("spr.latitude BETWEEN ? AND ?", "spr.longitude BETWEEN ? AND ?")
|
|
140
|
+
params.push(query.bbox.minLat, query.bbox.maxLat, query.bbox.minLon, query.bbox.maxLon)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Over-fetch a pool ordered by raw BM25, then re-rank in JS (exact-name tier, then
|
|
144
|
+
// population-weighted bm25). The over-fetch is essential: a famous place can sit a few rows
|
|
145
|
+
// below a tiny same-name town on raw BM25 ("New York" loses to "West New York" by a hair), so a
|
|
146
|
+
// tight LIMIT on bm25 alone would truncate it before the re-rank could pull it up. This mirrors
|
|
147
|
+
// the post-scoring tier + population boost in resolver-wof-sqlite/lookup.ts. (v1 issued pure
|
|
148
|
+
// bm25, which is why the demo targeted West New York for "New York, NY".)
|
|
149
|
+
const hasPop = this.#hasPopulation()
|
|
150
|
+
const pool = Math.max(limit, 50)
|
|
151
|
+
const sql =
|
|
152
|
+
`SELECT spr.id, spr.name, spr.placetype, spr.country, spr.latitude, spr.longitude, spr.parent_id, ` +
|
|
153
|
+
`spr.min_latitude, spr.max_latitude, spr.min_longitude, spr.max_longitude, ` +
|
|
154
|
+
`place_search.alt_names AS alt_names, ` +
|
|
155
|
+
`${hasPop ? "pp.population" : "NULL"} AS population, bm25(place_search) AS bm25 ` +
|
|
156
|
+
`FROM place_search JOIN spr ON spr.id = place_search.wof_id ` +
|
|
157
|
+
`${hasPop ? "LEFT JOIN place_population pp ON pp.id = spr.id " : ""}` +
|
|
158
|
+
`WHERE ${conditions.join(" AND ")} ` +
|
|
159
|
+
`ORDER BY bm25(place_search) ASC ` +
|
|
160
|
+
`LIMIT ?`
|
|
161
|
+
params.push(pool)
|
|
162
|
+
|
|
163
|
+
const rows = this.#db.selectObjects(sql, params) as Array<{
|
|
164
|
+
id: number
|
|
165
|
+
name: string
|
|
166
|
+
placetype: string
|
|
167
|
+
country: string
|
|
168
|
+
latitude: number
|
|
169
|
+
longitude: number
|
|
170
|
+
parent_id: number | null
|
|
171
|
+
min_latitude: number | null
|
|
172
|
+
max_latitude: number | null
|
|
173
|
+
min_longitude: number | null
|
|
174
|
+
max_longitude: number | null
|
|
175
|
+
alt_names: string | null
|
|
176
|
+
population: number | null
|
|
177
|
+
bm25: number
|
|
178
|
+
}>
|
|
179
|
+
|
|
180
|
+
const normQuery = normalizeName(text)
|
|
181
|
+
// Exact-abbreviation ids: region/state abbreviations live in the slim DB's `place_abbr` table
|
|
182
|
+
// (carried by build-slim before `names` is dropped). A candidate whose abbreviation equals the
|
|
183
|
+
// query is an EXACT match — same tier as an exact name match — so "VT" → Vermont outranks a
|
|
184
|
+
// foreign region that merely token-matches "VT" via a multilingual name fragment. No-op on slim
|
|
185
|
+
// DBs built before place_abbr (the table is absent → empty set). This is the data-driven
|
|
186
|
+
// replacement for the demo's hardcoded `expandUSRegion` map; it also generalizes beyond US.
|
|
187
|
+
const abbrIds = this.#abbrExactIds(text)
|
|
188
|
+
// Strict exact = canonical name or region abbreviation equals the query. Computed for the whole
|
|
189
|
+
// pool FIRST because the ALIAS tier below only engages when no strict exact exists.
|
|
190
|
+
const strictExact = (row: { name: string; id: number }): boolean =>
|
|
191
|
+
normalizeName(row.name) === normQuery || abbrIds.has(row.id)
|
|
192
|
+
const anyStrictExact = rows.some(strictExact)
|
|
193
|
+
|
|
194
|
+
return rows
|
|
195
|
+
.map((row) => {
|
|
196
|
+
// Alias tier: `alt_names` is the FTS row's alias bag (the slim DB's only surviving alias
|
|
197
|
+
// source), aliases joined on the boundary-preserving ALIAS_SEPARATOR (#523). The shared
|
|
198
|
+
// parser does a true per-alias equality check, ungated; on a LEGACY bag (pre-#523 slim
|
|
199
|
+
// artifact, boundaries lost) it falls back to padded containment gated on "no strictly
|
|
200
|
+
// exact candidate" so interior fragments ("York" inside "New York City") can't be
|
|
201
|
+
// false-promoted. Mirrors the Node resolver's alias tier
|
|
202
|
+
// (`WOFSqlitePlaceLookup.#exactMatchIds`).
|
|
203
|
+
const aliasExact = aliasBagExactMatch(row.alt_names, normQuery, anyStrictExact)
|
|
204
|
+
const exactTier = strictExact(row) || aliasExact ? 0 : 1
|
|
205
|
+
const popBoost =
|
|
206
|
+
row.population && row.population > 0
|
|
207
|
+
? POPULATION_BOOST * Math.min(1, Math.log10(1 + row.population) / POPULATION_SCALE_LOG10)
|
|
208
|
+
: 0
|
|
209
|
+
// Lower adjScore = better, matching SQLite's bm25 convention (more negative = better).
|
|
210
|
+
const adjScore = row.bm25 - popBoost
|
|
211
|
+
|
|
212
|
+
return { row, exactTier, adjScore }
|
|
213
|
+
})
|
|
214
|
+
.sort((a, b) => a.exactTier - b.exactTier || a.adjScore - b.adjScore)
|
|
215
|
+
.slice(0, limit)
|
|
216
|
+
.map(({ row, adjScore, exactTier }) => ({
|
|
217
|
+
id: row.id,
|
|
218
|
+
name: row.name,
|
|
219
|
+
placetype: row.placetype as WOFPlacetype,
|
|
220
|
+
country: row.country,
|
|
221
|
+
lat: row.latitude,
|
|
222
|
+
lon: row.longitude,
|
|
223
|
+
parent_id: row.parent_id ?? undefined,
|
|
224
|
+
// Surface the exact-match tier so a downstream country re-rank (#369) can keep the country
|
|
225
|
+
// pin from crossing it — parity with `WOFSqlitePlaceLookup`. See ResolvedPlace.exactMatch.
|
|
226
|
+
exactMatch: exactTier === 0,
|
|
227
|
+
bbox:
|
|
228
|
+
row.min_latitude != null && row.max_latitude != null && row.min_longitude != null && row.max_longitude != null
|
|
229
|
+
? {
|
|
230
|
+
minLat: row.min_latitude,
|
|
231
|
+
maxLat: row.max_latitude,
|
|
232
|
+
minLon: row.min_longitude,
|
|
233
|
+
maxLon: row.max_longitude,
|
|
234
|
+
}
|
|
235
|
+
: undefined,
|
|
236
|
+
// Flip sign so higher = better (PlaceLookup contract). The adjusted, population-aware
|
|
237
|
+
// score is what we sorted by, so callers see the same ordering they're shown.
|
|
238
|
+
score: -adjScore,
|
|
239
|
+
}))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Dual-role localities coincident with an admin id, from the `coincident_roles` relation (#403) carried into the slim
|
|
244
|
+
* DB by build-slim. Backs the resolver's hierarchy completion (on by default) in the browser — mirrors
|
|
245
|
+
* `WOFSqlitePlaceLookup.coincidentLocalitiesFor`. Returns `[]` when the slim DB predates the relation. Loaded once +
|
|
246
|
+
* memoized (the relation is ~hundreds of rows).
|
|
247
|
+
*/
|
|
248
|
+
coincidentLocalitiesFor(adminID: number | string): CoincidentLocality[] {
|
|
249
|
+
const id = typeof adminID === "number" ? adminID : Number(adminID)
|
|
250
|
+
|
|
251
|
+
if (!Number.isFinite(id)) return []
|
|
252
|
+
|
|
253
|
+
if (!this.#coincidentRolesCache) {
|
|
254
|
+
const map = new Map<number, CoincidentLocality[]>()
|
|
255
|
+
const exists = this.#db.selectObjects(
|
|
256
|
+
`SELECT 1 FROM sqlite_master WHERE type='table' AND name='coincident_roles' LIMIT 1`
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
if (exists.length > 0) {
|
|
260
|
+
const rows = this.#db.selectObjects(
|
|
261
|
+
`SELECT cr.admin_id AS adminID, s.id AS id, s.name AS name, s.country AS country,
|
|
262
|
+
s.latitude AS lat, s.longitude AS lon, cr.relationship_type AS relationshipType,
|
|
263
|
+
cr.locality_population AS population, cr.distance_km AS distanceKm
|
|
264
|
+
FROM coincident_roles cr JOIN spr s ON s.id = cr.locality_id`
|
|
265
|
+
) as Array<{
|
|
266
|
+
adminID: number
|
|
267
|
+
id: number
|
|
268
|
+
name: string
|
|
269
|
+
country: string
|
|
270
|
+
lat: number
|
|
271
|
+
lon: number
|
|
272
|
+
relationshipType: string
|
|
273
|
+
population: number
|
|
274
|
+
distanceKm: number
|
|
275
|
+
}>
|
|
276
|
+
|
|
277
|
+
for (const r of rows) {
|
|
278
|
+
const candidate: CoincidentLocality = {
|
|
279
|
+
id: r.id,
|
|
280
|
+
name: r.name,
|
|
281
|
+
placetype: "locality",
|
|
282
|
+
country: r.country,
|
|
283
|
+
lat: r.lat,
|
|
284
|
+
lon: r.lon,
|
|
285
|
+
score: 0,
|
|
286
|
+
relationshipType: r.relationshipType,
|
|
287
|
+
population: r.population,
|
|
288
|
+
distanceKm: r.distanceKm,
|
|
289
|
+
}
|
|
290
|
+
const list = map.get(r.adminID)
|
|
291
|
+
|
|
292
|
+
if (list) {
|
|
293
|
+
list.push(candidate)
|
|
294
|
+
} else {
|
|
295
|
+
map.set(r.adminID, [candidate])
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
this.#coincidentRolesCache = map
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
return this.#coincidentRolesCache.get(id) ?? []
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
close(): void {
|
|
306
|
+
this.#db.close()
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Trim raw user input into something FTS5 will accept. Preserves trailing `*` as the FTS5 prefix operator (matching the
|
|
312
|
+
* resolver-wof-sqlite implementation). Strips characters FTS5 treats as punctuation or operators so a user typing
|
|
313
|
+
* `Paris's` or `St. (Petersburg)` doesn't trigger an "fts5: syntax error" inside the WASM runtime.
|
|
314
|
+
*/
|
|
315
|
+
function sanitizeFTSQuery(text: string, opts?: { fuseTokens?: boolean }): string {
|
|
316
|
+
const out: string[] = []
|
|
317
|
+
|
|
318
|
+
for (const rawToken of text.normalize("NFKC").split(/\s+/u)) {
|
|
319
|
+
const trimmed = rawToken.trim()
|
|
320
|
+
|
|
321
|
+
if (!trimmed) continue
|
|
322
|
+
const hasPrefixStar = trimmed.endsWith("*")
|
|
323
|
+
|
|
324
|
+
// #920 name law (postcode-typed queries): delete intra-token punctuation and fuse.
|
|
325
|
+
if (opts?.fuseTokens) {
|
|
326
|
+
const body = trimmed.replace(/[^\p{L}\p{N}]/gu, "")
|
|
327
|
+
|
|
328
|
+
if (!body) continue
|
|
329
|
+
out.push(hasPrefixStar ? `${body}*` : `"${body.replace(/"/g, '""')}"`)
|
|
330
|
+
continue
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// Non-postcode queries SPLIT on intra-token punctuation — fusing made "Thiron-Gardais" an
|
|
334
|
+
// unmatchable single term while the FTS doc holds two (#945).
|
|
335
|
+
const parts = trimmed.split(/[^\p{L}\p{N}]+/u).filter(Boolean)
|
|
336
|
+
|
|
337
|
+
for (let i = 0; i < parts.length; i++) {
|
|
338
|
+
const body = parts[i]!.replace(/\*/g, "")
|
|
339
|
+
|
|
340
|
+
if (!body) continue
|
|
341
|
+
out.push(hasPrefixStar && i === parts.length - 1 ? `${body}*` : `"${body.replace(/"/g, '""')}"`)
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return out.join(" ")
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function normalizePlacetypes(input: FindPlaceQuery["placetype"]): WOFPlacetype[] | null {
|
|
349
|
+
if (!input) return null
|
|
350
|
+
|
|
351
|
+
return Array.isArray(input) ? input : [input]
|
|
352
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mailwoman/resolver-wof-wasm",
|
|
3
|
-
"version": "7.2.
|
|
3
|
+
"version": "7.2.1",
|
|
4
4
|
"description": "Who's On First WASM resolver — browser-side PlaceLookup backed by @sqlite.org/sqlite-wasm. Drop-in replacement for @mailwoman/resolver-wof-sqlite when you need a static-asset deploy (Phase B of the demo plan).",
|
|
5
5
|
"license": "AGPL-3.0-only OR LicenseRef-Commercial",
|
|
6
6
|
"repository": {
|
|
@@ -13,24 +13,38 @@
|
|
|
13
13
|
"out/**/*.js.map",
|
|
14
14
|
"out/**/*.d.ts",
|
|
15
15
|
"out/**/*.d.ts.map",
|
|
16
|
-
"README.md"
|
|
16
|
+
"README.md",
|
|
17
|
+
"*.ts",
|
|
18
|
+
"*.tsx",
|
|
19
|
+
"**/*.ts",
|
|
20
|
+
"**/*.tsx",
|
|
21
|
+
"!*.test.ts",
|
|
22
|
+
"!*.test.tsx",
|
|
23
|
+
"!**/*.test.ts",
|
|
24
|
+
"!**/*.test.tsx"
|
|
17
25
|
],
|
|
18
26
|
"type": "module",
|
|
19
27
|
"exports": {
|
|
20
28
|
"./package.json": "./package.json",
|
|
21
29
|
".": {
|
|
22
|
-
"
|
|
23
|
-
"default": "./out/index.js"
|
|
24
|
-
"types": "./out/index.d.ts"
|
|
30
|
+
"types": "./out/index.d.ts",
|
|
31
|
+
"default": "./out/index.js"
|
|
25
32
|
}
|
|
26
33
|
},
|
|
27
34
|
"publishConfig": {
|
|
28
|
-
"access": "public"
|
|
35
|
+
"access": "public",
|
|
36
|
+
"exports": {
|
|
37
|
+
"./package.json": "./package.json",
|
|
38
|
+
".": {
|
|
39
|
+
"types": "./out/index.d.ts",
|
|
40
|
+
"default": "./out/index.js"
|
|
41
|
+
}
|
|
42
|
+
}
|
|
29
43
|
},
|
|
30
44
|
"dependencies": {
|
|
31
|
-
"@mailwoman/core": "7.2.
|
|
32
|
-
"@mailwoman/resolver": "7.2.
|
|
33
|
-
"@mailwoman/resolver-wof-sqlite": "7.2.
|
|
45
|
+
"@mailwoman/core": "7.2.1",
|
|
46
|
+
"@mailwoman/resolver": "7.2.1",
|
|
47
|
+
"@mailwoman/resolver-wof-sqlite": "7.2.1",
|
|
34
48
|
"@sqlite.org/sqlite-wasm": "^3.53.0-build1"
|
|
35
49
|
}
|
|
36
50
|
}
|