@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.
@@ -0,0 +1,26 @@
1
+ import type { Feature, FeatureCollection, Geometry, Position } from "./types.js";
2
+ /** Strict planar GeoJSON subset. No CRS transformation, longitude wrapping or snapping. */
3
+ export declare function importGeoJSON(input: unknown): FeatureCollection;
4
+ /** Output accepts an empty query result, unlike the build input. */
5
+ export declare function exportGeoJSON(input: FeatureCollection): FeatureCollection;
6
+ type TopoGeometry = {
7
+ type: Geometry["type"];
8
+ arcs: unknown;
9
+ id?: string | number;
10
+ properties?: Feature["properties"];
11
+ };
12
+ export interface TopoJSONTopology {
13
+ type: "Topology";
14
+ objects: Record<string, {
15
+ type: "GeometryCollection";
16
+ geometries: TopoGeometry[];
17
+ }>;
18
+ arcs: Position[][];
19
+ }
20
+ /** Decode signed zero-based TopoJSON arcs; transformed arcs are delta-encoded per arc. */
21
+ export declare function importTopoJSON(input: unknown): FeatureCollection;
22
+ /** Internal decoder: caller must apply the appropriate coordinate validation. */
23
+ export declare function decodeTopoJSON(input: unknown, objectName?: string, normalize?: (p: Position) => Position): FeatureCollection;
24
+ /** Export unquantized absolute-coordinate TopoJSON, with shared arcs stored once. */
25
+ export declare function exportTopoJSON(input: FeatureCollection): TopoJSONTopology;
26
+ export {};
@@ -0,0 +1,229 @@
1
+ import { buildTopology } from "./topology.js";
2
+ function obj(v, label) {
3
+ if (!v || typeof v !== "object" || Array.isArray(v))
4
+ throw new Error("Invalid " + label);
5
+ return v;
6
+ }
7
+ function arr(v, label) {
8
+ if (!Array.isArray(v))
9
+ throw new Error("Invalid " + label);
10
+ return v;
11
+ }
12
+ function pos(v) {
13
+ const a = arr(v, "position");
14
+ if (a.length !== 2 ||
15
+ a.some((n) => typeof n !== "number" || !Number.isFinite(n)))
16
+ throw new Error("Expected finite planar 2D position");
17
+ return [a[0], a[1]];
18
+ }
19
+ function same(a, b) {
20
+ return a[0] === b[0] && a[1] === b[1];
21
+ }
22
+ function path(v, closed) {
23
+ const p = arr(v, "coordinate path").map(pos);
24
+ if (p.length < (closed ? 4 : 2) || (closed && !same(p[0], p.at(-1))))
25
+ throw new Error("Invalid or unclosed coordinate path");
26
+ return p;
27
+ }
28
+ function nonempty(a) {
29
+ if (!a.length)
30
+ throw new Error("Empty geometry");
31
+ return a;
32
+ }
33
+ function geom(v) {
34
+ const g = obj(v, "geometry"), c = g.coordinates;
35
+ switch (g.type) {
36
+ case "LineString":
37
+ return { type: g.type, coordinates: path(c, false) };
38
+ case "MultiLineString":
39
+ return {
40
+ type: g.type,
41
+ coordinates: nonempty(arr(c, "lines").map((x) => path(x, false))),
42
+ };
43
+ case "Polygon":
44
+ return {
45
+ type: g.type,
46
+ coordinates: nonempty(arr(c, "rings").map((x) => path(x, true))),
47
+ };
48
+ case "MultiPolygon":
49
+ return {
50
+ type: g.type,
51
+ coordinates: nonempty(arr(c, "polygons").map((x) => nonempty(arr(x, "rings").map((y) => path(y, true))))),
52
+ };
53
+ default:
54
+ throw new Error("Unsupported geometry: " + String(g.type));
55
+ }
56
+ }
57
+ function feature(g, metadata) {
58
+ const id = metadata.id;
59
+ if (id !== undefined &&
60
+ typeof id !== "string" &&
61
+ !(typeof id === "number" && Number.isFinite(id)))
62
+ throw new Error("Invalid feature id");
63
+ const properties = metadata.properties == null
64
+ ? null
65
+ : { ...obj(metadata.properties, "properties") };
66
+ return {
67
+ type: "Feature",
68
+ ...(id === undefined ? {} : { id: id }),
69
+ properties,
70
+ geometry: g,
71
+ };
72
+ }
73
+ function collection(features, allowEmpty = false) {
74
+ const fc = { type: "FeatureCollection", features };
75
+ if (features.length || !allowEmpty)
76
+ buildTopology(fc);
77
+ return fc;
78
+ }
79
+ /** Strict planar GeoJSON subset. No CRS transformation, longitude wrapping or snapping. */
80
+ export function importGeoJSON(input) {
81
+ const root = obj(input, "GeoJSON");
82
+ if ("crs" in root)
83
+ throw new Error("Explicit CRS is unsupported; reproject before import");
84
+ const values = root.type === "FeatureCollection" ? arr(root.features, "features") : [root];
85
+ return collection(values.map((value) => {
86
+ const f = obj(value, "feature");
87
+ if (f.type !== "Feature" || "crs" in f)
88
+ throw new Error("Expected GeoJSON Feature without CRS");
89
+ return feature(geom(f.geometry), f);
90
+ }));
91
+ }
92
+ /** Output accepts an empty query result, unlike the build input. */
93
+ export function exportGeoJSON(input) {
94
+ if (input.type !== "FeatureCollection" || !Array.isArray(input.features))
95
+ throw new Error("Expected FeatureCollection");
96
+ if (!input.features.length)
97
+ return { type: "FeatureCollection", features: [] };
98
+ return importGeoJSON(input);
99
+ }
100
+ /** Decode signed zero-based TopoJSON arcs; transformed arcs are delta-encoded per arc. */
101
+ export function importTopoJSON(input) {
102
+ const decoded = decodeTopoJSON(input);
103
+ return collection(decoded.features);
104
+ }
105
+ /** Internal decoder: caller must apply the appropriate coordinate validation. */
106
+ export function decodeTopoJSON(input, objectName, normalize) {
107
+ const root = obj(input, "TopoJSON");
108
+ if (root.type !== "Topology" || "crs" in root)
109
+ throw new Error("Expected Topology without explicit CRS");
110
+ let scale, translate;
111
+ if (root.transform !== undefined) {
112
+ const t = obj(root.transform, "transform");
113
+ scale = pos(t.scale);
114
+ translate = pos(t.translate);
115
+ if (scale.some((n) => n === 0))
116
+ throw new Error("Invalid transform scale");
117
+ }
118
+ const arcs = arr(root.arcs, "arcs").map((raw) => {
119
+ let x = 0, y = 0;
120
+ const points = arr(raw, "arc").map((v) => {
121
+ const p = pos(v);
122
+ if (!scale || !translate)
123
+ return normalize ? normalize(p) : p;
124
+ if (!p.every(Number.isSafeInteger))
125
+ throw new Error("Expected integer transformed delta");
126
+ x += p[0];
127
+ y += p[1];
128
+ if (!Number.isSafeInteger(x) || !Number.isSafeInteger(y))
129
+ throw new Error("Unsafe accumulated delta");
130
+ const decoded = pos([
131
+ x * scale[0] + translate[0],
132
+ y * scale[1] + translate[1],
133
+ ]);
134
+ return normalize ? normalize(decoded) : decoded;
135
+ });
136
+ if (points.length < 2)
137
+ throw new Error("Arc requires at least two positions");
138
+ return points;
139
+ });
140
+ function stitch(v, closed) {
141
+ const out = [];
142
+ for (const ref of nonempty(arr(v, "arc references"))) {
143
+ if (typeof ref !== "number" || !Number.isSafeInteger(ref))
144
+ throw new Error("Invalid arc reference");
145
+ const index = ref < 0 ? -ref - 1 : ref, a = arcs[index];
146
+ if (!a)
147
+ throw new Error("Arc reference out of range");
148
+ const oriented = ref < 0 ? [...a].reverse() : a;
149
+ if (out.length && !same(out.at(-1), oriented[0]))
150
+ throw new Error("Disconnected arcs");
151
+ for (let i = out.length ? 1 : 0; i < oriented.length; i++)
152
+ out.push(oriented[i]);
153
+ }
154
+ return path(out, closed);
155
+ }
156
+ function decode(value) {
157
+ const g = obj(value, "TopoJSON geometry"), a = g.arcs;
158
+ switch (g.type) {
159
+ case "LineString":
160
+ return feature({ type: g.type, coordinates: stitch(a, false) }, g);
161
+ case "MultiLineString":
162
+ return feature({
163
+ type: g.type,
164
+ coordinates: nonempty(arr(a, "lines").map((v) => stitch(v, false))),
165
+ }, g);
166
+ case "Polygon":
167
+ return feature({
168
+ type: g.type,
169
+ coordinates: nonempty(arr(a, "rings").map((v) => stitch(v, true))),
170
+ }, g);
171
+ case "MultiPolygon":
172
+ return feature({
173
+ type: g.type,
174
+ coordinates: nonempty(arr(a, "polygons").map((v) => nonempty(arr(v, "rings").map((w) => stitch(w, true))))),
175
+ }, g);
176
+ default:
177
+ throw new Error("Unsupported TopoJSON geometry: " + String(g.type));
178
+ }
179
+ }
180
+ const features = [];
181
+ const objects = obj(root.objects, "objects");
182
+ if (objectName !== undefined &&
183
+ !Object.prototype.hasOwnProperty.call(objects, objectName))
184
+ throw new Error("Unknown TopoJSON object: " + objectName);
185
+ for (const value of objectName === undefined
186
+ ? Object.values(objects)
187
+ : [objects[objectName]]) {
188
+ const g = obj(value, "named object");
189
+ if (g.type === "GeometryCollection")
190
+ for (const child of arr(g.geometries, "geometries"))
191
+ features.push(decode(child));
192
+ else
193
+ features.push(decode(g));
194
+ }
195
+ return { type: "FeatureCollection", features };
196
+ }
197
+ /** Export unquantized absolute-coordinate TopoJSON, with shared arcs stored once. */
198
+ export function exportTopoJSON(input) {
199
+ const fc = exportGeoJSON(input);
200
+ if (!fc.features.length)
201
+ return {
202
+ type: "Topology",
203
+ objects: { data: { type: "GeometryCollection", geometries: [] } },
204
+ arcs: [],
205
+ };
206
+ const t = buildTopology(fc);
207
+ const geometries = t.features.map((f, i) => {
208
+ const groups = f.groups.map((group) => group.map((p) => f.paths[p].arcs.map((ref) => (ref > 0 ? ref - 1 : ref))));
209
+ const arcs = f.geometryType === "LineString"
210
+ ? groups[0][0]
211
+ : f.geometryType === "MultiLineString"
212
+ ? groups.map((g) => g[0])
213
+ : f.geometryType === "Polygon"
214
+ ? groups[0]
215
+ : groups;
216
+ const original = fc.features[i];
217
+ return {
218
+ type: f.geometryType,
219
+ arcs,
220
+ ...(original.id === undefined ? {} : { id: original.id }),
221
+ properties: original.properties,
222
+ };
223
+ });
224
+ return {
225
+ type: "Topology",
226
+ objects: { data: { type: "GeometryCollection", geometries } },
227
+ arcs: t.arcs.map((a) => a.vertexIds.map((id) => [t.vertices[id].x, t.vertices[id].y])),
228
+ };
229
+ }
package/dist/blg.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /** Ordered min-Cartesian tree over vertex priorities; inorder restores exact input order. */
2
+ export interface BlgNode {
3
+ position: number;
4
+ level: number;
5
+ random: number;
6
+ left: BlgNode | null;
7
+ right: BlgNode | null;
8
+ }
9
+ export interface BlgTree {
10
+ root: BlgNode | null;
11
+ count: number;
12
+ }
13
+ export declare function stableBlgRandom(key: number): number;
14
+ export declare function buildBlgTree(levels: readonly number[], randomValues?: readonly number[]): BlgTree;
15
+ /** Iterative inorder traversal: no recursion depth limitation. */
16
+ export declare function selectBlgPositions(tree: BlgTree, maxLevel: number): number[];
17
+ export declare function assertBlgInvariants(tree: BlgTree): void;
package/dist/blg.js ADDED
@@ -0,0 +1,83 @@
1
+ export function stableBlgRandom(key) {
2
+ let hash = Math.imul(key + 1, 0x9e3779b1);
3
+ hash ^= hash >>> 16;
4
+ hash = Math.imul(hash, 0x85ebca6b);
5
+ hash ^= hash >>> 13;
6
+ return (hash >>> 0) / 0x100000000;
7
+ }
8
+ export function buildBlgTree(levels, randomValues) {
9
+ if (randomValues && randomValues.length !== levels.length)
10
+ throw new Error("BLG random values must match priorities");
11
+ const stack = [];
12
+ for (let position = 0; position < levels.length; position++) {
13
+ const level = levels[position];
14
+ if (!Number.isFinite(level) || level < 0)
15
+ throw new Error("BLG priorities must be nonnegative and finite");
16
+ const node = {
17
+ position,
18
+ level,
19
+ random: randomValues?.[position] ?? stableBlgRandom(position),
20
+ left: null,
21
+ right: null,
22
+ };
23
+ let last = null;
24
+ while (stack.length && stack[stack.length - 1].level > level)
25
+ last = stack.pop();
26
+ node.left = last;
27
+ if (stack.length)
28
+ stack[stack.length - 1].right = node;
29
+ stack.push(node);
30
+ }
31
+ return { root: stack[0] ?? null, count: levels.length };
32
+ }
33
+ /** Iterative inorder traversal: no recursion depth limitation. */
34
+ export function selectBlgPositions(tree, maxLevel) {
35
+ if (!Number.isFinite(maxLevel) && maxLevel !== Infinity)
36
+ throw new Error("Invalid selection level");
37
+ if (maxLevel < 0)
38
+ throw new Error("Invalid selection level");
39
+ if (maxLevel === Infinity)
40
+ maxLevel = Number.MAX_SAFE_INTEGER;
41
+ const wholeLevel = Math.floor(maxLevel), fraction = maxLevel - wholeLevel, partialLevel = wholeLevel + 1, traversalLevel = fraction === 0 ? wholeLevel : partialLevel;
42
+ const selected = [], stack = [];
43
+ let current = tree.root;
44
+ while (current || stack.length) {
45
+ while (current && current.level <= traversalLevel) {
46
+ stack.push(current);
47
+ current = current.left;
48
+ }
49
+ if (!stack.length)
50
+ break;
51
+ const node = stack.pop();
52
+ if (node.level <= wholeLevel ||
53
+ (fraction > 0 &&
54
+ node.level === partialLevel &&
55
+ (node.level === 0 || node.random >= 1 - fraction)))
56
+ selected.push(node.position);
57
+ current = node.right;
58
+ }
59
+ return selected;
60
+ }
61
+ export function assertBlgInvariants(tree) {
62
+ const stack = [];
63
+ if (tree.root)
64
+ stack.push({ node: tree.root, parentLevel: -Infinity });
65
+ const seen = new Set();
66
+ while (stack.length) {
67
+ const { node, parentLevel } = stack.pop();
68
+ if (node.level < parentLevel)
69
+ throw new Error("BLG heap invariant violated");
70
+ if (seen.has(node.position))
71
+ throw new Error("BLG duplicate position");
72
+ seen.add(node.position);
73
+ if (node.left)
74
+ stack.push({ node: node.left, parentLevel: node.level });
75
+ if (node.right)
76
+ stack.push({ node: node.right, parentLevel: node.level });
77
+ }
78
+ if (seen.size !== tree.count)
79
+ throw new Error("BLG vertex accounting mismatch");
80
+ const all = selectBlgPositions(tree, Infinity);
81
+ if (all.some((position, i) => position !== i))
82
+ throw new Error("BLG inorder invariant violated");
83
+ }
@@ -0,0 +1,16 @@
1
+ import type { FeatureCollection, QueryOptions, QueryResult, SparseQuadtree, Topology } from "./types.js";
2
+ import type { BlgTree } from "./blg.js";
3
+ export declare class QuadstreamDataset {
4
+ readonly topology: Topology;
5
+ readonly quadtree: SparseQuadtree;
6
+ readonly arcTrees: readonly BlgTree[];
7
+ private readonly featureIndex;
8
+ private readonly validityCache;
9
+ constructor(input: FeatureCollection, { maxLevel }?: {
10
+ maxLevel?: number;
11
+ });
12
+ query(options?: QueryOptions): QueryResult;
13
+ }
14
+ export declare function buildQuadstream(input: FeatureCollection, options?: {
15
+ maxLevel?: number;
16
+ }): QuadstreamDataset;
@@ -0,0 +1,61 @@
1
+ import { assertBounds } from "./geometry.js";
2
+ import { buildTopology } from "./topology.js";
3
+ import { buildSparseQuadtree } from "./quadtree.js";
4
+ import { createSpatialIndex } from "./spatial-index.js";
5
+ import { buildArcTrees, reconstructFeature } from "./reconstruct.js";
6
+ export class QuadstreamDataset {
7
+ topology;
8
+ quadtree;
9
+ arcTrees;
10
+ featureIndex;
11
+ validityCache = new Map();
12
+ constructor(input, { maxLevel = 20 } = {}) {
13
+ this.topology = buildTopology(input);
14
+ this.quadtree = buildSparseQuadtree(this.topology.vertices, this.topology.bounds, maxLevel);
15
+ this.arcTrees = buildArcTrees(this.topology.arcs, this.quadtree.levelByVertexId, this.topology.vertices.map((v) => v.critical));
16
+ this.featureIndex = createSpatialIndex(this.topology.features.map((f, i) => ({ bounds: f.bounds, value: i })));
17
+ }
18
+ query(options = {}) {
19
+ const level = options.level ?? this.quadtree.maxLevel - 1;
20
+ if (!Number.isFinite(level) || level < 0 || level >= this.quadtree.maxLevel)
21
+ throw new Error("Invalid query level");
22
+ if (options.bounds)
23
+ assertBounds(options.bounds);
24
+ const selected = options.bounds
25
+ ? this.featureIndex.query(options.bounds)
26
+ : this.topology.features.map((_, i) => i);
27
+ const coords = (id) => {
28
+ const v = this.topology.vertices[id];
29
+ return v ? [v.x, v.y] : undefined;
30
+ };
31
+ let globallyInvalid = false;
32
+ if (options.validate !== false) {
33
+ const cached = this.validityCache.get(level);
34
+ if (cached !== undefined)
35
+ globallyInvalid = !cached;
36
+ else {
37
+ // Viewport-independent decision: shared boundaries must render consistently
38
+ // even when two viewports select different subsets of features.
39
+ globallyInvalid = this.topology.features.some((f) => !reconstructFeature(f, this.topology.arcs, this.arcTrees, level, coords).valid);
40
+ this.validityCache.set(level, !globallyInvalid);
41
+ }
42
+ }
43
+ let total = 0;
44
+ const results = selected.map((i) => {
45
+ const r = reconstructFeature(this.topology.features[i], this.topology.arcs, this.arcTrees, globallyInvalid ? Infinity : level, coords);
46
+ total += r.selectedVertices;
47
+ return r.feature;
48
+ });
49
+ return {
50
+ geojson: { type: "FeatureCollection", features: results },
51
+ level,
52
+ valid: !globallyInvalid,
53
+ usedFallback: globallyInvalid,
54
+ selectedFeatures: results.length,
55
+ selectedVertices: total,
56
+ };
57
+ }
58
+ }
59
+ export function buildQuadstream(input, options) {
60
+ return new QuadstreamDataset(input, options);
61
+ }
@@ -0,0 +1,13 @@
1
+ import type { Bounds, Position } from "./types.js";
2
+ export declare function assertPosition(value: unknown): Position;
3
+ export declare function boundsOf(points: readonly Position[]): Bounds;
4
+ export declare function unionBounds(a: Bounds, b: Bounds): Bounds;
5
+ export declare function intersects(a: Bounds, b: Bounds): boolean;
6
+ export declare function assertBounds(b: Bounds): Bounds;
7
+ export declare function signedArea(ring: readonly Position[]): number;
8
+ /** Includes touching endpoints; callers skip adjacent polygon edges. */
9
+ export declare function segmentsIntersect(a: Position, b: Position, c: Position, d: Position): boolean;
10
+ /** O(n^2) reference predicate; safe but not intended as the final large-data validator. */
11
+ export declare function simpleClosedRing(ring: readonly Position[]): boolean;
12
+ export declare function pointInRing(p: Position, ring: readonly Position[]): boolean;
13
+ export declare function validPolygon(rings: readonly Position[][]): boolean;
@@ -0,0 +1,126 @@
1
+ export function assertPosition(value) {
2
+ if (!Array.isArray(value) ||
3
+ value.length !== 2 ||
4
+ !value.every((v) => typeof v === "number" && Number.isFinite(v))) {
5
+ throw new Error("Coordinates must be finite planar [x, y] pairs");
6
+ }
7
+ return [
8
+ Object.is(value[0], -0) ? 0 : value[0],
9
+ Object.is(value[1], -0) ? 0 : value[1],
10
+ ];
11
+ }
12
+ export function boundsOf(points) {
13
+ if (!points.length)
14
+ throw new Error("Cannot construct bounds of empty coordinates");
15
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
16
+ for (const [x, y] of points) {
17
+ x0 = Math.min(x0, x);
18
+ y0 = Math.min(y0, y);
19
+ x1 = Math.max(x1, x);
20
+ y1 = Math.max(y1, y);
21
+ }
22
+ return [x0, y0, x1, y1];
23
+ }
24
+ export function unionBounds(a, b) {
25
+ return [
26
+ Math.min(a[0], b[0]),
27
+ Math.min(a[1], b[1]),
28
+ Math.max(a[2], b[2]),
29
+ Math.max(a[3], b[3]),
30
+ ];
31
+ }
32
+ export function intersects(a, b) {
33
+ return a[0] <= b[2] && a[2] >= b[0] && a[1] <= b[3] && a[3] >= b[1];
34
+ }
35
+ export function assertBounds(b) {
36
+ if (!Array.isArray(b) ||
37
+ b.length !== 4 ||
38
+ !b.every(Number.isFinite) ||
39
+ b[0] > b[2] ||
40
+ b[1] > b[3])
41
+ throw new Error("Invalid [xmin,ymin,xmax,ymax] bounds");
42
+ return b;
43
+ }
44
+ export function signedArea(ring) {
45
+ let a = 0;
46
+ for (let i = 0; i < ring.length - 1; i++) {
47
+ const p = ring[i], q = ring[i + 1];
48
+ a += p[0] * q[1] - q[0] * p[1];
49
+ }
50
+ return a / 2;
51
+ }
52
+ function orientation(a, b, c) {
53
+ return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
54
+ }
55
+ function within(a, b, p) {
56
+ return (Math.min(a[0], b[0]) <= p[0] &&
57
+ p[0] <= Math.max(a[0], b[0]) &&
58
+ Math.min(a[1], b[1]) <= p[1] &&
59
+ p[1] <= Math.max(a[1], b[1]));
60
+ }
61
+ /** Includes touching endpoints; callers skip adjacent polygon edges. */
62
+ export function segmentsIntersect(a, b, c, d) {
63
+ const abC = orientation(a, b, c), abD = orientation(a, b, d), cdA = orientation(c, d, a), cdB = orientation(c, d, b);
64
+ if (((abC > 0 && abD < 0) || (abC < 0 && abD > 0)) &&
65
+ ((cdA > 0 && cdB < 0) || (cdA < 0 && cdB > 0)))
66
+ return true;
67
+ return ((abC === 0 && within(a, b, c)) ||
68
+ (abD === 0 && within(a, b, d)) ||
69
+ (cdA === 0 && within(c, d, a)) ||
70
+ (cdB === 0 && within(c, d, b)));
71
+ }
72
+ function same(a, b) {
73
+ return a[0] === b[0] && a[1] === b[1];
74
+ }
75
+ /** O(n^2) reference predicate; safe but not intended as the final large-data validator. */
76
+ export function simpleClosedRing(ring) {
77
+ const n = ring.length - 1;
78
+ if (n < 3 || !same(ring[0], ring[n]) || signedArea(ring) === 0)
79
+ return false;
80
+ for (let i = 0; i < n; i++) {
81
+ if (same(ring[i], ring[i + 1]))
82
+ return false;
83
+ for (let j = i + 1; j < n; j++) {
84
+ if (j === i + 1 || (i === 0 && j === n - 1))
85
+ continue;
86
+ if (segmentsIntersect(ring[i], ring[i + 1], ring[j], ring[j + 1]))
87
+ return false;
88
+ }
89
+ }
90
+ return true;
91
+ }
92
+ export function pointInRing(p, ring) {
93
+ let inside = false;
94
+ for (let i = 0, j = ring.length - 2; i < ring.length - 1; j = i++) {
95
+ const a = ring[i], b = ring[j];
96
+ if (orientation(a, b, p) === 0 && within(a, b, p))
97
+ return true;
98
+ if (a[1] > p[1] !== b[1] > p[1] &&
99
+ p[0] < ((b[0] - a[0]) * (p[1] - a[1])) / (b[1] - a[1]) + a[0])
100
+ inside = !inside;
101
+ }
102
+ return inside;
103
+ }
104
+ function ringsIntersect(a, b) {
105
+ for (let i = 0; i < a.length - 1; i++)
106
+ for (let j = 0; j < b.length - 1; j++)
107
+ if (segmentsIntersect(a[i], a[i + 1], b[j], b[j + 1]))
108
+ return true;
109
+ return false;
110
+ }
111
+ export function validPolygon(rings) {
112
+ if (!rings.length || rings.some((r) => !simpleClosedRing(r)))
113
+ return false;
114
+ for (let i = 1; i < rings.length; i++) {
115
+ if (!pointInRing(rings[i][0], rings[0]) ||
116
+ ringsIntersect(rings[0], rings[i]))
117
+ return false;
118
+ for (let j = 1; j < i; j++) {
119
+ if (ringsIntersect(rings[j], rings[i]) ||
120
+ pointInRing(rings[i][0], rings[j]) ||
121
+ pointInRing(rings[j][0], rings[i]))
122
+ return false;
123
+ }
124
+ }
125
+ return true;
126
+ }
@@ -0,0 +1,22 @@
1
+ export { buildQuadstream, QuadstreamDataset } from "./dataset.js";
2
+ export { buildTopology } from "./topology.js";
3
+ export { buildSparseQuadtree, cellKey, cellAddress } from "./quadtree.js";
4
+ export { buildBlgTree, selectBlgPositions, stableBlgRandom, assertBlgInvariants, } from "./blg.js";
5
+ export { createSpatialIndex } from "./spatial-index.js";
6
+ export { exportPartitions, encodePartition, decodePartition, checksum, requiredPartitionKeys, partitionsWithVerticesInBounds, } from "./partition.js";
7
+ export { QuadstreamSession } from "./session.js";
8
+ export { QuadstreamLoader, fetchFromBundle } from "./loader.js";
9
+ export type { PartitionFetcher, LoaderOptions } from "./loader.js";
10
+ export { validPolygon, simpleClosedRing, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
11
+ export type * from "./types.js";
12
+ export { importGeoJSON, exportGeoJSON, importTopoJSON, exportTopoJSON, } from "./adapters.js";
13
+ export type { TopoJSONTopology } from "./adapters.js";
14
+ export { validateManifest, MANIFEST_VERSION } from "./manifest-schema.js";
15
+ export { ProgressiveMap } from "./progressive-map.js";
16
+ export type { MapQuery, MapFrame, ProgressiveMapClient, } from "./progressive-map.js";
17
+ export { attachMapLibre, mapLibreBounds } from "./maplibre-adapter.js";
18
+ export type { MapLibreLike, MapLibreAdapterOptions, } from "./maplibre-adapter.js";
19
+ export { canonicalLonLat, lonLatVector, angularDistance, validGreatCirclePath, sphericalCellAddress, buildSphericalPriorities, sphericalChart, projectSpherical, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
20
+ export type { UnitVector, CubeFace, SphericalCell, SphericalPriorities, SphericalChart, SphericalPolygonSignature, } from "./spherical-geometry.js";
21
+ export { SphericalQuadstreamDataset, buildSphericalQuadstream, importSphericalTopoJSON, } from "./spherical-dataset.js";
22
+ export type { SphericalQueryOptions } from "./spherical-dataset.js";
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ export { buildQuadstream, QuadstreamDataset } from "./dataset.js";
2
+ export { buildTopology } from "./topology.js";
3
+ export { buildSparseQuadtree, cellKey, cellAddress } from "./quadtree.js";
4
+ export { buildBlgTree, selectBlgPositions, stableBlgRandom, assertBlgInvariants, } from "./blg.js";
5
+ export { createSpatialIndex } from "./spatial-index.js";
6
+ export { exportPartitions, encodePartition, decodePartition, checksum, requiredPartitionKeys, partitionsWithVerticesInBounds, } from "./partition.js";
7
+ export { QuadstreamSession } from "./session.js";
8
+ export { QuadstreamLoader, fetchFromBundle } from "./loader.js";
9
+ export { validPolygon, simpleClosedRing, segmentsIntersect, pointInRing, intersects, boundsOf, } from "./geometry.js";
10
+ export { importGeoJSON, exportGeoJSON, importTopoJSON, exportTopoJSON, } from "./adapters.js";
11
+ export { validateManifest, MANIFEST_VERSION } from "./manifest-schema.js";
12
+ export { ProgressiveMap } from "./progressive-map.js";
13
+ export { attachMapLibre, mapLibreBounds } from "./maplibre-adapter.js";
14
+ export { canonicalLonLat, lonLatVector, angularDistance, validGreatCirclePath, sphericalCellAddress, buildSphericalPriorities, sphericalChart, projectSpherical, sphericalPolygonSignature, validSphericalPolygon, } from "./spherical-geometry.js";
15
+ export { SphericalQuadstreamDataset, buildSphericalQuadstream, importSphericalTopoJSON, } from "./spherical-dataset.js";
@@ -0,0 +1,34 @@
1
+ import { QuadstreamSession } from "./session.js";
2
+ import type { QueryOptions, PartitionBundle } from "./types.js";
3
+ export type PartitionFetcher = (key: string, context: {
4
+ signal: AbortSignal;
5
+ }) => Promise<Uint8Array>;
6
+ export interface LoaderOptions {
7
+ /** Maximum concurrent fetches *per request*; default 4. */
8
+ concurrency?: number;
9
+ /** Limit for the optional raw-byte LRU. Parsed vertices remain in the session. */
10
+ cacheBytes?: number;
11
+ }
12
+ /** Optional, transport-independent loader around a validated progressive session. */
13
+ export declare class QuadstreamLoader {
14
+ readonly session: QuadstreamSession;
15
+ private readonly fetchPartition;
16
+ private readonly concurrency;
17
+ private readonly cacheLimit;
18
+ private readonly cache;
19
+ private cachedBytes;
20
+ private latestRequest?;
21
+ constructor(session: QuadstreamSession, fetchPartition: PartitionFetcher, options?: LoaderOptions);
22
+ get cachedPartitionKeys(): string[];
23
+ get cacheSizeBytes(): number;
24
+ private remember;
25
+ /** Lazily fetch partitions required for this level. Already ingested keys are skipped. */
26
+ ensureLevel(level: number, options?: {
27
+ signal?: AbortSignal;
28
+ }): Promise<void>;
29
+ /** Supersede the preceding latest-view request without clearing valid stored geometry. */
30
+ loadLatest(query?: QueryOptions): Promise<ReturnType<QuadstreamSession["query"]>>;
31
+ cancelLatest(): void;
32
+ }
33
+ /** In-memory adapter for examples and deterministic end-to-end tests. */
34
+ export declare function fetchFromBundle(bundle: PartitionBundle): PartitionFetcher;