@mailwoman/resolver-wof-sqlite 12.1.0 → 12.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 (49) hide show
  1. package/lib/address/keys/lookup.ts +114 -0
  2. package/lib/address/keys/open.ts +1 -0
  3. package/lib/address/keys/point-lookup.ts +57 -2
  4. package/lib/address/point/schema.ts +113 -35
  5. package/lib/address/point.ts +141 -5
  6. package/lib/labels/street/normalize.ts +121 -1
  7. package/lib/landmark.ts +43 -2
  8. package/lib/poi/lookup.ts +144 -52
  9. package/lib/poi/schema.ts +9 -1
  10. package/lib/weights/overlay-linker.ts +6 -2
  11. package/out/address/keys/lookup.d.ts +25 -0
  12. package/out/address/keys/lookup.d.ts.map +1 -1
  13. package/out/address/keys/lookup.js +63 -0
  14. package/out/address/keys/lookup.js.map +1 -1
  15. package/out/address/keys/open.d.ts.map +1 -1
  16. package/out/address/keys/open.js +1 -0
  17. package/out/address/keys/open.js.map +1 -1
  18. package/out/address/keys/point-lookup.d.ts +6 -1
  19. package/out/address/keys/point-lookup.d.ts.map +1 -1
  20. package/out/address/keys/point-lookup.js +39 -1
  21. package/out/address/keys/point-lookup.js.map +1 -1
  22. package/out/address/point/schema.d.ts +3 -1
  23. package/out/address/point/schema.d.ts.map +1 -1
  24. package/out/address/point/schema.js +87 -31
  25. package/out/address/point/schema.js.map +1 -1
  26. package/out/address/point.d.ts +12 -1
  27. package/out/address/point.d.ts.map +1 -1
  28. package/out/address/point.js +88 -4
  29. package/out/address/point.js.map +1 -1
  30. package/out/labels/street/normalize.d.ts.map +1 -1
  31. package/out/labels/street/normalize.js +115 -1
  32. package/out/labels/street/normalize.js.map +1 -1
  33. package/out/landmark.d.ts +8 -0
  34. package/out/landmark.d.ts.map +1 -1
  35. package/out/landmark.js +25 -2
  36. package/out/landmark.js.map +1 -1
  37. package/out/poi/lookup.d.ts +5 -1
  38. package/out/poi/lookup.d.ts.map +1 -1
  39. package/out/poi/lookup.js +111 -53
  40. package/out/poi/lookup.js.map +1 -1
  41. package/out/poi/schema.d.ts +7 -2
  42. package/out/poi/schema.d.ts.map +1 -1
  43. package/out/poi/schema.js +3 -0
  44. package/out/poi/schema.js.map +1 -1
  45. package/out/weights/overlay-linker.d.ts +1 -1
  46. package/out/weights/overlay-linker.d.ts.map +1 -1
  47. package/out/weights/overlay-linker.js +5 -1
  48. package/out/weights/overlay-linker.js.map +1 -1
  49. package/package.json +12 -12
@@ -61,6 +61,21 @@ export interface AddressKeyHit {
61
61
  level: AddressKeyLevel
62
62
  }
63
63
 
64
+ /**
65
+ * One precomputed street aggregate row from `street_postcode` or `street_locality`.
66
+ */
67
+ export interface AddressStreetHit {
68
+ lat: number
69
+ lon: number
70
+ minLat: number
71
+ maxLat: number
72
+ minLon: number
73
+ maxLon: number
74
+ points: number
75
+ level: typeof AddressKeyLevel.Postcode | typeof AddressKeyLevel.Locality
76
+ matchedStreet: string
77
+ }
78
+
64
79
  /**
65
80
  * What a parse resolved, in the encoder's terms.
66
81
  */
@@ -124,9 +139,22 @@ interface KeyRow {
124
139
  source_id: number
125
140
  }
126
141
 
