@mailwoman/spatial 9.2.0 → 9.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/{bbox.ts → lib/bbox.ts} +4 -4
  2. package/{coordinate-bounds.ts → lib/coordinate-bounds.ts} +11 -0
  3. package/{coordinate-formats.ts → lib/coordinate-formats.ts} +3 -1
  4. package/lib/distance.ts +204 -0
  5. package/{feature.ts → lib/feature.ts} +1 -1
  6. package/{geometries → lib/geometries}/collection.ts +4 -4
  7. package/lib/geometries/index.ts +13 -0
  8. package/{geometries → lib/geometries}/line-string.ts +4 -4
  9. package/{geometries → lib/geometries}/point.ts +14 -13
  10. package/{geometries → lib/geometries}/polygon.ts +82 -158
  11. package/lib/geometries/ring-blob.ts +521 -0
  12. package/{google → lib/google}/index.ts +1 -1
  13. package/{h3 → lib/h3}/cell.ts +83 -1
  14. package/lib/h3/coverage.ts +45 -0
  15. package/{h3 → lib/h3}/index.ts +5 -3
  16. package/lib/h3/interior-cells.ts +138 -0
  17. package/lib/h3/polygon-cells.ts +462 -0
  18. package/lib/index.ts +21 -0
  19. package/{objects.ts → lib/objects.ts} +1 -1
  20. package/{open-location-code.ts → lib/open-location-code.ts} +1 -1
  21. package/{osgb36.ts → lib/osgb36.ts} +2 -2
  22. package/{polyline.ts → lib/polyline.ts} +5 -5
  23. package/{position.ts → lib/position.ts} +2 -2
  24. package/lib/projection-transform.ts +115 -0
  25. package/{regions → lib/regions}/codes.ts +1 -1
  26. package/{regions → lib/regions}/index.ts +2 -2
  27. package/lib/tools/ogr-stream.ts +99 -0
  28. package/lib/tools/ogr.ts +201 -0
  29. package/out/bbox.d.ts +2 -2
  30. package/out/bbox.d.ts.map +1 -1
  31. package/out/bbox.js +3 -3
  32. package/out/bbox.js.map +1 -1
  33. package/out/coordinate-bounds.d.ts +9 -0
  34. package/out/coordinate-bounds.d.ts.map +1 -1
  35. package/out/coordinate-bounds.js +9 -0
  36. package/out/coordinate-bounds.js.map +1 -1
  37. package/out/coordinate-formats.d.ts.map +1 -1
  38. package/out/coordinate-formats.js +2 -1
  39. package/out/coordinate-formats.js.map +1 -1
  40. package/out/distance.d.ts +64 -1
  41. package/out/distance.d.ts.map +1 -1
  42. package/out/distance.js +85 -1
  43. package/out/distance.js.map +1 -1
  44. package/out/feature.d.ts +1 -1
  45. package/out/feature.d.ts.map +1 -1
  46. package/out/feature.js.map +1 -1
  47. package/out/geometries/collection.d.ts +4 -4
  48. package/out/geometries/collection.d.ts.map +1 -1
  49. package/out/geometries/collection.js.map +1 -1
  50. package/out/geometries/index.d.ts +5 -4
  51. package/out/geometries/index.d.ts.map +1 -1
  52. package/out/geometries/index.js +5 -4
  53. package/out/geometries/index.js.map +1 -1
  54. package/out/geometries/line-string.d.ts +4 -4
  55. package/out/geometries/line-string.d.ts.map +1 -1
  56. package/out/geometries/line-string.js.map +1 -1
  57. package/out/geometries/point.d.ts +14 -13
  58. package/out/geometries/point.d.ts.map +1 -1
  59. package/out/geometries/point.js +11 -10
  60. package/out/geometries/point.js.map +1 -1
  61. package/out/geometries/polygon.d.ts +51 -100
  62. package/out/geometries/polygon.d.ts.map +1 -1
  63. package/out/geometries/polygon.js +60 -90
  64. package/out/geometries/polygon.js.map +1 -1
  65. package/out/geometries/ring-blob.d.ts +183 -0
  66. package/out/geometries/ring-blob.d.ts.map +1 -0
  67. package/out/geometries/ring-blob.js +376 -0
  68. package/out/geometries/ring-blob.js.map +1 -0
  69. package/out/google/index.d.ts +1 -1
  70. package/out/google/index.d.ts.map +1 -1
  71. package/out/google/index.js +1 -1
  72. package/out/google/index.js.map +1 -1
  73. package/out/google/place-id.d.ts.map +1 -1
  74. package/out/google/place-id.js.map +1 -1
  75. package/out/h3/cell.d.ts +32 -0
  76. package/out/h3/cell.d.ts.map +1 -1
  77. package/out/h3/cell.js +68 -1
  78. package/out/h3/cell.js.map +1 -1
  79. package/out/h3/coverage.d.ts +32 -0
  80. package/out/h3/coverage.d.ts.map +1 -0
  81. package/out/h3/coverage.js +27 -0
  82. package/out/h3/coverage.js.map +1 -0
  83. package/out/h3/index.d.ts +5 -3
  84. package/out/h3/index.d.ts.map +1 -1
  85. package/out/h3/index.js +5 -3
  86. package/out/h3/index.js.map +1 -1
  87. package/out/h3/interior-cells.d.ts +54 -0
  88. package/out/h3/interior-cells.d.ts.map +1 -0
  89. package/out/h3/interior-cells.js +111 -0
  90. package/out/h3/interior-cells.js.map +1 -0
  91. package/out/h3/polygon-cells.d.ts +182 -0
  92. package/out/h3/polygon-cells.d.ts.map +1 -0
  93. package/out/h3/polygon-cells.js +339 -0
  94. package/out/h3/polygon-cells.js.map +1 -0
  95. package/out/index.d.ts +15 -15
  96. package/out/index.d.ts.map +1 -1
  97. package/out/index.js +15 -15
  98. package/out/index.js.map +1 -1
  99. package/out/objects.d.ts +1 -1
  100. package/out/objects.d.ts.map +1 -1
  101. package/out/objects.js +1 -1
  102. package/out/objects.js.map +1 -1
  103. package/out/open-location-code.d.ts.map +1 -1
  104. package/out/open-location-code.js +1 -1
  105. package/out/open-location-code.js.map +1 -1
  106. package/out/osgb36.d.ts +2 -2
  107. package/out/osgb36.d.ts.map +1 -1
  108. package/out/osgb36.js +1 -1
  109. package/out/osgb36.js.map +1 -1
  110. package/out/polyline.d.ts +4 -4
  111. package/out/polyline.d.ts.map +1 -1
  112. package/out/polyline.js +5 -5
  113. package/out/polyline.js.map +1 -1
  114. package/out/position.d.ts +1 -1
  115. package/out/position.d.ts.map +1 -1
  116. package/out/position.js +2 -2
  117. package/out/position.js.map +1 -1
  118. package/out/projection-transform.d.ts +67 -0
  119. package/out/projection-transform.d.ts.map +1 -0
  120. package/out/projection-transform.js +48 -0
  121. package/out/projection-transform.js.map +1 -0
  122. package/out/projection.d.ts.map +1 -1
  123. package/out/projection.js.map +1 -1
  124. package/out/regions/codes.d.ts.map +1 -1
  125. package/out/regions/codes.js.map +1 -1
  126. package/out/regions/index.d.ts +2 -2
  127. package/out/regions/index.d.ts.map +1 -1
  128. package/out/regions/index.js +2 -2
  129. package/out/regions/index.js.map +1 -1
  130. package/out/regions/names.d.ts.map +1 -1
  131. package/out/regions/names.js.map +1 -1
  132. package/out/tools/ogr-stream.d.ts +34 -0
  133. package/out/tools/ogr-stream.d.ts.map +1 -0
  134. package/out/tools/ogr-stream.js +74 -0
  135. package/out/tools/ogr-stream.js.map +1 -0
  136. package/out/tools/ogr.d.ts +87 -0
  137. package/out/tools/ogr.d.ts.map +1 -0
  138. package/out/tools/ogr.js +84 -0
  139. package/out/tools/ogr.js.map +1 -0
  140. package/out/tsconfig.test.tsbuildinfo +1 -1
  141. package/out/well-known-text.d.ts.map +1 -0
  142. package/out/well-known-text.js.map +1 -0
  143. package/package.json +94 -25
  144. package/distance.ts +0 -84
  145. package/geometries/index.ts +0 -12
  146. package/index.ts +0 -21
  147. package/out/sdk/index.d.ts +0 -7
  148. package/out/sdk/index.d.ts.map +0 -1
  149. package/out/sdk/index.js +0 -7
  150. package/out/sdk/index.js.map +0 -1
  151. package/out/sdk/well-known-text.d.ts.map +0 -1
  152. package/out/sdk/well-known-text.js.map +0 -1
  153. package/out/tsconfig.tsbuildinfo +0 -1
  154. package/sdk/index.ts +0 -7
  155. /package/{google → lib/google}/place-id.ts +0 -0
  156. /package/{projection.ts → lib/projection.ts} +0 -0
  157. /package/{regions → lib/regions}/names.ts +0 -0
  158. /package/{sdk → lib}/well-known-text.ts +0 -0
  159. /package/out/{sdk/well-known-text.d.ts → well-known-text.d.ts} +0 -0
  160. /package/out/{sdk/well-known-text.js → well-known-text.js} +0 -0
