@mailwoman/tiger 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.
@@ -1 +1 @@
1
- {"version":"7.0.2","root":["../lib/files.test.ts","../sdk/redistricting.test.ts"],"packageJsons":["../../../node_modules/@sister.software/h3/package.json","../../../node_modules/@types/chai/package.json","../../../node_modules/@types/deep-eql/package.json","../../../node_modules/@types/node/package.json","../../../node_modules/@vitest/browser-playwright/package.json","../../../node_modules/@vitest/coverage-v8/package.json","../../../node_modules/@vitest/mocker/package.json","../../../node_modules/@vitest/ui/package.json","../../../node_modules/assertion-error/package.json","../../../node_modules/buffer/package.json","../../../node_modules/chai/package.json","../../../node_modules/deep-eql/package.json","../../../node_modules/esbuild/package.json","../../../node_modules/events/package.json","../../../node_modules/expect-type/package.json","../../../node_modules/jiti/package.json","../../../node_modules/jsdom/package.json","../../../node_modules/punycode/package.json","../../../node_modules/string_decoder/package.json","../../../node_modules/tagged-tag/package.json","../../../node_modules/terser/package.json","../../../node_modules/tinybench/package.json","../../../node_modules/type-fest/package.json","../../../node_modules/undici-types/package.json","../../../node_modules/vite/package.json","../../../node_modules/vitest/package.json","../../../node_modules/yaml/package.json","../../annotations/package.json","../../spatial/package.json","../package.json"],"missingPackageJsons":["../../../node_modules/@edge-runtime/vm/package.json","../../../node_modules/@opentelemetry/api/package.json","../../../node_modules/@sister.software/h3/out/lib/api/package.json","../../../node_modules/@sister.software/h3/out/lib/package.json","../../../node_modules/@sister.software/h3/out/lib/runtime/package.json","../../../node_modules/@sister.software/h3/out/package.json","../../../node_modules/@types/assert/package.json","../../../node_modules/@types/assert/strict/package.json","../../../node_modules/@types/async_hooks/package.json","../../../node_modules/@types/child_process/package.json","../../../node_modules/@types/cluster/package.json","../../../node_modules/@types/console/package.json","../../../node_modules/@types/constants/package.json","../../../node_modules/@types/crypto/package.json","../../../node_modules/@types/dgram/package.json","../../../node_modules/@types/diagnostics_channel/package.json","../../../node_modules/@types/dns/package.json","../../../node_modules/@types/dns/promises/package.json","../../../node_modules/@types/domain/package.json","../../../node_modules/@types/events/package.json","../../../node_modules/@types/fs/package.json","../../../node_modules/@types/fs/promises/package.json","../../../node_modules/@types/http/package.json","../../../node_modules/@types/http2/package.json","../../../node_modules/@types/https/package.json","../../../node_modules/@types/inspector/package.json","../../../node_modules/@types/inspector/promises/package.json","../../../node_modules/@types/module/package.json","../../../node_modules/@types/net/package.json","../../../node_modules/@types/node/assert/package.json","../../../node_modules/@types/node/dns/package.json","../../../node_modules/@types/node/fs/package.json","../../../node_modules/@types/node/inspector/package.json","../../../node_modules/@types/node/path/package.json","../../../node_modules/@types/node/readline/package.json","../../../node_modules/@types/node/stream/package.json","../../../node_modules/@types/node/test/package.json","../../../node_modules/@types/node/timers/package.json","../../../node_modules/@types/node/util/package.json","../../../node_modules/@types/node/web-globals/package.json","../../../node_modules/@types/node/zlib/package.json","../../../node_modules/@types/os/package.json","../../../node_modules/@types/path/package.json","../../../node_modules/@types/path/posix/package.json","../../../node_modules/@types/path/win32/package.json","../../../node_modules/@types/perf_hooks/package.json","../../../node_modules/@types/process/package.json","../../../node_modules/@types/punycode/package.json","../../../node_modules/@types/querystring/package.json","../../../node_modules/@types/readline/package.json","../../../node_modules/@types/readline/promises/package.json","../../../node_modules/@types/repl/package.json","../../../node_modules/@types/stream/consumers/package.json","../../../node_modules/@types/stream/iter/package.json","../../../node_modules/@types/stream/package.json","../../../node_modules/@types/stream/promises/package.json","../../../node_modules/@types/stream/web/package.json","../../../node_modules/@types/string_decoder/package.json","../../../node_modules/@types/timers/package.json","../../../node_modules/@types/timers/promises/package.json","../../../node_modules/@types/tls/package.json","../../../node_modules/@types/trace_events/package.json","../../../node_modules/@types/tty/package.json","../../../node_modules/@types/url/package.json","../../../node_modules/@types/util/package.json","../../../node_modules/@types/util/types/package.json","../../../node_modules/@types/v8/package.json","../../../node_modules/@types/vm/package.json","../../../node_modules/@types/wasi/package.json","../../../node_modules/@types/worker_threads/package.json","../../../node_modules/@types/zlib/package.json","../../../node_modules/@vitejs/devtools/package.json","../../../node_modules/@vitest/browser-preview/package.json","../../../node_modules/@vitest/browser-webdriverio/package.json","../../../node_modules/@vitest/coverage-istanbul/package.json","../../../node_modules/@vitest/mocker/dist/package.json","../../../node_modules/assert/package.json","../../../node_modules/assert/strict/package.json","../../../node_modules/async_hooks/package.json","../../../node_modules/child_process/package.json","../../../node_modules/cluster/package.json","../../../node_modules/console/package.json","../../../node_modules/constants/package.json","../../../node_modules/crypto/package.json","../../../node_modules/dgram/package.json","../../../node_modules/diagnostics_channel/package.json","../../../node_modules/dns/package.json","../../../node_modules/dns/promises/package.json","../../../node_modules/domain/package.json","../../../node_modules/expect-type/dist/package.json","../../../node_modules/fs/package.json","../../../node_modules/fs/promises/package.json","../../../node_modules/happy-dom/package.json","../../../node_modules/http/package.json","../../../node_modules/http2/package.json","../../../node_modules/https/package.json","../../../node_modules/inspector/package.json","../../../node_modules/inspector/promises/package.json","../../../node_modules/less/package.json","../../../node_modules/module/package.json","../../../node_modules/msw/package.json","../../../node_modules/net/package.json","../../../node_modules/os/package.json","../../../node_modules/path/package.json","../../../node_modules/path/posix/package.json","../../../node_modules/path/win32/package.json","../../../node_modules/perf_hooks/package.json","../../../node_modules/process/package.json","../../../node_modules/querystring/package.json","../../../node_modules/readline/package.json","../../../node_modules/readline/promises/package.json","../../../node_modules/repl/package.json","../../../node_modules/sass-embedded/package.json","../../../node_modules/sass/package.json","../../../node_modules/stream/consumers/package.json","../../../node_modules/stream/iter/package.json","../../../node_modules/stream/package.json","../../../node_modules/stream/promises/package.json","../../../node_modules/stream/web/package.json","../../../node_modules/stylus/package.json","../../../node_modules/sugarss/package.json","../../../node_modules/timers/package.json","../../../node_modules/timers/promises/package.json","../../../node_modules/tinybench/dist/package.json","../../../node_modules/tls/package.json","../../../node_modules/trace_events/package.json","../../../node_modules/tsx/package.json","../../../node_modules/tty/package.json","../../../node_modules/type-fest/source/internal/package.json","../../../node_modules/type-fest/source/package.json","../../../node_modules/url/package.json","../../../node_modules/util/package.json","../../../node_modules/util/types/package.json","../../../node_modules/v8/package.json","../../../node_modules/vite/dist/node/chunks/package.json","../../../node_modules/vite/dist/node/package.json","../../../node_modules/vite/dist/package.json","../../../node_modules/vite/module-runner/package.json","../../../node_modules/vite/types/package.json","../../../node_modules/vitest/dist/chunks/package.json","../../../node_modules/vitest/dist/package.json","../../../node_modules/vm/package.json","../../../node_modules/wasi/package.json","../../../node_modules/worker_threads/package.json","../../../node_modules/zlib/package.json"]}
1
+ {"version":"7.0.2","root":["../lib/files.test.ts","../sdk/gazetteer.test.ts","../sdk/redistricting.test.ts"],"packageJsons":["../../../node_modules/@sister.software/h3/package.json","../../../node_modules/@types/chai/package.json","../../../node_modules/@types/deep-eql/package.json","../../../node_modules/@types/node/package.json","../../../node_modules/@vitest/browser-playwright/package.json","../../../node_modules/@vitest/coverage-v8/package.json","../../../node_modules/@vitest/mocker/package.json","../../../node_modules/@vitest/ui/package.json","../../../node_modules/assertion-error/package.json","../../../node_modules/buffer/package.json","../../../node_modules/chai/package.json","../../../node_modules/deep-eql/package.json","../../../node_modules/esbuild/package.json","../../../node_modules/events/package.json","../../../node_modules/expect-type/package.json","../../../node_modules/jiti/package.json","../../../node_modules/jsdom/package.json","../../../node_modules/path-ts/package.json","../../../node_modules/punycode/package.json","../../../node_modules/string_decoder/package.json","../../../node_modules/tagged-tag/package.json","../../../node_modules/terser/package.json","../../../node_modules/tinybench/package.json","../../../node_modules/type-fest/package.json","../../../node_modules/undici-types/package.json","../../../node_modules/vite/package.json","../../../node_modules/vitest/package.json","../../../node_modules/yaml/package.json","../../annotations/package.json","../../core/package.json","../../recognizer/package.json","../../registry/package.json","../../spatial/package.json","../package.json"],"missingPackageJsons":["../../../node_modules/@edge-runtime/vm/package.json","../../../node_modules/@mailwoman/core/fs/temporary/package.json","../../../node_modules/@mailwoman/core/fs/writers/package.json","../../../node_modules/@mailwoman/recognizer/coordinates.generated/package.json","../../../node_modules/@mailwoman/recognizer/identifiers.generated/package.json","../../../node_modules/@mailwoman/recognizer/spatial.generated/package.json","../../../node_modules/@mailwoman/recognizer/types/package.json","../../../node_modules/@mailwoman/registry/types/package.json","../../../node_modules/@opentelemetry/api/package.json","../../../node_modules/@sister.software/h3/out/lib/api/package.json","../../../node_modules/@sister.software/h3/out/lib/package.json","../../../node_modules/@sister.software/h3/out/lib/runtime/package.json","../../../node_modules/@sister.software/h3/out/package.json","../../../node_modules/@types/assert/package.json","../../../node_modules/@types/assert/strict/package.json","../../../node_modules/@types/async_hooks/package.json","../../../node_modules/@types/child_process/package.json","../../../node_modules/@types/cluster/package.json","../../../node_modules/@types/console/package.json","../../../node_modules/@types/constants/package.json","../../../node_modules/@types/crypto/package.json","../../../node_modules/@types/dgram/package.json","../../../node_modules/@types/diagnostics_channel/package.json","../../../node_modules/@types/dns/package.json","../../../node_modules/@types/dns/promises/package.json","../../../node_modules/@types/domain/package.json","../../../node_modules/@types/events/package.json","../../../node_modules/@types/fs/package.json","../../../node_modules/@types/fs/promises/package.json","../../../node_modules/@types/http/package.json","../../../node_modules/@types/http2/package.json","../../../node_modules/@types/https/package.json","../../../node_modules/@types/inspector/package.json","../../../node_modules/@types/inspector/promises/package.json","../../../node_modules/@types/module/package.json","../../../node_modules/@types/net/package.json","../../../node_modules/@types/node/assert/package.json","../../../node_modules/@types/node/dns/package.json","../../../node_modules/@types/node/fs/package.json","../../../node_modules/@types/node/inspector/package.json","../../../node_modules/@types/node/path/package.json","../../../node_modules/@types/node/readline/package.json","../../../node_modules/@types/node/stream/package.json","../../../node_modules/@types/node/test/package.json","../../../node_modules/@types/node/timers/package.json","../../../node_modules/@types/node/util/package.json","../../../node_modules/@types/node/web-globals/package.json","../../../node_modules/@types/node/zlib/package.json","../../../node_modules/@types/os/package.json","../../../node_modules/@types/path/package.json","../../../node_modules/@types/path/posix/package.json","../../../node_modules/@types/path/win32/package.json","../../../node_modules/@types/perf_hooks/package.json","../../../node_modules/@types/process/package.json","../../../node_modules/@types/punycode/package.json","../../../node_modules/@types/querystring/package.json","../../../node_modules/@types/readline/package.json","../../../node_modules/@types/readline/promises/package.json","../../../node_modules/@types/repl/package.json","../../../node_modules/@types/stream/consumers/package.json","../../../node_modules/@types/stream/iter/package.json","../../../node_modules/@types/stream/package.json","../../../node_modules/@types/stream/promises/package.json","../../../node_modules/@types/stream/web/package.json","../../../node_modules/@types/string_decoder/package.json","../../../node_modules/@types/timers/package.json","../../../node_modules/@types/timers/promises/package.json","../../../node_modules/@types/tls/package.json","../../../node_modules/@types/trace_events/package.json","../../../node_modules/@types/tty/package.json","../../../node_modules/@types/url/package.json","../../../node_modules/@types/util/package.json","../../../node_modules/@types/util/types/package.json","../../../node_modules/@types/v8/package.json","../../../node_modules/@types/vm/package.json","../../../node_modules/@types/wasi/package.json","../../../node_modules/@types/worker_threads/package.json","../../../node_modules/@types/zlib/package.json","../../../node_modules/@vitejs/devtools/package.json","../../../node_modules/@vitest/browser-preview/package.json","../../../node_modules/@vitest/browser-webdriverio/package.json","../../../node_modules/@vitest/coverage-istanbul/package.json","../../../node_modules/@vitest/mocker/dist/package.json","../../../node_modules/assert/package.json","../../../node_modules/assert/strict/package.json","../../../node_modules/async_hooks/package.json","../../../node_modules/child_process/package.json","../../../node_modules/cluster/package.json","../../../node_modules/console/package.json","../../../node_modules/constants/package.json","../../../node_modules/crypto/package.json","../../../node_modules/dgram/package.json","../../../node_modules/diagnostics_channel/package.json","../../../node_modules/dns/package.json","../../../node_modules/dns/promises/package.json","../../../node_modules/domain/package.json","../../../node_modules/expect-type/dist/package.json","../../../node_modules/fs/package.json","../../../node_modules/fs/promises/package.json","../../../node_modules/happy-dom/package.json","../../../node_modules/http/package.json","../../../node_modules/http2/package.json","../../../node_modules/https/package.json","../../../node_modules/inspector/package.json","../../../node_modules/inspector/promises/package.json","../../../node_modules/less/package.json","../../../node_modules/module/package.json","../../../node_modules/msw/package.json","../../../node_modules/net/package.json","../../../node_modules/os/package.json","../../../node_modules/path-ts/out/lib/package.json","../../../node_modules/path-ts/out/package.json","../../../node_modules/path/package.json","../../../node_modules/path/posix/package.json","../../../node_modules/path/win32/package.json","../../../node_modules/perf_hooks/package.json","../../../node_modules/process/package.json","../../../node_modules/querystring/package.json","../../../node_modules/readline/package.json","../../../node_modules/readline/promises/package.json","../../../node_modules/repl/package.json","../../../node_modules/sass-embedded/package.json","../../../node_modules/sass/package.json","../../../node_modules/stream/consumers/package.json","../../../node_modules/stream/iter/package.json","../../../node_modules/stream/package.json","../../../node_modules/stream/promises/package.json","../../../node_modules/stream/web/package.json","../../../node_modules/stylus/package.json","../../../node_modules/sugarss/package.json","../../../node_modules/timers/package.json","../../../node_modules/timers/promises/package.json","../../../node_modules/tinybench/dist/package.json","../../../node_modules/tls/package.json","../../../node_modules/trace_events/package.json","../../../node_modules/tsx/package.json","../../../node_modules/tty/package.json","../../../node_modules/type-fest/source/internal/package.json","../../../node_modules/type-fest/source/package.json","../../../node_modules/url/package.json","../../../node_modules/util/package.json","../../../node_modules/util/types/package.json","../../../node_modules/v8/package.json","../../../node_modules/vite/dist/node/chunks/package.json","../../../node_modules/vite/dist/node/package.json","../../../node_modules/vite/dist/package.json","../../../node_modules/vite/module-runner/package.json","../../../node_modules/vite/types/package.json","../../../node_modules/vitest/dist/chunks/package.json","../../../node_modules/vitest/dist/package.json","../../../node_modules/vm/package.json","../../../node_modules/wasi/package.json","../../../node_modules/worker_threads/package.json","../../../node_modules/zlib/package.json"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailwoman/tiger",
3
- "version": "11.1.0",
3
+ "version": "11.2.0",
4
4
  "description": "US Census TIGER/Line data processing and analysis.",
5
5
  "keywords": [
6
6
  "census",
@@ -132,9 +132,9 @@
132
132
  "test": "node ./out/sdk/TIGERService.test.js"
133
133
  },
134
134
  "dependencies": {
135
- "@mailwoman/core": "11.1.0",
136
- "@mailwoman/spatial": "11.1.0",
137
- "@mailwoman/sqlite": "11.1.0",
135
+ "@mailwoman/core": "11.2.0",
136
+ "@mailwoman/spatial": "11.2.0",
137
+ "@mailwoman/sqlite": "11.2.0",
138
138
  "@turf/boolean-contains": "^7.4.0",
139
139
  "kysely": "^0.29.7",
140
140
  "path-ts": "^2.5.0",
@@ -145,6 +145,6 @@
145
145
  "@protomaps/basemaps": "^5.7.2"
146
146
  },
147
147
  "engines": {
148
- "node": "^24.22.1 || >=26.12.1"
148
+ "node": "^24.22.3 || >=26.13.1"
149
149
  }
150
150
  }
package/sdk/fetch.ts CHANGED
@@ -171,6 +171,115 @@ function buildRow(level: TIGERFetchLevel, p: Record<string, unknown>, geometry:
171
171
  }
172
172
  }