142
+ interface StreetRow {
143
+ lat: number
144
+ lon: number
145
+ min_lat: number
146
+ max_lat: number
147
+ min_lon: number
148
+ max_lon: number
149
+ points: number
150
+ }
151
+
127
152
  const SELECT_SCOPED = (table: string, cap: number) =>
128
153
  `SELECT lat, lon, address_id, source_id FROM ${table} WHERE scope = ? AND street = ? AND number = ? LIMIT ${cap}`
129
154
 
155
+ const SELECT_STREET = (table: "street_postcode" | "street_locality") =>
156
+ `SELECT lat, lon, min_lat, max_lat, min_lon, max_lon, points FROM ${table} WHERE scope = ? AND street = ? LIMIT 1`
157
+
130
158
  /**
131
159
  * Finds address points by the most precise level a parse states: postcode,
132
160
  * then each locality name, then the subregion, then the file's whole region.
@@ -277,6 +305,74 @@ export class AddressKeyLookup {
277
305
  return null
278
306
  }
279
307
 
308
+ /**
309
+ * Finds the precomputed street aggregate row inside a postcode or locality.
310
+ *
311
+ * When `query.postcode` is supplied, only `street_postcode` is queried.
312
+ * When `query.postcode` is absent, `street_locality` is queried for each locality.
313
+ */
314
+ async findStreet(query: {
315
+ street: string
316
+ postcode?: string | null
317
+ localities?: readonly string[]
318
+ }): Promise<AddressStreetHit | null> {
319
+ const postcodeRaw = query.postcode?.trim() || null
320
+ const postcode = postcodeRaw ? addressPostcodeKey(this.#country, postcodeRaw) : ""
321
+
322
+ const localities = (query.localities ?? [])
323
+ .map((locality) => normalizeLocalityForKey(locality))
324
+ .filter((key) => key.length > 0)
325
+
326
+ if (postcodeRaw && !postcode) return null
327
+
328
+ if (!postcode && !localities.length) return null
329
+
330
+ const tables = await this.#optionalTables()
331
+ const streetTable: "street_postcode" | "street_locality" = postcode ? "street_postcode" : "street_locality"
332
+
333
+ if (!tables.has(streetTable)) return null
334
+
335
+ const aliasTable: "street_alias_postcode" | "street_alias_locality" = postcode
336
+ ? "street_alias_postcode"
337
+ : "street_alias_locality"
338
+
339
+ const level = postcode ? AddressKeyLevel.Postcode : AddressKeyLevel.Locality
340
+ const scopeValues = postcode ? [postcode] : localities
341
+ const surfaceLocale = streetLocaleForSurface(query.street, this.#locale)
342
+ const variants = streetKeyVariants(query.street, surfaceLocale).filter((key) => key.length > 0)
343
+
344
+ for (const scope of scopeValues) {
345
+ for (const street of variants) {
346
+ const [row] = await this.#runner.query<StreetRow>(SELECT_STREET(streetTable), [scope, street])
347
+
348
+ if (row && Number(row.points) > 0) {
349
+ return toStreetHit(row, level, street)
350
+ }
351
+ }
352
+
353
+ if (!tables.has(aliasTable)) continue
354
+
355
+ const canon = canonicalStreetKey(query.street, surfaceLocale)
356
+
357
+ if (!canon.key) continue
358
+
359
+ const aliasRows = await this.#runner.query<{ street: string }>(
360
+ `SELECT street FROM ${aliasTable} WHERE scope = ? AND street_canon = ?`,
361
+ [scope, canon.key]
362
+ )
363
+
364
+ for (const { street } of aliasRows) {
365
+ const [row] = await this.#runner.query<StreetRow>(SELECT_STREET(streetTable), [scope, street])
366
+
367
+ if (row && Number(row.points) > 0) {
368
+ return toStreetHit(row, level, street)
369
+ }
370
+ }
371
+ }
372
+
373
+ return null
374
+ }
375
+
280
376
  #aliasScopes(query: AddressKeyQuery): Array<{
281
377
  level: AddressKeyLevel
282
378
  keyTable: "key_postcode" | "key_locality"
@@ -401,3 +497,21 @@ function toHit(row: KeyRow, level: AddressKeyLevel): AddressKeyHit {
401
497
  level,
402
498
  }
403
499
  }