@@ -0,0 +1,138 @@
1
+ /**
2
+ * @copyright Sister Software.
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Turn an outline into the H3 cell set a coverage claim may be keyed to.
7
+ *
8
+ * Polyfilling a rectangle is right for a rectangular extract and wrong for a region: a region is
9
+ * clipped to a polygon, so a rectangle polyfilled over it claims survey across whatever the rectangle
10
+ * overhangs. These helpers answer the narrower question — which cells lie wholly INSIDE the outline —
11
+ * and they answer conservatively, because the cells they return are the ones a completeness claim will
12
+ * be written to.
13
+ *
14
+ * Interior is two tests, both required. A cell must have its whole `gridDisk(cell, 1)` inside the
15
+ * outline's own polyfill, and all six of its boundary vertices inside the polygon. The first removes the
16
+ * polyfill's edge ring (H3's polyfill keeps a cell whose CENTRE is inside, so an edge cell can be half
17
+ * outside); the second catches a boundary that re-enters between two neighbours. Neither test alone is
18
+ * sufficient, and the cost of being wrong is asymmetric — a cell wrongly called interior claims a survey
19
+ * over ground the source never covered.
20
+ *
21
+ * Measured on the Île-de-France région (OSM relation 8649, admin_level 4) at res 6: 371 polyfilled
22
+ * cells, 290 interior, holding 3,248 of the extract's 3,308 `amenity=pharmacy` features.
23
+ */
24
+
25
+ import { cellToBoundary, gridDisk, polygonToCells } from "h3-js"
26
+
27
+ import { arealPolygons, geometryContains, type ParsedGeometry, type PolygonRings } from "#geometries/polygon"
28
+ import { shortCellToInt, type H3Cell } from "#h3/cell"
29
+
30
+ /**
31
+ * The rings a polyfill walks: every polygon's OUTER ring. Holes are deliberately not subtracted here — a hole would
32
+ * only ever remove cells, and the interior test below re-checks every returned cell's vertices against the full
33
+ * geometry (holes included), so a hole cannot survive into the result.
34
+ */
35
+ function outerRings(geometry: ParsedGeometry): PolygonRings {
36
+ const polygons = arealPolygons(geometry)
37
+
38
+ if (!polygons) {
39
+ throw new Error(
40
+ `coverage region: expected a Polygon or MultiPolygon geometry, got ${JSON.stringify(geometry.type)}`
41
+ )
42
+ }
43
+
44
+ return polygons.filter((rings) => rings.length).map((rings) => rings[0]!)
45
+ }
46
+
47
+ /**
48
+ * The outline's bounding rectangle, for pre-clipping a reference inventory that can only be probed by range.
49
+ *
50
+ * A coarse filter and nothing more — it CONTAINS the outline and is never the outline. The exact clip is
51
+ * {@link interiorCoverageCellSet}; using this rectangle as the region would claim survey over every corner the outline
52
+ * does not reach.
53
+ */
54
+ export function geometryBBox(geometry: ParsedGeometry): {
55
+ minLon: number
56
+ minLat: number
57
+ maxLon: number
58
+ maxLat: number
59
+ } {
60
+ let minLon = Infinity
61
+ let minLat = Infinity
62
+ let maxLon = -Infinity
63
+ let maxLat = -Infinity
64
+
65
+ for (const ring of outerRings(geometry)) {
66
+ for (const [lon, lat] of ring) {
67
+ if (lon! < minLon) {
68
+ minLon = lon!
69
+ }
70
+
71
+ if (lon! > maxLon) {
72
+ maxLon = lon!
73
+ }
74
+
75
+ if (lat! < minLat) {
76
+ minLat = lat!
77
+ }
78
+
79
+ if (lat! > maxLat) {
80
+ maxLat = lat!
81
+ }
82
+ }
83
+ }
84
+
85
+ if (!Number.isFinite(minLon) || !Number.isFinite(minLat)) {
86
+ throw new TypeError("coverage region: geometry carries no coordinates to bound")
87
+ }
88
+
89
+ return { minLon, minLat, maxLon, maxLat }
90
+ }
91
+
92
+ /**
93
+ * Every cell whose CENTRE falls inside `geometry`, at `resolution`. The raw polyfill — {@link interiorCoverageCells}
94
+ * narrows it.
95
+ */
96
+ export function regionCoverageCells(geometry: ParsedGeometry, resolution: number): H3Cell[] {
97
+ const cells = new Set<string>()
98
+
99
+ for (const ring of outerRings(geometry)) {
100
+ // polygonToCells's default (non-GeoJSON) coordinate order is [lat, lng] per vertex.
101
+ const latLng = ring.map(([lon, lat]) => [lat!, lon!])
102
+
103
+ for (const cell of polygonToCells(latLng, resolution)) {
104
+ cells.add(cell)
105
+ }
106
+ }
107
+
108
+ return [...cells] as H3Cell[]
109
+ }
110
+
111
+ /**
112
+ * The cells of {@link regionCoverageCells} that lie wholly inside `geometry` — see the module docstring for why both
113
+ * tests are applied.
114
+ */
115
+ export function interiorCoverageCells(geometry: ParsedGeometry, resolution: number): H3Cell[] {
116
+ const polyfilled = new Set<string>(regionCoverageCells(geometry, resolution))
117
+ const interior: H3Cell[] = []
118
+
119
+ for (const cell of polyfilled) {
120
+ if (!gridDisk(cell, 1).every((neighbor) => polyfilled.has(neighbor))) continue
121
+
122
+ const vertices = cellToBoundary(cell) as number[][]
123
+
124
+ if (!vertices.every(([lat, lon]) => geometryContains(geometry, lon!, lat!))) continue
125
+
126
+ interior.push(cell as H3Cell)
127
+ }
128
+
129
+ return interior
130
+ }
131
+
132
+ /**
133
+ * The 48-bit short-cell form of {@link interiorCoverageCells}, as a membership set — the shape both a row clipper and a
134
+ * coverage writer probe.
135
+ */
136
+ export function interiorCoverageCellSet(geometry: ParsedGeometry, resolution: number): Set<number> {
137
+ return new Set(interiorCoverageCells(geometry, resolution).map((cell) => shortCellToInt(cell)))
138
+ }
@@ -0,0 +1,462 @@
1
+ /**
2
+ * @copyright Sister Software
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ *
6
+ * Turn one authority polygon into the H3 cells that summarize it — the conversion SCOPE invariant 6 asks
7
+ * for, done once at build time so the runtime probes structure instead of geometry.
8
+ *
9
+ * SHARED BY EVERY POLYGON LAYER RATHER THAN COPIED INTO EACH, because the traps below are properties of
10
+ * the TOOL rather than of any one product. `packages/flood` measured them; `packages/soil` inherits them
11
+ * unchanged; the layer contract's polygon-builder section states them as requirements. A second copy of
12
+ * an allocator guard is a second place for it to stop guarding.
13
+ *
14
+ * THE INDEX IS CELL-TOUCHES-POLYGON, NOT CENTRE-IN-POLYGON, AND A ZERO-CELL FEATURE FAILS THE BUILD.
15
+ * A polyfill keyed on cell centres drops every polygon smaller than a cell, and each dropped feature
16
+ * reads downstream as an absence. Measured: on Ireland's zoning layer `polygonToCells` returns zero cells
17
+ * for 86.8% of polygons at resolution 9, and the EA flood product's first row is a 128 m² square that
18
+ * `polygonToCells` misses at resolutions 7 through 10 while `containmentOverlapping` returns one cell for
19
+ * it. So the index takes overlapping containment, and {@link classifyFeatureCells} throws on a feature
20
+ * that reaches no cell rather than skipping it.
21
+ *
22
+ * THE `[lat, lng]` TRAP IS AVOIDED BY NOT ENTERING IT. h3-js reads a vertex as `[lat, lng]` in its
23
+ * default mode; every call here passes `isGeoJSON = true` and hands it GeoJSON-order `[lon, lat]` rings,
24
+ * which is the order an ingest already produces. Converting instead would put a transposition between the
25
+ * geometry and the index that nothing downstream could see.
26
+ *
27
+ * WHOLE AND PARTIAL ARE TWO POLYFILLS OF THE SAME RING, NOT A TEST WE INVENT. `containmentFull` is the
28
+ * cell set entirely inside the polygon; `containmentOverlapping` is the set that touches it at all. The
29
+ * difference is exactly the boundary fringe, which is where the geometry tier has to be consulted.
30
+ *
31
+ * MOST PARTS NEVER REACH h3 AT ALL, AND THAT IS THE POINT. The WASM heap is exhausted by CALL VOLUME, not
32
+ * by any one polygon: h3-js frees every buffer it allocates, so what accumulates over millions of
33
+ * interleaved tiny and large allocations is fragmentation. Three runs over the EA product died on the
34
+ * same feature after roughly 510,000 others — a 164 m² feature of 23 parts and 130 vertices that
35
+ * classifies in 35 ms at every resolution 9 through 4 in a fresh process. So the calls are removed rather
36
+ * than shrunk, in the two places where the answer is a fact about geometry: {@link enclosingCell} (a part
37
+ * whose bounding-box corners all fall in one cell lies inside it, because a cell is convex) and
38
+ * {@link canContainCell} (a part narrower than `edge × √3` cannot enclose a hexagon, so its
39
+ * `containmentFull` set is empty). Both were checked against the unconditional polyfill over 60,000 real
40
+ * features at resolution 9 with zero disagreements, and `packages/flood/test/unit/cells.test.ts` pins the
41
+ * comparison.
42
+ *
43
+ * A BIG POLYGON IS ALSO INDEXED COARSER, BECAUSE h3's ALLOCATOR IS SIZED FROM THE BOUNDING BOX.
44
+ * `polygonToCells` reserves room for the whole bounding box before it walks anything, so a long thin river
45
+ * polygon reserves the rectangle the river's meanders span rather than the river. Each feature is
46
+ * therefore indexed at the finest resolution whose bounding-box estimate fits {@link CELL_ESTIMATE_BUDGET},
47
+ * and the resolution it got is returned on the result. That is not a compromise bolted on: a coarse cell
48
+ * wholly inside a large polygon is exactly what `compactCells` would have produced anyway, so the whole
49
+ * tier is unchanged in meaning and only the fringe is coarser.
50
+ *
51
+ * AND THE ESTIMATE IS A PREDICTION, SO AN ALLOCATION FAILURE IS RECOVERED RATHER THAN FATAL.
52
+ * {@linkcode classifyFeatureCells} steps the resolution down and retries; only a feature that fails at
53
+ * {@linkcode MIN_INDEX_RESOLUTION} is refused. Nothing is ever skipped, because a skipped feature is an
54
+ * invented absence.
55
+ *
56
+ * BOUNDING THE CALL VOLUME IS THE CALLER'S JOB AND IT IS NOT OPTIONAL. The shortcuts here make a build
57
+ * faster; they are not what makes it reproducible. A builder runs the classification in child processes
58
+ * over ranges of the source's own stable ids, so each gets a heap that starts empty — see
59
+ * `packages/flood/lib/sdk/ingest-chunk.ts` and `packages/soil/lib/sdk/ingest-chunk.ts`.
60
+ */
61
+
62
+ import {
63
+ cellToChildren,
64
+ cellToParent,
65
+ compactCells,
66
+ getHexagonAreaAvg,
67
+ getHexagonEdgeLengthAvg,
68
+ getResolution,
69
+ latLngToCell,
70
+ polygonToCellsExperimental,
71
+ POLYGON_TO_CELLS_FLAGS,
72
+ } from "h3-js"
73
+
74
+ import { METRES_PER_DEGREE } from "#distance"
75
+ import type { MultiPolygonRings } from "#geometries/polygon"
76
+ import { ringsBoundingBox } from "#geometries/ring-blob"
77
+ import { shortCellToInt, type H3Cell } from "#h3/cell"
78
+
79
+ /**
80
+ * The largest bounding-box cell estimate a single polyfill may reserve.
81
+ *
82
+ * H3-js allocates its output buffer from the polygon's bounding box before walking, so this is a memory ceiling rather
83
+ * than a limit on real output: two million cells is sixteen megabytes of `uint64`, comfortably inside the WASM heap,
84
+ * and the largest EA flood features exceed it by orders of magnitude at resolution 9 (the run that established this
85
+ * failed with `Memory allocation failed (code: 13)`).
86
+ */
87
+ export const CELL_ESTIMATE_BUDGET = 2_000_000
88
+
89
+ /**
90
+ * The coarsest resolution a feature may be pushed down to. Below this a "cell" is tens of thousands of square
91
+ * kilometres and the index stops summarizing anything.
92
+ */
93
+ export const MIN_INDEX_RESOLUTION = 4
94
+
95
+ /**
96
+ * A rectangle in degrees, the shape every helper here prefilters on.
97
+ */
98
+ export interface DegreeBox {
99
+ minLat: number
100
+ minLon: number
101
+ maxLat: number
102
+ maxLon: number
103
+ }
104
+
105
+ /**
106
+ * A degree box's height and width in metres, longitude scaled at the box's mid-latitude so the two are comparable.
107
+ */
108
+ function boxExtentMetres(box: DegreeBox): { heightM: number; widthM: number } {
109
+ const midLat = ((box.minLat + box.maxLat) / 2) * (Math.PI / 180)
110
+
111
+ return {
112
+ heightM: (box.maxLat - box.minLat) * METRES_PER_DEGREE,
113
+ widthM: (box.maxLon - box.minLon) * METRES_PER_DEGREE * Math.cos(midLat),
114
+ }
115
+ }
116
+
117
+ /**
118
+ * The single cell containing this whole bounding box, or `undefined` when it spans more than one.
119
+ *
120
+ * An H3 cell is convex, so a rectangle whose four corners all fall in the same cell lies entirely inside it. That makes
121
+ * this an exact answer rather than an approximation, and it takes the WASM polyfill off the majority of a small-polygon
122
+ * product's parts: 38.8% of the EA flood features are under 11 m across, and most parts of the multi-part ones are
123
+ * smaller still.
124
+ */
125
+ function enclosingCell(box: DegreeBox, resolution: number): string | undefined {
126
+ if (!Number.isFinite(box.minLat)) return undefined
127
+
128
+ const first = latLngToCell(box.minLat, box.minLon, resolution)
129
+
130
+ for (const [lat, lon] of [
131
+ [box.minLat, box.maxLon],
132
+ [box.maxLat, box.minLon],
133
+ [box.maxLat, box.maxLon],
134
+ ] as Array<[number, number]>) {
135
+ if (latLngToCell(lat, lon, resolution) !== first) return undefined
136
+ }
137
+
138
+ return first
139
+ }
140
+
141
+ /**
142
+ * Could a shape this size contain a whole cell?
143
+ *
144
+ * A hexagon's minimum width is twice its inradius, and its inradius is `edge × √3/2` — so a bounding box narrower than
145
+ * `edge × √3` in either direction cannot enclose one, and the `containmentFull` polyfill is guaranteed to return
146
+ * nothing. The comparison is deliberately permissive: a wrong `true` costs one polyfill call, while a wrong `false`
147
+ * would demote a whole cell to a partial one, which the ray cast still answers correctly but more slowly.
148
+ */
149
+ function canContainCell(box: DegreeBox, resolution: number): boolean {
150
+ if (!Number.isFinite(box.minLat)) return false
151
+
152
+ const minimumWidthM = getHexagonEdgeLengthAvg(resolution, "m") * Math.sqrt(3)
153
+ const { heightM, widthM } = boxExtentMetres(box)
154
+
155
+ return heightM >= minimumWidthM && widthM >= minimumWidthM
156
+ }
157
+
158
+ /**
159
+ * The two cell sets one feature produces, and the resolution they came out at.
160
+ */
161
+ export interface FeatureCells {
162
+ /**
163
+ * The resolution this feature was indexed at — the target, or coarser where the target's estimate did not fit.
164
+ */
165
+ resolution: number
166
+ /**
167
+ * Cells lying entirely inside the feature. A point in one of these is inside without a geometry read.
168
+ */
169
+ whole: H3Cell[]
170
+ /**
171
+ * Cells the feature reaches but does not fill. A point in one of these needs the ray cast.
172
+ */
173
+ partial: H3Cell[]
174
+ }
175
+
176
+ /**
177
+ * How many cells at `resolution` the feature's bounding box spans.
178
+ *
179
+ * The same quantity h3 reserves its buffer from, computed here so an oversized polyfill is never issued. Approximate on
180
+ * purpose: it decides which resolution to ask for, not what the answer is.
181
+ */
182
+ export function estimateCellCount(polygons: MultiPolygonRings, resolution: number): number {
183
+ const box = ringsBoundingBox(polygons)
184
+
185
+ if (!Number.isFinite(box.minLat)) return 0
186
+
187
+ const { heightM, widthM } = boxExtentMetres(box)
188
+ const heightKM = heightM / 1000
189
+ const widthKM = widthM / 1000
190
+
191
+ return (Math.max(widthKM, 0.001) * Math.max(heightKM, 0.001)) / getHexagonAreaAvg(resolution, "km2")
192
+ }
193
+
194
+ /**
195
+ * The finest resolution at or below `target` whose estimate fits the budget.
196
+ */
197
+ export function resolutionForFeature(polygons: MultiPolygonRings, target: number): number {
198
+ for (let resolution = target; resolution > MIN_INDEX_RESOLUTION; resolution--) {
199
+ if (estimateCellCount(polygons, resolution) <= CELL_ESTIMATE_BUDGET) return resolution
200
+ }
201
+
202
+ return MIN_INDEX_RESOLUTION
203
+ }
204
+
205
+ /**
206
+ * Classify one feature's cells, at `targetResolution` or the coarsest resolution its bounding box allows.
207
+ *
208
+ * @param layerLabel Names the layer in every message, so a build log says which artifact refused rather than only which
209
+ * feature.
210
+ * @throws {Error} When the feature reaches no cell at all. That cannot happen with overlapping containment on a valid
211
+ * ring, so it means the geometry is degenerate — and a silently skipped feature is an invented absence.
212
+ */
213
+ export function classifyFeatureCells(
214
+ polygons: MultiPolygonRings,
215
+ targetResolution: number,
216
+ featureID: string,
217
+ layerLabel = "polygon index"
218
+ ): FeatureCells {
219
+ let resolution = resolutionForFeature(polygons, targetResolution)
220
+ let touched = new Set<string>()
221
+ let full = new Set<string>()
222
+
223
+ // THE BUDGET IS A PREDICTION AND THE RETRY IS WHAT MAKES IT NON-FATAL. `estimateCellCount` is a bounding-box
224
+ // approximation of what h3 will reserve, and h3's own reservation depends on the polygon's shape and on what the WASM
225
+ // heap already holds — measured over the EA product, a run that had classified 350,000 features threw `Memory
226
+ // allocation failed (code: 13)` on a feature that classified cleanly on its own. So an allocation failure steps the
227
+ // resolution down and tries again rather than ending the build, and only a feature that fails at
228
+ // {@link MIN_INDEX_RESOLUTION} is refused: a coarser cell is a real answer, and a skipped feature is an invented
229
+ // absence.
230
+ for (;;) {
231
+ try {
232
+ touched = new Set<string>()
233
+ full = new Set<string>()
234
+
235
+ for (const rings of polygons) {
236
+ // `isGeoJSON = true`: the rings are already `[lon, lat]`, which is the order an ingest emits. Converting
237
+ // instead would put a transposition between the geometry and the index that nothing downstream could see.
238
+ const geoJSONRings = rings as number[][][]
239
+ const box = ringsBoundingBox([rings])
240
+ const enclosing = enclosingCell(box, resolution)
241
+
242
+ // A PART THAT FITS INSIDE ONE CELL IS ANSWERED WITHOUT THE ALLOCATOR, and that is a fact rather than an
243
+ // approximation: an H3 cell is convex, so a rectangle whose four corners all fall in one cell lies entirely
244
+ // within it. Such a part touches exactly that cell and fills none of it.
245
+ if (enclosing) {
246
+ touched.add(enclosing)
247
+
248
+ continue
249
+ }
250
+
251
+ const overlapping = polygonToCellsExperimental(
252
+ geoJSONRings,
253
+ resolution,
254
+ POLYGON_TO_CELLS_FLAGS.containmentOverlapping,
255
+ true
256
+ )
257
+
258
+ // AN EMPTY ANSWER FOR A REAL PART IS AN ALLOCATOR FAILURE WEARING A RESULT'S CLOTHES, and it has to be caught
259
+ // HERE rather than after the whole feature. h3-js sizes its output buffer with `_calloc`, and a `_calloc`
260
+ // that fails returns the null pointer — which in WASM is ordinary writable memory, so the call reports
261
+ // success and the reader hands back an array of zeros, i.e. nothing. Every part with a non-degenerate
262
+ // bounding box touches at least one cell, so zero is impossible as an answer. Checking per FEATURE instead
263
+ // would pass any multi-part feature whose other parts happened to answer, and silently index it short.
264
+ if (!overlapping.length) {
265
+ throw new Error(
266
+ `${layerLabel}: part of feature ${featureID} spanning ${box.minLat},${box.minLon} to ${box.maxLat},${box.maxLon} returned no cell at resolution ${resolution} — a part always touches at least one, so this is an allocator failure reported as an answer`
267
+ )
268
+ }
269
+
270
+ for (const cell of overlapping) {
271
+ touched.add(cell)
272
+ }
273
+
274
+ // A part narrower than a cell's minimum width cannot contain one, so its `full` set is empty and asking for it
275
+ // is pure cost. Erring towards asking is safe — a missed whole cell becomes a partial one and the ray cast
276
+ // still answers correctly — so the comparison is the permissive one.
277
+ if (!canContainCell(box, resolution)) continue
278
+
279
+ for (const cell of polygonToCellsExperimental(
280
+ geoJSONRings,
281
+ resolution,
282
+ POLYGON_TO_CELLS_FLAGS.containmentFull,
283
+ true
284
+ )) {
285
+ full.add(cell)
286
+ }
287
+ }
288
+
289
+ break
290
+ } catch (error) {
291
+ if (resolution <= MIN_INDEX_RESOLUTION) {
292
+ throw new Error(
293
+ `${layerLabel}: feature ${featureID} could not be indexed at any resolution down to ${MIN_INDEX_RESOLUTION} — ${String(
294
+ (error as Error).message
295
+ )}`
296
+ )
297
+ }
298
+
299
+ resolution--
300
+ }
301
+ }
302
+
303
+ if (!touched.size) {
304
+ throw new Error(
305
+ `${layerLabel}: feature ${featureID} reaches no cell at resolution ${resolution} — a feature indexed to nothing reads downstream as an absence, which is the one answer a layer must never invent`
306
+ )
307
+ }
308
+
309
+ // A cell can be full for one polygon of a MultiPolygon and merely touched by another; full wins, because the point
310
+ // is inside either way.
311
+ const partial: H3Cell[] = []
312
+
313
+ for (const cell of touched) {
314
+ if (!full.has(cell)) {
315
+ partial.push(cell as H3Cell)
316
+ }
317
+ }
318
+
319
+ return { resolution, whole: [...full] as H3Cell[], partial }
320
+ }
321
+
322
+ /**
323
+ * Split a cell set into same-resolution groups — what `compactCells` requires, and what an adaptively-indexed layer
324
+ * cannot assume it already has.
325
+ *
326
+ * Pooling mixed resolutions throws inside h3; compacting only the target-resolution group would silently drop every
327
+ * coarsened feature's interior, which is the shape of failure that still produces an artifact.
328
+ */
329
+ export function groupCellsByResolution(cells: Iterable<string>): string[][] {
330
+ const groups = new Map<number, string[]>()
331
+
332
+ for (const cell of cells) {
333
+ const resolution = getResolution(cell)
334
+ const group = groups.get(resolution)
335
+
336
+ if (group) {
337
+ group.push(cell)
338
+ } else {
339
+ groups.set(resolution, [cell])
340
+ }
341
+ }
342
+
343
+ return [...groups.values()]
344
+ }
345
+
346
+ /**
347
+ * Compact a cell set that may span several resolutions.
348
+ *
349
+ * `compactCells` takes one resolution at a time, and an adaptively-indexed layer's coarsened features sit at another —
350
+ * so the set is grouped before compaction rather than pooled. Pooling would throw; compacting only the
351
+ * target-resolution group would silently drop every coarsened feature's interior, which is the shape of failure that
352
+ * still produces an artifact.
353
+ */
354
+ export function compactAcrossResolutions(cells: Iterable<string>): string[] {
355
+ const compacted: string[] = []
356
+
357
+ for (const group of groupCellsByResolution(cells)) {
358
+ compacted.push(...compactCells(group))
359
+ }
360
+
361
+ return compacted
362
+ }
363
+
364
+ /**
365
+ * The cells a probe walks for one index cell: the cell itself at the index resolution, and its parent at every other
366
+ * resolution the layer stores.
367
+ *
368
+ * The stored rows sit at SEVERAL resolutions — each feature's whole tier is compacted parent-ward, and a polygon too
369
+ * large for h3's allocator at the index resolution was indexed coarser — so a point is answered by walking its own
370
+ * ancestor chain over every resolution the layer stores.
371
+ */
372
+ export function ancestorChainCells(
373
+ indexCell: H3Cell,
374
+ indexResolution: number,
375
+ resolutions: readonly number[]
376
+ ): H3Cell[] {
377
+ return resolutions.map((resolution) =>
378
+ resolution === indexResolution ? indexCell : (cellToParent(indexCell, resolution) as H3Cell)
379
+ )
380
+ }
381
+
382
+ /**
383
+ * One classified feature's cell rows, ready for insertion — the whole set compacted, the partial set left at its own
384
+ * resolution.
385
+ *
386
+ * SHARED BY EVERY POLYGON LAYER WHOSE CELL ROW NAMES A POLYGON rather than a class accumulated across features. There
387
+ * is no product knowledge in it: compaction, the short-cell encoding and the belt-and-braces subtraction below are h3
388
+ * and blob arithmetic, and a second copy is a second place for the subtraction to stop happening.
389
+ *
390
+ * COMPACTION IS PER FEATURE, which is what keeps a build's memory flat in row count with no temporary table: a row that
391
+ * names one polygon is final the moment that polygon is classified. Only the WHOLE set is compacted — compacting the
392
+ * fringe would claim it covers ground it does not.
393
+ */
394
+ export function featureCellRows(cells: FeatureCells): Array<{
395
+ h3Cell: number
396
+ resolution: number
397
+ containment: "whole" | "partial"
398
+ }> {
399
+ const rows: Array<{ h3Cell: number; resolution: number; containment: "whole" | "partial" }> = []
400
+ const wholeShort = new Set<number>()
401
+
402
+ for (const cell of compactAcrossResolutions(cells.whole)) {
403
+ const resolution = getResolution(cell)
404
+ const short = shortCellToInt(cell as H3Cell)
405
+
406
+ wholeShort.add(short)
407
+ rows.push({ h3Cell: short, resolution, containment: "whole" })
408
+ }
409
+
410
+ for (const cell of cells.partial) {
411
+ const short = shortCellToInt(cell)
412
+
413
+ // A cell cannot be both for one polygon; the classifier already subtracts the whole set, and this is belt and braces
414
+ // against a compaction that produced a parent the partial set also names.
415
+ if (wholeShort.has(short)) continue
416
+
417
+ rows.push({ h3Cell: short, resolution: cells.resolution, containment: "partial" })
418
+ }
419
+
420
+ return rows
421
+ }
422
+
423
+ /**
424
+ * The coverage cell a row at `cell` belongs to.
425
+ *
426
+ * `cellToParent` of the finer cell, never a fresh `latLngToCell` at the coarse resolution: every existing reader in
427
+ * this repo derives a coverage cell that way, and the two agree for a point but not for a cell — a re-derivation from a
428
+ * representative point would put a fringe row in a neighbouring coverage cell.
429
+ */
430
+ export function coverageCellFor(cell: H3Cell, coverageResolution: number): H3Cell {
431
+ return cellToParent(cell, coverageResolution) as H3Cell
432
+ }
433
+
434
+ /**
435
+ * Record the coverage cells one index cell falls in.
436
+ *
437
+ * An adaptively-coarsened cell can be COARSER than the coverage resolution, in which case it spans several coverage
438
+ * cells and every one of them is recorded: a coarse cell counted against one arbitrary child would leave the others
439
+ * reading as empty.
440
+ */
441
+ export function addCoverageCells(
442
+ into: Set<number>,
443
+ cell: H3Cell,
444
+ cellResolution: number,
445
+ coverageResolution: number
446
+ ): void {
447
+ if (cellResolution === coverageResolution) {
448
+ into.add(shortCellToInt(cell))
449
+
450
+ return
451
+ }
452
+
453
+ if (cellResolution > coverageResolution) {
454
+ into.add(shortCellToInt(coverageCellFor(cell, coverageResolution)))
455
+
456
+ return
457
+ }
458
+
459
+ for (const child of cellToChildren(cell, coverageResolution)) {
460
+ into.add(shortCellToInt(child as H3Cell))
461
+ }
462
+ }
package/lib/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @copyright Sister Software.
3
+ * @license AGPL-3.0
4
+ * @author Teffen Ellis, et al.
5
+ */
6
+
7
+ export * from "#bbox"
8
+ export * from "#coordinate-formats"
9
+ export * from "#coordinate-bounds"
10
+ export * from "#distance"
11
+ export * from "#feature"
12
+ export * from "#open-location-code"
13
+ export * from "#geometries/index"
14
+ export * from "#google/index"
15
+ export * from "#h3/index"
16
+ export * from "#objects"
17
+ export * from "#osgb36"
18
+ export * from "#polyline"
19
+ export * from "#position"
20
+ export * from "#projection"
21
+ export * from "#regions/index"
@@ -4,7 +4,7 @@
4
4
  * @author Teffen Ellis, et al.
