@vizhub/quadstream 0.0.0-stage → 0.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ First planned experimental npm release of the modern Quadstream library.
6
+
7
+ - Deterministic shared topology, sparse quadtree and BLG reconstruction.
8
+ - Planar GeoJSON/TopoJSON interchange, viewport selection, v1 binary partitions,
9
+ partial sessions and transport-independent loading.
10
+ - CLI for build, inspect, validate, query and benchmark.
11
+ - MapLibre integration and experimental in-memory spherical reconstruction.
12
+ - Standalone map and globe demos with regression tests.
13
+ - MIT license for modern implementation; legacy license terms preserved.
14
+ - ESM package, TypeScript declarations and clean-install tarball validation.
15
+
16
+ No spherical network streaming, production scalability or physical mobile
17
+ parity is claimed. Publication requires separate sign-off.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Curran Kelleher
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,397 @@
1
- # Temporary Holding Version
1
+ # Quadstream
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Progressive, topology-aware, multiresolution geometry for the web.**
4
+
5
+ Quadstream prepares geographic shapes at multiple levels of detail while
6
+ sharing exactly matching boundaries. Build once, query a simpler representation
7
+ for a map or globe, or serialize planar geometry into independently loadable
8
+ binary partitions. The TypeScript-first core is ESM with no runtime dependencies,
9
+ and requires no VizHub account, map framework or server.
10
+
11
+ > **Experimental 0.1.0 release preparation.** The package is not yet published
12
+ > and remains private pending release sign-off. Reference validation can be
13
+ > expensive; do not use it for safety-critical geometry.
14
+
15
+ ## Features
16
+
17
+ - Deterministic spatial vertex priorities and BLG-style ordered reconstruction.
18
+ - Exact shared arcs, reversible references and explicit validity fallback.
19
+ - Planar viewport queries, GeoJSON/TopoJSON adapters and versioned binary partitions.
20
+ - Transport-independent progressive loading with cancellation and a bounded raw-byte cache.
21
+ - Experimental spherical geometry for D3 globes, including seam and pole aliases.
22
+ - Standalone CLI and local Canvas, MapLibre and D3 globe demos.
23
+
24
+ ## Install
25
+
26
+ Once the public package is released (Node.js 20+, ESM):
27
+
28
+ ```sh
29
+ npm install @vizhub/quadstream
30
+ ```
31
+
32
+ Until then, use a checkout and build the package:
33
+
34
+ ```sh
35
+ git clone https://github.com/vizhub-studio/quadstream.git
36
+ cd quadstream
37
+ npm ci
38
+ npm run build
39
+ node examples/hello.mjs
40
+ npm pack
41
+ ```
42
+
43
+ The generated tarball can be installed into a separate project. The following
44
+ examples use the package's public import path. From a checkout, examples in
45
+ `examples/` instead import `../dist/index.js`.
46
+
47
+ ## Quick start: planar geometry
48
+
49
+ ```js
50
+ import { buildQuadstream } from '@vizhub/quadstream';
51
+
52
+ const source = {
53
+ type: 'FeatureCollection',
54
+ features: [{
55
+ type: 'Feature',
56
+ id: 'square',
57
+ properties: { value: 42 },
58
+ geometry: {
59
+ type: 'Polygon',
60
+ coordinates: [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]]
61
+ }
62
+ }]
63
+ };
64
+
65
+ const dataset = buildQuadstream(source, { maxLevel: 12 });
66
+ const result = dataset.query({ level: 4, bounds: [0, 0, 10, 10] });
67
+ console.log(result.geojson, result.usedFallback);
68
+ ```
69
+
70
+ Detail levels run from 0 (coarsest) to `maxLevel - 1` (finest).
71
+ The returned feature collection can be rendered with your preferred renderer.
72
+ TypeScript users can annotate the source with the exported `FeatureCollection`
73
+ type.
74
+
75
+ The planar engine interprets coordinates as Cartesian numbers. Project or
76
+ split dateline-crossing geography upstream; use the spherical API for
77
+ great-circle globe geometry.
78
+
79
+ ## Progressive planar loading
80
+
81
+ ```js
82
+ import {
83
+ exportPartitions, QuadstreamSession, QuadstreamLoader, fetchFromBundle
84
+ } from '@vizhub/quadstream';
85
+
86
+ const bundle = exportPartitions(dataset, { fileDepth: 3 });
87
+ const session = new QuadstreamSession(bundle.manifest);
88
+ const loader = new QuadstreamLoader(session, fetchFromBundle(bundle), {
89
+ concurrency: 4,
90
+ cacheBytes: 1024 * 1024
91
+ });
92
+
93
+ const frame = await loader.loadLatest({ level: 4 });
94
+ console.log(frame.geojson, frame.complete, frame.usedFallback);
95
+ ```
96
+
97
+ Replace `fetchFromBundle` with an async function accepting a partition key and
98
+ `{ signal }` to retrieve bytes from your own transport. The session validates
99
+ partition checksums, sizes and records before ingestion. A new latest-view
100
+ request cancels the preceding one. Partial session queries report incomplete
101
+ or omitted features until required partitions arrive.
102
+
103
+ The raw-byte cache does not evict parsed session vertices. The planner is
104
+ conservative: it may request partitions outside the viewport to reconstruct
105
+ segments that cross it. No production HTTP/CDN client is bundled.
106
+
107
+ ## Spherical geometry and D3
108
+
109
+ Use the distinct spherical engine for longitude/latitude coordinates in
110
+ degrees with D3 spherical winding (clockwise small polygon interiors).
111
+ The following example assumes a TopoJSON atlas is already loaded:
112
+
113
+ ```js
114
+ import { buildSphericalQuadstream, importSphericalTopoJSON } from '@vizhub/quadstream';
115
+
116
+ const countries = importSphericalTopoJSON(atlas, 'countries');
117
+ const globe = buildSphericalQuadstream(countries, { maxLevel: 20 });
118
+ const { geojson, valid, promotedArcs } = globe.query({ level: 8.5 });
119
+ // Supply geojson to your D3 geoPath renderer.
120
+ ```
121
+
122
+ Spherical queries reconstruct global geometry in memory. Fractional detail uses
123
+ stable vertex-ID hashing; shared-arc promotion repairs invalid features without
124
+ a global full-detail fallback. They do not support
125
+ planar viewport bounds, v1 partition serialization or network streaming.
126
+ They may reject inputs that cannot be validated in the reference hemisphere
127
+ chart. See [spherical semantics](https://github.com/vizhub-studio/quadstream/blob/master/docs/SPHERICAL.md).
128
+
129
+ ## Interactive demos
130
+
131
+ From a checkout, install dependencies and build, then run either command:
132
+
133
+ | Demo | Command | What it demonstrates |
134
+ | --- | --- | --- |
135
+ | Progressive map | `npm run demo:map` | Canvas/MapLibre, detail levels, shared arcs, simulated partition latency |
136
+ | Orthographic globe | `npm run demo:globe` | D3 Canvas, real 110m/50m atlas inputs, pinch zoom, rotation, worker-based LOD and original/reconstructed comparison |
137
+
138
+ Open the local URL printed by the server (normally http://127.0.0.1:4173/).
139
+ The demos are not included in the npm artifact. The globe downloads the full
140
+ atlas up front; its LOD reduction is not a bandwidth-saving streaming protocol.
141
+ See [map demo](https://github.com/vizhub-studio/quadstream/blob/master/docs/PROGRESSIVE-MAP.md)
142
+ and [globe demo](https://github.com/vizhub-studio/quadstream/blob/master/docs/GLOBE.md).
143
+
144
+ ## CLI
145
+
146
+ After installing the released package, run its executable with
147
+ `npx --no-install quadstream` (or use `node bin/quadstream.mjs` from a built checkout):
148
+
149
+ ```sh
150
+ npx --no-install quadstream build countries.geojson countries.bundle --max-level 20 --file-depth 4
151
+ npx --no-install quadstream inspect countries.bundle
152
+ npx --no-install quadstream validate countries.bundle
153
+ npx --no-install quadstream query countries.bundle --level 10 --output simplified.geojson
154
+ npx --no-install quadstream benchmark countries.geojson --iterations 3
155
+ ```
156
+
157
+ The CLI currently operates on planar coordinates. Query output and build
158
+ directories must not already exist. See [CLI and format policy](https://github.com/vizhub-studio/quadstream/blob/master/docs/CLI.md)
159
+ for input restrictions, bounds, exit codes and static staging.
160
+
161
+ ## Public API guide
162
+
163
+ | API | Purpose |
164
+ | --- | --- |
165
+ | `buildQuadstream`, `QuadstreamDataset` | Build planar multiresolution geometry and query by detail/bounds |
166
+ | `buildSphericalQuadstream`, `SphericalQuadstreamDataset`, `importSphericalTopoJSON` | In-memory D3-style geographic reconstruction |
167
+ | `importGeoJSON`, `exportGeoJSON`, `importTopoJSON`, `exportTopoJSON` | Planar geographic interchange |
168
+ | `exportPartitions`, `validateManifest`, `MANIFEST_VERSION` | Versioned planar artifacts |
169
+ | `QuadstreamSession`, `QuadstreamLoader`, `fetchFromBundle` | Partial reconstruction and injected async delivery |
170
+ | `ProgressiveMap`, `attachMapLibre`, `mapLibreBounds` | Renderer-independent orchestration and MapLibre integration |
171
+ | `buildTopology`, `buildSparseQuadtree`, `buildBlgTree`, `createSpatialIndex` | Lower-level algorithm building blocks |
172
+
173
+ See the [export list](https://github.com/vizhub-studio/quadstream/blob/master/src/index.ts)
174
+ and included TypeScript declarations for complete signatures and utilities.
175
+
176
+ ## Detailed API reference
177
+
178
+ The package exports its public API from `src/index.ts` and ships declarations
179
+ with the build. The signatures below describe the stable development-preview
180
+ surface; TypeScript is the authoritative source for exact structural types.
181
+
182
+ ### Core planar dataset
183
+
184
+ ```ts
185
+ buildQuadstream(
186
+ input: FeatureCollection,
187
+ options?: { maxLevel?: number },
188
+ ): QuadstreamDataset
189
+
190
+ dataset.query(options?: {
191
+ level?: number;
192
+ bounds?: Bounds;
193
+ validate?: boolean;
194
+ }): QueryResult
195
+ ```
196
+
197
+ `QuadstreamDataset` exposes `topology`, `quadtree`, and `arcTrees` for
198
+ inspection. `QueryResult` contains `geojson`, the requested `level`, `valid`,
199
+ `usedFallback`, `selectedFeatures`, and `selectedVertices`. `level` ranges
200
+ from `0` through `maxLevel - 1`; the default is the finest level. `bounds`
201
+ selects features by intersecting feature bounds and does not clip geometry.
202
+ Set `validate: false` only when the caller accepts unvalidated reconstructed
203
+ geometry.
204
+
205
+ The public planar model includes `Position`, `Bounds`, `Geometry`, `Feature`,
206
+ `FeatureCollection`, `Topology`, `TopologyFeature`, `Arc`, `TopologyPath`,
207
+ `Vertex`, `SparseQuadtree`, `QueryOptions`, and `QueryResult`. Supported
208
+ geometries are `Polygon`, `MultiPolygon`, `LineString`, and
209
+ `MultiLineString`.
210
+
211
+ ### Topology, priorities, and geometry helpers
212
+
213
+ - `buildTopology(collection)` deduplicates exact coordinates, shared arcs, and
214
+ feature metadata.
215
+ - `buildSparseQuadtree(vertices, bounds, maxLevel)`, `cellKey(level, i, j)`,
216
+ and `cellAddress(key)` expose deterministic sparse spatial priorities.
217
+ - `buildBlgTree(levels)`, `selectBlgPositions(tree, maxLevel)`, and
218
+ `assertBlgInvariants(tree)` expose the ordered vertex-selection structure.
219
+ - `createSpatialIndex(items)` builds a packed bounds index whose `query(bounds)`
220
+ returns matching values.
221
+ - `boundsOf(points)`, `intersects(a, b)`, `simpleClosedRing(ring)`,
222
+ `segmentsIntersect(a, b, c, d)`, `pointInRing(point, ring)`, and
223
+ `validPolygon(rings)` provide the reference planar predicates.
224
+
225
+ These lower-level functions are useful for diagnostics, custom pipelines, and
226
+ tests. They enforce the same finite-coordinate and exact-coordinate policies as
227
+ the dataset builder.
228
+
229
+ ### GeoJSON and TopoJSON
230
+
231
+ - `importGeoJSON(input)` validates and normalizes a GeoJSON
232
+ `FeatureCollection` or `Feature`.
233
+ - `exportGeoJSON(collection)` returns a serializable GeoJSON collection.
234
+ - `importTopoJSON(input)` decodes unquantized or quantized TopoJSON into a
235
+ feature collection.
236
+ - `exportTopoJSON(collection)` writes unquantized TopoJSON with shared arcs.
237
+ - `decodeTopoJSON(input, objectName, position?)` decodes one named TopoJSON
238
+ object with an optional coordinate normalizer.
239
+
240
+ `TopoJSONTopology` is exported for typed adapter integration. TopoJSON arc
241
+ references use standard zero-based indices and bitwise-complement reversal.
242
+ Feature IDs and properties are preserved by the adapters; the core normalizes
243
+ missing IDs and null properties during topology construction.
244
+
245
+ ### Partitioned artifacts and progressive loading
246
+
247
+ ```ts
248
+ exportPartitions(dataset, options?: { fileDepth?: number }): PartitionBundle
249
+ encodePartition(records): Uint8Array
250
+ decodePartition(bytes, maxRecords?): PartitionRecord[]
251
+ validateManifest(input): QuadstreamManifest
252
+ ```
253
+
254
+ `exportPartitions` returns a manifest and `Map<string, Uint8Array>` containing
255
+ deterministic QSTR v1 partitions. `checksum(bytes)` computes the non-authenticating
256
+ FNV-1a corruption check. `requiredPartitionKeys(manifest, level)` returns all
257
+ partitions needed for a level, while `partitionsWithVerticesInBounds(manifest,
258
+ bounds)` is diagnostic vertex coverage and is not a safe request planner.
259
+ `MANIFEST_VERSION` is the current artifact version.
260
+
261
+ `QuadstreamSession` validates a manifest in its constructor, then accepts
262
+ partitions with `load(key, bytes)`. Its `loadedKeys`, `missingKeys(level)`, and
263
+ `query(options)` APIs report partial results through `complete`, `missingKeys`,
264
+ `omittedFeatures`, and `usedFallback`.
265
+
266
+ `QuadstreamLoader` wraps a session with an injected `PartitionFetcher`:
267
+
268
+ ```ts
269
+ type PartitionFetcher = (
270
+ key: string,
271
+ context: { signal: AbortSignal },
272
+ ) => Promise<Uint8Array>;
273
+
274
+ loader.ensureLevel(level, { signal? }): Promise<void>
275
+ loader.loadLatest(query?): Promise<SessionQueryResult>
276
+ loader.cancelLatest(): void
277
+ ```
278
+
279
+ `LoaderOptions` limits per-request concurrency (default `4`, maximum `32`) and
280
+ the optional raw-byte LRU cache (default 16 MiB). `fetchFromBundle(bundle)`
281
+ provides an in-memory fetcher for tests and demos. Fetching, HTTP, retries,
282
+ persistent caching, and authentication remain application responsibilities.
283
+
284
+ ### Progressive map client and MapLibre adapter
285
+
286
+ `ProgressiveMap` stages requests at coarse, intermediate, and target levels.
287
+ Implement `ProgressiveMapClient` with `request(query, onFrame)` and `cancel()`
288
+ when integrating another renderer. Each `MapFrame` reports the session result,
289
+ target level, whether it is final, and loaded/total partition counts.
290
+
291
+ `attachMapLibre(map, loader, options?)` connects the loader to a MapLibre-like
292
+ map interface, and `mapLibreBounds(bounds)` converts the current map bounds to
293
+ the planar query bounds. The adapter intentionally has no MapLibre runtime
294
+ dependency; `MapLibreLike` and `MapLibreAdapterOptions` describe the minimal
295
+ integration surface. See [the progressive map guide](docs/PROGRESSIVE-MAP.md).
296
+
297
+ ### Spherical geographic API
298
+
299
+ ```ts
300
+ importSphericalTopoJSON(input, objectName): FeatureCollection
301
+ buildSphericalQuadstream(
302
+ input: FeatureCollection,
303
+ options?: { maxLevel?: number },
304
+ ): SphericalQuadstreamDataset
305
+ dataset.query(options?: { level?: number }): QueryResult
306
+ ```
307
+
308
+ The spherical API uses longitude/latitude degrees, D3's clockwise-small-interior
309
+ winding convention, minor great-circle arcs, and six cube-face sparse
310
+ priorities. It is intentionally separate from planar partitions and viewport
311
+ culling. Exported helpers include `canonicalLonLat`, `lonLatVector`,
312
+ `angularDistance`, `validGreatCirclePath`, `sphericalCellAddress`,
313
+ `buildSphericalPriorities`, `sphericalChart`, `projectSpherical`,
314
+ `sphericalPolygonSignature`, and `validSphericalPolygon`. Supporting types are
315
+ `UnitVector`, `CubeFace`, `SphericalCell`, `SphericalPriorities`,
316
+ `SphericalChart`, `SphericalPolygonSignature`, and `SphericalQueryOptions`.
317
+ Spherical queries support fractional levels. Invalid features are repaired by
318
+ promoting shared arcs to finer levels; `promotedArcs` reports the number of
319
+ promoted arcs. `valid: false` indicates geometry that remains invalid at full
320
+ detail. No global full-detail fallback is applied. See [spherical semantics](docs/SPHERICAL.md) for winding,
321
+ poles, seams, charts, and topology junctions.
322
+
323
+ Spherical reconstruction applies three additional safeguards:
324
+
325
+ - vertices shared by three or more feature IDs are critical, preserving
326
+ multi-shape junctions and shared topology;
327
+ - a vertex is promoted to critical when its removal would reverse a ring's
328
+ projected winding, collapse its area, or make a small ring fail the spherical
329
+ validity predicate;
330
+ - closed rings that would reconstruct with fewer than three distinct vertices
331
+ are restored from their source path rather than emitted as degenerate rings.
332
+
333
+ These safeguards and shared-arc repair preserve shared topology without promoting
334
+ the entire query to a finer level. The globe demo separately isolates malformed
335
+ source features, so one invalid atlas feature does not force its whole
336
+ coordinate-connected component to full detail.
337
+
338
+
339
+ ## How it works
340
+
341
+ Quadstream deduplicates exact shared vertices and arcs, assigns deterministic
342
+ spatial importance using a sparse hierarchy, and reconstructs source order
343
+ through Binary Line Generalization (BLG)-style priority trees. Planar geometry
344
+ uses a sparse quadtree, while spherical geometry uses hierarchical occupancy
345
+ on six cube faces. A packed planar spatial index selects viewport candidates.
346
+ The versioned planar binary format stores checksummed vertex batches separately
347
+ from topology metadata.
348
+
349
+ ## Geometry semantics and limitations
350
+
351
+ - Supported shapes: Polygon, MultiPolygon, LineString and MultiLineString.
352
+ No points, nested geometry collections, 3D coordinates or nonfinite positions.
353
+ - Only exact coordinate matches establish shared borders; no approximate
354
+ snapping or differently digitized boundary reconciliation.
355
+ - Planar bounds filter whole features; they do not clip geometry. Planar IDs
356
+ are normalized to strings, and null properties become empty objects.
357
+ - Full-detail reconstruction retains coordinates and order subject to documented
358
+ normalization and cyclic ring starts. Coarse BLG subsets are nested, but
359
+ validated output may not be monotonic when a fallback occurs.
360
+ - By default, invalid planar simplified geometry triggers a global full-detail
361
+ fallback, not independent per-feature simplification. Partial results are
362
+ explicit; validation does not prove global cross-feature topology.
363
+ - Reference polygon validity checks are quadratic; large-scale performance,
364
+ measured screen-space error, robust global spherical predicates and
365
+ production resource hardening remain future work.
366
+ - Binary checksums detect accidental corruption, not malicious changes.
367
+
368
+ See the [architecture](https://github.com/vizhub-studio/quadstream/blob/master/docs/ARCHITECTURE.md)
369
+ and [roadmap](https://github.com/vizhub-studio/quadstream/blob/master/plans/PROJECT_ROADMAP.md)
370
+ for implementation details and planned work.
371
+
372
+ ## Development
373
+
374
+ ```sh
375
+ npm ci
376
+ npm run check
377
+ npm run lint
378
+ npm run test:package
379
+ npx playwright install --with-deps chromium webkit
380
+ npm run test:globe:browser
381
+ ```
382
+
383
+ Use `npm run prettier` to format maintained sources. CI retains Node 26 and Chromium/WebKit globe regression tests and adds
384
+ packed-package verification for Node 20 and 26. The real-atlas globe tests
385
+ compare original and full-resolution reconstruction across multiple views and
386
+ zoom levels. Physical mobile-device validation and production benchmarks remain
387
+ outstanding. See [contributing](https://github.com/vizhub-studio/quadstream/blob/master/CONTRIBUTING.md).
388
+
389
+ ## History and license
390
+
391
+ Quadstream revives research and prototypes from 2010–2012 in a self-contained
392
+ modern TypeScript implementation. See [historical provenance](https://github.com/vizhub-studio/quadstream/blob/master/docs/HISTORY.md).
393
+
394
+ Run `npm run build` and `npm run demo:globe`. This geometry-only D3 Canvas demo includes touch rotation and repeated pinch zoom, real atlas inputs, Quadstream/original comparison, and render-time view culling and spherical clipping (`?clip=0` to disable; the engine query itself is not viewport-aware). See [globe controls, provenance and limitations](docs/GLOBE.md).
395
+ The modern implementation is MIT-licensed. Historical Java/browser code
396
+ retains its existing license terms.
397
+ See [LICENSE](https://github.com/vizhub-studio/quadstream/blob/master/LICENSE).
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+ import { createReadStream } from "node:fs";
3
+ import { mkdir, writeFile, lstat, rm } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { performance } from "node:perf_hooks";
6
+ import { TextDecoder } from "node:util";
7
+ import {
8
+ buildQuadstream,
9
+ exportPartitions,
10
+ QuadstreamSession,
11
+ importGeoJSON,
12
+ importTopoJSON,
13
+ exportGeoJSON,
14
+ exportTopoJSON,
15
+ validateManifest,
16
+ } from "../dist/index.js";
17
+
18
+ const usage = `Quadstream (development preview)
19
+ quadstream build INPUT OUTPUT_DIR [--max-level N] [--file-depth N] [--max-bytes N]
20
+ quadstream validate INPUT_OR_BUNDLE [--max-bytes N]
21
+ quadstream inspect BUNDLE [--max-bytes N]
22
+ quadstream query BUNDLE [--level N] [--bounds xmin,ymin,xmax,ymax] [--format geojson|topojson] [--output FILE] [--max-bytes N]
23
+ quadstream benchmark INPUT [--max-level N] [--iterations N] [--max-bytes N]
24
+ Inputs are GeoJSON or TopoJSON files; all coordinates are planar. Output paths must not exist.
25
+ Exit codes: 0 success, 1 data/IO failure, 2 usage error.
26
+ `;
27
+ class UsageError extends Error {}
28
+ function parse(args, allowed, n) {
29
+ const options = {},
30
+ positional = [];
31
+ for (let i = 0; i < args.length; i++) {
32
+ const token = args[i];
33
+ if (!token.startsWith("--")) {
34
+ positional.push(token);
35
+ continue;
36
+ }
37
+ const key = token.slice(2),
38
+ value = args[++i];
39
+ if (
40
+ !allowed.includes(key) ||
41
+ Object.hasOwn(options, key) ||
42
+ value === undefined ||
43
+ value.startsWith("--")
44
+ )
45
+ throw new UsageError("Invalid option: " + token);
46
+ options[key] = value;
47
+ }
48
+ if (positional.length !== n)
49
+ throw new UsageError("Wrong number of arguments");
50
+ return { options, positional };
51
+ }
52
+ function int(v, min, max, name) {
53
+ if (
54
+ !/^[0-9]+$/.test(String(v)) ||
55
+ !Number.isSafeInteger(Number(v)) ||
56
+ Number(v) < min ||
57
+ Number(v) > max
58
+ )
59
+ throw new UsageError("Invalid " + name);
60
+ return Number(v);
61
+ }
62
+ function budget(max) {
63
+ let remaining = max;
64
+ return async function read(path) {
65
+ const st = await lstat(path);
66
+ if (!st.isFile() || st.size > remaining)
67
+ throw new Error("Not a regular file or byte limit exceeded: " + path);
68
+ const chunks = [];
69
+ let size = 0;
70
+ for await (const chunk of createReadStream(path)) {
71
+ size += chunk.length;
72
+ if (size > remaining) throw new Error("Byte limit exceeded: " + path);
73
+ chunks.push(chunk);
74
+ }
75
+ remaining -= size;
76
+ return Buffer.concat(chunks, size);
77
+ };
78
+ }
79
+ const json = (bytes) =>
80
+ JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
81
+ const asSource = (v) =>
82
+ v?.type === "Topology" ? importTopoJSON(v) : importGeoJSON(v);
83
+ const print = (v) => process.stdout.write(JSON.stringify(v, null, 2) + "\n");
84
+ async function manifest(dir, read) {
85
+ return validateManifest(json(await read(join(dir, "manifest.json"))));
86
+ }
87
+ async function load(dir, read) {
88
+ const m = await manifest(dir, read),
89
+ session = new QuadstreamSession(m);
90
+ for (const p of m.partitions)
91
+ session.load(p.key, await read(join(dir, p.key + ".qstr")));
92
+ return { m, session };
93
+ }
94
+ function inspect(m) {
95
+ return {
96
+ format: m.format,
97
+ version: m.version,
98
+ maxLevel: m.maxLevel,
99
+ fileDepth: m.fileDepth,
100
+ bounds: m.bounds,
101
+ features: m.features.length,
102
+ arcs: m.arcs.length,
103
+ vertices: m.vertices.length,
104
+ partitions: m.partitions.length,
105
+ partitionBytes: m.partitions.reduce((n, p) => n + p.byteLength, 0),
106
+ };
107
+ }
108
+ function bbox(v) {
109
+ const parts = v.split(",");
110
+ if (
111
+ parts.length !== 4 ||
112
+ parts.some((x) => !x.trim() || !Number.isFinite(Number(x)))
113
+ )
114
+ throw new UsageError("Invalid bounds");
115
+ const b = parts.map(Number);
116
+ if (b[0] > b[2] || b[1] > b[3]) throw new UsageError("Invalid bounds order");
117
+ return b;
118
+ }
119
+ async function main() {
120
+ const [cmd, ...args] = process.argv.slice(2);
121
+ if (cmd === "--help" || cmd === "help" || args.includes("--help")) {
122
+ process.stdout.write(usage);
123
+ return;
124
+ }
125
+ const config = {
126
+ build: [["max-level", "file-depth"], 2],
127
+ validate: [[], 1],
128
+ inspect: [[], 1],
129
+ query: [["level", "bounds", "format", "output"], 1],
130
+ benchmark: [["max-level", "iterations"], 1],
131
+ };
132
+ if (!Object.hasOwn(config, cmd)) throw new UsageError("Unknown command");
133
+ const [allowed, n] = config[cmd],
134
+ {
135
+ options: o,
136
+ positional: [input, output],
137
+ } = parse(args, [...allowed, "max-bytes"], n);
138
+ const read = budget(
139
+ int(o["max-bytes"] ?? "67108864", 1, 1073741824, "max-bytes"),
140
+ );
141
+ const maxLevel = () => int(o["max-level"] ?? "20", 1, 26, "max-level");
142
+ if (cmd === "build") {
143
+ const level = maxLevel(),
144
+ depth = int(
145
+ o["file-depth"] ?? String(Math.min(4, level)),
146
+ 1,
147
+ level,
148
+ "file-depth",
149
+ );
150
+ const bundle = exportPartitions(
151
+ buildQuadstream(asSource(json(await read(input))), { maxLevel: level }),
152
+ { fileDepth: depth },
153
+ );
154
+ validateManifest(bundle.manifest);
155
+ await mkdir(output);
156
+ try {
157
+ for (const [key, bytes] of bundle.partitions)
158
+ await writeFile(join(output, key + ".qstr"), bytes, { flag: "wx" });
159
+ await writeFile(
160
+ join(output, "manifest.json"),
161
+ JSON.stringify(bundle.manifest) + "\n",
162
+ { flag: "wx" },
163
+ );
164
+ } catch (e) {
165
+ await rm(output, { recursive: true, force: true });
166
+ throw e;
167
+ }
168
+ print(inspect(bundle.manifest));
169
+ return;
170
+ }
171
+ if (cmd === "inspect") {
172
+ print(inspect(await manifest(input, read)));
173
+ return;
174
+ }
175
+ if (cmd === "validate") {
176
+ if ((await lstat(input)).isDirectory()) {
177
+ const { m, session } = await load(input, read),
178
+ result = session.query({ level: m.maxLevel - 1 });
179
+ if (!result.complete || result.omittedFeatures)
180
+ throw new Error("Incomplete full-detail reconstruction");
181
+ print({ valid: true, ...inspect(m) });
182
+ } else {
183
+ const data = asSource(json(await read(input)));
184
+ print({ valid: true, features: data.features.length });
185
+ }
186
+ return;
187
+ }
188
+ if (cmd === "query") {
189
+ const format = o.format ?? "geojson";
190
+ if (!["geojson", "topojson"].includes(format))
191
+ throw new UsageError("Invalid format");
192
+ const bounds = o.bounds === undefined ? undefined : bbox(o.bounds);
193
+ const { m, session } = await load(input, read);
194
+ const level = int(
195
+ o.level ?? String(m.maxLevel - 1),
196
+ 0,
197
+ m.maxLevel - 1,
198
+ "level",
199
+ );
200
+ const result = session.query({ level, bounds });
201
+ if (!result.complete) throw new Error("Incomplete query result");
202
+ const data =
203
+ format === "topojson"
204
+ ? exportTopoJSON(result.geojson)
205
+ : exportGeoJSON(result.geojson);
206
+ if (o.output !== undefined)
207
+ await writeFile(o.output, JSON.stringify(data) + "\n", { flag: "wx" });
208
+ else print(data);
209
+ return;
210
+ }
211
+ const iterations = int(o.iterations ?? "3", 1, 100, "iterations"),
212
+ level = maxLevel(),
213
+ data = asSource(json(await read(input))),
214
+ runs = [];
215
+ for (let i = 0; i < iterations; i++) {
216
+ const start = performance.now(),
217
+ dataset = buildQuadstream(data, { maxLevel: level }),
218
+ built = performance.now(),
219
+ bundle = exportPartitions(dataset, { fileDepth: Math.min(4, level) }),
220
+ packed = performance.now();
221
+ const coarse = dataset.query({ level: 0 }),
222
+ full = dataset.query({ level: level - 1 }),
223
+ done = performance.now();
224
+ runs.push({
225
+ buildMs: built - start,
226
+ partitionMs: packed - built,
227
+ queryMs: done - packed,
228
+ vertices: dataset.topology.vertices.length,
229
+ coarseVertices: coarse.selectedVertices,
230
+ fullVertices: full.selectedVertices,
231
+ coarseFallback: coarse.usedFallback,
232
+ partitionBytes: inspect(bundle.manifest).partitionBytes,
233
+ });
234
+ }
235
+ print({ iterations, maxLevel: level, runs });
236
+ }
237
+ main().catch((e) => {
238
+ process.stderr.write((e instanceof Error ? e.message : String(e)) + "\n");
239
+ process.exitCode = e instanceof UsageError ? 2 : 1;
240
+ });