@mailwoman/spatial 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.
@@ -0,0 +1,323 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file What a typed query resolves to when it is a point rather than an address, read from recognitions.
6
+ *
7
+ * A search field receives coordinates in a dozen spellings, a plus code, an H3 cell, a geohash or a
8
+ * Who's On First id beside ordinary addresses. {@link recognizePointQuery} runs one recognizer over the `coordinates`,
9
+ * `spatial` and `identifiers` families of `@mailwoman/recognizer` and answers from the recognition that spans the text.
10
+ * It decodes no cell: decoding a code to a coordinate belongs to the module that owns the format,
11
+ * and the H3 reader loads a WebAssembly binary that a text test shouldn't pay for.
12
+ *
13
+ * # What makes a recognition a reading
14
+ *
15
+ * A recognition is trusted when the engine's validator accepted it and its span is the whole text.
16
+ * An embedded span or a rejected recognition never becomes a reading: `Apt 4, 12 Main St` holds the valid pair `4, 12`.
17
+ *
18
+ * The grammars admit no white space around a value, so **the caller trims** the text before it is read.
19
+ * The earth app trims where it takes the typed input.
20
+ *
21
+ * # One handler for every kind
22
+ *
23
+ * `handlers` has an entry for each kind of the three families, and the object is checked against
24
+ * `HandlerMap<typeof families>`. A kind added to any family fails the TypeScript build until it has a handler.
25
+ * A handler returns a point reading, or a {@link NotAPointQuery} with the recognized kind and the reason it isn't a point.
26
+ */
27
+
28
+ import {
29
+ createRecognizer,
30
+ type HandlerMap,
31
+ type KindsOf,
32
+ type Recognition,
33
+ type RecognitionsOf,
34
+ } from "@mailwoman/recognizer"
35
+ import { coordinates } from "@mailwoman/recognizer/coordinates"
36
+ import { isDeterministicSpatial } from "@mailwoman/recognizer/deterministic/spatial"
37
+ import { identifiers } from "@mailwoman/recognizer/identifiers"
38
+ import { spatial } from "@mailwoman/recognizer/spatial"
39
+ import type { AxisOrder, Validated } from "@mailwoman/recognizer/types"
40
+
41
+ /**
42
+ * The families a point query is read from, composed once.
43
+ */
44
+ const families = [coordinates, spatial, identifiers] as const
45
+
46
+ /**
47
+ * Every kind of recognition a point query reads, one per shape of the three families.
48
+ */
49
+ export type PointQueryKind = KindsOf<typeof families>
50
+
51
+ const recognizer = createRecognizer(families)
52
+
53
+ /**
54
+ * A point reading is the point a text resolves to.
55
+ *
56
+ * `recognized` is the generated kind of the recognition the reading came from.
57
+ */
58
+ export type PointReading = {
59
+ readonly recognized: PointQueryKind
60
+ } & (
61
+ | {
62
+ /**
63
+ * A coordinate pair in decimal, degrees-minutes-seconds, labeled, `geo:`
64
+ * or Google Maps form, latitude and longitude as the validator branded them.
65
+ *
66
+ * `lon_lat` is reported when the first number is out of latitude range,
67
+ * so it can only be a longitude.
68
+ */
69
+ readonly kind: "coordinates"
70
+ readonly latitude: Validated.Latitude
71
+ readonly longitude: Validated.Longitude
72
+ readonly order: AxisOrder
73
+ }
74
+ | {
75
+ /**
76
+ * A GeoJSON `Point`.
77
+ * Its position is already latitude first in the payload.
78
+ */
79
+ readonly kind: "geojson_point"
80
+ readonly latitude: Validated.Latitude
81
+ readonly longitude: Validated.Longitude
82
+ }
83
+ | {
84
+ /**
85
+ * A full Open Location Code, upper-cased.
86
+ * It decodes to a cell with no further input.
87
+ */
88
+ readonly kind: "plus_code"
89
+ readonly full: true
90
+ readonly code: Validated.FullPlusCode
91
+ }
92
+ | {
93
+ /**
94
+ * A short Open Location Code, upper-cased.
95
+ * It decodes only beside a reference position.
96
+ */
97
+ readonly kind: "plus_code"
98
+ readonly full: false
99
+ readonly code: Validated.ShortPlusCode
100
+ }
101
+ | {
102
+ /**
103
+ * A DIGIPIN, ten upper-case characters without hyphens.
104
+ */
105
+ readonly kind: "digipin"
106
+ readonly code: Validated.Digipin
107
+ }
108
+ | {
109
+ /**
110
+ * An H3 cell index in its hexadecimal form, lower-cased.
111
+ *
112
+ * The validator checks the shape, and the H3 library decides validity when it decodes the cell.
113
+ */
114
+ readonly kind: "h3"
115
+ readonly cell: string
116
+ }
117
+ | {
118
+ /**
119
+ * A geohash behind its `geohash:` or `gh:` prefix, lower-cased.
120
+ */
121
+ readonly kind: "geohash"
122
+ readonly hash: string
123
+ }
124
+ | {
125
+ /**
126
+ * A Who's On First id, from `wof:85633793`, `wof 85633793` or a Spelunker link.
127
+ */
128
+ readonly kind: "wof"
129
+ readonly id: Validated.Integer
130
+ }
131
+ )
132
+
133
+ /**
134
+ * Lists why a recognized text isn't a point query.
135
+ *
136
+ * - `names_no_position`: the text is an identifier or a document with no single position,
137
+ * such as a Census GEOID, a GNIS feature id or a GeoJSON `LineString`.
138
+ * - `ambiguous_without_prefix`: the text is a valid code whose spelling is also a phone number
139
+ * or a count, so no prefix or separator makes it a position.
140
+ * - `digit_group`: the text is a well-formed code made only of digits in a grouped form.
141
+ * A phone number is written the same way.
142
+ */
143
+ export type NotAPointReason = "names_no_position" | "ambiguous_without_prefix" | "digit_group"
144
+
145
+ /**
146
+ * The text is a recognized shape and not a point query: a caller sends it to the address classifier.
147
+ */
148
+ export interface NotAPointQuery {
149
+ readonly kind: "not_a_point"
150
+ readonly recognized: PointQueryKind
151
+ readonly reason: NotAPointReason
152
+ }
153
+
154
+ /**
155
+ * A text that's a whole recognition resolves to a point or to a shape that isn't a point.
156
+ */
157
+ export type PointQueryReading = PointReading | NotAPointQuery
158
+
159
+ /**
160
+ * The payload of a recognition the reader has already checked is validated.
161
+ *
162
+ * A recognition without one is a defect in the reader, so it throws rather than answering with an absence.
163
+ */
164
+ function payloadOf<Payload>(recognition: {
165
+ readonly kind: string
166
+ readonly validation:
167
+ | { readonly status: "validated"; readonly payload: Payload }
168
+ | { readonly status: "rejected" | "unvalidated" }
169
+ }): Payload {
170
+ const { validation } = recognition
171
+
172
+ if (validation.status !== "validated") {
173
+ throw new RangeError(`${recognition.kind} reached its point handler without a validated payload`)
174
+ }
175
+
176
+ return validation.payload
177
+ }
178
+
179
+ interface PairPayload {
180
+ readonly latitude: Validated.Latitude
181
+ readonly longitude: Validated.Longitude
182
+ readonly order: AxisOrder
183
+ }
184
+
185
+ function coordinatePair(recognition: Recognition<PointQueryKind, PairPayload, string>): PointReading {
186
+ const { latitude, longitude, order } = payloadOf(recognition)
187
+
188
+ return { kind: "coordinates", recognized: recognition.kind, latitude, longitude, order }
189
+ }
190
+
191
+ function noPosition(recognition: { readonly kind: PointQueryKind }): NotAPointQuery {
192
+ return { kind: "not_a_point", recognized: recognition.kind, reason: "names_no_position" }
193
+ }
194
+
195
+ function wofID(recognition: Recognition<PointQueryKind, { readonly id: Validated.Integer }, string>): PointReading {
196
+ return { kind: "wof", recognized: recognition.kind, id: payloadOf(recognition).id }
197
+ }
198
+
199
+ function h3Cell(recognition: Recognition<PointQueryKind, { readonly cell: string }, string>): PointReading {
200
+ return { kind: "h3", recognized: recognition.kind, cell: payloadOf(recognition).cell.toLowerCase() }
201
+ }
202
+
203
+ /**
204
+ * One handler per kind.
205
+ *
206
+ * A new kind in any composed family fails this object's `satisfies` clause.
207
+ *
208
+ * The second clause fixes each handler's return type.
209
+ * `HandlerMap` leaves it open.
210
+ */
211
+ const handlers = {
212
+ "coordinate.decimal_pair": coordinatePair,
213
+ "coordinate.decimal_pair_spaced": coordinatePair,
214
+ "coordinate.dms_pair": coordinatePair,
215
+ "coordinate.dms_pair_spaced": coordinatePair,
216
+ "coordinate.labeled_pair": coordinatePair,
217
+ "coordinate.maps_segment": coordinatePair,
218
+ // RFC 5870 fixes the order as latitude, longitude, altitude, and the payload has no order of its own.
219
+ "coordinate.geo_uri": (recognition): PointReading => {
220
+ const { latitude, longitude } = payloadOf(recognition)
221
+
222
+ return { kind: "coordinates", recognized: recognition.kind, latitude, longitude, order: "lat_lon" }
223
+ },
224
+
225
+ "plus_code.token": (recognition): PointReading => {
226
+ const { full_code, short_code } = payloadOf(recognition)
227
+
228
+ if (full_code != null) return { kind: "plus_code", recognized: recognition.kind, full: true, code: full_code }
229
+
230
+ if (short_code != null) return { kind: "plus_code", recognized: recognition.kind, full: false, code: short_code }
231
+
232
+ // The validator fills exactly one of the two fields, so a validated payload with neither is a defect in the engine.
233
+ throw new RangeError(`${recognition.kind} validated with neither a full code nor a short code`)
234
+ },
235
+ // The validator accepts the all-digit form.
236
+ // A phone number is written the same way.
237
+ // The trust rule decides.
238
+ "digipin.display": (recognition): PointQueryReading =>
239
+ isDeterministicSpatial(recognition, recognition.text)
240
+ ? { kind: "digipin", recognized: recognition.kind, code: payloadOf(recognition).code }
241
+ : { kind: "not_a_point", recognized: recognition.kind, reason: "digit_group" },
242
+ // Ten characters from `2` to `9` and `C F J K L M P T` are also a phone number, a count or a postcode.
243
+ "digipin.compact": (recognition): NotAPointQuery => ({
244
+ kind: "not_a_point",
245
+ recognized: recognition.kind,
246
+ reason: "ambiguous_without_prefix",
247
+ }),
248
+ // A GeoJSON `Point` is the point.
249
+ // Every other GeoJSON type is a document with no single position.
250
+ "geojson.object": (recognition): PointQueryReading => {
251
+ const { type, latitude, longitude } = payloadOf(recognition)
252
+
253
+ if (type === "Point" && latitude != null && longitude != null) {
254
+ return { kind: "geojson_point", recognized: recognition.kind, latitude, longitude }
255
+ }
256
+
257
+ return noPosition(recognition)
258
+ },
259
+
260
+ // A Census GEOID is a run of digits, and the state code is the only part the validator can check.
261
+ "census.geoid_block": noPosition,
262
+ "census.geoid_block_group": noPosition,
263
+ "census.geoid_county": noPosition,
264
+ "census.geoid_state": noPosition,
265
+ "census.geoid_tract": noPosition,
266
+ "gnis.reference": noPosition,
267
+ "gnis.summary_url": noPosition,
268
+
269
+ "geohash.prefixed": (recognition): PointReading => ({
270
+ kind: "geohash",
271
+ recognized: recognition.kind,
272
+ hash: payloadOf(recognition).hash.toLowerCase(),
273
+ }),
274
+ // A bare H3 cell is read as a point here: the map's copy menu writes one,
275
+ // and a search field that reads back what the map copied is the contract.
276
+ // `isDeterministicIdentifier` withholds a bare cell from an address parse,
277
+ // because 15 hexadecimal digits are also a count.
278
+ "h3.cell": h3Cell,
279
+ "h3.prefixed_cell": h3Cell,
280
+ "wof.reference": wofID,
281
+ "wof.spelunker_url": wofID,
282
+ } satisfies HandlerMap<typeof families> & Record<PointQueryKind, (recognition: never) => PointQueryReading>
283
+
284
+ /**
285
+ * Reads a trimmed text as a point, or as a recognized shape that isn't a point query.
286
+ *
287
+ * Returns `null` when no recognition of the three families is validated and covers the whole text.
288
+ * Every address is such a text.
289
+ *
290
+ * A coordinate out of range in both axis orders is a rejected recognition,
291
+ * so it reads as `null`, never clamped.
292
+ *
293
+ * @param text The text the caller already trimmed, because the grammars admit no outer white space.
294
+ */
295
+ export function recognizePointQuery(text: string): PointQueryReading | null {
296
+ let notAPoint: NotAPointQuery | null = null
297
+
298
+ for (const recognition of recognizer.recognize(text).recognitions) {
299
+ if (recognition.validation.status !== "validated" || recognition.start !== 0 || recognition.end !== text.length) {
300
+ continue
301
+ }
302
+
303
+ const handler = handlers[recognition.kind] as (recognition: RecognitionsOf<typeof families>) => PointQueryReading
304
+ const reading = handler(recognition)
305
+
306
+ // Two shapes may cover one text, such as a Census GEOID and an H3 cell.
307
+ // The point wins.
308
+ if (reading.kind !== "not_a_point") return reading
309
+
310
+ notAPoint ??= reading
311
+ }
312
+
313
+ return notAPoint
314
+ }
315
+
316
+ /**
317
+ * Reads a trimmed text as a point, or `null` when it is an address or a recognized shape with no position.
318
+ */
319
+ export function pointFromText(text: string): PointReading | null {
320
+ const reading = recognizePointQuery(text)
321
+
322
+ return reading && reading.kind !== "not_a_point" ? reading : null
323
+ }
@@ -0,0 +1,70 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file The text that writes and labels a point query, apart from the reader.
6
+ *
7
+ * The reader in `reading.ts` imports the recognition engine and three artifacts.
8
+ * A page that only writes a coordinate pair or labels a kind in a sentence imports this module.
9
+ * This module holds none of the engine, because its one import is a type and the build erases it.
10
+ */
11
+
12
+ import type { PointQueryKind } from "#point/reading"
13
+
14
+ /**
15
+ * A coordinate pair as text, latitude first, in the form `pointFromText` reads back.
16
+ *
17
+ * Six decimals place a point within about 11 cm.
18
+ */
19
+ export function coordinatePairText(lat: number, lon: number, decimals = 6): string {
20
+ return `${lat.toFixed(decimals)}, ${lon.toFixed(decimals)}`
21
+ }
22
+
23
+ /**
24
+ * Labels a recognized shape in a result panel and in a sentence.
25
+ */
26
+ export interface PointQueryDescription {
27
+ /**
28
+ * The name a result is shown under, such as the tag column of a parse.
29
+ */
30
+ readonly label: string
31
+ /**
32
+ * The same name as a noun phrase with its article: "this is a plus code".
33
+ */
34
+ readonly phrase: string
35
+ }
36
+
37
+ const COORDINATE_PAIR = { label: "coordinates", phrase: "a coordinate pair" } as const
38
+ const CENSUS_GEOID = { label: "Census GEOID", phrase: "a Census GEOID" } as const
39
+ const GNIS_ID = { label: "GNIS id", phrase: "a GNIS feature id" } as const
40
+ const H3_CELL = { label: "H3 cell", phrase: "an H3 cell" } as const
41
+ const WOF_ID = { label: "Who's On First id", phrase: "a Who's On First id" } as const
42
+
43
+ /**
44
+ * The description of every kind, so a new kind in any composed family fails the build until it has one.
45
+ */
46
+ export const POINT_QUERY_DESCRIPTIONS = {
47
+ "coordinate.decimal_pair": COORDINATE_PAIR,
48
+ "coordinate.decimal_pair_spaced": COORDINATE_PAIR,
49
+ "coordinate.dms_pair": COORDINATE_PAIR,
50
+ "coordinate.dms_pair_spaced": COORDINATE_PAIR,
51
+ "coordinate.geo_uri": COORDINATE_PAIR,
52
+ "coordinate.labeled_pair": COORDINATE_PAIR,
53
+ "coordinate.maps_segment": COORDINATE_PAIR,
54
+ "plus_code.token": { label: "plus code", phrase: "a plus code" },
55
+ "digipin.compact": { label: "DIGIPIN", phrase: "a DIGIPIN" },
56
+ "digipin.display": { label: "DIGIPIN", phrase: "a DIGIPIN" },
57
+ "geojson.object": { label: "GeoJSON", phrase: "a GeoJSON object" },
58
+ "census.geoid_block": CENSUS_GEOID,
59
+ "census.geoid_block_group": CENSUS_GEOID,
60
+ "census.geoid_county": CENSUS_GEOID,
61
+ "census.geoid_state": CENSUS_GEOID,
62
+ "census.geoid_tract": CENSUS_GEOID,
63
+ "geohash.prefixed": { label: "geohash", phrase: "a geohash" },
64
+ "gnis.reference": GNIS_ID,
65
+ "gnis.summary_url": GNIS_ID,
66
+ "h3.cell": H3_CELL,
67
+ "h3.prefixed_cell": H3_CELL,
68
+ "wof.reference": WOF_ID,
69
+ "wof.spelunker_url": WOF_ID,
70
+ } satisfies Readonly<Record<PointQueryKind, PointQueryDescription>>
@@ -0,0 +1,94 @@
1
+ import type { Validated } from "@mailwoman/recognizer/types";
2
+ import type { Coordinates2D } from "#position";
3
+ /**
4
+ * Geographic width or height of one DIGIPIN cell, in degrees.
5
+ *
6
+ * It is the span of the cell whose center a decoded position is.
7
+ */
8
+ export declare const DIGIPIN_CELL_DEGREES: number;
9
+ /**
10
+ * Validate geographic coordinates against DIGIPIN coverage bounds.
11
+ *
12
+ * Both coordinates must be finite numbers within the supported geographic region, including its boundaries.
13
+ *
14
+ * @param latitude - Latitude in WGS 84 degrees.
15
+ * @param longitude - Longitude in WGS 84 degrees.
16
+ *
17
+ * @throws {RangeError} If latitude or longitude is outside DIGIPIN bounds.
18
+ */
19
+ export declare function validateDIGIPINCoordinates(latitude: number, longitude: number): void;
20
+ /**
21
+ * Encode geographic coordinates into a 10-character DIGIPIN.
22
+ *
23
+ * Coordinates are quantized into 20-bit integer cell indices.
24
+ * Each iteration extracts two bits from each coordinate and combines them into
25
+ * an index into the DIGIPIN alphabet.
26
+ *
27
+ * @param latitude - Latitude in WGS 84 degrees.
28
+ * @param longitude - Longitude in WGS 84 degrees.
29
+ * @returns Uppercase 10-character DIGIPIN.
30
+ *
31
+ * @throws {RangeError} If coordinates are outside DIGIPIN bounds.
32
+ *
33
+ * @example
34
+ * const pin = getDIGIPIN(13.11179621, 80.20264269)
35
+ */
36
+ export declare function getDIGIPIN(latitude: number, longitude: number): Validated.Digipin;
37
+ /**
38
+ * Encode geographic coordinates without validating their bounds.
39
+ *
40
+ * Intended for performance-sensitive batch processing where coordinates have already been validated.
41
+ *
42
+ * Coordinates are quantized into 20-bit indices and encoded using bitwise operations.
43
+ *
44
+ * @param latitude - Latitude in WGS 84 degrees.
45
+ * @param longitude - Longitude in WGS 84 degrees.
46
+ * @returns Uppercase 10-character DIGIPIN.
47
+ *
48
+ * @remarks Inputs must be finite and inside DIGIPIN coverage bounds.
49
+ * Out-of-range inputs produce unspecified results.
50
+ */
51
+ export declare function getDIGIPINUnsafe(latitude: number, longitude: number): string;
52
+ /**
53
+ * Decode a DIGIPIN into the center coordinates of its cell.
54
+ *
55
+ * Returns a GeoJSON-compatible position in longitude-first order.
56
+ * Coordinates retain floating-point precision without decimal rounding.
57
+ *
58
+ * The parameter is the validated code of the `spatial` family of `@mailwoman/recognizer`:
59
+ * ten upper-case characters without hyphens.
60
+ * The validator accepts lower case and the display form `39J-49L-L8T4`
61
+ * and normalizes both, so this decoder skips every check.
62
+ *
63
+ * A caller that holds a string reads it through the recognizer.
64
+ *
65
+ * @param pin - Validated DIGIPIN.
66
+ * @returns Cell center as [longitude, latitude].
67
+ *
68
+ * @example
69
+ * const [longitude, latitude] = getLatLngFromDIGIPIN(getDIGIPIN(13.11179621, 80.20264269))
70
+ */
71
+ export declare function getLatLngFromDIGIPIN(pin: Validated.Digipin): Coordinates2D;
72
+ /**
73
+ * Decode a DIGIPIN directly into an existing coordinate buffer.
74
+ *
75
+ * Avoids allocating intermediate coordinate tuples.
76
+ *
77
+ * The destination receives longitude followed by latitude.
78
+ * Supports both ordinary JavaScript arrays and Float64Array buffers.
79
+ *
80
+ * @param pin - Validated DIGIPIN, ten upper-case characters.
81
+ * @param output - Destination coordinate buffer.
82
+ * @param offset - Starting element offset.
83
+ * Defaults to zero.
84
+ *
85
+ * @example
86
+ * const pins = [getDIGIPIN(13.11179621, 80.20264269), getDIGIPIN(28.6139, 77.209)]
87
+ * const output = new Float64Array(pins.length * 2)
88
+ *
89
+ * for (let i = 0; i < pins.length; i++) {
90
+ * getLatLngFromDIGIPINInto(pins[i]!, output, i * 2)
91
+ * }
92
+ */
93
+ export declare function getLatLngFromDIGIPINInto(pin: Validated.Digipin, output: number[] | Float64Array, offset?: number): void;
94
+ //# sourceMappingURL=digipin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"digipin.d.ts","sourceRoot":"","sources":["../lib/digipin.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAA;AAE5D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAA;AAgF9C;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,QAAoB,CAAA;AA8BrD;;;;;;;;;GASG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CAQpF;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,SAAS,CAAC,OAAO,CAKjF;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CA2B5E;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,SAAS,CAAC,OAAO,GAAG,aAAa,CAS1E;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,YAAY,EAAE,MAAM,SAAI,GAAG,IAAI,CAuBlH"}