500
+
501
+ function toStreetHit(
502
+ row: StreetRow,
503
+ level: typeof AddressKeyLevel.Postcode | typeof AddressKeyLevel.Locality,
504
+ matchedStreet: string
505
+ ): AddressStreetHit {
506
+ return {
507
+ lat: Number(row.lat),
508
+ lon: Number(row.lon),
509
+ minLat: Number(row.min_lat),
510
+ maxLat: Number(row.max_lat),
511
+ minLon: Number(row.min_lon),
512
+ maxLon: Number(row.max_lon),
513
+ points: Number(row.points),
514
+ level,
515
+ matchedStreet,
516
+ }
517
+ }
@@ -25,6 +25,7 @@ export function openAddressLayerLookup(lookupPath: PathBuilderLike, country: str
25
25
 
26
26
  return {
27
27
  find: (query) => lookup.find(query),
28
+ findStreetCentroid: (query) => lookup.findStreetCentroid(query),
28
29
  [Symbol.dispose]: () => {
29
30
  db[Symbol.dispose]()
30
31
  detail[Symbol.dispose]()
@@ -7,8 +7,9 @@
7
7
  */
8
8
 
9
9
  import { memoizeResettable } from "@mailwoman/core/async/memoize"
10
- import type { AddressPointHit, AddressPointLookup } from "@mailwoman/core/resolver"
10
+ import type { AddressPointHit, AddressPointLookup, StreetCentroidHit } from "@mailwoman/core/resolver"
11
11
  import { parseJSONStrict } from "@mailwoman/core/values/json"
12
+ import { haversine } from "@mailwoman/spatial"
12
13
  import { type LatLonBounds, latLonBoundsContain } from "@mailwoman/spatial/bbox"
13
14
 
14
15
  import {
@@ -93,6 +94,28 @@ export class AddressKeyPointLookup implements AddressPointLookup {
93
94
  return undefined
94
95
  }
95
96
 
97
+ /**
98
+ * Selects the first hit whose `detail.db` record has no sub-unit (`unit IS NULL OR unit = ''`),
99
+ * so a base building beats a sub-unit outbuilding (`FUEL CENTE`, `APT 2`)
100
+ * when multiple records share `(scope, street, number)`.
101
+ */
102
+ async #preferBaseBuilding(hits: readonly AddressKeyHit[]): Promise<AddressKeyHit | undefined> {
103
+ const first = hits[0]
104
+
105
+ if (!first || hits.length <= 1 || !this.#detail) return first
106
+
107
+ const placeholders = hits.map(() => "?").join(", ")
108
+
109
+ const rows = await this.#detail.query<{ address_id: number }>(
110
+ `SELECT address_id FROM address WHERE address_id IN (${placeholders}) AND (unit IS NULL OR unit = '')`,
111
+ hits.map((hit) => hit.addressID)
112
+ )
113
+
114
+ const baseIDs = new Set(rows.map((row) => Number(row.address_id)))
115
+
116
+ return hits.find((hit) => baseIDs.has(hit.addressID)) ?? first
117
+ }
118
+
96
119
  async find(query: Parameters<AddressPointLookup["find"]>[0]): Promise<AddressPointHit | null> {
97
120
  const answer = await this.#lookup.find({
98
121
  street: query.street,
@@ -109,7 +132,7 @@ export class AddressKeyPointLookup implements AddressPointLookup {
109
132
  ? query.bbox
110
133
  ? await this.#unscopedInside(answer.hits, query.bbox)
111
134
  : undefined
112
- : answer.hits[0]
135
+ : await this.#preferBaseBuilding(answer.hits)
113
136
 
114
137
  if (!hit) return null
115
138
 
@@ -131,4 +154,36 @@ export class AddressKeyPointLookup implements AddressPointLookup {
131
154
  streetMatch: answer.streetMatch,
132
155
  }
133
156
  }
157
+
158
+ async findStreetCentroid(query: {
159
+ street: string
160
+ postcode?: string
161
+ locality?: string
162
+ }): Promise<StreetCentroidHit | null> {
163
+ const hit = await this.#lookup.findStreet({
164
+ street: query.street,
165
+ postcode: query.postcode ?? null,
166
+ localities: query.locality ? [query.locality] : [],
167
+ })
168
+
169
+ if (!hit) return null
170
+
171
+ const spanKm = haversine(hit.minLat, hit.minLon, hit.maxLat, hit.maxLon)
172
+
173
+ if (!Number.isFinite(spanKm) || spanKm > MAX_STREET_CENTROID_SPAN_KM) return null
174
+
175
+ const [sources, release] = await Promise.all([this.#sourceNames(), this.#releaseVersion()])
176
+ const source = sources.size === 1 ? ([...sources.values()][0] ?? "address-layer") : "address-layer"
177
+
178
+ return {
179
+ lat: hit.lat,
180
+ lon: hit.lon,
181
+ uncertaintyM: Math.max(MIN_STREET_CENTROID_UNCERTAINTY_M, Math.round((spanKm * 1000) / 2)),
182
+ source,
183
+ release,
184
+ }
185
+ }
134
186
  }
187
+
188
+ const MAX_STREET_CENTROID_SPAN_KM = 25
189
+ const MIN_STREET_CENTROID_UNCERTAINTY_M = 50
@@ -90,7 +90,14 @@ export type AddressPointSchemaHandle = Pick<Kysely<AddressPointDatabase>, "schem
90
90
  /**
91
91
  * The subset of a `DatabaseClient` needed to create and populate `street_scope_index`.
92
92
  */
93
- export type StreetScopeIndexHandle = Pick<DatabaseClient<AddressPointDatabase>, "schema" | "exec" | "function">
93
+ export type StreetScopeIndexHandle = Pick<DatabaseClient<AddressPointDatabase>, "schema" | "exec" | "prepare">
94
+
95
+ /**
96
+ * Default number of rows written per transaction when streaming into `street_scope_index`.
97
+ *
98
+ * Keeps WAL growth bounded on 50M–100M+ row builds while amortizing commit overhead.
99
+ */
100
+ const DEFAULT_SCOPE_INDEX_BATCH_SIZE = 100_000
94
101
 
95
102
  /**
96
103
  * The `address_point` columns in insert order, from which the builder derives its positional placeholders.
@@ -171,6 +178,77 @@ export async function createStreetScopeIndexTable(db: AddressPointSchemaHandle):
171
178
  .execute()
172
179
  }
173
180
 
181
+ /**
182
+ * Streams distinct scope rows from one query into `street_scope_index` in batched transactions.
183
+ *
184
+ * A single `db.exec()` call with JS SQLite user-defined functions retains V8 handles
185
+ * across millions of invocations and exhausts an 8 GiB heap on 50M–100M+ row builds.
186
+ * The `StatementSync.iterate()` cursor returns control to V8 on every row
187
+ * so temporary keys are collected between batches.
188
+ */
189
+ function streamScopeRows(params: {
190
+ db: StreetScopeIndexHandle
191
+ selectSQL: string
192
+ scopeKind: "postcode" | "locality"
193
+ streetLocale: StreetLocale
194
+ batchSize: number
195
+ formatScope: (raw: unknown) => string
196
+ }): void {
197
+ const { db, selectSQL, scopeKind, streetLocale, batchSize, formatScope } = params
198
+ const select = db.prepare(selectSQL)
199
+
200
+ const insert = db.prepare(
201
+ "INSERT OR IGNORE INTO street_scope_index (scope_kind, scope, street_canon, street_norm) VALUES (?, ?, ?, ?)"
202
+ )
203
+
204
+ let inTransaction = false
205
+ let inBatch = 0
206
+
207
+ try {
208
+ db.exec("BEGIN")
209
+ inTransaction = true
210
+
211
+ for (const row of select.iterate()) {
212
+ const scope = formatScope(row["scope_raw"])
213
+
214
+ if (!scope) continue
215
+
216
+ const streetRaw = typeof row["street_raw"] === "string" ? row["street_raw"] : ""
217
+
218
+ if (!streetRaw) continue
219
+
220
+ const canon = canonicalStreetKey(streetRaw, streetLocale).key
221
+
222
+ if (!canon) continue
223
+
224
+ const streetNorm = typeof row["street_norm"] === "string" ? row["street_norm"] : ""
225
+
226
+ if (!streetNorm) continue
227
+
228
+ insert.run(scopeKind, scope, canon, streetNorm)
229
+
230
+ inBatch++
231
+
232
+ if (inBatch >= batchSize) {
233
+ db.exec("COMMIT")
234
+ inTransaction = false
235
+ db.exec("BEGIN")
236
+ inTransaction = true
237
+ inBatch = 0
238
+ }
239
+ }
240
+
241
+ db.exec("COMMIT")
242
+ inTransaction = false
243
+ } catch (error) {
244
+ if (inTransaction) {
245
+ db.exec("ROLLBACK")
246
+ }
247
+
248
+ throw error
249
+ }
250
+ }
251
+
174
252
  /**
175
253
  * Creates and populates `street_scope_index` from a table holding `postcode`,
176
254
  * `street_raw`, `street_norm`, and `localityColumn`.
@@ -185,49 +263,49 @@ export async function populateStreetScopeIndex(
185
263
  sourceTable: "address_point" | "street_centroid"
186
264
  localityColumn: "locality_norm" | "locality_base"
187
265
  country?: string
266
+ batchSize?: number
188
267
  }
189
268
  ): Promise<void> {
269
+ const batchSize = options.batchSize ?? DEFAULT_SCOPE_INDEX_BATCH_SIZE
270
+
271
+ if (!Number.isInteger(batchSize) || batchSize < 1) {
272
+ throw new RangeError(`populateStreetScopeIndex: batchSize must be a positive integer, got ${batchSize}`)
273
+ }
274
+
190
275
  await createStreetScopeIndexTable(db)
191
276
 
192
277
  const rules = streetKeyRulesOf(streetLocale)
193
278
  const { sourceTable, localityColumn, country } = options
194
279
 
195
- db.function("mw_street_canon", { deterministic: true }, (streetRaw: unknown): string =>
196
- typeof streetRaw === "string" && streetRaw ? canonicalStreetKey(streetRaw, streetLocale).key : ""
197
- )
198
-
199
- db.function("mw_postcode_scope", { deterministic: true }, (postcode: unknown): string => {
200
- if (typeof postcode !== "string") return ""
280
+ streamScopeRows({
281
+ db,
282
+ selectSQL: `
283
+ SELECT DISTINCT postcode AS scope_raw, street_raw, street_norm
284
+ FROM ${sourceTable}
285
+ WHERE postcode IS NOT NULL AND postcode != ''
286
+ `,
287
+ scopeKind: "postcode",
288
+ streetLocale,
289
+ batchSize,
290
+ formatScope: (raw) => {
291
+ if (typeof raw !== "string") return ""
201
292
 
202
- return (country ? addressPostcodeKey(country, postcode) : rules.postcodeKey(postcode)) ?? ""
293
+ return (country ? addressPostcodeKey(country, raw) : rules.postcodeKey(raw)) ?? ""
294
+ },
203
295
  })
204
296
 
205
- db.exec(`
206
- INSERT OR IGNORE INTO street_scope_index (scope_kind, scope, street_canon, street_norm)
207
- SELECT scope_kind, scope, street_canon, street_norm FROM (
208
- SELECT 'postcode' AS scope_kind,
209
- mw_postcode_scope(postcode) AS scope,
210
- mw_street_canon(street_raw) AS street_canon,
211
- street_norm
212
- FROM (
213
- SELECT DISTINCT postcode, street_raw, street_norm
214
- FROM ${sourceTable}
215
- WHERE postcode IS NOT NULL AND postcode != ''
216
- )
217
- UNION ALL
218
- SELECT 'locality' AS scope_kind,
219
- ${localityColumn} AS scope,
220
- mw_street_canon(street_raw) AS street_canon,
221
- street_norm
222
- FROM (
223
- SELECT DISTINCT ${localityColumn}, street_raw, street_norm
224
- FROM ${sourceTable}
225
- WHERE ${localityColumn} IS NOT NULL AND ${localityColumn} != ''
226
- )
227
- )
228
- WHERE scope != '' AND street_canon != ''
229
- ORDER BY scope_kind, scope, street_canon, street_norm
230
- `)
297
+ streamScopeRows({
298
+ db,
299
+ selectSQL: `
300
+ SELECT DISTINCT ${localityColumn} AS scope_raw, street_raw, street_norm
301
+ FROM ${sourceTable}
302
+ WHERE ${localityColumn} IS NOT NULL AND ${localityColumn} != ''
303
+ `,
304
+ scopeKind: "locality",
305
+ streetLocale,
306
+ batchSize,
307
+ formatScope: (raw) => (typeof raw === "string" ? raw : ""),
308
+ })
231
309
  }
232
310
 
233
311
  /**
@@ -237,7 +315,7 @@ export async function populateStreetScopeIndex(
237
315
  export async function createStreetScopeIndex(
238
316
  db: StreetScopeIndexHandle,
239
317
  streetLocale: StreetLocale,
240
- options?: { country?: string }
318
+ options?: { country?: string; batchSize?: number }
241
319
  ): Promise<void> {
242
320
  await populateStreetScopeIndex(db, streetLocale, {
243
321
  sourceTable: "address_point",
@@ -5,7 +5,7 @@
5
5
  * @file SQLite implementation of core's `AddressPointLookup`.
6
6
  */
7
7
 
8
- import type { AddressPointHit, AddressPointLookup, StreetMatchKind } from "@mailwoman/core/resolver"
8
+ import type { AddressPointHit, AddressPointLookup, StreetCentroidHit, StreetMatchKind } from "@mailwoman/core/resolver"
9
9
  import { allRows } from "@mailwoman/core/utils"
10
10
  import { haversine, shortCellToInt } from "@mailwoman/spatial"
11
11
  import { latLonBoundsContain } from "@mailwoman/spatial/bbox"
@@ -64,6 +64,31 @@ const H3_RING_1_CELL_COUNT = 7
64
64
  */
65
65
  const DEFAULT_STREET_NEAR_RADIUS_M = 200
66
66
 
67
+ /**
68
+ * Maximum diagonal span in kilometers allowed for a street centroid aggregate.
69
+ *
70
+ * Prevents multi-city or corrupt point clusters from answering as one street.
71
+ */
72
+ const MAX_STREET_CENTROID_SPAN_KM = 25
73
+
74
+ /**
75
+ * Minimum reported uncertainty radius in meters for a street centroid derived from address points.
76
+ */
77
+ const MIN_STREET_CENTROID_UNCERTAINTY_M = 50
78
+
79
+ interface StreetCentroidAggregateRow {
80
+ lat: number | null
81
+ lon: number | null
82
+ min_lat: number | null
83
+ max_lat: number | null
84
+ min_lon: number | null
85
+ max_lon: number | null
86
+ places: number
87
+ n: number
88
+ source: string | null
89
+ release: string | null
90
+ }
91
+
67
92
  /**
68
93
  * Finds an address point by exact normalized `(street, number)` within a postcode,
69
94
  * a locality, or a bounding box.
@@ -112,6 +137,15 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
112
137
  AddressPointRow
113
138
  >
114
139
  | undefined
140
+ readonly #centroidByPostcode:
141
+ | PreparedGet<[postcode: string, street: StreetKey], StreetCentroidAggregateRow>
142
+ | undefined
143
+ readonly #centroidByPostcodeLocality:
144
+ | PreparedGet<[postcode: string, locality: NameKey, street: StreetKey], StreetCentroidAggregateRow>
145
+ | undefined
146
+ readonly #centroidByLocality:
147
+ | PreparedGet<[locality: NameKey, street: StreetKey], StreetCentroidAggregateRow>
148
+ | undefined
115
149
 
116
150
  /**
117
151
  * @param dbPath Extract path.
@@ -152,13 +186,13 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
152
186
  this.#byPostcode = prepareGet(
153
187
  this.#db,
154
188
  `SELECT ${SELECT_COLS} FROM address_point
155
- WHERE postcode = ? AND street_norm = ? AND number = ? LIMIT 1`
189
+ WHERE postcode = ? AND street_norm = ? AND number = ? ORDER BY unit IS NOT NULL LIMIT 1`
156
190
  )
157
191
 
158
192
  this.#byPostcodeLocality = prepareGet(
159
193
  this.#db,
160
194
  `SELECT ${SELECT_COLS} FROM address_point
161
- WHERE postcode = ? AND locality_norm = ? AND street_norm = ? AND number = ? LIMIT 1`
195
+ WHERE postcode = ? AND locality_norm = ? AND street_norm = ? AND number = ? ORDER BY unit IS NOT NULL LIMIT 1`
162
196
  )
163
197
 
164
198
  this.#postcodeKeyPlaces = prepareGet(
@@ -170,7 +204,7 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
170
204
  this.#byLocality = prepareGet(
171
205
  this.#db,
172
206
  `SELECT ${SELECT_COLS} FROM address_point
173
- WHERE locality_norm = ? AND street_norm = ? AND number = ? LIMIT 1`
207
+ WHERE locality_norm = ? AND street_norm = ? AND number = ? ORDER BY unit IS NOT NULL LIMIT 1`
174
208
  )
175
209
 
176
210
  this.#hasStreetIndex = indexExists(this.#db, "idx_ap_street")
@@ -185,7 +219,7 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
185
219
  this.#byBbox = prepareGet(
186
220
  this.#db,
187
221
  `SELECT ${SELECT_COLS} FROM address_point
188
- WHERE street_norm = ? AND number = ? AND lat BETWEEN ? AND ? AND lon BETWEEN ? AND ? LIMIT 1`
222
+ WHERE street_norm = ? AND number = ? AND lat BETWEEN ? AND ? AND lon BETWEEN ? AND ? ORDER BY unit IS NOT NULL LIMIT 1`
189
223
  )
190
224
 
191
225
  this.#byLocalityTail = prepareGet(
@@ -194,6 +228,26 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
194
228
  WHERE street_norm = ? AND number = ? AND locality_norm LIKE ? LIMIT 1`
195
229
  )
196
230
 
231
+ const centroidCols =
232
+ "AVG(lat) AS lat, AVG(lon) AS lon, MIN(lat) AS min_lat, MAX(lat) AS max_lat, " +
233
+ "MIN(lon) AS min_lon, MAX(lon) AS max_lon, COUNT(DISTINCT locality_norm) AS places, " +
234
+ "COUNT(*) AS n, MIN(source) AS source, MIN(release) AS release"
235
+
236
+ this.#centroidByPostcode = prepareGet(
237
+ this.#db,
238
+ `SELECT ${centroidCols} FROM address_point WHERE postcode = ? AND street_norm = ?`
239
+ )
240
+
241
+ this.#centroidByPostcodeLocality = prepareGet(
242
+ this.#db,
243
+ `SELECT ${centroidCols} FROM address_point WHERE postcode = ? AND locality_norm = ? AND street_norm = ?`
244
+ )
245
+
246
+ this.#centroidByLocality = prepareGet(
247
+ this.#db,
248
+ `SELECT ${centroidCols} FROM address_point WHERE locality_norm = ? AND street_norm = ?`
249
+ )
250
+
197
251
  this.#scopeIndex = prepareStreetScopeIndexQueries(this.#db)
198
252
  }
199
253
  }
@@ -562,6 +616,88 @@ export class AddressPointSqliteLookup<DB extends AddressPointDatabase = AddressP
562
616
  return false
563
617
  }
564
618
 
619
+ /**
620
+ * Aggregates a street-tier centroid inside `postcode` or `locality`.
621
+ *
622
+ * When `postcode` is given, only rows in that postcode are eligible.
623
+ * Returns `null` when no rows match or the span exceeds {@link MAX_STREET_CENTROID_SPAN_KM}.
624
+ */
625
+ findStreetCentroid(query: { street: string; postcode?: string; locality?: string }): StreetCentroidHit | null {
626
+ if (!this.#centroidByPostcode || !this.#centroidByPostcodeLocality || !this.#centroidByLocality) return null
627
+
628
+ const postcodeRaw = query.postcode?.trim() || null
629
+ const localityRaw = query.locality?.trim() || null
630
+
631
+ if (!postcodeRaw && !localityRaw) return null
632
+
633
+ const surfaceLocale = streetLocaleForSurface(query.street, this.#locale)
634
+ const variants = streetKeyVariants(query.street, surfaceLocale)
635
+ const localityKey = localityRaw ? this.#localityKey(localityRaw) : null
636
+
637
+ for (const streetNorm of variants) {
638
+ let aggregate: StreetCentroidAggregateRow | null = null
639
+
640
+ if (postcodeRaw) {
641
+ for (const postcode of postcodeProbeForms(postcodeRaw, this.#locale)) {
642
+ const byBoth = localityKey ? this.#centroidByPostcodeLocality(postcode, localityKey, streetNorm) : null
643
+
644
+ if (byBoth && byBoth.n > 0) {
645
+ aggregate = byBoth
646
+
647
+ break
648
+ }
649
+
650
+ const byPC = this.#centroidByPostcode(postcode, streetNorm)
651
+
652
+ if (
653
+ byPC &&
654
+ byPC.n > 0 &&
655
+ (!localityKey ||
656
+ this.#localityKeys === "abbreviated" ||
657
+ (this.#localityLevel === "finest" && byPC.places <= 1))
658
+ ) {
659
+ aggregate = byPC
660
+
661
+ break
662
+ }
663
+ }
664
+ } else if (localityKey) {
665
+ const byLoc = this.#centroidByLocality(localityKey, streetNorm)
666
+
667
+ if (byLoc && byLoc.n > 0) {
668
+ aggregate = byLoc
669
+ }
670
+ }
671
+
672
+ if (
673
+ !aggregate ||
674
+ aggregate.n <= 0 ||
675
+ aggregate.lat == null ||
676
+ aggregate.lon == null ||
677
+ aggregate.min_lat == null ||
678
+ aggregate.max_lat == null ||
679
+ aggregate.min_lon == null ||
680
+ aggregate.max_lon == null
681
+ ) {
682
+ continue
683
+ }
684
+
685
+ const spanKm = haversine(aggregate.min_lat, aggregate.min_lon, aggregate.max_lat, aggregate.max_lon)
686
+
687
+ if (spanKm > MAX_STREET_CENTROID_SPAN_KM) continue
688
+
689
+ return {
690
+ lat: aggregate.lat,
691
+ lon: aggregate.lon,
692
+ uncertaintyM: Math.max(MIN_STREET_CENTROID_UNCERTAINTY_M, Math.round((spanKm * 1000) / 2)),
693
+ source: aggregate.source ?? "",
694
+ release: aggregate.release ?? "",
695
+ }
696
+ }
697
+
698
+ return null
699
+ }
700
+
565
701
  [Symbol.dispose](): void {
566
702
  this.#db[Symbol.dispose]()
567
703
  }