173
173
 
174
+ /**
175
+ * Downloads one TIGER/Line shapefile archive into `cacheDir` unless a valid copy is there, and extracts it.
176
+ *
177
+ * @param directory The product directory under `TIGER<vintage>/`, such as `PLACE`.
178
+ * @param product The product name in the file name, such as `place`.
179
+ * @param unit The state FIPS code, a state and county code, or `us` for a national file.
180
+ */
181
+ async function downloadTIGERLayer(
182
+ directory: string,
183
+ product: string,
184
+ unit: string,
185
+ vintage: number,
186
+ cacheDir: PathBuilder
187
+ ): Promise<{ layer: string; shpPath: PathBuilder; cached: boolean }> {
188
+ const layer = `tl_${vintage}_${unit}_${product}`
189
+ const zipPath = cacheDir(`${layer}.zip`)
190
+ const cached = await downloadIfNeeded(`${CENSUS_HOST}/geo/tiger/TIGER${vintage}/${directory}/${layer}.zip`, zipPath)
191
+
192
+ await extractZipEntries(zipPath, cacheDir)
193
+
194
+ return { layer, shpPath: cacheDir(`${layer}.shp`), cached }
195
+ }
196
+
197
+ /**
198
+ * A TIGER/Line boundary product that {@link readTIGERBoundaries} reads with its geometry.
199
+ */
200
+ export const TIGERBoundaryLevel = {
201
+ County: "county",
202
+ CountySubdivision: "cousub",
203
+ Place: "place",
204
+ } as const
205
+
206
+ export type TIGERBoundaryLevel = (typeof TIGERBoundaryLevel)[keyof typeof TIGERBoundaryLevel]
207
+
208
+ /**
209
+ * One boundary {@link readTIGERBoundaries} yields, in EPSG:4326.
210
+ */
211
+ export interface TIGERBoundary {
212
+ level: TIGERBoundaryLevel
213
+ geoid: string
214
+ /**
215
+ * The name with its legal/statistical area description (`NAMELSAD`), such as `Adjuntas Municipio`.
216
+ */
217
+ name: string
218
+ statefp: string
219
+ geometry: { type: string; coordinates: unknown }
220
+ }
221
+
222
+ /**
223
+ * Options for {@link readTIGERBoundaries}.
224
+ */
225
+ export interface ReadTIGERBoundariesOptions {
226
+ level: TIGERBoundaryLevel
227
+ /**
228
+ * The two-digit state or territory FIPS code, such as `"72"`.
229
+ */
230
+ stateFIPS: string
231
+ /**
232
+ * @defaultValue `2024`
233
+ */
234
+ vintage?: number
235
+ /**
236
+ * The root of the download cache.
237
+ *
238
+ * @defaultValue the Mailwoman data root.
239
+ */
240
+ dataRoot?: string
241
+ }
242
+
243
+ /**
244
+ * Downloads one state's or territory's TIGER/Line boundaries at `level` and yields each with its geometry.
245
+ *
246
+ * Counties come from the national file, filtered to the state.
247
+ * County subdivisions and places come from the state's own file.
248
+ *
249
+ * @throws When the Census Bureau serves no file for the state at `level`.
250
+ */
251
+ export async function* readTIGERBoundaries(options: ReadTIGERBoundariesOptions): AsyncGenerator<TIGERBoundary> {
252
+ const { level, stateFIPS } = options
253
+ const vintage = options.vintage ?? 2024
254
+ const unit = level === TIGERBoundaryLevel.County ? "us" : stateFIPS
255
+ const cacheDir = PathBuilder.from(options.dataRoot ?? DEFAULT_DATA_ROOT)("tiger", String(vintage), unit)
256
+
257
+ await makeDirectories(cacheDir)
258
+
259
+ const { layer, shpPath } = await downloadTIGERLayer(level.toUpperCase(), level, unit, vintage, cacheDir)
260
+
261
+ const sql = `SELECT GEOID AS geoid, NAMELSAD AS name, STATEFP AS statefp FROM "${layer}" WHERE STATEFP = '${stateFIPS}'`
262
+
263
+ for await (const feature of ogr2ogrGeoJSONSeq<{
264
+ properties?: { geoid?: string; name?: string; statefp?: string }
265
+ geometry?: TIGERBoundary["geometry"] | null
266
+ }>(["-f", "GeoJSONSeq", "-t_srs", "EPSG:4326", "-sql", sql, "/vsistdout/", shpPath], layer)) {
267
+ const { properties, geometry } = feature
268
+
269
+ if (!properties?.geoid || !geometry) {
270
+ throw new Error(`${layer}: a feature has no GEOID or no geometry`)
271
+ }
272
+
273
+ yield {
274
+ level,
275
+ geoid: properties.geoid,
276
+ name: properties.name ?? "",
277
+ statefp: properties.statefp ?? stateFIPS,
278
+ geometry,
279
+ }
280
+ }
281
+ }
282
+
174
283
  async function discoverCounties(state: string, vintage: number): Promise<string[]> {
175
284
  const html = await new APIClient({ displayName: "tiger-listing", retry: true })
176
285
  .fetch<string>({ url: `${CENSUS_HOST}/geo/tiger/TIGER${vintage}/ADDRFEAT/`, responseType: "text" })
@@ -257,16 +366,9 @@ export async function* fetchTIGER(options: FetchTIGEROptions): AsyncGenerator<Fe
257
366
 
258
367
  for (const geo of geoCodes) {
259
368
  const unit = level === "addrfeat" ? state + geo : state
260
- const zipName = `tl_${vintage}_${unit}_${level}.zip`
261
- const zipPath = cacheDir(zipName)
262
- const url = `${CENSUS_HOST}/geo/tiger/TIGER${vintage}/${LEVEL_DIR[level]}/${zipName}`
263
-
264
- const cached = await downloadIfNeeded(url, zipPath)
265
- yield { phase: "download", file: zipName, cached }
369
+ const { layer, shpPath, cached } = await downloadTIGERLayer(LEVEL_DIR[level], level, unit, vintage, cacheDir)
266
370
 
267
- await extractZipEntries(zipPath, cacheDir)
268
- const layer = `tl_${vintage}_${unit}_${level}`
269
- const shpPath = cacheDir(layer + ".shp")
371
+ yield { phase: "download", file: `${layer}.zip`, cached }
270
372
  yield { phase: "extract", file: layer + ".shp" }
271
373
 
272
374
  const args = [
@@ -0,0 +1,138 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ /**
5
+ * @file The Census Bureau's national gazetteer files: one row per place or county subdivision, with its
6
+ * GEOID, its GNIS feature id (`ANSICODE`), its legal/statistical area description, its functional
7
+ * status and an interior point.
8
+ *
9
+ * The GNIS id ties a Census entity to the GNIS populated place of the same feature, and the GEOID ties
10
+ * it to a Who's On First record holding it as its `uscensus:geoid` concordance. A GNIS place whose
11
+ * Census entity a WOF record already holds is the same place, whatever either source calls it.
12
+ *
13
+ * A work of the United States Government, public domain under 17 U.S.C. § 105.
14
+ */
15
+
16
+ import { dataRootPath } from "@mailwoman/core/data-root"
17
+ import { readUnquotedTSV } from "@mailwoman/core/fs/delimited"
18
+ import { makeDirectories } from "@mailwoman/core/fs/writers"
19
+ import { extractZipEntries } from "@mailwoman/core/fs/zip"
20
+ import { PathBuilder, type PathBuilderLike } from "path-ts"
21
+
22
+ import { downloadIfNeeded } from "#sdk/download"
23
+
24
+ /**
25
+ * The gazetteer files {@link fetchCensusGazetteer} reads, by the name the Census Bureau files them under.
26
+ */
27
+ export const CensusGazetteerKind = {
28
+ Place: "place",
29
+ CountySubdivision: "cousubs",
30
+ } as const
31
+
32
+ export type CensusGazetteerKind = (typeof CensusGazetteerKind)[keyof typeof CensusGazetteerKind]
33
+
34
+ /**
35
+ * One row of a Census gazetteer file.
36
+ */
37
+ export interface CensusGazetteerEntry {
38
+ kind: CensusGazetteerKind
39
+ /**
40
+ * The USPS state code.
41
+ */
42
+ state: string
43
+ geoid: string
44
+ /**
45
+ * The GNIS feature id, from the zero-padded `ANSICODE`.
46
+ */
47
+ gnisID: number
48
+ name: string
49
+ /**
50
+ * The legal/statistical area description code (`LSAD`), or `null` in the county subdivision file.
51
+ * That file has no `LSAD` column.
52
+ */
53
+ lsad: string | null
54
+ /**
55
+ * The functional status code (`FUNCSTAT`), as `TIGERFunctionalStatus` defines it.
56
+ */
57
+ functionalStatus: string
58
+ latitude: number
59
+ longitude: number
60
+ }
61
+
62
+ /**
63
+ * The gazetteer vintage {@link fetchCensusGazetteer} reads unless told otherwise.
64
+ */
65
+ export const DEFAULT_CENSUS_GAZETTEER_VINTAGE = 2024
66
+
67
+ function gazetteerFileName(kind: CensusGazetteerKind, vintage: number): string {
68
+ return `${vintage}_Gaz_${kind}_national`
69
+ }
70
+
71
+ /**
72
+ * Downloads one national gazetteer file into `<dataRoot>/tiger/<vintage>/`
73
+ * unless a valid copy is there, and returns the path of its extracted text file.
74
+ */
75
+ export async function fetchCensusGazetteer(
76
+ kind: CensusGazetteerKind,
77
+ options: { vintage?: number; dataRoot?: PathBuilderLike } = {}
78
+ ): Promise<PathBuilder> {
79
+ const vintage = options.vintage ?? DEFAULT_CENSUS_GAZETTEER_VINTAGE
80
+ const directory = PathBuilder.from(options.dataRoot ?? dataRootPath())("tiger", String(vintage))
81
+ const name = gazetteerFileName(kind, vintage)
82
+ const zipPath = directory(`${name}.zip`)
83
+
84
+ await makeDirectories(directory)
85
+
86
+ await downloadIfNeeded(
87
+ `https://www2.census.gov/geo/docs/maps-data/data/gazetteer/${vintage}_Gazetteer/${name}.zip`,
88
+ zipPath
89
+ )
90
+
91
+ await extractZipEntries(zipPath, directory, { skipExisting: true })
92
+
93
+ return directory(`${name}.txt`)
94
+ }
95
+
96
+ /**
97
+ * Reads a national gazetteer text file.
98
+ *
99
+ * The files are tab-separated with a header row, and they pad the last column with trailing spaces.
100
+ *
101
+ * @throws When the header lacks a column the reader needs.
102
+ */
103
+ export async function* readCensusGazetteer(
104
+ path: PathBuilderLike,
105
+ kind: CensusGazetteerKind
106
+ ): AsyncGenerator<CensusGazetteerEntry> {
107
+ let header: string[] | null = null
108
+
109
+ const at = (column: string): number => {
110
+ const index = header!.indexOf(column)
111
+
112
+ if (index === -1) throw new Error(`${path}: the gazetteer header has no ${column} column`)
113
+
114
+ return index
115
+ }
116
+
117
+ for await (const fields of readUnquotedTSV(path)) {
118
+ const row = fields.map((field) => String(field ?? "").trim())
119
+
120
+ if (!header) {
121
+ header = row
122
+
123
+ continue
124
+ }
125
+
126
+ yield {
127
+ kind,
128
+ state: row[at("USPS")]!,
129
+ geoid: row[at("GEOID")]!,
130
+ gnisID: Number(row[at("ANSICODE")]),
131
+ name: row[at("NAME")]!,
132
+ lsad: header.includes("LSAD") ? row[at("LSAD")]! : null,
133
+ functionalStatus: row[at("FUNCSTAT")]!,
134
+ latitude: Number(row[at("INTPTLAT")]),
135
+ longitude: Number(row[at("INTPTLONG")]),
136
+ }
137
+ }
138
+ }