@duoquote/polytini 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +120 -3
- package/dist/deckgl.cjs +250 -0
- package/dist/flexible.cjs +229 -0
- package/dist/google.cjs +232 -0
- package/dist/leaflet-auto.cjs +209 -0
- package/dist/leaflet.cjs +231 -0
- package/dist/mapbox.cjs +185 -0
- package/dist/maplibre.cjs +185 -0
- package/dist/node.cjs +322 -0
- package/dist/presets.cjs +65 -0
- package/dist/turf.cjs +267 -0
- package/dist/types/cli.d.cts +2 -0
- package/dist/types/deckgl.d.cts +60 -0
- package/dist/types/flexible.d.cts +80 -0
- package/dist/types/google.d.cts +48 -0
- package/dist/types/google.jsr.d.cts +60 -0
- package/dist/types/index.d.cts +87 -0
- package/dist/types/leaflet-auto.d.cts +4 -0
- package/dist/types/leaflet-auto.jsr.d.cts +2 -0
- package/dist/types/leaflet.d.cts +39 -0
- package/dist/types/leaflet.jsr.d.cts +13 -0
- package/dist/types/mapbox.d.cts +50 -0
- package/dist/types/maplibre.d.cts +54 -0
- package/dist/types/openlayers.d.cts +23 -0
- package/dist/types/presets.d.cts +66 -0
- package/dist/types/turf.d.cts +33 -0
- package/dist/types/wasm.d.cts +33 -0
- package/dist/web.cjs +231 -0
- package/package.json +200 -6
- package/src/browser.js +15 -0
- package/src/bun.js +4 -0
- package/src/cli-lib.js +160 -0
- package/src/cli.js +7 -0
- package/src/core.js +268 -0
- package/src/deckgl.js +176 -0
- package/src/deno.js +12 -0
- package/src/error.js +15 -0
- package/src/fast.js +179 -0
- package/src/flexible.js +283 -0
- package/src/google.js +70 -0
- package/src/leaflet-auto.js +11 -0
- package/src/leaflet.js +44 -0
- package/src/mapbox.js +10 -0
- package/src/maplibre.js +57 -0
- package/src/node.js +17 -0
- package/src/openlayers.js +172 -0
- package/src/presets.js +242 -0
- package/src/text.js +111 -0
- package/src/turf.js +80 -0
- package/src/wasm-bytes.js +2 -0
- package/src/wasm.js +235 -0
- package/src/web.js +9 -0
- package/types/cli.d.ts +2 -0
- package/types/deckgl.d.ts +60 -0
- package/types/flexible.d.ts +80 -0
- package/types/google.d.ts +48 -0
- package/types/google.jsr.d.ts +60 -0
- package/types/index.d.ts +87 -0
- package/types/leaflet-auto.d.ts +4 -0
- package/types/leaflet-auto.jsr.d.ts +2 -0
- package/types/leaflet.d.ts +39 -0
- package/types/leaflet.jsr.d.ts +13 -0
- package/types/mapbox.d.ts +50 -0
- package/types/maplibre.d.ts +54 -0
- package/types/openlayers.d.ts +23 -0
- package/types/presets.d.ts +66 -0
- package/types/turf.d.ts +33 -0
- package/types/wasm.d.ts +33 -0
- package/wasm/polytini.wasm +0 -0
package/src/text.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Byte-buffer paths through TextEncoder/TextDecoder, for runtimes without
|
|
2
|
+
// Node's Buffer where those are fast: Deno. Measured on Deno 2.5 with the
|
|
3
|
+
// benchmark fixtures (see "Platform notes" in the README):
|
|
4
|
+
//
|
|
5
|
+
// - Decode: encodeInto copies the string into a reused Uint8Array, then the
|
|
6
|
+
// loop reads bytes instead of calling charCodeAt. 20 to 35% faster from 100
|
|
7
|
+
// points up. Any non-ASCII character makes `written` differ from the
|
|
8
|
+
// length, and those strings go to the exact slow path, so strict mode stays
|
|
9
|
+
// exact. Under 64 characters the copy costs more than it saves.
|
|
10
|
+
// - Encode: bytes into a reused buffer, then one TextDecoder call. 30 to 60%
|
|
11
|
+
// faster from 1,000 points up, but the call has a fixed cost that made
|
|
12
|
+
// lines of a few hundred points slower than the core's string building, so
|
|
13
|
+
// it starts at 512 points.
|
|
14
|
+
import { opts, st, LIMIT, slowDecode, slowEncode, decodeLoop, flip, encode as coreEncode, encodeFlat as coreEncodeFlat } from './core.js';
|
|
15
|
+
|
|
16
|
+
const te = new TextEncoder(), td = new TextDecoder('latin1');
|
|
17
|
+
// Reused up to 1 MB, like the Buffer paths.
|
|
18
|
+
let kept = new Uint8Array(1 << 14);
|
|
19
|
+
const scratch = (n) => (n <= kept.length ? kept : n <= 1 << 20 ? (kept = new Uint8Array(n)) : new Uint8Array(n));
|
|
20
|
+
|
|
21
|
+
function big(str, f, sw, flat) {
|
|
22
|
+
const len = str.length, b = scratch(len + 8);
|
|
23
|
+
if (te.encodeInto(str, b).written != len) return null;
|
|
24
|
+
// '?' padding: a truncated string stops inside the buffer, past len.
|
|
25
|
+
b[len] = b[len + 1] = 63;
|
|
26
|
+
let t = 0;
|
|
27
|
+
for (let k = 0; k < len; k++) t += (b[k] - 95) >>> 31;
|
|
28
|
+
const out = flat ? new Float64Array(t & ~1) : Array(t >> 1), a = +sw;
|
|
29
|
+
let i = 0, n = 0, lat = 0, lng = 0, bad = 0, c, v, s;
|
|
30
|
+
while (i < len) {
|
|
31
|
+
c = b[i++] - 63;
|
|
32
|
+
bad |= c;
|
|
33
|
+
v = c & 31;
|
|
34
|
+
for (s = 5; c >= 32; s += 5) {
|
|
35
|
+
c = b[i++] - 63;
|
|
36
|
+
bad |= c | (25 - s);
|
|
37
|
+
v |= (c & 31) << s;
|
|
38
|
+
}
|
|
39
|
+
lat += (v >>> 1) ^ -(v & 1);
|
|
40
|
+
c = b[i++] - 63;
|
|
41
|
+
bad |= c;
|
|
42
|
+
v = c & 31;
|
|
43
|
+
for (s = 5; c >= 32; s += 5) {
|
|
44
|
+
c = b[i++] - 63;
|
|
45
|
+
bad |= c | (25 - s);
|
|
46
|
+
v |= (c & 31) << s;
|
|
47
|
+
}
|
|
48
|
+
lng += (v >>> 1) ^ -(v & 1);
|
|
49
|
+
if (flat) {
|
|
50
|
+
out[n + a] = lat / f;
|
|
51
|
+
out[n + 1 - a] = lng / f;
|
|
52
|
+
n += 2;
|
|
53
|
+
} else out[n++] = [lat / f, lng / f];
|
|
54
|
+
}
|
|
55
|
+
return bad & ~63 || i != len ? null : out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const decodeWith = (str, o, flat) => {
|
|
59
|
+
const f = opts(o);
|
|
60
|
+
if (st.dims != 2 || typeof str != 'string') return slowDecode(str, f, flat);
|
|
61
|
+
const out = (str.length < 64 ? decodeLoop : big)(str, f, st.swap, flat);
|
|
62
|
+
return out ? (st.swap && !flat ? flip(out) : out) : slowDecode(str, f, flat);
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
function encodeLoop(src, f, a, flat) {
|
|
66
|
+
const n = flat ? src.length >> 1 : src.length, b = scratch(n * 14 + 8);
|
|
67
|
+
let i = 0, k = 0, la = 0, lb = 0, x, y, p, q, z, pt;
|
|
68
|
+
try {
|
|
69
|
+
for (; i < n; i++) {
|
|
70
|
+
if (flat) {
|
|
71
|
+
x = src[i * 2 + a];
|
|
72
|
+
y = src[i * 2 + 1 - a];
|
|
73
|
+
} else {
|
|
74
|
+
pt = src[i];
|
|
75
|
+
x = pt[a];
|
|
76
|
+
y = pt[1 - a];
|
|
77
|
+
}
|
|
78
|
+
if (typeof x != 'number' || typeof y != 'number' || !((x *= f) < LIMIT && x > -LIMIT && (y *= f) < LIMIT && y > -LIMIT)) return null;
|
|
79
|
+
// Half away from zero, the same way as core.js.
|
|
80
|
+
p = x < 0 ? -((0.5 - x) | 0) : (x + 0.5) | 0;
|
|
81
|
+
q = y < 0 ? -((0.5 - y) | 0) : (y + 0.5) | 0;
|
|
82
|
+
if (x < 0.5 && x > -0.5) p = 0;
|
|
83
|
+
if (y < 0.5 && y > -0.5) q = 0;
|
|
84
|
+
z = p - la;
|
|
85
|
+
z = (z << 1) ^ (z >> 31);
|
|
86
|
+
for (; z >= 32; z >>>= 5) b[k++] = (z & 31) + 95;
|
|
87
|
+
b[k++] = z + 63;
|
|
88
|
+
z = q - lb;
|
|
89
|
+
z = (z << 1) ^ (z >> 31);
|
|
90
|
+
for (; z >= 32; z >>>= 5) b[k++] = (z & 31) + 95;
|
|
91
|
+
b[k++] = z + 63;
|
|
92
|
+
la = p;
|
|
93
|
+
lb = q;
|
|
94
|
+
}
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
return td.decode(b.subarray(0, k));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const encodeWith = (src, o, flat, core) => {
|
|
102
|
+
// Short lines: the core's string building is faster than a TextDecoder call.
|
|
103
|
+
if (!(src?.length >= (flat ? 1024 : 512))) return core(src, o);
|
|
104
|
+
const f = opts(o);
|
|
105
|
+
return (st.dims == 2 && f <= 1e6 && (flat ? !(src.length % 2) : Array.isArray(src)) ? encodeLoop(src, f, +st.swap, flat) : null) ?? slowEncode(src, f, flat);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export const decode = (str, o) => decodeWith(str, o, 0);
|
|
109
|
+
export const decodeFlat = (str, o) => decodeWith(str, o, 1);
|
|
110
|
+
export const encode = (src, o) => encodeWith(src, o, 0, coreEncode);
|
|
111
|
+
export const encodeFlat = (src, o) => encodeWith(src, o, 1, coreEncodeFlat);
|
package/src/turf.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Turf.js interop: decode straight to GeoJSON Features in Turf's shape, and
|
|
2
|
+
// encode whatever Turf hands back. No Turf code is imported; the types come
|
|
3
|
+
// from @turf/helpers and geojson.
|
|
4
|
+
//
|
|
5
|
+
// import { toFeature, fromGeoJSON } from '@duoquote/polytini/turf';
|
|
6
|
+
// const km = turf.length(toFeature(route.geometry, { precision: 6 }));
|
|
7
|
+
// const [simplified] = fromGeoJSON(turf.simplify(toFeature(str), { tolerance: 0.001 }));
|
|
8
|
+
/* @ts-self-types="../types/turf.d.ts" */
|
|
9
|
+
import { decode, encode } from './web.js';
|
|
10
|
+
import { fail } from './error.js';
|
|
11
|
+
|
|
12
|
+
const lngLat = (o) => ({ ...(typeof o == 'number' ? { precision: o } : o), order: 'lnglat' });
|
|
13
|
+
|
|
14
|
+
// [west, south, east, north] over every position of nested arrays.
|
|
15
|
+
function bbox(c) {
|
|
16
|
+
const b = [1 / 0, 1 / 0, -1 / 0, -1 / 0];
|
|
17
|
+
const walk = (a) => {
|
|
18
|
+
if (typeof a[0] == 'number') {
|
|
19
|
+
b[0] = Math.min(b[0], a[0]);
|
|
20
|
+
b[1] = Math.min(b[1], a[1]);
|
|
21
|
+
b[2] = Math.max(b[2], a[0]);
|
|
22
|
+
b[3] = Math.max(b[3], a[1]);
|
|
23
|
+
} else a.forEach(walk);
|
|
24
|
+
};
|
|
25
|
+
walk(c);
|
|
26
|
+
return b;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Turf's feature() shape: type, id, bbox, properties, geometry.
|
|
30
|
+
function feature(geometry, o, i) {
|
|
31
|
+
const f = { type: 'Feature' }, p = o?.properties;
|
|
32
|
+
if (o?.id != null) f.id = Array.isArray(o.id) ? o.id[i] : o.id;
|
|
33
|
+
if (o?.bbox && geometry.coordinates.length) f.bbox = bbox(geometry.coordinates);
|
|
34
|
+
f.properties = (Array.isArray(p) ? p[i] : p) ?? {};
|
|
35
|
+
f.geometry = geometry;
|
|
36
|
+
return f;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A Feature<LineString> from one encoded line. Options: polytini options plus properties, id and bbox. */
|
|
40
|
+
export const toFeature = (str, o, i) => feature({ type: 'LineString', coordinates: decode(str, lngLat(o)) }, o, i);
|
|
41
|
+
|
|
42
|
+
/** A FeatureCollection<LineString>, one Feature per string. properties and id may be arrays, one per line. */
|
|
43
|
+
export const toFeatureCollection = (strs, o) => ({ type: 'FeatureCollection', features: strs.map((s, i) => toFeature(s, o, i)) });
|
|
44
|
+
|
|
45
|
+
/** A Feature<Polygon> from encoded rings: the outer ring first, then holes, like Google's encoded polygons. */
|
|
46
|
+
export const toPolygonFeature = (rings, o) => feature({ type: 'Polygon', coordinates: rings.map((s) => decode(s, lngLat(o))) }, o, 0);
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Encodes every line in any GeoJSON object: a LineString, each part of a
|
|
50
|
+
* MultiLineString, each ring of a Polygon or MultiPolygon, recursing into
|
|
51
|
+
* Features, FeatureCollections and GeometryCollections. Points are skipped.
|
|
52
|
+
* Always returns an array of strings, in document order.
|
|
53
|
+
*/
|
|
54
|
+
export function fromGeoJSON(g, o) {
|
|
55
|
+
const out = [], ll = lngLat(o);
|
|
56
|
+
const walk = (g) => {
|
|
57
|
+
switch (g?.type) {
|
|
58
|
+
case 'Feature':
|
|
59
|
+
return g.geometry && walk(g.geometry);
|
|
60
|
+
case 'FeatureCollection':
|
|
61
|
+
return g.features.forEach(walk);
|
|
62
|
+
case 'GeometryCollection':
|
|
63
|
+
return g.geometries.forEach(walk);
|
|
64
|
+
case 'LineString':
|
|
65
|
+
return out.push(encode(g.coordinates, ll));
|
|
66
|
+
case 'MultiLineString':
|
|
67
|
+
case 'Polygon':
|
|
68
|
+
return g.coordinates.forEach((c) => out.push(encode(c, ll)));
|
|
69
|
+
case 'MultiPolygon':
|
|
70
|
+
return g.coordinates.forEach((p) => p.forEach((c) => out.push(encode(c, ll))));
|
|
71
|
+
case 'Point':
|
|
72
|
+
case 'MultiPoint':
|
|
73
|
+
return;
|
|
74
|
+
default:
|
|
75
|
+
fail('input', 'Expected GeoJSON');
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
walk(g);
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// Generated by scripts/build-wasm.js from wasm/polytini.wat. Do not edit.
|
|
2
|
+
export default 'AGFzbQEAAAABLAVgBX9/f3x/AX9gB39/f39/fH8Bf2ABfAF/YAR/f3x/AX9gBn9/f3x/fwF/AwgHAAABAgMDBAUDAQABBzgFBm1lbW9yeQIABmRlY29kZQABC2RlY29kZV9tYW55AAIGZW5jb2RlAAULZW5jb2RlX21hbnkABgqIBgflAQEJfyAAIAFqIQUgAiEGAkADQCAAIAVPDQFBACENA0BBACEIQQAhCQNAIAAgBU8gCUEZS3IEQEF/DwsgAC0AAEE/ayEHIAwgB3IhDCAAQQFqIQAgCCAHQR9xIAl0ciEIIAlBBWohCSAHQSBODQALIAhBAXZBACAIQQFxa3MhCCANBEAgCyAIaiELBSAKIAhqIQoLIA1BAWohDSANQQJJDQALIAYgBEEDdGogCrcgA6M5AwAgBkEIaiAEQQN0ayALtyADozkDACAGQRBqIQYMAAsLIAxBQHEEQEF/DwsgBiACa0EDdgsOACAAIAEgAiADIAQQAAt6AQR/IAMhCiAEQQA2AgACQANAIAcgAk8NASABIAdBAnRqKAIAIQggACAIIAogBSAGEAAhCSAJQQBIBEBBfyAHaw8LIAogCUEDdGohCiAAIAhqIQAgB0EBaiEHIAQgB0ECdGogCiADa0EEdjYCAAwACwsgCiADa0EDdgtXAgF/AXwgAJlEAAAAAAAAwEFjRQRAQYCAgIB4DwsgAKohASAAIAG3oSECIAJEAAAAAAAA4D9mBEAgAUEBag8LIAJEAAAAAAAA4L9lBEAgAUEBaw8LIAELtAEBB38gACABQQN0aiEEIAMhBQJAA0AgACAETw0BIAArAwAgAqIQAyEGIAZBgICAgHhGBEBBfw8LIAoEQCAGIAlrIQcgBiEJBSAGIAhrIQcgBiEICyAKQQFzIQogB0EBdCAHQR91cyEHAkADQCAHQSBJDQEgBSAHQR9xQd8AajoAACAFQQFqIQUgB0EFdiEHDAALCyAFIAdBP2o6AAAgBUEBaiEFIABBCGohAAwACwsgBSADawsMACAAIAEgAiADEAQLegEFfyAEIQoCQANAIAYgAk8NASABIAZBAnRqKAIAIQcgASAGQQJ0aigCBCEIIAAgB0EEdGogCCAHa0EBdCADIAoQBCEJIAlBAEgEQEF/IAZrDwsgCiAJaiEKIAUgBkECdGogCiAEazYCACAGQQFqIQYMAAsLIAogBGsL';
|
package/src/wasm.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Opt-in WebAssembly build. Call `await init()` once (or `initSync()`), then
|
|
2
|
+
// the functions are synchronous and take the same arguments as the main
|
|
3
|
+
// entry, plus two batch functions for many lines in one call.
|
|
4
|
+
//
|
|
5
|
+
// The module (wasm/polytini.wat, under 1 KB) does the parsing and
|
|
6
|
+
// formatting. The glue keeps one instance and one memory for the whole
|
|
7
|
+
// program, grows it when an input doesn't fit, and moves data with
|
|
8
|
+
// TextEncoder.encodeInto and Buffer#latin1Slice (or TextDecoder). Anything the module doesn't handle
|
|
9
|
+
// (objects, other dimensions, bad input) goes to the JS core, so results and
|
|
10
|
+
// errors are the same as the main entry's.
|
|
11
|
+
/* @ts-self-types="../types/wasm.d.ts" */
|
|
12
|
+
import bytes from './wasm-bytes.js';
|
|
13
|
+
import { opts, st, slowDecode, slowEncode, fail, latLngs, toGeo, fromGeo, decode as jsDecode, decodeFlat as jsFlat, encode as jsEncode, encodeFlat as jsEncodeFlat } from './core.js';
|
|
14
|
+
|
|
15
|
+
export { PolylineError } from './core.js';
|
|
16
|
+
|
|
17
|
+
// The module keeps nothing in its memory, so the glue uses all of it.
|
|
18
|
+
const base = 0;
|
|
19
|
+
let ex, mem, u8, f64, u32, input, size = 0;
|
|
20
|
+
// Deno has a global Buffer too, but its latin1Slice is a JS polyfill that
|
|
21
|
+
// made encoding 2 times slower there than TextDecoder.
|
|
22
|
+
const latin1Slice = !globalThis.Deno && globalThis.Buffer?.prototype.latin1Slice;
|
|
23
|
+
const te = new TextEncoder(), td = new TextDecoder('latin1');
|
|
24
|
+
|
|
25
|
+
const bin = () => Uint8Array.from(atob(bytes), (c) => c.charCodeAt(0));
|
|
26
|
+
const ready = (instance) => {
|
|
27
|
+
ex = instance.exports;
|
|
28
|
+
mem = ex.memory;
|
|
29
|
+
views();
|
|
30
|
+
};
|
|
31
|
+
const views = () => {
|
|
32
|
+
u8 = new Uint8Array(mem.buffer);
|
|
33
|
+
f64 = new Float64Array(mem.buffer);
|
|
34
|
+
u32 = new Uint32Array(mem.buffer);
|
|
35
|
+
size = u8.length;
|
|
36
|
+
// encodeInto writes at the start of its target, so keep one view at base.
|
|
37
|
+
input = u8.subarray(base);
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/** Compiles and instantiates the module. Safe to call more than once. */
|
|
41
|
+
export async function init() {
|
|
42
|
+
if (!ex) ready((await WebAssembly.instantiate(bin())).instance);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Synchronous init. Browsers allow it here because the module is small. */
|
|
46
|
+
export function initSync() {
|
|
47
|
+
if (!ex) ready(new WebAssembly.Instance(new WebAssembly.Module(bin())));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Makes sure `n` bytes past base exist. The memory only grows, so a big
|
|
51
|
+
// line costs its memory once, not on every call.
|
|
52
|
+
function room(n) {
|
|
53
|
+
if (!ex) fail('init', 'Call init() before using polytini/wasm');
|
|
54
|
+
const need = base + n - size;
|
|
55
|
+
if (need > 0) {
|
|
56
|
+
mem.grow(Math.ceil(need / 65536));
|
|
57
|
+
views();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const align = (n) => (n + 15) & ~7;
|
|
62
|
+
const text = (a, b) => (latin1Slice ? latin1Slice.call(u8, a, b) : td.decode(u8.subarray(a, b)));
|
|
63
|
+
|
|
64
|
+
// Copies an ASCII string to base. False when it isn't ASCII, which the JS
|
|
65
|
+
// core then reports.
|
|
66
|
+
const put = (str, len) => te.encodeInto(str, input).written == len;
|
|
67
|
+
|
|
68
|
+
// Decodes str to f64 pairs in memory. Returns [offset in f64s, count], or
|
|
69
|
+
// null when the JS core has to handle it.
|
|
70
|
+
function run(str, f) {
|
|
71
|
+
const len = str.length, out = base + align(len);
|
|
72
|
+
room(align(len) + len * 8 + 16);
|
|
73
|
+
if (!put(str, len)) return null;
|
|
74
|
+
const k = ex.decode(base, len, out, f, +st.swap);
|
|
75
|
+
return k < 0 ? null : [out >> 3, k];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Lines this short are faster in JS on every runtime measured: the call and
|
|
79
|
+
// moving the data in and out cost more than the work. About 30 points.
|
|
80
|
+
const SHORT = 128;
|
|
81
|
+
|
|
82
|
+
export function decodeFlat(str, o) {
|
|
83
|
+
if (typeof str == 'string' && str.length < SHORT) return jsFlat(str, o);
|
|
84
|
+
const f = opts(o);
|
|
85
|
+
if (typeof str != 'string') fail('input', 'Expected a string');
|
|
86
|
+
const r = st.dims == 2 && run(str, f);
|
|
87
|
+
return r ? f64.slice(r[0], r[0] + r[1]) : slowDecode(str, f, 1);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// [lat, lng] tuples come from the JS decoder. Building one array per point
|
|
91
|
+
// is most of the work, and reading the numbers back out of WASM memory only
|
|
92
|
+
// added to it: the WASM version was 15 to 40% slower at every size.
|
|
93
|
+
export const decode = (str, o) => jsDecode(str, o);
|
|
94
|
+
|
|
95
|
+
// f64 values at base to a string.
|
|
96
|
+
function finish(values, f) {
|
|
97
|
+
const out = base + values * 8;
|
|
98
|
+
const k = ex.encode(base, values, f, out);
|
|
99
|
+
return k < 0 ? null : text(out, out + k);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function encode(points, o) {
|
|
103
|
+
if (points?.length < SHORT / 4) return jsEncode(points, o);
|
|
104
|
+
const f = opts(o);
|
|
105
|
+
if (st.dims != 2 || !Array.isArray(points)) return slowEncode(points, f);
|
|
106
|
+
const n = points.length, a = +st.swap, b = 1 - a;
|
|
107
|
+
room(n * 16 + n * 14 + 16);
|
|
108
|
+
const m = f64;
|
|
109
|
+
try {
|
|
110
|
+
for (let i = 0, j = 0; i < n; i++, j += 2) {
|
|
111
|
+
const p = points[i], x = p[a], y = p[b];
|
|
112
|
+
// A Float64Array store would turn null into 0 and '1' into 1.
|
|
113
|
+
if (typeof x != 'number' || typeof y != 'number') return slowEncode(points, f);
|
|
114
|
+
m[j] = x;
|
|
115
|
+
m[j + 1] = y;
|
|
116
|
+
}
|
|
117
|
+
} catch {
|
|
118
|
+
// A null or missing point.
|
|
119
|
+
return slowEncode(points, f);
|
|
120
|
+
}
|
|
121
|
+
return finish(n * 2, f) ?? slowEncode(points, f);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function encodeFlat(values, o) {
|
|
125
|
+
if (values?.length < SHORT / 2) return jsEncodeFlat(values, o);
|
|
126
|
+
const f = opts(o);
|
|
127
|
+
if (st.dims != 2 || values == null || values.length % 2) return slowEncode(values, f, 1);
|
|
128
|
+
const n = values.length;
|
|
129
|
+
room(n * 8 + n * 7 + 16);
|
|
130
|
+
if (!(values instanceof Float64Array || values instanceof Float32Array)) {
|
|
131
|
+
for (let i = 0; i < n; i++) if (typeof values[i] != 'number') return slowEncode(values, f, 1);
|
|
132
|
+
}
|
|
133
|
+
const at = base >> 3;
|
|
134
|
+
if (st.swap) for (let i = 0; i < n; i += 2) (f64[at + i] = values[i + 1]), (f64[at + i + 1] = values[i]);
|
|
135
|
+
else f64.set(values, at);
|
|
136
|
+
return finish(n, f) ?? slowEncode(values, f, 1);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Decodes many lines in one call into one Float64Array of lat/lng pairs,
|
|
141
|
+
* plus `starts`: the first point of each line, and the total point count
|
|
142
|
+
* at the end, as deck.gl's binary paths expect.
|
|
143
|
+
*/
|
|
144
|
+
export function decodeMany(lines, o) {
|
|
145
|
+
const f = opts(o);
|
|
146
|
+
if (!Array.isArray(lines)) fail('input', 'Expected an array of strings');
|
|
147
|
+
const count = lines.length;
|
|
148
|
+
let len = 0;
|
|
149
|
+
for (let i = 0; i < count; i++) {
|
|
150
|
+
if (typeof lines[i] != 'string') return many(lines, o);
|
|
151
|
+
len += lines[i].length;
|
|
152
|
+
}
|
|
153
|
+
if (st.dims != 2) return many(lines, o);
|
|
154
|
+
const lens = base + align(len), out = lens + align(count * 4), starts = out + len * 8 + 8;
|
|
155
|
+
room(starts - base + count * 4 + 16);
|
|
156
|
+
if (!put(lines.join(''), len)) return many(lines, o);
|
|
157
|
+
const L = u32, l0 = lens >> 2;
|
|
158
|
+
for (let i = 0; i < count; i++) L[l0 + i] = lines[i].length;
|
|
159
|
+
const k = ex.decode_many(base, lens, count, out, starts, f, +st.swap);
|
|
160
|
+
if (k < 0) return many(lines, o);
|
|
161
|
+
return { coords: f64.slice(out >> 3, (out >> 3) + k), starts: u32.slice(starts >> 2, (starts >> 2) + count + 1) };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// The JS path for decodeMany, for bad lines (strict mode throws on the
|
|
165
|
+
// first one) and anything the module doesn't take.
|
|
166
|
+
function many(lines, o) {
|
|
167
|
+
const parts = lines.map((s) => jsFlat(s, o)), starts = new Uint32Array(parts.length + 1);
|
|
168
|
+
let n = 0;
|
|
169
|
+
parts.forEach((p, i) => (starts[i + 1] = n += p.length / st.dims));
|
|
170
|
+
const coords = new Float64Array(n * st.dims);
|
|
171
|
+
let at = 0;
|
|
172
|
+
for (const p of parts) coords.set(p, (at += p.length) - p.length);
|
|
173
|
+
return { coords, starts };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Encodes many lines in one call. Takes an array of point arrays, or the
|
|
178
|
+
* { coords, starts } shape decodeMany returns. Returns one string per line.
|
|
179
|
+
*/
|
|
180
|
+
export function encodeMany(lines, o) {
|
|
181
|
+
const f = opts(o);
|
|
182
|
+
if (st.dims != 2) return toLines(lines).map((l) => slowEncode(l, f, ArrayBuffer.isView(l) ? 1 : 0));
|
|
183
|
+
let coords, starts, count;
|
|
184
|
+
if (Array.isArray(lines)) {
|
|
185
|
+
count = lines.length;
|
|
186
|
+
let n = 0;
|
|
187
|
+
for (const l of lines) {
|
|
188
|
+
if (!Array.isArray(l)) return lines.map((x) => jsEncode(x, o));
|
|
189
|
+
n += l.length;
|
|
190
|
+
}
|
|
191
|
+
room(n * 16 + count * 8 + n * 14 + 64);
|
|
192
|
+
const a = +st.swap, b = 1 - a, m = f64, S = u32, s0 = (base + n * 16) >> 2;
|
|
193
|
+
let j = base >> 3, k = 0;
|
|
194
|
+
S[s0] = 0;
|
|
195
|
+
try {
|
|
196
|
+
for (let i = 0; i < count; i++) {
|
|
197
|
+
const l = lines[i], len = l.length;
|
|
198
|
+
for (let q = 0; q < len; q++) {
|
|
199
|
+
const p = l[q], x = p[a], y = p[b];
|
|
200
|
+
if (typeof x != 'number' || typeof y != 'number') return lines.map((x) => jsEncode(x, o));
|
|
201
|
+
m[j++] = x;
|
|
202
|
+
m[j++] = y;
|
|
203
|
+
}
|
|
204
|
+
S[s0 + i + 1] = k += len;
|
|
205
|
+
}
|
|
206
|
+
} catch {
|
|
207
|
+
return lines.map((x) => jsEncode(x, o));
|
|
208
|
+
}
|
|
209
|
+
return manyOut(base + n * 16, count, n, f) ?? lines.map((x) => jsEncode(x, o));
|
|
210
|
+
}
|
|
211
|
+
({ coords, starts } = lines ?? {});
|
|
212
|
+
if (!coords || !starts) fail('input', 'Expected an array of lines or { coords, starts }');
|
|
213
|
+
count = starts.length - 1;
|
|
214
|
+
const n = coords.length >> 1;
|
|
215
|
+
room(n * 16 + count * 8 + n * 14 + 64);
|
|
216
|
+
const at = base >> 3;
|
|
217
|
+
if (st.swap) for (let i = 0; i < n * 2; i += 2) (f64[at + i] = coords[i + 1]), (f64[at + i + 1] = coords[i]);
|
|
218
|
+
else f64.set(coords, at);
|
|
219
|
+
u32.set(starts, (base + n * 16) >> 2);
|
|
220
|
+
return manyOut(base + n * 16, count, n, f) ?? toLines(lines).map((l) => jsEncodeFlat(l, o));
|
|
221
|
+
}
|
|
222
|
+
const toLines = (l) => (Array.isArray(l) ? l : Array.from({ length: l.starts.length - 1 }, (_, i) => l.coords.subarray(l.starts[i] * 2, l.starts[i + 1] * 2)));
|
|
223
|
+
|
|
224
|
+
function manyOut(startsAt, count, n, f) {
|
|
225
|
+
const ends = startsAt + align((count + 1) * 4), out = ends + align(count * 4);
|
|
226
|
+
const k = ex.encode_many(base, startsAt, count, f, out, ends);
|
|
227
|
+
if (k < 0) return null;
|
|
228
|
+
const r = Array(count), e = u32, e0 = ends >> 2;
|
|
229
|
+
for (let i = 0, a = out; i < count; i++) r[i] = text(a, (a = out + e[e0 + i]));
|
|
230
|
+
return r;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export const decodeLatLng = /* @__PURE__ */ latLngs(decode);
|
|
234
|
+
export const toGeoJSON = /* @__PURE__ */ toGeo(decode);
|
|
235
|
+
export const fromGeoJSON = /* @__PURE__ */ fromGeo(encode);
|
package/src/web.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Default and browser entry: the portable core and nothing else, so it has
|
|
2
|
+
// no Node, Bun or Deno globals and bundles small.
|
|
3
|
+
/* @ts-self-types="../types/index.d.ts" */
|
|
4
|
+
import { decode, encode, latLngs, toGeo, fromGeo } from './core.js';
|
|
5
|
+
|
|
6
|
+
export { decode, encode, decodeFlat, encodeFlat, PolylineError } from './core.js';
|
|
7
|
+
export const decodeLatLng = /* @__PURE__ */ latLngs(decode);
|
|
8
|
+
export const toGeoJSON = /* @__PURE__ */ toGeo(decode);
|
|
9
|
+
export const fromGeoJSON = /* @__PURE__ */ fromGeo(encode);
|
package/types/cli.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Types for @duoquote/polytini/deckgl. The results are plain objects in
|
|
2
|
+
// deck.gl's binary data shape, so they need no deck.gl types: they can be
|
|
3
|
+
// passed as `data` to PathLayer, TripsLayer and SolidPolygonLayer.
|
|
4
|
+
import type { Options } from './index.d.ts';
|
|
5
|
+
|
|
6
|
+
export interface BinaryOptions extends Options {
|
|
7
|
+
/** Float32Array instead of Float64Array. Smaller, and enough for most maps; deck.gl uses 64-bit positions only when given them. Default false. */
|
|
8
|
+
float32?: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface PathOptions extends BinaryOptions {
|
|
12
|
+
/**
|
|
13
|
+
* For TripsLayer: the last value of each point (with dimensions 3 or 4) goes
|
|
14
|
+
* to attributes.getTimestamps instead of the positions. The values are
|
|
15
|
+
* divided by zFactor, like any value after the second, and always come out
|
|
16
|
+
* as a Float32Array, because TripsLayer's timestamp attribute is 32-bit
|
|
17
|
+
* (deck.gl 9.4 drew nothing given Float64Array timestamps). Default false.
|
|
18
|
+
*/
|
|
19
|
+
timestamps?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A deck.gl binary attribute. */
|
|
23
|
+
export interface BinaryAttribute<T extends Float32Array | Float64Array = Float32Array | Float64Array, S extends number = number> {
|
|
24
|
+
value: T;
|
|
25
|
+
size: S;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface BinaryPaths<T extends Float32Array | Float64Array = Float32Array | Float64Array> {
|
|
29
|
+
/** The number of paths, one per string. */
|
|
30
|
+
length: number;
|
|
31
|
+
/** The first vertex of each path, plus the vertex count at the end (length + 1 entries). */
|
|
32
|
+
startIndices: Uint32Array;
|
|
33
|
+
attributes: {
|
|
34
|
+
/** [lng, lat] (size 2) or [lng, lat, z] (size 3) per vertex. */
|
|
35
|
+
getPath: BinaryAttribute<T, 2 | 3>;
|
|
36
|
+
/** One value per vertex, with the timestamps option. Always 32-bit. */
|
|
37
|
+
getTimestamps?: BinaryAttribute<Float32Array, 1>;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface BinaryPolygons<T extends Float32Array | Float64Array = Float32Array | Float64Array> {
|
|
42
|
+
/** The number of polygons, one ring per string. */
|
|
43
|
+
length: number;
|
|
44
|
+
/** The first vertex of each ring, plus the vertex count at the end (length + 1 entries). */
|
|
45
|
+
startIndices: Uint32Array;
|
|
46
|
+
attributes: {
|
|
47
|
+
/** [lng, lat] (size 2) or [lng, lat, z] (size 3) per vertex, every ring closed. */
|
|
48
|
+
getPolygon: BinaryAttribute<T, 2 | 3>;
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Binary data for PathLayer and TripsLayer, one path per string. Pass _pathType: 'open' to skip deck.gl's normalization. */
|
|
53
|
+
export function binaryPaths(encoded: string | string[], options: PathOptions & { float32: true }): BinaryPaths<Float32Array>;
|
|
54
|
+
export function binaryPaths(encoded: string | string[], options?: number | (PathOptions & { float32?: false })): BinaryPaths<Float64Array>;
|
|
55
|
+
export function binaryPaths(encoded: string | string[], options?: number | PathOptions): BinaryPaths;
|
|
56
|
+
|
|
57
|
+
/** Binary data for SolidPolygonLayer, one closed ring per string (no holes). */
|
|
58
|
+
export function binaryPolygons(encoded: string | string[], options: BinaryOptions & { float32: true }): BinaryPolygons<Float32Array>;
|
|
59
|
+
export function binaryPolygons(encoded: string | string[], options?: number | (BinaryOptions & { float32?: false })): BinaryPolygons<Float64Array>;
|
|
60
|
+
export function binaryPolygons(encoded: string | string[], options?: number | BinaryOptions): BinaryPolygons;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Types for @duoquote/polytini/flexible, HERE's Flexible Polyline format
|
|
2
|
+
// (version 1). Separate from the Google-format entry points.
|
|
3
|
+
import type { ErrorCode } from './index.d.ts';
|
|
4
|
+
|
|
5
|
+
/** Third dimension types, as stored in the header. */
|
|
6
|
+
export const ABSENT: 0;
|
|
7
|
+
export const LEVEL: 1;
|
|
8
|
+
export const ALTITUDE: 2;
|
|
9
|
+
export const ELEVATION: 3;
|
|
10
|
+
/** Reserved by the spec: decode accepts it, encode refuses it. */
|
|
11
|
+
export const RESERVED1: 4;
|
|
12
|
+
/** Reserved by the spec: decode accepts it, encode refuses it. */
|
|
13
|
+
export const RESERVED2: 5;
|
|
14
|
+
export const CUSTOM1: 6;
|
|
15
|
+
export const CUSTOM2: 7;
|
|
16
|
+
|
|
17
|
+
/** Any type a header can hold. */
|
|
18
|
+
export type ThirdDimension = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
|
|
19
|
+
/** The types encode accepts. */
|
|
20
|
+
export type EncodableThirdDimension = 0 | 1 | 2 | 3 | 6 | 7;
|
|
21
|
+
|
|
22
|
+
export interface Header {
|
|
23
|
+
/** Decimal places of latitude and longitude, 0 to 15. */
|
|
24
|
+
precision: number;
|
|
25
|
+
/** What the third value means. ABSENT (0) for 2D lines. */
|
|
26
|
+
thirdDim: ThirdDimension;
|
|
27
|
+
/** Decimal places of the third value, 0 to 15. */
|
|
28
|
+
thirdDimPrecision: number;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface DecodedResult extends Header {
|
|
32
|
+
/** [lat, lng] points, or [lat, lng, z] when thirdDim is not ABSENT. */
|
|
33
|
+
polyline: number[][];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface EncodeOptions {
|
|
37
|
+
/** Decimal places of latitude and longitude, an integer from 0 to 15. Default 5. */
|
|
38
|
+
precision?: number;
|
|
39
|
+
/** Type of the third value. Default ABSENT, which ignores any third value. */
|
|
40
|
+
thirdDim?: EncodableThirdDimension;
|
|
41
|
+
/** Decimal places of the third value, an integer from 0 to 15. Default 0. */
|
|
42
|
+
thirdDimPrecision?: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** [lat, lng] or [lat, lng, z] points, or one flat array of numbers: [lat0, lng0, lat1, lng1, ...]. */
|
|
46
|
+
export type Points = ArrayLike<ArrayLike<number>> | ArrayLike<number>;
|
|
47
|
+
|
|
48
|
+
/** The argument of @here/flexpolyline's encode. */
|
|
49
|
+
export interface EncodeInput extends EncodeOptions {
|
|
50
|
+
polyline: Points;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Codes of a PolylineError from this entry: the main entry's, plus 'version'
|
|
55
|
+
* for a format version other than 1 or a header with bits set above bit 10.
|
|
56
|
+
*/
|
|
57
|
+
export type FlexibleErrorCode = Exclude<ErrorCode, 'init'> | 'version';
|
|
58
|
+
|
|
59
|
+
/** The same class as the main entry's PolylineError. */
|
|
60
|
+
export class PolylineError extends Error {
|
|
61
|
+
readonly name: 'PolylineError';
|
|
62
|
+
/** What went wrong. */
|
|
63
|
+
readonly code: FlexibleErrorCode;
|
|
64
|
+
/** Character index (decode) or point index (encode), when there is one. */
|
|
65
|
+
readonly index: number | undefined;
|
|
66
|
+
constructor(code: FlexibleErrorCode, message: string, index?: number);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Encodes a line. Takes @here/flexpolyline's argument, or the points with
|
|
71
|
+
* the header fields in `options`, which win over the input object's.
|
|
72
|
+
* Rounds half away from zero.
|
|
73
|
+
*/
|
|
74
|
+
export function encode(input: EncodeInput | Points, options?: EncodeOptions): string;
|
|
75
|
+
|
|
76
|
+
/** Decodes a line, with its header. The same result shape as @here/flexpolyline. */
|
|
77
|
+
export function decode(str: string): DecodedResult;
|
|
78
|
+
|
|
79
|
+
/** Reads only the header. */
|
|
80
|
+
export function header(str: string): Header;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Types for @duoquote/polytini/google, using the google.maps types from
|
|
2
|
+
// @types/google.maps. Those are global declarations, not a module, so they
|
|
3
|
+
// are pulled in with a reference directive: types only, nothing at runtime.
|
|
4
|
+
/// <reference types="google.maps" />
|
|
5
|
+
import type * as P from './index.d.ts';
|
|
6
|
+
import type { Options, Point } from './index.d.ts';
|
|
7
|
+
|
|
8
|
+
export declare const PolylineError: typeof P.PolylineError;
|
|
9
|
+
export type PolylineError = P.PolylineError;
|
|
10
|
+
|
|
11
|
+
/** A LatLng constructor: google.maps.LatLng or anything built the same way. */
|
|
12
|
+
export type LatLngConstructor = new (lat: number, lng: number, noClampNoWrap?: boolean) => google.maps.LatLng;
|
|
13
|
+
|
|
14
|
+
export interface DecodePathOptions extends Omit<Options, 'order'> {
|
|
15
|
+
/**
|
|
16
|
+
* The class to build points with. Default: globalThis.google.maps.LatLng
|
|
17
|
+
* when it exists. false or null returns LatLngLiteral objects.
|
|
18
|
+
*/
|
|
19
|
+
LatLng?: LatLngConstructor | false | null;
|
|
20
|
+
/** Passed to the LatLng constructor. Without it, LatLng clamps latitude and wraps longitude into [-180, 180). */
|
|
21
|
+
noClampNoWrap?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A point encodePath takes: google.maps.LatLng, LatLngLiteral or a [lat, lng] tuple. */
|
|
25
|
+
export type PathPoint = google.maps.LatLng | google.maps.LatLngLiteral | Point;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Decodes an encoded path to LatLngLiteral objects (`LatLng: false`).
|
|
29
|
+
*/
|
|
30
|
+
export function decodePath(encodedPath: string, options: DecodePathOptions & { LatLng: false | null }): google.maps.LatLngLiteral[];
|
|
31
|
+
/**
|
|
32
|
+
* Decodes an encoded path, like google.maps.geometry.encoding.decodePath,
|
|
33
|
+
* to google.maps.LatLng objects. Without a `LatLng` option this uses
|
|
34
|
+
* globalThis.google.maps.LatLng; when the Maps JavaScript API isn't loaded
|
|
35
|
+
* the result is LatLngLiteral objects at runtime, so pass `LatLng: false`
|
|
36
|
+
* there to get that type. Strict by default: a malformed string throws a
|
|
37
|
+
* PolylineError unless `strict: false`.
|
|
38
|
+
*/
|
|
39
|
+
export function decodePath(encodedPath: string, options?: number | (DecodePathOptions & { LatLng?: LatLngConstructor })): google.maps.LatLng[];
|
|
40
|
+
export function decodePath(encodedPath: string, options?: number | DecodePathOptions): google.maps.LatLng[] | google.maps.LatLngLiteral[];
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Encodes a path, like google.maps.geometry.encoding.encodePath: an array or
|
|
44
|
+
* MVCArray of google.maps.LatLng, LatLngLiteral or [lat, lng] tuples, mixed
|
|
45
|
+
* or not. Precision 5 by default. `order: 'lnglat'` applies to tuples and
|
|
46
|
+
* LatLng objects; literals are read by name. Strict by default.
|
|
47
|
+
*/
|
|
48
|
+
export function encodePath(path: readonly PathPoint[] | google.maps.MVCArray<PathPoint>, options?: number | Options): string;
|