@mailwoman/core 7.1.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/api/APIClient.ts +175 -0
- package/api/headless.ts +23 -0
- package/api/index.ts +11 -0
- package/api/responses.ts +135 -0
- package/coarse-placer/coarse-placer.ts +300 -0
- package/coarse-placer/featurize.ts +171 -0
- package/coarse-placer/tools/build-dataset.ts +223 -0
- package/coarse-placer/tools/build-outlier-exposure.ts +172 -0
- package/coarse-placer/tools/build-outlier-latin.ts +200 -0
- package/coarse-placer/tools/build-outlier-oa.ts +231 -0
- package/coarse-placer/tools/eval-latin-offmap.ts +140 -0
- package/coarse-placer/tools/eval-openset.ts +519 -0
- package/coarse-placer/tools/eval-quant-compare.ts +151 -0
- package/coarse-placer/tools/eval.ts +187 -0
- package/coarse-placer/tools/fnv-hash.ts +24 -0
- package/coarse-placer/tools/index.ts +23 -0
- package/coarse-placer/tools/probe-frontier.ts +216 -0
- package/coarse-placer/tools/quantize.ts +116 -0
- package/coarse-placer/tools/train.ts +244 -0
- package/collections.ts +134 -0
- package/db/schema.ts +21 -0
- package/decoder/build-tree.ts +228 -0
- package/decoder/calibration.ts +101 -0
- package/decoder/containment.ts +87 -0
- package/decoder/index.ts +17 -0
- package/decoder/proposals-to-tree.ts +83 -0
- package/decoder/resolve-proposal-overlaps.ts +79 -0
- package/decoder/serialize-json.ts +70 -0
- package/decoder/serialize-tuples.ts +61 -0
- package/decoder/serialize-xml.ts +209 -0
- package/decoder/types.ts +159 -0
- package/decoder/unknown-spans.ts +103 -0
- package/decoder/validate-tree.ts +100 -0
- package/env/index.ts +42 -0
- package/env/load.ts +14 -0
- package/env/paths.ts +40 -0
- package/env/schema.ts +125 -0
- package/errors/index.ts +9 -0
- package/errors/schema.ts +155 -0
- package/fs/node.ts +38 -0
- package/identifiers.ts +58 -0
- package/index.ts +13 -0
- package/kysley/adapter.ts +29 -0
- package/kysley/client.ts +30 -0
- package/kysley/dialect-config.ts +30 -0
- package/kysley/dialect.ts +67 -0
- package/kysley/driver.ts +175 -0
- package/layers/index.ts +12 -0
- package/layers/manifest.ts +154 -0
- package/layers/schema.ts +105 -0
- package/lifecycle/ServiceSymbol.ts +95 -0
- package/lifecycle/index.ts +11 -0
- package/lifecycle/lru-cache.ts +44 -0
- package/lifecycle/services.ts +322 -0
- package/locale/index.ts +9 -0
- package/locale/locale.ts +49 -0
- package/locale/profiles/en-us.ts +69 -0
- package/locale/profiles/fr-fr.ts +75 -0
- package/locale/profiles/index.ts +9 -0
- package/locale/profiles/ja-jp.ts +33 -0
- package/locale/registry.ts +68 -0
- package/logging/index.ts +8 -0
- package/logging/shared.ts +145 -0
- package/logging/utils.ts +46 -0
- package/objects.ts +211 -0
- package/out/layers/index.d.ts +12 -0
- package/out/layers/index.d.ts.map +1 -0
- package/out/layers/index.js +12 -0
- package/out/layers/index.js.map +1 -0
- package/out/layers/manifest.d.ts +64 -0
- package/out/layers/manifest.d.ts.map +1 -0
- package/out/layers/manifest.js +102 -0
- package/out/layers/manifest.js.map +1 -0
- package/out/layers/schema.d.ts +72 -0
- package/out/layers/schema.d.ts.map +1 -0
- package/out/layers/schema.js +61 -0
- package/out/layers/schema.js.map +1 -0
- package/out/pipeline/index.d.ts +1 -1
- package/out/pipeline/index.d.ts.map +1 -1
- package/out/pipeline/runtime-pipeline.d.ts.map +1 -1
- package/out/pipeline/runtime-pipeline.js +27 -0
- package/out/pipeline/runtime-pipeline.js.map +1 -1
- package/out/pipeline/types.d.ts +74 -4
- package/out/pipeline/types.d.ts.map +1 -1
- package/out/pipeline/types.js.map +1 -1
- package/package.json +21 -21
- package/pipeline/index.ts +46 -0
- package/pipeline/reconcile-lookups.ts +108 -0
- package/pipeline/reconcile.ts +542 -0
- package/pipeline/runtime-pipeline.ts +732 -0
- package/pipeline/span-logit-aggregation.ts +151 -0
- package/pipeline/span-proposer.ts +587 -0
- package/pipeline/types.ts +348 -0
- package/policy/defaults.ts +35 -0
- package/policy/index.ts +10 -0
- package/policy/policy.ts +60 -0
- package/policy/proposal-collection.ts +64 -0
- package/policy/registry.ts +149 -0
- package/resolver/index.ts +29 -0
- package/resolver/types.ts +584 -0
- package/resources/LocaleIndex.ts +124 -0
- package/resources/ResourceMapCache.ts +126 -0
- package/resources/collections.ts +93 -0
- package/resources/debugging.ts +19 -0
- package/resources/git.ts +54 -0
- package/resources/index.ts +17 -0
- package/resources/languages/index.ts +49 -0
- package/resources/languages/types.gen.ts +1368 -0
- package/resources/libaddressinput.ts +105 -0
- package/resources/libpostal.ts +182 -0
- package/resources/locale.ts +23 -0
- package/resources/set.ts +179 -0
- package/resources/whosonfirst/DataSourceCache.ts +72 -0
- package/resources/whosonfirst/PlacetypeDataSource.ts +199 -0
- package/resources/whosonfirst/index.ts +10 -0
- package/resources/whosonfirst/loader.ts +157 -0
- package/resources/whosonfirst/placetypes/Placetype.ts +438 -0
- package/resources/whosonfirst/placetypes/admin.ts +173 -0
- package/resources/whosonfirst/placetypes/definition.ts +135 -0
- package/resources/whosonfirst/placetypes/graph.ts +0 -0
- package/resources/whosonfirst/placetypes/index.ts +12 -0
- package/resources/whosonfirst/placetypes/mermaid.ts +168 -0
- package/resources/whosonfirst/placetypes/tree.ts +46 -0
- package/routing/index.ts +208 -0
- package/scripting/index.ts +40 -0
- package/scripting/utils/index.ts +106 -0
- package/tokenization/Graph.ts +50 -0
- package/tokenization/Span.ts +297 -0
- package/tokenization/index.ts +9 -0
- package/tokenization/normalizer.ts +123 -0
- package/tools/download-libpostal-resources.ts +98 -0
- package/tools/download-ssl-address.ts +99 -0
- package/tools/generate-language-types.ts +194 -0
- package/tools/index.ts +13 -0
- package/types/Classification.ts +211 -0
- package/types/classifier.ts +133 -0
- package/types/component.ts +75 -0
- package/types/index.ts +10 -0
- package/types/mapping.ts +81 -0
- package/utils/data-root.ts +56 -0
- package/utils/hash.ts +27 -0
- package/utils/index.ts +14 -0
- package/utils/jsonl.ts +43 -0
- package/utils/python-json.ts +105 -0
- package/utils/python-random.ts +90 -0
- package/utils/repo.ts +118 -0
- package/utils/sealed-db.ts +85 -0
- package/utils/stats.ts +32 -0
- package/vitest.config.ts +53 -0
package/kysley/driver.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { DatabaseSync, StatementSync } from "node:sqlite"
|
|
8
|
+
|
|
9
|
+
import {
|
|
10
|
+
CompiledQuery,
|
|
11
|
+
createQueryId,
|
|
12
|
+
type DatabaseConnection,
|
|
13
|
+
type Driver,
|
|
14
|
+
IdentifierNode,
|
|
15
|
+
type QueryCompiler,
|
|
16
|
+
type QueryResult,
|
|
17
|
+
RawNode,
|
|
18
|
+
SelectQueryNode,
|
|
19
|
+
} from "kysely"
|
|
20
|
+
|
|
21
|
+
import type { SqliteDialectConfig } from "./dialect-config.ts"
|
|
22
|
+
|
|
23
|
+
class ConnectionMutex {
|
|
24
|
+
#promise?: Promise<void>
|
|
25
|
+
#resolve?: () => void
|
|
26
|
+
|
|
27
|
+
async lock(): Promise<void> {
|
|
28
|
+
while (this.#promise) {
|
|
29
|
+
await this.#promise
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
this.#promise = new Promise((resolve) => {
|
|
33
|
+
this.#resolve = resolve
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
unlock(): void {
|
|
38
|
+
const resolve = this.#resolve
|
|
39
|
+
|
|
40
|
+
this.#promise = undefined
|
|
41
|
+
this.#resolve = undefined
|
|
42
|
+
|
|
43
|
+
resolve?.()
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class SqliteDriver implements Driver {
|
|
48
|
+
readonly #config: SqliteDialectConfig
|
|
49
|
+
readonly #connectionMutex = new ConnectionMutex()
|
|
50
|
+
|
|
51
|
+
#db?: DatabaseSync
|
|
52
|
+
#connection?: DatabaseConnection
|
|
53
|
+
|
|
54
|
+
constructor(config: SqliteDialectConfig) {
|
|
55
|
+
this.#config = Object.freeze({ ...config })
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async init(): Promise<void> {
|
|
59
|
+
const db = typeof this.#config.database === "function" ? await this.#config.database() : this.#config.database
|
|
60
|
+
|
|
61
|
+
this.#db = db
|
|
62
|
+
this.#connection = new SqliteConnection(db)
|
|
63
|
+
|
|
64
|
+
if (this.#config.onCreateConnection) {
|
|
65
|
+
await this.#config.onCreateConnection(this.#connection)
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async acquireConnection(): Promise<DatabaseConnection> {
|
|
70
|
+
// SQLite only has one single connection. We use a mutex here to wait
|
|
71
|
+
// until the single connection has been released.
|
|
72
|
+
await this.#connectionMutex.lock()
|
|
73
|
+
|
|
74
|
+
// biome-ignore lint/style/noNonNullAssertion: :shrug:
|
|
75
|
+
return this.#connection!
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async beginTransaction(connection: DatabaseConnection): Promise<void> {
|
|
79
|
+
await connection.executeQuery(CompiledQuery.raw("begin"))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async commitTransaction(connection: DatabaseConnection): Promise<void> {
|
|
83
|
+
await connection.executeQuery(CompiledQuery.raw("commit"))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
|
|
87
|
+
await connection.executeQuery(CompiledQuery.raw("rollback"))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async savepoint(
|
|
91
|
+
connection: DatabaseConnection,
|
|
92
|
+
savepointName: string,
|
|
93
|
+
compileQuery: QueryCompiler["compileQuery"]
|
|
94
|
+
): Promise<void> {
|
|
95
|
+
await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId()))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async rollbackToSavepoint(
|
|
99
|
+
connection: DatabaseConnection,
|
|
100
|
+
savepointName: string,
|
|
101
|
+
compileQuery: QueryCompiler["compileQuery"]
|
|
102
|
+
): Promise<void> {
|
|
103
|
+
await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId()))
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async releaseSavepoint(
|
|
107
|
+
connection: DatabaseConnection,
|
|
108
|
+
savepointName: string,
|
|
109
|
+
compileQuery: QueryCompiler["compileQuery"]
|
|
110
|
+
): Promise<void> {
|
|
111
|
+
await connection.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId()))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async releaseConnection(): Promise<void> {
|
|
115
|
+
this.#connectionMutex.unlock()
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async destroy(): Promise<void> {
|
|
119
|
+
this.#db?.close()
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
class SqliteConnection implements DatabaseConnection {
|
|
124
|
+
readonly #db: DatabaseSync
|
|
125
|
+
|
|
126
|
+
constructor(db: DatabaseSync) {
|
|
127
|
+
this.#db = db
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
executeQuery<O>(compiledQuery: CompiledQuery): Promise<QueryResult<O>> {
|
|
131
|
+
const { sql, parameters } = compiledQuery
|
|
132
|
+
const stmt = this.#db.prepare(sql)
|
|
133
|
+
|
|
134
|
+
const args = Array.isArray(parameters) ? parameters : []
|
|
135
|
+
|
|
136
|
+
if (stmt.columns().length) {
|
|
137
|
+
const rows = stmt.all(...args) as O[]
|
|
138
|
+
|
|
139
|
+
return Promise.resolve({ rows })
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const result = stmt.run(...args)
|
|
143
|
+
|
|
144
|
+
return Promise.resolve({
|
|
145
|
+
numAffectedRows: BigInt(result.changes),
|
|
146
|
+
insertID: BigInt(result.lastInsertRowid),
|
|
147
|
+
rows: [],
|
|
148
|
+
})
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async *streamQuery<R>(compiledQuery: CompiledQuery, _chunkSize: number): AsyncIterableIterator<QueryResult<R>> {
|
|
152
|
+
const { sql, parameters, query } = compiledQuery
|
|
153
|
+
const stmt: StatementSync = this.#db.prepare(sql)
|
|
154
|
+
const args = Array.isArray(parameters) ? parameters : []
|
|
155
|
+
|
|
156
|
+
if (!SelectQueryNode.is(query)) {
|
|
157
|
+
throw new Error("Sqlite driver only supports streaming of select queries")
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const iter = stmt.iterate(...args) as IterableIterator<R>
|
|
161
|
+
|
|
162
|
+
for (const row of iter) {
|
|
163
|
+
yield {
|
|
164
|
+
rows: [row],
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function parseSavepointCommand(command: string, savepointName: string): RawNode {
|
|
171
|
+
return RawNode.createWithChildren([
|
|
172
|
+
RawNode.createWithSql(`${command} `),
|
|
173
|
+
IdentifierNode.create(savepointName), // ensures savepointName gets sanitized
|
|
174
|
+
])
|
|
175
|
+
}
|
package/layers/index.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The spatial-layer contract: manifest/coverage schema + IO. Every layer database — shipped,
|
|
7
|
+
* build-local, or private — embeds these tables. Spec:
|
|
8
|
+
* docs/superpowers/specs/2026-07-18-spatial-layers-and-poi-design.md §2.1.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export * from "./manifest.ts"
|
|
12
|
+
export * from "./schema.ts"
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Read/write helpers over the layer-contract tables. The parsed {@link LayerManifest} is the
|
|
7
|
+
* camelCase face of `layer_manifest`; validation happens at BOTH ends so a hand-built or
|
|
8
|
+
* corrupted layer fails loudly at open time rather than misbehaving downstream.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Kysely } from "kysely"
|
|
12
|
+
|
|
13
|
+
import { LayerFreshnessPolicy, LayerTier, type LayerContractDatabase } from "./schema.ts"
|
|
14
|
+
|
|
15
|
+
/** Which spine columns a layer carries. At least one key is required. */
|
|
16
|
+
export interface SpineKeys {
|
|
17
|
+
h3?: { column: string; resolution: number }
|
|
18
|
+
/** Column name holding WOF ids, when present. */
|
|
19
|
+
wofID?: string
|
|
20
|
+
/** Column name holding `@mailwoman/address-id` keys, when present. */
|
|
21
|
+
addressID?: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Parsed manifest — see {@link LayerManifestTable} for the storage form. */
|
|
25
|
+
export interface LayerManifest {
|
|
26
|
+
name: string
|
|
27
|
+
version: string
|
|
28
|
+
schemaVersion: number
|
|
29
|
+
tier: LayerTier
|
|
30
|
+
license: string
|
|
31
|
+
attribution?: string
|
|
32
|
+
source: string
|
|
33
|
+
sourceVintage: string
|
|
34
|
+
buildCmd: string
|
|
35
|
+
buildSHA: string
|
|
36
|
+
freshnessPolicy: LayerFreshnessPolicy
|
|
37
|
+
spineKeys: SpineKeys
|
|
38
|
+
createdAt: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface CoverageCell {
|
|
42
|
+
h3Cell: number
|
|
43
|
+
completeness: number
|
|
44
|
+
observedRows: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const TIERS = new Set<string>(Object.values(LayerTier))
|
|
48
|
+
const POLICIES = new Set<string>(Object.values(LayerFreshnessPolicy))
|
|
49
|
+
|
|
50
|
+
function assertManifestInvariants(manifest: Pick<LayerManifest, "tier" | "freshnessPolicy" | "spineKeys">): void {
|
|
51
|
+
if (!TIERS.has(manifest.tier)) {
|
|
52
|
+
throw new Error(`layer manifest: unknown tier ${JSON.stringify(manifest.tier)}`)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!POLICIES.has(manifest.freshnessPolicy)) {
|
|
56
|
+
throw new Error(`layer manifest: unknown freshness_policy ${JSON.stringify(manifest.freshnessPolicy)}`)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (!manifest.spineKeys.h3 && !manifest.spineKeys.wofID && !manifest.spineKeys.addressID) {
|
|
60
|
+
throw new Error("layer manifest: at least one spine key (h3, wofID, addressID) is required")
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Insert the single manifest row. Call exactly once, from the layer's build script. */
|
|
65
|
+
export async function writeLayerManifest(db: Kysely<LayerContractDatabase>, manifest: LayerManifest): Promise<void> {
|
|
66
|
+
assertManifestInvariants(manifest)
|
|
67
|
+
|
|
68
|
+
await db
|
|
69
|
+
.insertInto("layer_manifest")
|
|
70
|
+
.values({
|
|
71
|
+
name: manifest.name,
|
|
72
|
+
version: manifest.version,
|
|
73
|
+
schema_version: manifest.schemaVersion,
|
|
74
|
+
tier: manifest.tier,
|
|
75
|
+
license: manifest.license,
|
|
76
|
+
attribution: manifest.attribution ?? null,
|
|
77
|
+
source: manifest.source,
|
|
78
|
+
source_vintage: manifest.sourceVintage,
|
|
79
|
+
build_cmd: manifest.buildCmd,
|
|
80
|
+
build_sha: manifest.buildSHA,
|
|
81
|
+
freshness_policy: manifest.freshnessPolicy,
|
|
82
|
+
spine_keys: JSON.stringify(manifest.spineKeys),
|
|
83
|
+
created_at: manifest.createdAt,
|
|
84
|
+
})
|
|
85
|
+
.execute()
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Read + validate the manifest. Throws if the table is empty, multi-row, or invalid. */
|
|
89
|
+
export async function readLayerManifest(db: Kysely<LayerContractDatabase>): Promise<LayerManifest> {
|
|
90
|
+
const rows = await db.selectFrom("layer_manifest").selectAll().execute()
|
|
91
|
+
|
|
92
|
+
if (rows.length !== 1) {
|
|
93
|
+
throw new Error(`layer manifest: expected exactly 1 row, found ${rows.length}`)
|
|
94
|
+
}
|
|
95
|
+
const row = rows[0]!
|
|
96
|
+
const manifest: LayerManifest = {
|
|
97
|
+
name: row.name,
|
|
98
|
+
version: row.version,
|
|
99
|
+
schemaVersion: row.schema_version,
|
|
100
|
+
tier: row.tier as LayerTier,
|
|
101
|
+
license: row.license,
|
|
102
|
+
...(row.attribution === null ? {} : { attribution: row.attribution }),
|
|
103
|
+
source: row.source,
|
|
104
|
+
sourceVintage: row.source_vintage,
|
|
105
|
+
buildCmd: row.build_cmd,
|
|
106
|
+
buildSHA: row.build_sha,
|
|
107
|
+
freshnessPolicy: row.freshness_policy as LayerFreshnessPolicy,
|
|
108
|
+
spineKeys: JSON.parse(row.spine_keys) as SpineKeys,
|
|
109
|
+
createdAt: row.created_at,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
assertManifestInvariants(manifest)
|
|
113
|
+
|
|
114
|
+
return manifest
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Rows per INSERT statement (3 bound params/row = 15,000 params/statement), kept safely under SQLite's default 32,766
|
|
119
|
+
* bound-variable ceiling — a continental-scale build's res-6 coverage cell count blows past that limit in a single
|
|
120
|
+
* `.values()` call (found 2026-07-19).
|
|
121
|
+
*/
|
|
122
|
+
export const COVERAGE_INSERT_BATCH = 5_000
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Bulk-insert coverage cells (build-time; cold path, so Kysely inserts are fine), chunked to stay under SQLite's
|
|
126
|
+
* bound-variable limit.
|
|
127
|
+
*/
|
|
128
|
+
export async function writeLayerCoverage(db: Kysely<LayerContractDatabase>, cells: CoverageCell[]): Promise<void> {
|
|
129
|
+
if (cells.length === 0) return
|
|
130
|
+
|
|
131
|
+
for (let i = 0; i < cells.length; i += COVERAGE_INSERT_BATCH) {
|
|
132
|
+
const batch = cells.slice(i, i + COVERAGE_INSERT_BATCH)
|
|
133
|
+
|
|
134
|
+
await db
|
|
135
|
+
.insertInto("layer_coverage")
|
|
136
|
+
.values(batch.map((c) => ({ h3_cell: c.h3Cell, completeness: c.completeness, observed_rows: c.observedRows })))
|
|
137
|
+
.execute()
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Look up coverage for one short H3 cell. `undefined` = the cell was never surveyed (UNKNOWN) — callers must not
|
|
143
|
+
* conflate this with `{completeness: 0}`.
|
|
144
|
+
*/
|
|
145
|
+
export async function readLayerCoverage(
|
|
146
|
+
db: Kysely<LayerContractDatabase>,
|
|
147
|
+
h3Cell: number
|
|
148
|
+
): Promise<CoverageCell | undefined> {
|
|
149
|
+
const row = await db.selectFrom("layer_coverage").selectAll().where("h3_cell", "=", h3Cell).executeTakeFirst()
|
|
150
|
+
|
|
151
|
+
if (!row) return undefined
|
|
152
|
+
|
|
153
|
+
return { h3Cell: row.h3_cell, completeness: row.completeness, observedRows: row.observed_rows }
|
|
154
|
+
}
|
package/layers/schema.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Typed schema for the spatial-layer contract — the two tables EVERY layer database embeds,
|
|
7
|
+
* regardless of tier: `layer_manifest` (single-row identity/provenance/licensing record) and
|
|
8
|
+
* `layer_coverage` (per-H3-cell survey completeness). The contract is what lets shipped,
|
|
9
|
+
* build-local, and private layers share one query surface. Spec:
|
|
10
|
+
* docs/superpowers/specs/2026-07-18-spatial-layers-and-poi-design.md §2.1.
|
|
11
|
+
*
|
|
12
|
+
* Coverage carries the meaning-of-zero rule: a MISSING coverage row means "unmapped/unknown",
|
|
13
|
+
* never "surveyed and empty". Consumers must treat absence as absence of evidence.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { sql, type Kysely } from "kysely"
|
|
17
|
+
|
|
18
|
+
/** Distribution tier of a layer. Shipped = permissive-license, published by us. */
|
|
19
|
+
export const LayerTier = {
|
|
20
|
+
Shipped: "shipped",
|
|
21
|
+
/** Share-alike sources (ODbL): we ship the builder CLI, the user builds locally. */
|
|
22
|
+
BuildLocal: "build-local",
|
|
23
|
+
/** The user's own data, conforming to the contract, never distributed. */
|
|
24
|
+
Private: "private",
|
|
25
|
+
} as const
|
|
26
|
+
export type LayerTier = (typeof LayerTier)[keyof typeof LayerTier]
|
|
27
|
+
|
|
28
|
+
/** How a layer is kept current. */
|
|
29
|
+
export const LayerFreshnessPolicy = {
|
|
30
|
+
/** Immutable artifact; updates are full rebuilds (the gazetteer discipline). */
|
|
31
|
+
Sealed: "sealed",
|
|
32
|
+
/** Periodically re-issued under the same name (e.g. registries of people/programs). */
|
|
33
|
+
VersionedRefresh: "versioned-refresh",
|
|
34
|
+
} as const
|
|
35
|
+
export type LayerFreshnessPolicy = (typeof LayerFreshnessPolicy)[keyof typeof LayerFreshnessPolicy]
|
|
36
|
+
|
|
37
|
+
/** The single-row layer identity record. See {@link LayerManifest} for the parsed form. */
|
|
38
|
+
export interface LayerManifestTable {
|
|
39
|
+
name: string
|
|
40
|
+
version: string
|
|
41
|
+
schema_version: number
|
|
42
|
+
/** One of {@link LayerTier}. */
|
|
43
|
+
tier: string
|
|
44
|
+
/** SPDX-ish license expression, e.g. `CDLA-Permissive-2.0`, `ODbL-1.0`. */
|
|
45
|
+
license: string
|
|
46
|
+
attribution: string | null
|
|
47
|
+
source: string
|
|
48
|
+
source_vintage: string
|
|
49
|
+
build_cmd: string
|
|
50
|
+
build_sha: string
|
|
51
|
+
/** One of {@link LayerFreshnessPolicy}. */
|
|
52
|
+
freshness_policy: string
|
|
53
|
+
/** JSON-encoded spine-key declaration (see `SpineKeys` in `manifest.ts`). */
|
|
54
|
+
spine_keys: string
|
|
55
|
+
/** ISO-8601, supplied by the build script (never generated in-library). */
|
|
56
|
+
created_at: string
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Per-cell survey completeness. Missing row = unknown, NOT zero. */
|
|
60
|
+
export interface LayerCoverageTable {
|
|
61
|
+
/** 48-bit short H3 cell at the resolution declared by the manifest's spine keys. */
|
|
62
|
+
h3_cell: number
|
|
63
|
+
/** Estimated completeness of the source survey in this cell, 0..1. */
|
|
64
|
+
completeness: number
|
|
65
|
+
/** Rows this layer actually holds in the cell. */
|
|
66
|
+
observed_rows: number
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Pass to `new DatabaseClient<LayerContractDatabase>(...)` (or intersect into a layer's own schema). */
|
|
70
|
+
export interface LayerContractDatabase {
|
|
71
|
+
layer_manifest: LayerManifestTable
|
|
72
|
+
layer_coverage: LayerCoverageTable
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Create `layer_manifest`. Single row enforced by `name` PK + the writer's insert-once discipline. */
|
|
76
|
+
export async function createLayerManifestTable(db: Kysely<LayerContractDatabase>): Promise<void> {
|
|
77
|
+
await db.schema
|
|
78
|
+
.createTable("layer_manifest")
|
|
79
|
+
.addColumn("name", "text", (c) => c.primaryKey())
|
|
80
|
+
.addColumn("version", "text", (c) => c.notNull())
|
|
81
|
+
.addColumn("schema_version", "integer", (c) => c.notNull())
|
|
82
|
+
.addColumn("tier", "text", (c) => c.notNull())
|
|
83
|
+
.addColumn("license", "text", (c) => c.notNull())
|
|
84
|
+
.addColumn("attribution", "text")
|
|
85
|
+
.addColumn("source", "text", (c) => c.notNull())
|
|
86
|
+
.addColumn("source_vintage", "text", (c) => c.notNull())
|
|
87
|
+
.addColumn("build_cmd", "text", (c) => c.notNull())
|
|
88
|
+
.addColumn("build_sha", "text", (c) => c.notNull())
|
|
89
|
+
.addColumn("freshness_policy", "text", (c) => c.notNull())
|
|
90
|
+
.addColumn("spine_keys", "text", (c) => c.notNull())
|
|
91
|
+
.addColumn("created_at", "text", (c) => c.notNull())
|
|
92
|
+
.execute()
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Create `layer_coverage` — small fixed-width rows probed by PK, the WITHOUT ROWID sweet spot. */
|
|
96
|
+
export async function createLayerCoverageTable(db: Kysely<LayerContractDatabase>): Promise<void> {
|
|
97
|
+
await db.schema
|
|
98
|
+
.createTable("layer_coverage")
|
|
99
|
+
.addColumn("h3_cell", "integer", (c) => c.primaryKey())
|
|
100
|
+
.addColumn("completeness", "real", (c) => c.notNull())
|
|
101
|
+
.addColumn("observed_rows", "integer", (c) => c.notNull())
|
|
102
|
+
// `WITHOUT ROWID` has no first-class builder; the raw modifier is the idiomatic fallback.
|
|
103
|
+
.modifyEnd(sql`without rowid`)
|
|
104
|
+
.execute()
|
|
105
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { ConsoleLogger } from "../logging/index.ts"
|
|
8
|
+
|
|
9
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Supplemental interface for objects which can be further initialized asynchronously.
|
|
13
|
+
*/
|
|
14
|
+
export interface AsyncInitializable extends AsyncDisposable {
|
|
15
|
+
/**
|
|
16
|
+
* A method which can be called to asynchronously construct the object.
|
|
17
|
+
*/
|
|
18
|
+
[ServiceSymbol.asyncInit](...args: any[]): Promise<this>
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Alias for the `AsyncInitSymbol` method.
|
|
22
|
+
*/
|
|
23
|
+
ready?(...args: any[]): Promise<this>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Type definition for a class which implements the AsyncInitializable interface.
|
|
28
|
+
*/
|
|
29
|
+
export type AsyncInitializableConstructor<T> = T extends new (...args: any[]) => AsyncInitializable
|
|
30
|
+
? new (...args: ConstructorParameters<T>) => T
|
|
31
|
+
: never
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Symbol extensions associated with a service lifecycle.
|
|
35
|
+
*
|
|
36
|
+
* @singleton
|
|
37
|
+
* @static
|
|
38
|
+
*/
|
|
39
|
+
export class ServiceSymbol {
|
|
40
|
+
private constructor() {
|
|
41
|
+
throw new TypeError("Cannot instantiate static class `ServiceSymbol`.")
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Global symbol for the AsyncConstructable interface.
|
|
46
|
+
*/
|
|
47
|
+
public static readonly asyncInit: unique symbol = Symbol.for("asyncInit")
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Global symbol to mark an object as disposed.
|
|
51
|
+
*/
|
|
52
|
+
public static readonly asyncDisposed: unique symbol = Symbol.for("asyncDisposed")
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Mark an object as disposed.
|
|
56
|
+
*/
|
|
57
|
+
public static markAsDisposed(disposable: AsyncDisposable): boolean {
|
|
58
|
+
if (ServiceSymbol.asyncDisposed in disposable) {
|
|
59
|
+
ConsoleLogger.warn(`[${disposable}] Already disposed!`)
|
|
60
|
+
|
|
61
|
+
return false
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
Object.assign(disposable, { AsyncDisposedSymbol: true })
|
|
65
|
+
|
|
66
|
+
return true
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Type-predicate to determine if an object has been disposed.
|
|
71
|
+
*/
|
|
72
|
+
public static isDisposed(disposable: AsyncDisposable): boolean {
|
|
73
|
+
return ServiceSymbol.asyncDisposed in disposable
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Type-predicate to determine if a given input is an object which implements the `AsyncInitializable` interface.
|
|
78
|
+
*/
|
|
79
|
+
public static isAsyncInitializable(input: AsyncDisposable): input is AsyncInitializable {
|
|
80
|
+
return ServiceSymbol.asyncInit in input && typeof input[ServiceSymbol.asyncInit] === "function"
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Type-predicate to determine if a given input is an object which implements the `AsyncDisposable` interface.
|
|
85
|
+
*/
|
|
86
|
+
public static isAsyncDisposable<T>(input: T): input is T & AsyncDisposable {
|
|
87
|
+
if (!input || typeof input !== "object") return false
|
|
88
|
+
|
|
89
|
+
return Object.hasOwn(input, Symbol.asyncDispose)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
public static toString() {
|
|
93
|
+
return "ServiceSymbol"
|
|
94
|
+
}
|
|
95
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* LRU cache utilities.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { LRUCache } from "lru-cache"
|
|
10
|
+
|
|
11
|
+
export interface AsyncDisposableLRUCacheOptions {
|
|
12
|
+
max: number
|
|
13
|
+
displayName?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* An LRU cache that automatically disposes of its values when they are evicted.
|
|
18
|
+
*/
|
|
19
|
+
export class AsyncDisposableLRUCache<K extends object, V extends AsyncDisposable>
|
|
20
|
+
extends LRUCache<K, V>
|
|
21
|
+
implements AsyncDisposable
|
|
22
|
+
{
|
|
23
|
+
public readonly displayName: string
|
|
24
|
+
|
|
25
|
+
constructor({ max, displayName }: AsyncDisposableLRUCacheOptions) {
|
|
26
|
+
super({
|
|
27
|
+
max,
|
|
28
|
+
dispose: (value) => value[Symbol.asyncDispose](),
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
this.displayName = displayName ?? "cache"
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
public async [Symbol.asyncDispose]() {
|
|
35
|
+
for (const [key, value] of this.entries()) {
|
|
36
|
+
await value[Symbol.asyncDispose]()
|
|
37
|
+
this.delete(key)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
public override toString() {
|
|
42
|
+
return `Async LRU ${this.displayName}`
|
|
43
|
+
}
|
|
44
|
+
}
|