5
5
  */
6
6
 
7
- import { type BBox2DLiteral, type BBox3DLiteral, is2DBBox } from "./bbox.ts"
7
+ import { type BBox2DLiteral, type BBox3DLiteral, is2DBBox } from "#bbox"
8
8
 
9
9
  /**
10
10
  * GeoJSON object types.
@@ -106,7 +106,7 @@ export function decodePlusCode(code: string): DecodedPlusCode | null {
106
106
  }
107
107
 
108
108
  /**
109
- * Encode the pair digits of a coordinate to `length` digits (length ≤ 10, even) — the prefix machinery
109
+ * Encode the pair digits of a coordinate to `length` digits (length ≤ 10, even) — the prefix implementation
110
110
  * {@link recoverNearestPlusCode} needs; not a general encoder.
111
111
  */
112
112
  function encodePairDigits(lat: number, lon: number, length: number): string {
@@ -54,14 +54,14 @@
54
54
  *
55
55
  * **Do not use this module for anything that does.** Surveying, cadastral work, or any consumer
56
56
  * comparing our coordinates against another OSGB36-derived dataset at sub-10 m tolerance needs
57
- * OSTN15, which means shipping the shift grid. If that day comes, the seam is
57
+ * OSTN15, which means shipping the shift grid. If that day comes, the swap point is
58
58
  * {@link osgb36AiryToWGS84} — swap the Helmert for a grid interpolation and the projection step
59
59
  * above it is unchanged.
60
60
  *
61
61
  * @see https://www.ordnancesurvey.co.uk/documents/resources/guide-coordinate-systems-great-britain.pdf
62
62
  */
63
63
 
64
- import type { Coordinates2D } from "./position.ts"
64
+ import type { Coordinates2D } from "#position"
65
65
 
66
66
  /**
67
67
  * Semi-major axis of the Airy 1830 ellipsoid, in metres — the figure of the Earth OSGB36 is referenced to.
@@ -6,13 +6,13 @@
6
6
  * Position along a polyline, by arc length.
7
7
  *
8
8
  * This is what house-number interpolation stands on: given a street segment's geometry and how far
9
- * along its house-number range an address sits, it answers where that is on the ground. It lived in
10
- * two byte-identical copies — `resolver-wof-sqlite/interpolation.ts` and the browser twin in
11
- * `docs/src/shared/httpvfs-street.ts` — under a header telling both to be kept in lockstep by hand.
12
- * The geometry never differed between them; only the I/O around it did.
9
+ * along its house-number range an address sits, it answers where that is on the ground. The node
10
+ * reader (`resolver-wof-sqlite/interpolation.ts`) and the browser twin
11
+ * (`resolver-wof-wasm/httpvfs/street.ts`) both call it: the geometry never differs between them,
12
+ * only the I/O around it does.
13
13
  */
14
14
 
15
- import { haversineKm } from "./distance.ts"
15
+ import { haversineKm } from "#distance"
16
16
 
17
17
  /**
18
18
  * Clamp a fraction into `[0, 1]`.