@mailwoman/entity-resolution 0.0.0-stage → 11.0.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.
- package/README.md +114 -2
- package/lib/address-key.ts +46 -0
- package/lib/geocode-handler.ts +37 -0
- package/lib/geojson.ts +72 -0
- package/lib/index.ts +23 -0
- package/lib/ingest.ts +349 -0
- package/lib/learned-scorer.ts +134 -0
- package/lib/map-html.ts +287 -0
- package/lib/models/crosssource-gbt-en-us.ts +43 -0
- package/lib/models/dedup-gbt-en-us.ts +47 -0
- package/lib/models/org-crosssource-gbt-en-us.ts +43 -0
- package/lib/reconcile.ts +239 -0
- package/lib/resolve.ts +569 -0
- package/lib/types.ts +110 -0
- package/out/address-key.d.ts +34 -0
- package/out/address-key.d.ts.map +1 -0
- package/out/address-key.js +41 -0
- package/out/address-key.js.map +1 -0
- package/out/geocode-handler.d.ts +20 -0
- package/out/geocode-handler.d.ts.map +1 -0
- package/out/geocode-handler.js +29 -0
- package/out/geocode-handler.js.map +1 -0
- package/out/geojson.d.ts +28 -0
- package/out/geojson.d.ts.map +1 -0
- package/out/geojson.js +62 -0
- package/out/geojson.js.map +1 -0
- package/out/index.d.ts +23 -0
- package/out/index.d.ts.map +1 -0
- package/out/index.js +23 -0
- package/out/index.js.map +1 -0
- package/out/ingest.d.ts +173 -0
- package/out/ingest.d.ts.map +1 -0
- package/out/ingest.js +185 -0
- package/out/ingest.js.map +1 -0
- package/out/learned-scorer.d.ts +61 -0
- package/out/learned-scorer.d.ts.map +1 -0
- package/out/learned-scorer.js +91 -0
- package/out/learned-scorer.js.map +1 -0
- package/out/map-html.d.ts +39 -0
- package/out/map-html.d.ts.map +1 -0
- package/out/map-html.js +220 -0
- package/out/map-html.js.map +1 -0
- package/out/models/crosssource-gbt-en-us.d.ts +45 -0
- package/out/models/crosssource-gbt-en-us.d.ts.map +1 -0
- package/out/models/crosssource-gbt-en-us.js +40 -0
- package/out/models/crosssource-gbt-en-us.js.map +1 -0
- package/out/models/dedup-gbt-en-us.d.ts +44 -0
- package/out/models/dedup-gbt-en-us.d.ts.map +1 -0
- package/out/models/dedup-gbt-en-us.js +44 -0
- package/out/models/dedup-gbt-en-us.js.map +1 -0
- package/out/models/org-crosssource-gbt-en-us.d.ts +45 -0
- package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -0
- package/out/models/org-crosssource-gbt-en-us.js +40 -0
- package/out/models/org-crosssource-gbt-en-us.js.map +1 -0
- package/out/reconcile.d.ts +96 -0
- package/out/reconcile.d.ts.map +1 -0
- package/out/reconcile.js +127 -0
- package/out/reconcile.js.map +1 -0
- package/out/resolve.d.ts +264 -0
- package/out/resolve.d.ts.map +1 -0
- package/out/resolve.js +282 -0
- package/out/resolve.js.map +1 -0
- package/out/tools/coverage-reconciliation.d.ts +67 -0
- package/out/tools/coverage-reconciliation.d.ts.map +1 -0
- package/out/tools/coverage-reconciliation.js +113 -0
- package/out/tools/coverage-reconciliation.js.map +1 -0
- package/out/tools/cross/dataset-correlation.d.ts +61 -0
- package/out/tools/cross/dataset-correlation.d.ts.map +1 -0
- package/out/tools/cross/dataset-correlation.js +244 -0
- package/out/tools/cross/dataset-correlation.js.map +1 -0
- package/out/tools/cross/source-threshold-sweep.d.ts +60 -0
- package/out/tools/cross/source-threshold-sweep.d.ts.map +1 -0
- package/out/tools/cross/source-threshold-sweep.js +264 -0
- package/out/tools/cross/source-threshold-sweep.js.map +1 -0
- package/out/tools/dedup-ceiling.d.ts +62 -0
- package/out/tools/dedup-ceiling.d.ts.map +1 -0
- package/out/tools/dedup-ceiling.js +171 -0
- package/out/tools/dedup-ceiling.js.map +1 -0
- package/out/tools/eval-geocoder.d.ts +68 -0
- package/out/tools/eval-geocoder.d.ts.map +1 -0
- package/out/tools/eval-geocoder.js +13 -0
- package/out/tools/eval-geocoder.js.map +1 -0
- package/out/tools/geocoder/namesake-probe.d.ts +33 -0
- package/out/tools/geocoder/namesake-probe.d.ts.map +1 -0
- package/out/tools/geocoder/namesake-probe.js +60 -0
- package/out/tools/geocoder/namesake-probe.js.map +1 -0
- package/out/tools/geocoder/vs-provided-coords.d.ts +53 -0
- package/out/tools/geocoder/vs-provided-coords.d.ts.map +1 -0
- package/out/tools/geocoder/vs-provided-coords.js +161 -0
- package/out/tools/geocoder/vs-provided-coords.js.map +1 -0
- package/out/tools/gold-set-sample.d.ts +67 -0
- package/out/tools/gold-set-sample.d.ts.map +1 -0
- package/out/tools/gold-set-sample.js +81 -0
- package/out/tools/gold-set-sample.js.map +1 -0
- package/out/tools/learned/scorer/clustering-eval.d.ts +77 -0
- package/out/tools/learned/scorer/clustering-eval.d.ts.map +1 -0
- package/out/tools/learned/scorer/clustering-eval.js +207 -0
- package/out/tools/learned/scorer/clustering-eval.js.map +1 -0
- package/out/tools/learned/scorer/crossstate-eval.d.ts +65 -0
- package/out/tools/learned/scorer/crossstate-eval.d.ts.map +1 -0
- package/out/tools/learned/scorer/crossstate-eval.js +168 -0
- package/out/tools/learned/scorer/crossstate-eval.js.map +1 -0
- package/out/tools/learned/scorer/eval.d.ts +64 -0
- package/out/tools/learned/scorer/eval.d.ts.map +1 -0
- package/out/tools/learned/scorer/eval.js +275 -0
- package/out/tools/learned/scorer/eval.js.map +1 -0
- package/out/tools/matcher-scale.d.ts +40 -0
- package/out/tools/matcher-scale.d.ts.map +1 -0
- package/out/tools/matcher-scale.js +111 -0
- package/out/tools/matcher-scale.js.map +1 -0
- package/out/tools/nppes/dedup-benchmark.d.ts +82 -0
- package/out/tools/nppes/dedup-benchmark.d.ts.map +1 -0
- package/out/tools/nppes/dedup-benchmark.js +226 -0
- package/out/tools/nppes/dedup-benchmark.js.map +1 -0
- package/out/tools/nppes/org-name.d.ts +15 -0
- package/out/tools/nppes/org-name.d.ts.map +1 -0
- package/out/tools/nppes/org-name.js +6 -0
- package/out/tools/nppes/org-name.js.map +1 -0
- package/out/tools/nppes/overmerge-packet.d.ts +43 -0
- package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
- package/out/tools/nppes/overmerge-packet.js +54 -0
- package/out/tools/nppes/overmerge-packet.js.map +1 -0
- package/out/tools/nppes/report.d.ts +97 -0
- package/out/tools/nppes/report.d.ts.map +1 -0
- package/out/tools/nppes/report.js +178 -0
- package/out/tools/nppes/report.js.map +1 -0
- package/out/tools/nppes/sample.d.ts +101 -0
- package/out/tools/nppes/sample.d.ts.map +1 -0
- package/out/tools/nppes/sample.js +127 -0
- package/out/tools/nppes/sample.js.map +1 -0
- package/out/tools/nppes/scoring.d.ts +37 -0
- package/out/tools/nppes/scoring.d.ts.map +1 -0
- package/out/tools/nppes/scoring.js +81 -0
- package/out/tools/nppes/scoring.js.map +1 -0
- package/out/tools/nppes/settings.d.ts +41 -0
- package/out/tools/nppes/settings.d.ts.map +1 -0
- package/out/tools/nppes/settings.js +79 -0
- package/out/tools/nppes/settings.js.map +1 -0
- package/out/tools/nppes/truth-grains.d.ts +63 -0
- package/out/tools/nppes/truth-grains.d.ts.map +1 -0
- package/out/tools/nppes/truth-grains.js +142 -0
- package/out/tools/nppes/truth-grains.js.map +1 -0
- package/out/tools/shared.d.ts +325 -0
- package/out/tools/shared.d.ts.map +1 -0
- package/out/tools/shared.js +453 -0
- package/out/tools/shared.js.map +1 -0
- package/out/tools/train/cross-gbt.d.ts +89 -0
- package/out/tools/train/cross-gbt.d.ts.map +1 -0
- package/out/tools/train/cross-gbt.js +132 -0
- package/out/tools/train/cross-gbt.js.map +1 -0
- package/out/tools/train/gbt.d.ts +85 -0
- package/out/tools/train/gbt.d.ts.map +1 -0
- package/out/tools/train/gbt.js +155 -0
- package/out/tools/train/gbt.js.map +1 -0
- package/out/tools/train/org-cross-gbt.d.ts +85 -0
- package/out/tools/train/org-cross-gbt.d.ts.map +1 -0
- package/out/tools/train/org-cross-gbt.js +122 -0
- package/out/tools/train/org-cross-gbt.js.map +1 -0
- package/out/tools/txhhsc-to-oarow.d.ts +42 -0
- package/out/tools/txhhsc-to-oarow.d.ts.map +1 -0
- package/out/tools/txhhsc-to-oarow.js +78 -0
- package/out/tools/txhhsc-to-oarow.js.map +1 -0
- package/out/tools/viz/browser.d.ts +31 -0
- package/out/tools/viz/browser.d.ts.map +1 -0
- package/out/tools/viz/browser.js +26 -0
- package/out/tools/viz/browser.js.map +1 -0
- package/out/tools/viz/cross-dataset-map.d.ts +39 -0
- package/out/tools/viz/cross-dataset-map.d.ts.map +1 -0
- package/out/tools/viz/cross-dataset-map.js +84 -0
- package/out/tools/viz/cross-dataset-map.js.map +1 -0
- package/out/tools/viz/geocode-first-surface.d.ts +36 -0
- package/out/tools/viz/geocode-first-surface.d.ts.map +1 -0
- package/out/tools/viz/geocode-first-surface.js +234 -0
- package/out/tools/viz/geocode-first-surface.js.map +1 -0
- package/out/tools/viz/render/map.d.ts +42 -0
- package/out/tools/viz/render/map.d.ts.map +1 -0
- package/out/tools/viz/render/map.js +40 -0
- package/out/tools/viz/render/map.js.map +1 -0
- package/out/tools/viz/render.d.ts +46 -0
- package/out/tools/viz/render.d.ts.map +1 -0
- package/out/tools/viz/render.js +49 -0
- package/out/tools/viz/render.js.map +1 -0
- package/out/tools/viz/source-provenance-map.d.ts +57 -0
- package/out/tools/viz/source-provenance-map.d.ts.map +1 -0
- package/out/tools/viz/source-provenance-map.js +82 -0
- package/out/tools/viz/source-provenance-map.js.map +1 -0
- package/out/tools/viz/yardstick-figure.d.ts +22 -0
- package/out/tools/viz/yardstick-figure.d.ts.map +1 -0
- package/out/tools/viz/yardstick-figure.js +106 -0
- package/out/tools/viz/yardstick-figure.js.map +1 -0
- package/out/types.d.ts +108 -0
- package/out/types.d.ts.map +1 -0
- package/out/types.js +11 -0
- package/out/types.js.map +1 -0
- package/package.json +113 -3
- package/tools/coverage-reconciliation.ts +192 -0
- package/tools/cross/dataset-correlation.ts +380 -0
- package/tools/cross/source-threshold-sweep.ts +416 -0
- package/tools/dedup-ceiling.ts +225 -0
- package/tools/eval-geocoder.ts +77 -0
- package/tools/geocoder/namesake-probe.ts +91 -0
- package/tools/geocoder/vs-provided-coords.ts +232 -0
- package/tools/gold-set-sample.ts +147 -0
- package/tools/learned/scorer/clustering-eval.ts +349 -0
- package/tools/learned/scorer/crossstate-eval.ts +280 -0
- package/tools/learned/scorer/eval.ts +429 -0
- package/tools/matcher-scale.ts +185 -0
- package/tools/nppes/dedup-benchmark.ts +364 -0
- package/tools/nppes/org-name.ts +15 -0
- package/tools/nppes/overmerge-packet.ts +98 -0
- package/tools/nppes/report.ts +380 -0
- package/tools/nppes/sample.ts +250 -0
- package/tools/nppes/scoring.ts +115 -0
- package/tools/nppes/settings.ts +102 -0
- package/tools/nppes/truth-grains.ts +185 -0
- package/tools/shared.ts +743 -0
- package/tools/train/cross-gbt.ts +214 -0
- package/tools/train/gbt.ts +261 -0
- package/tools/train/org-cross-gbt.ts +189 -0
- package/tools/txhhsc-to-oarow.ts +118 -0
- package/tools/viz/browser.ts +41 -0
- package/tools/viz/cross-dataset-map.ts +133 -0
- package/tools/viz/geocode-first-surface.ts +305 -0
- package/tools/viz/render/map.ts +61 -0
- package/tools/viz/render.ts +103 -0
- package/tools/viz/source-provenance-map.ts +154 -0
- package/tools/viz/yardstick-figure.ts +197 -0
package/README.md
CHANGED
|
@@ -1,3 +1,115 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mailwoman/entity-resolution
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Geocode-first record-matching application** — the high-level entry point that
|
|
4
|
+
runs the full block → score → cluster pipeline over ingested records and returns
|
|
5
|
+
canonical entities ready for export.
|
|
6
|
+
|
|
7
|
+
This is the clinic-funding use case Mailwoman was built for, standing on a
|
|
8
|
+
calibrated, label-free matcher.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { ingestRows, resolveEntities, toGeoJSON } from "@mailwoman/entity-resolution"
|
|
12
|
+
|
|
13
|
+
// 1. Ingest — rows → normalized SourceRecords. The mapping is POSITIONAL (arg 2) rather than a field of the
|
|
14
|
+
// options object, and `geocodeAddress` belongs here: each address is resolved as it is ingested.
|
|
15
|
+
const records = await ingestRows(
|
|
16
|
+
rows,
|
|
17
|
+
{ organization: "Provider Name", address: ["Street Address", "City", "State", "ZIP"] },
|
|
18
|
+
{ geocodeAddress }
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
// 2. Resolve — block → score → cluster with geo-first defaults. SYNCHRONOUS, and it returns a
|
|
22
|
+
// ResolveResult rather than a bare array: `entities` alongside the pair counts blocking produced.
|
|
23
|
+
const { entities, candidatePairs, droppedBlocks } = resolveEntities(records)
|
|
24
|
+
|
|
25
|
+
// 3. Export — GeoJSON for QGIS. Entities with no resolved coordinate are skipped, so the feature
|
|
26
|
+
// count can be lower than `entities.length`.
|
|
27
|
+
const fc = toGeoJSON(entities)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## The full pipeline
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
CSV / SQLite → ingestRows → SourceRecord[] → resolveEntities → ResolveResult
|
|
34
|
+
↓
|
|
35
|
+
.entities → toGeoJSON()
|
|
36
|
+
↓
|
|
37
|
+
GeoJSON → QGIS
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## API
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// Ingest — parse CSV / map columns → normalized records
|
|
44
|
+
import { inferMapping, ingestRows, normalizeCSV, parseCSV } from "@mailwoman/entity-resolution"
|
|
45
|
+
// ingestRows(rows, mapping, opts?): Promise<SourceRecord[]>
|
|
46
|
+
// opts: { geocodeAddress?, addressSeparator? } — addressSeparator defaults to ", "
|
|
47
|
+
// parseCSV(text): Record<string, string>[]
|
|
48
|
+
// inferMapping(header): ColumnMapping
|
|
49
|
+
// normalizeCSV(path, { mapping, delimiter? }): AsyncGenerator<SourceRecord> — streams, does NOT geocode
|
|
50
|
+
// Resolve — run the full matcher pipeline
|
|
51
|
+
import { resolveEntities } from "@mailwoman/entity-resolution"
|
|
52
|
+
// resolveEntities(records, config?): ResolveResult
|
|
53
|
+
// ResolveResult: { entities, candidatePairs, droppedBlocks }
|
|
54
|
+
// config: { model?, blockingKeys?, threshold?, maxBlockSize?, trainEM?, addressFrequency?,
|
|
55
|
+
// collapseSpatial?, requireCorroboration?, usePhone?, linkage?, discriminators?,
|
|
56
|
+
// exactDiscriminators?, scorer?, learnedScorer? }
|
|
57
|
+
// Export — GeoJSON, MapLibre HTML, reconciliation reports
|
|
58
|
+
import { reconcile, toGeoJSON, toMapHTML } from "@mailwoman/entity-resolution"
|
|
59
|
+
// Learned scorer — pre-trained GBT for single-dataset dedup, default-on
|
|
60
|
+
import { DEDUP_GBT_META, DEDUP_GBT_MODEL } from "@mailwoman/entity-resolution"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`geocodeAddress` is an `ingestRows` option rather than a `resolveEntities` one — coordinates have to exist
|
|
64
|
+
before blocking can use them.
|
|
65
|
+
|
|
66
|
+
## Default configuration
|
|
67
|
+
|
|
68
|
+
`resolveEntities` ships with these defaults:
|
|
69
|
+
|
|
70
|
+
- **The blocking keys:** geo-cell on the resolved coordinate (0.05°, neighbors expanded) + canonical
|
|
71
|
+
address + phone + email
|
|
72
|
+
- **The scoring model:** Fellegi-Sunter with label-free EM, term frequency adjustment
|
|
73
|
+
- **Learned scorer:** the bundled `DEDUP_GBT_MODEL`, on by default for single-dataset dedup
|
|
74
|
+
- **Threshold:** `DEDUP_GBT_META.recommendedThreshold` (2.8324) while the bundled model is active,
|
|
75
|
+
otherwise 0. The unit is the GBT's own logit rather than a Fellegi-Sunter match weight in bits and not a
|
|
76
|
+
probability, so a 0-to-1 value is a category error here. Higher is stricter.
|
|
77
|
+
- **Linkage:** single (connected components), with average linkage available for the over-merge case
|
|
78
|
+
|
|
79
|
+
## CLI
|
|
80
|
+
|
|
81
|
+
The `mailwoman` CLI exposes `registry` as a command:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
# Multi-source entity resolution
|
|
85
|
+
mailwoman registry --sources config.json --resolve-db "$MAILWOMAN_CANDIDATE_DB" --out entities.geojson
|
|
86
|
+
|
|
87
|
+
# Cross-dataset reconciliation
|
|
88
|
+
mailwoman registry --sources tx-nppes.json --reconcile tx-fcc.json --resolve-db "$MAILWOMAN_CANDIDATE_DB"
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
`--resolve-db` (or `$MAILWOMAN_WOF_DB`) is required to BOOT, and is then ignored whenever
|
|
92
|
+
`$MAILWOMAN_CANDIDATE_DB` is set. `requireCommandWOFPath` throws before anything opens; `createResolverBackend`
|
|
93
|
+
then prefers the candidate backend and never touches the WOF path (the inline comment in `run.tsx` states
|
|
94
|
+
this correctly: `$MAILWOMAN_CANDIDATE_DB` selects the demo-parity candidate backend, and FTS over `wofPath` is the fallback).
|
|
95
|
+
A nonexistent path satisfies that requirement.
|
|
96
|
+
|
|
97
|
+
So: set `$MAILWOMAN_CANDIDATE_DB` and pass anything to `--resolve-db`. Do not pass `candidate.db` to
|
|
98
|
+
`--resolve-db` with the environment variable unset. The flag is believed on that path, and the admin
|
|
99
|
+
backend queries `place_search`/`spr`, which a candidate gazetteer does not have.
|
|
100
|
+
|
|
101
|
+
An argument required only to discard it is a defect in this command. Documented rather than fixed.
|
|
102
|
+
|
|
103
|
+
Two CLI defaults differ from the library defaults: `--threshold` defaults to `0`, which is the
|
|
104
|
+
Fellegi-Sunter baseline rather than the bundled model's calibrated 2.8324, and `--train-em` is on.
|
|
105
|
+
|
|
106
|
+
## Related
|
|
107
|
+
|
|
108
|
+
- [`@mailwoman/match`](../match) — the low-level block/score/cluster primitives
|
|
109
|
+
- [`@mailwoman/record`](../record) — `SourceRecord` schema and normalizers
|
|
110
|
+
- [`@mailwoman/address-id`](../address-id) — exact-match join key
|
|
111
|
+
- [Match messy records to one entity each](https://mailwoman.post/docs/developers/how-to/match-messy-records)
|
|
112
|
+
|
|
113
|
+
## License
|
|
114
|
+
|
|
115
|
+
[AGPL-3.0-only](https://www.gnu.org/licenses/AGPL-3.0.html)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The address-id consumer for the matcher. Derives a stable {@link PostalAddressID} from a
|
|
7
|
+
* resolved {@link SourceRecord} and exposes it as a blocking key, the deterministic
|
|
8
|
+
* exact-canonical-address complement to the fuzzy Fellegi-Sunter / GBT scoring. Two uses:
|
|
9
|
+
*
|
|
10
|
+
* - **As a pre-dedup / join key:** `group BY postalAddressID(record)` collapses records that resolve
|
|
11
|
+
* to the same place and share a canonical address with no scoring at all. That is the cheap,
|
|
12
|
+
* certain part of dedup before the matcher does the fuzzy rest.
|
|
13
|
+
* - **As a blocking key:** {@link addressIDBlockingKey} adds the address-id to the blocking union, so
|
|
14
|
+
* records sharing one are guaranteed to be compared.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createPostalAddressID, type PostalAddressID } from "@mailwoman/address-id"
|
|
18
|
+
import { type BlockingKey, exactKey } from "@mailwoman/match"
|
|
19
|
+
|
|
20
|
+
import type { SourceRecord } from "#types"
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The stable address primary key for a record, or null when it is not geocoded
|
|
24
|
+
* (no coordinate means no locality cell) or includes no raw address to hash.
|
|
25
|
+
*
|
|
26
|
+
* The state prefix is plucked from the address when present.
|
|
27
|
+
*/
|
|
28
|
+
export function postalAddressID(record: SourceRecord): PostalAddressID | null {
|
|
29
|
+
const coordinate = record.address?.geocode?.coordinate
|
|
30
|
+
const address = record.address?.raw
|
|
31
|
+
|
|
32
|
+
if (!coordinate || !address) return null
|
|
33
|
+
|
|
34
|
+
return createPostalAddressID({ coordinate, address })
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A blocking key on the {@link postalAddressID}.
|
|
39
|
+
*
|
|
40
|
+
* Records that resolve to the same place with the same canonical address block together.
|
|
41
|
+
*
|
|
42
|
+
* Add it to {@link defaultBlockingKeys}'s union when an exact address join should never be missed.
|
|
43
|
+
*/
|
|
44
|
+
export function addressIDBlockingKey(): BlockingKey<SourceRecord> {
|
|
45
|
+
return exactKey((record) => postalAddressID(record))
|
|
46
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* The per-record geocode step, factored out of the worker so it unit-tests against a fake geocoder (no
|
|
7
|
+
* neural model / SQLite). `geocode-worker.ts` builds the real geocoder from config and wraps this.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { type ColumnMapping, type GeocodeAddress, pick } from "#ingest"
|
|
11
|
+
import type { SourceRecord } from "#types"
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Build the handler `geocodeStream` runs per normalized record: recompute the joined address
|
|
15
|
+
* string from `record.raw` + `mapping.address` (the worker can't receive the original closure),
|
|
16
|
+
* geocode it via `geocode`, and attach the result.
|
|
17
|
+
*
|
|
18
|
+
* Records with no mapped address pass through untouched (no geocode call).
|
|
19
|
+
* The default separator matches {@link ingestRow}'s `addressSeparator`.
|
|
20
|
+
*/
|
|
21
|
+
export function makeGeocodeHandler(
|
|
22
|
+
geocode: GeocodeAddress,
|
|
23
|
+
mapping: ColumnMapping,
|
|
24
|
+
addressSeparator = ", "
|
|
25
|
+
): (record: SourceRecord) => Promise<SourceRecord> {
|
|
26
|
+
return async (record) => {
|
|
27
|
+
if (!record.raw) return record
|
|
28
|
+
|
|
29
|
+
const addressValue = pick(record.raw, mapping.address, addressSeparator)
|
|
30
|
+
|
|
31
|
+
if (!addressValue) return record
|
|
32
|
+
|
|
33
|
+
const address = (await geocode(addressValue)) ?? null
|
|
34
|
+
|
|
35
|
+
return { ...record, address }
|
|
36
|
+
}
|
|
37
|
+
}
|
package/lib/geojson.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Export resolved entities as GeoJSON — the bridge to QGIS and any web map. Each entity becomes a
|
|
7
|
+
* Point at its resolved coordinate, carrying the properties an analyst needs: the count of records
|
|
8
|
+
* merged into it, how tightly (cohesion), the canonical name/org/address and the geocode tier
|
|
9
|
+
* (so rooftop-precise entities can be styled apart from admin-centroid guesses). Entities without
|
|
10
|
+
* a coordinate are omitted (a Point feature needs one).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { formatPersonName } from "@mailwoman/record/name"
|
|
14
|
+
import type { GeoFeature, GeoFeatureCollection, PointLiteral } from "@mailwoman/spatial"
|
|
15
|
+
|
|
16
|
+
import type { EntityGeoData, ResolvedEntity, SourceRecord } from "#types"
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Assemble a display name from a record's parsed person name, if any.
|
|
20
|
+
*/
|
|
21
|
+
function displayName(record: SourceRecord): string | null {
|
|
22
|
+
return formatPersonName(record.name ?? null) || null
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One entity → one GeoJSON Point feature.
|
|
27
|
+
*
|
|
28
|
+
* `extra` merges over (and may override) the standard properties.
|
|
29
|
+
* The reconciliation flow adds its `bucket` and swaps the display name for the
|
|
30
|
+
* representative's org-or-person form.
|
|
31
|
+
*/
|
|
32
|
+
export function toFeature(
|
|
33
|
+
entity: ResolvedEntity,
|
|
34
|
+
extra?: Partial<EntityGeoData>
|
|
35
|
+
): GeoFeature<PointLiteral, EntityGeoData> {
|
|
36
|
+
const rep = entity.representative
|
|
37
|
+
|
|
38
|
+
return {
|
|
39
|
+
type: "Feature",
|
|
40
|
+
geometry: {
|
|
41
|
+
type: "Point",
|
|
42
|
+
coordinates: [entity.coordinate!.longitude, entity.coordinate!.latitude],
|
|
43
|
+
},
|
|
44
|
+
properties: {
|
|
45
|
+
entityID: entity.id,
|
|
46
|
+
recordCount: entity.records.length,
|
|
47
|
+
cohesion: entity.cohesion,
|
|
48
|
+
sourceIDs: entity.records.map((r) => r.id),
|
|
49
|
+
// Distinct provenance labels the entity's records span.
|
|
50
|
+
// An entity with ≥2 is a cross-dataset link.
|
|
51
|
+
sources: [...new Set(entity.records.map((r) => r.source).filter((s): s is string => !!s))].toSorted(),
|
|
52
|
+
name: displayName(rep),
|
|
53
|
+
organization: rep.organization?.canonical ?? null,
|
|
54
|
+
address: rep.address?.formatted ?? null,
|
|
55
|
+
geocodeTier: rep.address?.geocode?.tier ?? null,
|
|
56
|
+
bucket: null,
|
|
57
|
+
...extra,
|
|
58
|
+
},
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Convert resolved entities into a GeoJSON `FeatureCollection` of points, ready for QGIS.
|
|
64
|
+
*
|
|
65
|
+
* Entities with no resolved coordinate are skipped.
|
|
66
|
+
*/
|
|
67
|
+
export function toGeoJSON(entities: readonly ResolvedEntity[]): GeoFeatureCollection<PointLiteral, EntityGeoData> {
|
|
68
|
+
return {
|
|
69
|
+
type: "FeatureCollection",
|
|
70
|
+
features: entities.filter((entity) => entity.coordinate).map((entity) => toFeature(entity)),
|
|
71
|
+
}
|
|
72
|
+
}
|
package/lib/index.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* `@mailwoman/entity-resolution` — the geocode-first record-matching application.
|
|
7
|
+
*
|
|
8
|
+
* {@link resolveEntities} runs the whole matcher (block → score → cluster) over normalized
|
|
9
|
+
* contact/organization {@link SourceRecord}s and returns canonical {@link ResolvedEntity entities};
|
|
10
|
+
* {@link toGeoJSON} exports them for QGIS. This is the clinic-funding use case mailwoman was built
|
|
11
|
+
* for, finally standing on a calibrated, label-free matcher.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export * from "#address-key"
|
|
15
|
+
export * from "#geojson"
|
|
16
|
+
export * from "#ingest"
|
|
17
|
+
export * from "#geocode-handler"
|
|
18
|
+
export * from "#learned-scorer"
|
|
19
|
+
export * from "#map-html"
|
|
20
|
+
export * from "#models/dedup-gbt-en-us"
|
|
21
|
+
export * from "#reconcile"
|
|
22
|
+
export * from "#resolve"
|
|
23
|
+
export * from "#types"
|
package/lib/ingest.ts
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Column mapping and normalization are pure. The caller injects geocoding, so this package never imports the neural parser, resolver, or extracts.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { isPresent } from "@mailwoman/core/objects"
|
|
10
|
+
import type { AddressGeocode, PostalAddress } from "@mailwoman/record"
|
|
11
|
+
import { canonicalizeOrganizationName, parsePersonName, toPostalAddress, withGeocode } from "@mailwoman/record"
|
|
12
|
+
import type { PathBuilderLike } from "path-ts"
|
|
13
|
+
import { type AsyncSequence, CSVSpliterator, Delimiters } from "spliterator"
|
|
14
|
+
|
|
15
|
+
import type { SourceRecord } from "#types"
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Resolve a raw address string into a {@link PostalAddress}, the entry point to mailwoman's geocoder.
|
|
19
|
+
*/
|
|
20
|
+
export type GeocodeAddress = (raw: string) => Promise<PostalAddress | null> | PostalAddress | null
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The column delimiters a tabular source may declare, by name, each the spliterator's own byte.
|
|
24
|
+
*
|
|
25
|
+
* The `satisfies` clause makes a delimiter name spliterator no longer ships a compile error
|
|
26
|
+
* rather than a silently parallel vocabulary.
|
|
27
|
+
*/
|
|
28
|
+
const COLUMN_DELIMITERS = {
|
|
29
|
+
comma: Delimiters.Comma,
|
|
30
|
+
tab: Delimiters.Tab,
|
|
31
|
+
} as const satisfies Partial<Record<Lowercase<keyof typeof Delimiters>, (typeof Delimiters)[keyof typeof Delimiters]>>
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Column delimiter of a delimited source.
|
|
35
|
+
*/
|
|
36
|
+
export type Delimiter = keyof typeof COLUMN_DELIMITERS
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Infer the delimiter from a path's extension (`.tsv` → tab, else comma).
|
|
40
|
+
*/
|
|
41
|
+
export function delimiterFor(path: string): Delimiter {
|
|
42
|
+
return /\.tsv$/i.test(path) ? "tab" : "comma"
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Stream a delimited file's rows lazily as header-keyed objects.
|
|
47
|
+
*
|
|
48
|
+
* @returns The spliterator's own {@linkcode AsyncSequence}, whose `map`/`filter`
|
|
49
|
+
* fuse into the same pull loop.
|
|
50
|
+
* An `async function*` wrapper would add an async frame per row and remove those operators.
|
|
51
|
+
*/
|
|
52
|
+
export function streamRows(
|
|
53
|
+
source: PathBuilderLike,
|
|
54
|
+
opts: { delimiter?: Delimiter } = {}
|
|
55
|
+
): AsyncSequence<Record<string, string>> {
|
|
56
|
+
const path = source.toString()
|
|
57
|
+
|
|
58
|
+
return CSVSpliterator.fromAsync<Record<string, string>>(path, {
|
|
59
|
+
columnDelimiter: COLUMN_DELIMITERS[opts.delimiter ?? delimiterFor(path)],
|
|
60
|
+
// A {@linkcode ColumnMapping} holds columns in the publisher's spelling rather than a
|
|
61
|
+
// normalized key such as `facility_name`, so the keys must arrive as the file writes them.
|
|
62
|
+
// The reader's default normalizes.
|
|
63
|
+
normalizeKeys: false,
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Maps dataset columns to record fields, where a field may draw from several columns joined with spaces.
|
|
69
|
+
*/
|
|
70
|
+
export interface ColumnMapping {
|
|
71
|
+
/**
|
|
72
|
+
* Column holding a stable row id, falling back to the row index.
|
|
73
|
+
*/
|
|
74
|
+
id?: string
|
|
75
|
+
/**
|
|
76
|
+
* A literal provenance label for every row (not a column).
|
|
77
|
+
*/
|
|
78
|
+
source?: string
|
|
79
|
+
name?: string | string[]
|
|
80
|
+
organization?: string | string[]
|
|
81
|
+
address?: string | string[]
|
|
82
|
+
phone?: string
|
|
83
|
+
email?: string
|
|
84
|
+
/**
|
|
85
|
+
* Extra secondary-identifier fields mapped to the column(s) to draw each from, landing
|
|
86
|
+
* on `SourceRecord.attributes` under the same key for the matcher's `discriminators`.
|
|
87
|
+
*/
|
|
88
|
+
attributes?: Record<string, string | string[]>
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Best-effort {@link ColumnMapping} inferred from a header row, the "point it at any CSV" convenience.
|
|
93
|
+
*/
|
|
94
|
+
export function inferMapping(header: readonly string[]): ColumnMapping {
|
|
95
|
+
// Pad to whole-token boundaries so "state" doesn't match inside "statement".
|
|
96
|
+
const tok = (h: string) =>
|
|
97
|
+
` ${h
|
|
98
|
+
.toLowerCase()
|
|
99
|
+
.replaceAll(/[^a-z0-9]+/g, " ")
|
|
100
|
+
.trim()} `
|
|
101
|
+
|
|
102
|
+
const mapping: ColumnMapping = {}
|
|
103
|
+
const name: string[] = []
|
|
104
|
+
const address: string[] = []
|
|
105
|
+
|
|
106
|
+
for (const column of header) {
|
|
107
|
+
const h = tok(column)
|
|
108
|
+
const has = (...words: string[]): boolean => words.some((w) => h.includes(` ${w} `))
|
|
109
|
+
|
|
110
|
+
if (!mapping.email && has("email", "e mail")) {
|
|
111
|
+
mapping.email = column
|
|
112
|
+
} else if (!mapping.phone && has("phone", "telephone", "tel", "mobile", "cell")) {
|
|
113
|
+
mapping.phone = column
|
|
114
|
+
} else if (!mapping.id && has("id", "npi", "ein", "frn", "spin", "uuid", "guid", "key")) {
|
|
115
|
+
mapping.id = column
|
|
116
|
+
} else if (has("org", "organization", "organisation", "company", "business", "facility", "agency", "employer")) {
|
|
117
|
+
mapping.organization ??= column
|
|
118
|
+
} else if (
|
|
119
|
+
has(
|
|
120
|
+
"street",
|
|
121
|
+
"address",
|
|
122
|
+
"addr",
|
|
123
|
+
"city",
|
|
124
|
+
"town",
|
|
125
|
+
"state",
|
|
126
|
+
"province",
|
|
127
|
+
"zip",
|
|
128
|
+
"zipcode",
|
|
129
|
+
"postal",
|
|
130
|
+
"postcode",
|
|
131
|
+
"county"
|
|
132
|
+
)
|
|
133
|
+
) {
|
|
134
|
+
address.push(column)
|
|
135
|
+
} else if (has("name", "first", "last", "given", "family", "middle", "surname", "fullname", "contact")) {
|
|
136
|
+
name.push(column)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (name.length) {
|
|
141
|
+
mapping.name = name.length === 1 ? name[0]! : name
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (address.length) {
|
|
145
|
+
mapping.address = address
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return mapping
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Options for {@link ingestRows}.
|
|
153
|
+
*/
|
|
154
|
+
export interface IngestOptions {
|
|
155
|
+
/**
|
|
156
|
+
* The geocoding interface.
|
|
157
|
+
*
|
|
158
|
+
* Without it records include name/org but have no resolved address.
|
|
159
|
+
*/
|
|
160
|
+
geocodeAddress?: GeocodeAddress
|
|
161
|
+
/**
|
|
162
|
+
* Separator for joining a multi-column address mapping, comma-join giving the parser
|
|
163
|
+
* delimited input rather than a concatenated run (name/org always join with a space).
|
|
164
|
+
*
|
|
165
|
+
* @defaultValue `", "`
|
|
166
|
+
*/
|
|
167
|
+
addressSeparator?: string
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Join the selected columns of a row into a single trimmed string, or null if empty.
|
|
172
|
+
*/
|
|
173
|
+
export function pick(row: Record<string, string>, columns?: string | string[], separator = " "): string | null {
|
|
174
|
+
if (!columns) return null
|
|
175
|
+
const list = Array.isArray(columns) ? columns : [columns]
|
|
176
|
+
|
|
177
|
+
const value = list
|
|
178
|
+
.map((c) => row[c])
|
|
179
|
+
.filter(isPresent)
|
|
180
|
+
.join(separator)
|
|
181
|
+
.trim()
|
|
182
|
+
|
|
183
|
+
return value || null
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Normalize one tabular row into a {@link SourceRecord} under a {@link ColumnMapping},
|
|
188
|
+
* pure aside from the optional geocode interface so the deterministic normalization
|
|
189
|
+
* can run single-threaded while geocoding is offloaded.
|
|
190
|
+
*/
|
|
191
|
+
export async function ingestRow(
|
|
192
|
+
row: Record<string, string>,
|
|
193
|
+
mapping: ColumnMapping,
|
|
194
|
+
index: number,
|
|
195
|
+
opts: IngestOptions = {}
|
|
196
|
+
): Promise<SourceRecord> {
|
|
197
|
+
const id = (mapping.id ? row[mapping.id] : "") || String(index)
|
|
198
|
+
const nameValue = pick(row, mapping.name)
|
|
199
|
+
const orgValue = pick(row, mapping.organization)
|
|
200
|
+
const addressValue = pick(row, mapping.address, opts.addressSeparator ?? ", ")
|
|
201
|
+
|
|
202
|
+
let attributes: Record<string, string> | null = null
|
|
203
|
+
|
|
204
|
+
if (mapping.attributes) {
|
|
205
|
+
for (const [key, columns] of Object.entries(mapping.attributes)) {
|
|
206
|
+
const value = pick(row, columns)
|
|
207
|
+
|
|
208
|
+
if (value) {
|
|
209
|
+
;(attributes ??= {})[key] = value
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return {
|
|
215
|
+
id,
|
|
216
|
+
source: mapping.source ?? null,
|
|
217
|
+
name: nameValue ? parsePersonName(nameValue) : null,
|
|
218
|
+
organization: orgValue ? canonicalizeOrganizationName(orgValue) : null,
|
|
219
|
+
phone: (mapping.phone && row[mapping.phone]) || null,
|
|
220
|
+
email: (mapping.email && row[mapping.email]?.toLowerCase()) || null,
|
|
221
|
+
address: addressValue && opts.geocodeAddress ? ((await opts.geocodeAddress(addressValue)) ?? null) : null,
|
|
222
|
+
attributes,
|
|
223
|
+
raw: row,
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Normalize tabular rows into {@link SourceRecord}s under a {@link ColumnMapping}.
|
|
229
|
+
*
|
|
230
|
+
* @see {@link streamRows} for the streaming path. It is preferred for multi-GB files.
|
|
231
|
+
*/
|
|
232
|
+
export async function ingestRows(
|
|
233
|
+
rows: Iterable<Record<string, string>> | AsyncIterable<Record<string, string>>,
|
|
234
|
+
mapping: ColumnMapping,
|
|
235
|
+
opts: IngestOptions = {}
|
|
236
|
+
): Promise<SourceRecord[]> {
|
|
237
|
+
const records: SourceRecord[] = []
|
|
238
|
+
let index = 0
|
|
239
|
+
|
|
240
|
+
for await (const row of rows) {
|
|
241
|
+
records.push(await ingestRow(row, mapping, index, opts))
|
|
242
|
+
|
|
243
|
+
index++
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return records
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Stream a delimited file as normalized {@link SourceRecord}s in file order with no geocoding.
|
|
251
|
+
* Geocode separately through `geocodeStream`.
|
|
252
|
+
*/
|
|
253
|
+
export function normalizeCSV(
|
|
254
|
+
source: PathBuilderLike,
|
|
255
|
+
opts: { mapping: ColumnMapping; delimiter?: Delimiter }
|
|
256
|
+
): AsyncSequence<SourceRecord> {
|
|
257
|
+
return streamRows(source, { delimiter: opts.delimiter }).map((row, index) => ingestRow(row, opts.mapping, index))
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* The subset of mailwoman's `GeocodeResult` the adapter consumes, kept structural
|
|
262
|
+
* so this package never imports the heavy geocoder.
|
|
263
|
+
*/
|
|
264
|
+
export interface RawGeocode {
|
|
265
|
+
lat: number | null
|
|
266
|
+
lon: number | null
|
|
267
|
+
resolution_tier: AddressGeocode["tier"]
|
|
268
|
+
uncertainty_m: number | null
|
|
269
|
+
hierarchy?: AddressGeocode["hierarchy"]
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The component map {@link toPostalAddress} consumes
|
|
274
|
+
* (kept structural so this package never imports the geocoder).
|
|
275
|
+
*/
|
|
276
|
+
type GeocodeComponents = Parameters<typeof toPostalAddress>[0]
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* What every shape of {@link geocodeAddressVia}'s dependencies includes.
|
|
280
|
+
*/
|
|
281
|
+
export interface GeocodeDepsBase {
|
|
282
|
+
/**
|
|
283
|
+
* Country (ISO-2 or name) the address is formatted under.
|
|
284
|
+
*
|
|
285
|
+
* When omitted, {@link toPostalAddress} reads the parsed `country` component instead.
|
|
286
|
+
*/
|
|
287
|
+
country?: string
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Two independent calls: parse the address, then geocode it.
|
|
292
|
+
*
|
|
293
|
+
* Mailwoman's `geocodeAddress` re-parses internally, so the address is read twice
|
|
294
|
+
* unless the two callbacks share a parser.
|
|
295
|
+
*/
|
|
296
|
+
export interface TwoStepGeocodeDeps extends GeocodeDepsBase {
|
|
297
|
+
parse: (raw: string) => Promise<GeocodeComponents> | GeocodeComponents
|
|
298
|
+
geocode: (raw: string) => Promise<RawGeocode | null> | RawGeocode | null
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Parse the address once and answer both the components and the geocode, for
|
|
303
|
+
* when the parse is the expensive step you'd rather not pay for twice.
|
|
304
|
+
*/
|
|
305
|
+
export interface OneStepGeocodeDeps extends GeocodeDepsBase {
|
|
306
|
+
parseAndGeocode: (raw: string) => Promise<{ components: GeocodeComponents; geo: RawGeocode | null }>
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* The dependencies {@link geocodeAddressVia} builds a {@link GeocodeAddress} from;
|
|
311
|
+
* `"parseAndGeocode" in deps` tells the two shapes apart.
|
|
312
|
+
*/
|
|
313
|
+
export type GeocodeAddressViaDeps = TwoStepGeocodeDeps | OneStepGeocodeDeps
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Build a {@link GeocodeAddress} from injected parse and geocode primitives.
|
|
317
|
+
*
|
|
318
|
+
* When geocoding can't place the address, the parsed-but-unlocated address is still returned.
|
|
319
|
+
*/
|
|
320
|
+
export function geocodeAddressVia(deps: GeocodeAddressViaDeps): GeocodeAddress {
|
|
321
|
+
return async (raw: string): Promise<PostalAddress | null> => {
|
|
322
|
+
let components: GeocodeComponents
|
|
323
|
+
let resolved: RawGeocode | null
|
|
324
|
+
|
|
325
|
+
if ("parseAndGeocode" in deps) {
|
|
326
|
+
const r = await deps.parseAndGeocode(raw)
|
|
327
|
+
components = r.components
|
|
328
|
+
resolved = r.geo
|
|
329
|
+
} else {
|
|
330
|
+
components = await deps.parse(raw)
|
|
331
|
+
resolved = await deps.geocode(raw)
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const base = toPostalAddress(components, { country: deps.country, raw })
|
|
335
|
+
|
|
336
|
+
if (!resolved || resolved.lat === null || resolved.lon === null) return base
|
|
337
|
+
|
|
338
|
+
const geocode: AddressGeocode = {
|
|
339
|
+
coordinate: { latitude: resolved.lat, longitude: resolved.lon },
|
|
340
|
+
tier: resolved.resolution_tier,
|
|
341
|
+
uncertaintyMeters: resolved.uncertainty_m,
|
|
342
|
+
hierarchy: resolved.hierarchy ?? null,
|
|
343
|
+
poBox: null,
|
|
344
|
+
multiUnit: null,
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
return withGeocode(base, geocode)
|
|
348
|
+
}
|
|
349
|
+
}
|