@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/package.json
CHANGED
|
@@ -1,6 +1,200 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@duoquote/polytini",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@duoquote/polytini",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Encode and decode Google encoded polylines. Small, strict by default, with fast paths for Node, Bun and Deno.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"polyline",
|
|
7
|
+
"encoded polyline",
|
|
8
|
+
"google maps",
|
|
9
|
+
"geojson",
|
|
10
|
+
"osrm",
|
|
11
|
+
"valhalla",
|
|
12
|
+
"leaflet",
|
|
13
|
+
"turf"
|
|
14
|
+
],
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"author": "Güven Değirmenci",
|
|
17
|
+
"homepage": "https://github.com/Duoquote/polytini#readme",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/Duoquote/polytini.git"
|
|
21
|
+
},
|
|
22
|
+
"bugs": "https://github.com/Duoquote/polytini/issues",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"sideEffects": [
|
|
25
|
+
"./src/leaflet-auto.js",
|
|
26
|
+
"./dist/leaflet-auto.cjs"
|
|
27
|
+
],
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"browser": {
|
|
31
|
+
"types": "./types/index.d.ts",
|
|
32
|
+
"default": "./src/browser.js"
|
|
33
|
+
},
|
|
34
|
+
"require": {
|
|
35
|
+
"types": "./dist/types/index.d.cts",
|
|
36
|
+
"default": "./dist/node.cjs"
|
|
37
|
+
},
|
|
38
|
+
"types": "./types/index.d.ts",
|
|
39
|
+
"bun": "./src/bun.js",
|
|
40
|
+
"deno": "./src/deno.js",
|
|
41
|
+
"node": "./src/node.js",
|
|
42
|
+
"default": "./src/web.js"
|
|
43
|
+
},
|
|
44
|
+
"./web": {
|
|
45
|
+
"require": {
|
|
46
|
+
"types": "./dist/types/index.d.cts",
|
|
47
|
+
"default": "./dist/web.cjs"
|
|
48
|
+
},
|
|
49
|
+
"types": "./types/index.d.ts",
|
|
50
|
+
"default": "./src/web.js"
|
|
51
|
+
},
|
|
52
|
+
"./node": {
|
|
53
|
+
"require": {
|
|
54
|
+
"types": "./dist/types/index.d.cts",
|
|
55
|
+
"default": "./dist/node.cjs"
|
|
56
|
+
},
|
|
57
|
+
"types": "./types/index.d.ts",
|
|
58
|
+
"default": "./src/node.js"
|
|
59
|
+
},
|
|
60
|
+
"./browser": {
|
|
61
|
+
"types": "./types/index.d.ts",
|
|
62
|
+
"default": "./src/browser.js"
|
|
63
|
+
},
|
|
64
|
+
"./wasm": {
|
|
65
|
+
"types": "./types/wasm.d.ts",
|
|
66
|
+
"default": "./src/wasm.js"
|
|
67
|
+
},
|
|
68
|
+
"./turf": {
|
|
69
|
+
"require": {
|
|
70
|
+
"types": "./dist/types/turf.d.cts",
|
|
71
|
+
"default": "./dist/turf.cjs"
|
|
72
|
+
},
|
|
73
|
+
"types": "./types/turf.d.ts",
|
|
74
|
+
"default": "./src/turf.js"
|
|
75
|
+
},
|
|
76
|
+
"./leaflet": {
|
|
77
|
+
"require": {
|
|
78
|
+
"types": "./dist/types/leaflet.d.cts",
|
|
79
|
+
"default": "./dist/leaflet.cjs"
|
|
80
|
+
},
|
|
81
|
+
"types": "./types/leaflet.d.ts",
|
|
82
|
+
"default": "./src/leaflet.js"
|
|
83
|
+
},
|
|
84
|
+
"./presets": {
|
|
85
|
+
"require": {
|
|
86
|
+
"types": "./dist/types/presets.d.cts",
|
|
87
|
+
"default": "./dist/presets.cjs"
|
|
88
|
+
},
|
|
89
|
+
"types": "./types/presets.d.ts",
|
|
90
|
+
"default": "./src/presets.js"
|
|
91
|
+
},
|
|
92
|
+
"./flexible": {
|
|
93
|
+
"require": {
|
|
94
|
+
"types": "./dist/types/flexible.d.cts",
|
|
95
|
+
"default": "./dist/flexible.cjs"
|
|
96
|
+
},
|
|
97
|
+
"types": "./types/flexible.d.ts",
|
|
98
|
+
"default": "./src/flexible.js"
|
|
99
|
+
},
|
|
100
|
+
"./google": {
|
|
101
|
+
"require": {
|
|
102
|
+
"types": "./dist/types/google.d.cts",
|
|
103
|
+
"default": "./dist/google.cjs"
|
|
104
|
+
},
|
|
105
|
+
"types": "./types/google.d.ts",
|
|
106
|
+
"default": "./src/google.js"
|
|
107
|
+
},
|
|
108
|
+
"./maplibre": {
|
|
109
|
+
"require": {
|
|
110
|
+
"types": "./dist/types/maplibre.d.cts",
|
|
111
|
+
"default": "./dist/maplibre.cjs"
|
|
112
|
+
},
|
|
113
|
+
"types": "./types/maplibre.d.ts",
|
|
114
|
+
"default": "./src/maplibre.js"
|
|
115
|
+
},
|
|
116
|
+
"./mapbox": {
|
|
117
|
+
"require": {
|
|
118
|
+
"types": "./dist/types/mapbox.d.cts",
|
|
119
|
+
"default": "./dist/mapbox.cjs"
|
|
120
|
+
},
|
|
121
|
+
"types": "./types/mapbox.d.ts",
|
|
122
|
+
"default": "./src/mapbox.js"
|
|
123
|
+
},
|
|
124
|
+
"./deckgl": {
|
|
125
|
+
"require": {
|
|
126
|
+
"types": "./dist/types/deckgl.d.cts",
|
|
127
|
+
"default": "./dist/deckgl.cjs"
|
|
128
|
+
},
|
|
129
|
+
"types": "./types/deckgl.d.ts",
|
|
130
|
+
"default": "./src/deckgl.js"
|
|
131
|
+
},
|
|
132
|
+
"./leaflet/auto": {
|
|
133
|
+
"require": {
|
|
134
|
+
"types": "./dist/types/leaflet-auto.d.cts",
|
|
135
|
+
"default": "./dist/leaflet-auto.cjs"
|
|
136
|
+
},
|
|
137
|
+
"types": "./types/leaflet-auto.d.ts",
|
|
138
|
+
"default": "./src/leaflet-auto.js"
|
|
139
|
+
},
|
|
140
|
+
"./openlayers": {
|
|
141
|
+
"types": "./types/openlayers.d.ts",
|
|
142
|
+
"default": "./src/openlayers.js"
|
|
143
|
+
},
|
|
144
|
+
"./package.json": "./package.json"
|
|
145
|
+
},
|
|
146
|
+
"types": "./types/index.d.ts",
|
|
147
|
+
"main": "./dist/node.cjs",
|
|
148
|
+
"bin": {
|
|
149
|
+
"polytini": "src/cli.js"
|
|
150
|
+
},
|
|
151
|
+
"files": [
|
|
152
|
+
"src",
|
|
153
|
+
"types",
|
|
154
|
+
"dist",
|
|
155
|
+
"wasm/polytini.wasm"
|
|
156
|
+
],
|
|
157
|
+
"engines": {
|
|
158
|
+
"node": ">=22"
|
|
159
|
+
},
|
|
160
|
+
"publishConfig": {
|
|
161
|
+
"access": "public"
|
|
162
|
+
},
|
|
163
|
+
"scripts": {
|
|
164
|
+
"build": "node scripts/build.js",
|
|
165
|
+
"build:wasm": "node scripts/build-wasm.js",
|
|
166
|
+
"prepack": "node scripts/build.js",
|
|
167
|
+
"test": "node test/run.js",
|
|
168
|
+
"test:bun": "bun test/run.js",
|
|
169
|
+
"test:deno": "deno run --allow-read --allow-env --allow-run --allow-write test/run.js",
|
|
170
|
+
"test:browser": "node test/browser.js",
|
|
171
|
+
"size": "node scripts/size.js",
|
|
172
|
+
"smoke": "node test/smoke.js",
|
|
173
|
+
"check:deps": "node scripts/check-deps.js"
|
|
174
|
+
},
|
|
175
|
+
"devDependencies": {
|
|
176
|
+
"@deck.gl/core": "^9.4.2",
|
|
177
|
+
"@deck.gl/geo-layers": "^9.4.2",
|
|
178
|
+
"@deck.gl/layers": "^9.4.2",
|
|
179
|
+
"@here/flexpolyline": "^0.1.0",
|
|
180
|
+
"@maplibre/maplibre-gl-style-spec": "^26.11.0",
|
|
181
|
+
"@turf/helpers": "^7.4.0",
|
|
182
|
+
"@turf/turf": "^7.4.0",
|
|
183
|
+
"@types/geojson": "^7946.0.16",
|
|
184
|
+
"@types/google.maps": "^3.67.0",
|
|
185
|
+
"@types/leaflet": "^1.9.23",
|
|
186
|
+
"c8": "^12.0.0",
|
|
187
|
+
"esbuild": "^0.28.2",
|
|
188
|
+
"fast-check": "^4.11.0",
|
|
189
|
+
"jsdom": "^29.1.1",
|
|
190
|
+
"leaflet": "^1.9.4",
|
|
191
|
+
"leaflet-2": "npm:leaflet@^2.0.0-beta.5",
|
|
192
|
+
"mapbox-gl": "^3.36.0",
|
|
193
|
+
"maplibre-gl": "^6.19.0",
|
|
194
|
+
"ol": "^10.11.0",
|
|
195
|
+
"playwright-core": "^1.65.1",
|
|
196
|
+
"tinybench": "^6.2.5",
|
|
197
|
+
"typescript": "^7.0.2",
|
|
198
|
+
"wabt": "^1.0.39"
|
|
199
|
+
}
|
|
200
|
+
}
|
package/src/browser.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Browser entry (the "browser" export condition): the portable core, except
|
|
2
|
+
// that long lines encode through TextDecoder (text.js). In headless Chrome
|
|
3
|
+
// that was about 50% faster from 1,000 points up and the same below 512,
|
|
4
|
+
// where it falls back to the core. Decoding stays on the core's charCodeAt
|
|
5
|
+
// loop: TextEncoder.encodeInto made it slower in Chrome. No Node, Bun or
|
|
6
|
+
// Deno globals.
|
|
7
|
+
/* @ts-self-types="../types/index.d.ts" */
|
|
8
|
+
import { decode, latLngs, toGeo, fromGeo } from './core.js';
|
|
9
|
+
import { encode } from './text.js';
|
|
10
|
+
|
|
11
|
+
export { decode, decodeFlat, PolylineError } from './core.js';
|
|
12
|
+
export { encode, encodeFlat } from './text.js';
|
|
13
|
+
export const decodeLatLng = /* @__PURE__ */ latLngs(decode);
|
|
14
|
+
export const toGeoJSON = /* @__PURE__ */ toGeo(decode);
|
|
15
|
+
export const fromGeoJSON = /* @__PURE__ */ fromGeo(encode);
|
package/src/bun.js
ADDED
package/src/cli-lib.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// The polytini command line, minus the part that runs it (src/cli.js).
|
|
2
|
+
// No dependencies, and only node: built-ins that Node, Bun and Deno all
|
|
3
|
+
// have, so the same code runs under each.
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import process from 'node:process';
|
|
6
|
+
import { encode, decode, PolylineError } from './web.js';
|
|
7
|
+
|
|
8
|
+
// Kept in sync with package.json and jsr.json by test/cli.test.js.
|
|
9
|
+
export const VERSION = '0.1.0';
|
|
10
|
+
|
|
11
|
+
const HELP = `polytini ${VERSION}: encode and decode Google encoded polylines
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
polytini encode [input] [options]
|
|
15
|
+
polytini decode [input] [options]
|
|
16
|
+
|
|
17
|
+
Input is the argument, --file <path>, or stdin. Quote polylines on the
|
|
18
|
+
command line: they can contain \\ \` | and other shell characters.
|
|
19
|
+
|
|
20
|
+
encode reads JSON ([[lat, lng], ...], or GeoJSON), CSV with a header, or
|
|
21
|
+
"lat,lng" lines, and prints one polyline per line.
|
|
22
|
+
decode reads one polyline per line and prints coordinates.
|
|
23
|
+
|
|
24
|
+
Options:
|
|
25
|
+
-p, --precision <n> decimal places, 0 to 15 (default 5; OSRM polyline6
|
|
26
|
+
and Valhalla use 6)
|
|
27
|
+
--lnglat coordinates are [lng, lat], like GeoJSON (GeoJSON
|
|
28
|
+
input is always read that way)
|
|
29
|
+
--no-strict accept malformed input instead of failing
|
|
30
|
+
-f, --format <fmt> decode output: json (default), geojson, csv or lines
|
|
31
|
+
--file <path> read input from a file
|
|
32
|
+
-h, --help show this help
|
|
33
|
+
-v, --version show the version
|
|
34
|
+
|
|
35
|
+
Examples:
|
|
36
|
+
polytini decode '_p~iF~ps|U_ulLnnqC_mqNvxq\`@'
|
|
37
|
+
polytini decode -p 6 -f geojson --file route.txt
|
|
38
|
+
echo '[[38.5,-120.2],[40.7,-120.95]]' | polytini encode
|
|
39
|
+
polytini encode --file points.csv
|
|
40
|
+
`;
|
|
41
|
+
|
|
42
|
+
export function parseArgs(argv) {
|
|
43
|
+
const a = { precision: 5, order: 'latlng', strict: true, format: 'json', rest: [] };
|
|
44
|
+
for (let i = 0; i < argv.length; i++) {
|
|
45
|
+
const x = argv[i], value = () => argv[++i] ?? die(`${x} needs a value`);
|
|
46
|
+
if (x == '-h' || x == '--help') a.help = true;
|
|
47
|
+
else if (x == '-v' || x == '--version') a.version = true;
|
|
48
|
+
else if (x == '-p' || x == '--precision') a.precision = Number(value());
|
|
49
|
+
else if (x.startsWith('--precision=')) a.precision = Number(x.slice(12));
|
|
50
|
+
else if (x == '--lnglat') a.order = 'lnglat';
|
|
51
|
+
else if (x == '--no-strict') a.strict = false;
|
|
52
|
+
else if (x == '-f' || x == '--format') a.format = value();
|
|
53
|
+
else if (x.startsWith('--format=')) a.format = x.slice(9);
|
|
54
|
+
else if (x == '--file') a.file = value();
|
|
55
|
+
else if (x.startsWith('-') && x.length > 1) die(`unknown option ${x}`);
|
|
56
|
+
else a.rest.push(x);
|
|
57
|
+
}
|
|
58
|
+
return a;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
class Usage extends Error {}
|
|
62
|
+
const die = (m) => {
|
|
63
|
+
throw new Usage(m);
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Numbers from one CSV or "lat,lng" line: commas, semicolons, tabs or spaces.
|
|
67
|
+
const cells = (line) => line.trim().split(/\s*[,;\t]\s*|\s+/);
|
|
68
|
+
|
|
69
|
+
/** Parses encode input into lines of [a, b] tuples in the given order. */
|
|
70
|
+
export function readPoints(text, order) {
|
|
71
|
+
const t = text.trim();
|
|
72
|
+
if (!t) return [[]];
|
|
73
|
+
if (t[0] == '[' || t[0] == '{') {
|
|
74
|
+
const j = JSON.parse(t);
|
|
75
|
+
if (Array.isArray(j)) return Array.isArray(j[0]?.[0]) ? j : [j];
|
|
76
|
+
// GeoJSON: every LineString, MultiLineString part and polygon ring.
|
|
77
|
+
const out = [], flip = (c) => (order == 'lnglat' ? c : c.map(([x, y]) => [y, x]));
|
|
78
|
+
const walk = (g) => {
|
|
79
|
+
if (!g) return;
|
|
80
|
+
if (g.type == 'Feature') walk(g.geometry);
|
|
81
|
+
else if (g.type == 'FeatureCollection') g.features.forEach(walk);
|
|
82
|
+
else if (g.type == 'GeometryCollection') g.geometries.forEach(walk);
|
|
83
|
+
else if (g.type == 'LineString') out.push(flip(g.coordinates));
|
|
84
|
+
else if (g.type == 'MultiLineString' || g.type == 'Polygon') g.coordinates.forEach((c) => out.push(flip(c)));
|
|
85
|
+
else if (g.type == 'MultiPolygon') g.coordinates.forEach((p) => p.forEach((c) => out.push(flip(c))));
|
|
86
|
+
};
|
|
87
|
+
walk(j);
|
|
88
|
+
if (!out.length) die('no LineString in the GeoJSON input');
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
// CSV or lines. A header row picks the columns by name; otherwise the
|
|
92
|
+
// first two columns are lat, lng (or lng, lat with --lnglat).
|
|
93
|
+
const rows = t.split(/\r?\n/).filter((l) => l.trim());
|
|
94
|
+
let ia = 0, ib = 1;
|
|
95
|
+
const head = cells(rows[0]).map((c) => c.toLowerCase().replace(/^"|"$/g, ''));
|
|
96
|
+
if (head.some((c) => c && isNaN(c))) {
|
|
97
|
+
rows.shift();
|
|
98
|
+
const find = (...names) => head.findIndex((c) => names.includes(c));
|
|
99
|
+
const lat = find('lat', 'latitude', 'y'), lng = find('lng', 'lon', 'long', 'longitude', 'x');
|
|
100
|
+
if (lat < 0 || lng < 0) die('CSV header needs lat and lng (or lon, longitude) columns');
|
|
101
|
+
[ia, ib] = order == 'lnglat' ? [lng, lat] : [lat, lng];
|
|
102
|
+
}
|
|
103
|
+
return [
|
|
104
|
+
rows.map((r, i) => {
|
|
105
|
+
const c = cells(r);
|
|
106
|
+
if (c.length < 2) die(`line ${i + 1}: expected two numbers, got ${JSON.stringify(r.trim())}`);
|
|
107
|
+
return [Number(c[ia]), Number(c[ib])];
|
|
108
|
+
}),
|
|
109
|
+
];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Formats decoded lines. */
|
|
113
|
+
export function format(lines, fmt, order) {
|
|
114
|
+
const [a, b] = order == 'lnglat' ? ['lng', 'lat'] : ['lat', 'lng'];
|
|
115
|
+
const many = lines.length > 1;
|
|
116
|
+
switch (fmt) {
|
|
117
|
+
case 'json':
|
|
118
|
+
return JSON.stringify(many ? lines : lines[0]);
|
|
119
|
+
case 'geojson': {
|
|
120
|
+
const geo = (l) => ({ type: 'LineString', coordinates: order == 'lnglat' ? l : l.map(([x, y]) => [y, x]) });
|
|
121
|
+
return JSON.stringify(many ? { type: 'FeatureCollection', features: lines.map((l) => ({ type: 'Feature', properties: {}, geometry: geo(l) })) } : geo(lines[0]));
|
|
122
|
+
}
|
|
123
|
+
case 'csv':
|
|
124
|
+
return [many ? `line,${a},${b}` : `${a},${b}`, ...lines.flatMap((l, i) => l.map((p) => (many ? `${i},` : '') + p.join(',')))].join('\n');
|
|
125
|
+
case 'lines':
|
|
126
|
+
return lines.map((l) => l.map((p) => p.join(',')).join('\n')).join('\n\n');
|
|
127
|
+
default:
|
|
128
|
+
die(`unknown format ${fmt}: use json, geojson, csv or lines`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Runs one command and returns the output text (no trailing newline). */
|
|
133
|
+
export function run(argv, stdin = () => '') {
|
|
134
|
+
const a = parseArgs(argv);
|
|
135
|
+
if (a.help) return HELP.trimEnd();
|
|
136
|
+
if (a.version) return VERSION;
|
|
137
|
+
const [cmd, arg, extra] = a.rest;
|
|
138
|
+
if (cmd != 'encode' && cmd != 'decode') die(cmd ? `unknown command ${cmd}` : 'expected a command: encode or decode');
|
|
139
|
+
if (extra != null) die('expected one input argument; quote it');
|
|
140
|
+
if (arg != null && a.file) die('give an argument or --file, not both');
|
|
141
|
+
const input = arg ?? (a.file ? readFileSync(a.file, 'utf8') : stdin());
|
|
142
|
+
const o = { precision: a.precision, order: a.order, strict: a.strict };
|
|
143
|
+
if (cmd == 'encode') return readPoints(input, a.order).map((l) => encode(l, o)).join('\n');
|
|
144
|
+
// Polylines never contain whitespace, so one per line, blank lines skipped.
|
|
145
|
+
const strs = input.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
146
|
+
return format(strs.length ? strs.map((s) => decode(s, o)) : [[]], a.format, a.order);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Runs the CLI with process.argv and stdin, and sets the exit code. */
|
|
150
|
+
export function main() {
|
|
151
|
+
try {
|
|
152
|
+
const out = run(process.argv.slice(2), () => readFileSync(0, 'utf8'));
|
|
153
|
+
process.stdout.write(out + '\n');
|
|
154
|
+
} catch (e) {
|
|
155
|
+
const usage = e instanceof Usage;
|
|
156
|
+
process.stderr.write(`polytini: ${e instanceof PolylineError || usage || e instanceof SyntaxError ? e.message : e?.stack ?? e}\n`);
|
|
157
|
+
if (usage) process.stderr.write('Run polytini --help for usage.\n');
|
|
158
|
+
process.exitCode = usage ? 2 : 1;
|
|
159
|
+
}
|
|
160
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The polytini command. npx/bunx/pnpm dlx/yarn dlx run this through the
|
|
3
|
+
// package's bin, and `deno run jsr:@duoquote/polytini/cli` runs it directly.
|
|
4
|
+
/* @ts-self-types="../types/cli.d.ts" */
|
|
5
|
+
import { main } from './cli-lib.js';
|
|
6
|
+
|
|
7
|
+
main();
|
package/src/core.js
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// The portable codec. Every entry point builds on this file, and the web
|
|
2
|
+
// entry is only this file. It uses no Node, Bun or Deno globals.
|
|
3
|
+
//
|
|
4
|
+
// Each public function has a fast loop for the common case (2D points,
|
|
5
|
+
// precision up to 6, valid input) and falls back to the exact `slow*`
|
|
6
|
+
// functions for anything else: other dimensions, huge values, objects,
|
|
7
|
+
// and every kind of bad input. The slow functions do the same Number math
|
|
8
|
+
// as Google's algorithm description, so both paths give identical output.
|
|
9
|
+
|
|
10
|
+
import { PolylineError, fail } from './error.js';
|
|
11
|
+
|
|
12
|
+
export { PolylineError, fail };
|
|
13
|
+
|
|
14
|
+
// Options of the current call, set by opts() and read right after it, so the
|
|
15
|
+
// hot paths never allocate. A plain object on purpose: writing exported
|
|
16
|
+
// module-level `let` bindings cost about 30 ns per call on V8, this costs
|
|
17
|
+
// nothing measurable.
|
|
18
|
+
export const st = { swap: false, strict: true, dims: 2, zf: 1e5 };
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Parses options, fills `st` and returns the factor. Kept tiny so V8 inlines
|
|
22
|
+
* it into every caller; with the object branch in the same function it
|
|
23
|
+
* wasn't inlined, and decoding 10 points got about 25% slower.
|
|
24
|
+
*/
|
|
25
|
+
export function opts(o) {
|
|
26
|
+
st.swap = false;
|
|
27
|
+
st.strict = true;
|
|
28
|
+
st.dims = 2;
|
|
29
|
+
return o && typeof o == 'object' ? objOpts(o) : (st.zf = o == null ? 1e5 : pow(o));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function objOpts(o) {
|
|
33
|
+
const { order, dimensions: d } = o;
|
|
34
|
+
if (order == 'lnglat') st.swap = true;
|
|
35
|
+
else if (order != null && order != 'latlng') bad('order');
|
|
36
|
+
if (o.strict === false) st.strict = false;
|
|
37
|
+
if (d != null) st.dims = d >= 1 && d <= 16 && d % 1 == 0 ? d : bad('dimensions');
|
|
38
|
+
const f = o.factor != null ? num(o.factor) : pow(o.precision ?? 5);
|
|
39
|
+
st.zf = o.zFactor != null ? num(o.zFactor) : f;
|
|
40
|
+
return f;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const bad = (name) => fail('option', 'Invalid ' + name);
|
|
44
|
+
const num = (f) => (f > 0 && f < 1 / 0 ? f : bad('factor'));
|
|
45
|
+
const pow = (p) => (typeof p == 'number' && p >= 0 && p <= 15 && p % 1 == 0 ? 10 ** p : bad('precision'));
|
|
46
|
+
|
|
47
|
+
// Scaled values below this fit the 32-bit math of the fast loops, deltas and
|
|
48
|
+
// zigzag included. It covers every valid coordinate up to precision 6.
|
|
49
|
+
export const LIMIT = 2 ** 29;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Exact decoder for any input. Returns points, or a flat Float64Array.
|
|
53
|
+
* Strict mode throws on invalid characters, on a string that ends inside a
|
|
54
|
+
* value or a point, and on values past 2^53. Otherwise it skips invalid
|
|
55
|
+
* characters and drops an incomplete last point.
|
|
56
|
+
*/
|
|
57
|
+
export function slowDecode(str, f, flat) {
|
|
58
|
+
if (typeof str != 'string') fail('input', 'Expected a string');
|
|
59
|
+
const { dims: d, strict, zf } = st, sw = st.swap && d > 1, values = [];
|
|
60
|
+
let v = 0, scale = 1, i = 0, c;
|
|
61
|
+
for (; i < str.length; i++) {
|
|
62
|
+
c = str.charCodeAt(i) - 63;
|
|
63
|
+
if (c < 0 || c > 63) {
|
|
64
|
+
if (strict) fail('char', 'Invalid character', i);
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
v += (c & 31) * scale;
|
|
68
|
+
scale *= 32;
|
|
69
|
+
if (v > 2 ** 53 && strict) fail('overflow', 'Value too large', i);
|
|
70
|
+
if (c < 32) {
|
|
71
|
+
values.push(v % 2 ? -(v + 1) / 2 : v / 2);
|
|
72
|
+
v = 0;
|
|
73
|
+
scale = 1;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (strict && (scale > 1 || values.length % d)) fail('truncated', 'Truncated', i);
|
|
77
|
+
const n = (values.length / d) | 0, sum = Array(d).fill(0), out = flat ? new Float64Array(n * d) : Array(n);
|
|
78
|
+
for (let j = 0, k = 0; j < n; j++) {
|
|
79
|
+
const p = flat ? out : Array(d);
|
|
80
|
+
for (let a = 0; a < d; a++, k++) {
|
|
81
|
+
sum[a] += values[k];
|
|
82
|
+
p[(flat ? k - a : 0) + (sw && a < 2 ? 1 - a : a)] = sum[a] / (a < 2 ? f : zf);
|
|
83
|
+
}
|
|
84
|
+
if (!flat) out[j] = p;
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Exact encoder for any input: [a, b] tuples (or any array-like), objects
|
|
91
|
+
* with lat/latitude and lng/lon/longitude, or a flat array of numbers.
|
|
92
|
+
* Rounds half away from zero, like Google's reference implementation.
|
|
93
|
+
*/
|
|
94
|
+
export function slowEncode(points, f, flat) {
|
|
95
|
+
if (points == null || !(points.length >= 0)) fail('input', 'Expected an array');
|
|
96
|
+
const { dims: d, strict, zf } = st, sw = st.swap && d > 1, last = Array(d).fill(0), n = flat ? points.length / d : points.length;
|
|
97
|
+
if (n % 1 && strict) fail('input', 'Length not a multiple of ' + d);
|
|
98
|
+
let s = '';
|
|
99
|
+
for (let i = 0; i < (n | 0); i++) {
|
|
100
|
+
const p = flat ? 0 : points[i];
|
|
101
|
+
for (let a = 0; a < d; a++) {
|
|
102
|
+
const b = sw && a < 2 ? 1 - a : a;
|
|
103
|
+
let x = flat ? points[i * d + b] : p == null ? p : p.length >= 0 ? p[b] : a ? (a > 1 ? p.alt ?? p.altitude : p.lng ?? p.lon ?? p.longitude) : p.lat ?? p.latitude;
|
|
104
|
+
// null and undefined are missing, not 0. Numeric strings are numbers.
|
|
105
|
+
x = x == null ? NaN : +x * (a < 2 ? f : zf);
|
|
106
|
+
if (!(x - x == 0)) {
|
|
107
|
+
if (strict) fail('coordinate', 'Invalid coordinate', i);
|
|
108
|
+
x = 0;
|
|
109
|
+
}
|
|
110
|
+
x = Math.sign(x) * Math.round(Math.abs(x));
|
|
111
|
+
let z = x - last[a];
|
|
112
|
+
last[a] = x;
|
|
113
|
+
z = z < 0 ? -z * 2 - 1 : z * 2;
|
|
114
|
+
if (z > 2 ** 53 && strict) fail('overflow', 'Value too large', i);
|
|
115
|
+
for (; z >= 32; z = Math.floor(z / 32)) s += String.fromCharCode((z % 32) + 95);
|
|
116
|
+
s += String.fromCharCode(z + 63);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return s;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const decodeWith = (str, o, flat) => {
|
|
123
|
+
const f = opts(o), out = st.dims == 2 && typeof str == 'string' && decodeLoop(str, f, st.swap, flat);
|
|
124
|
+
return out ? (st.swap && !flat ? flip(out) : out) : slowDecode(str, f, flat);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
// The fast loops always build [lat, lng]; lnglat output is flipped in place
|
|
128
|
+
// afterwards. A per-point `swap ? [b, a] : [a, b]` cost the default order
|
|
129
|
+
// about 5%, and the extra pass is small next to allocating the points.
|
|
130
|
+
export const flip = (out) => {
|
|
131
|
+
for (const p of out) {
|
|
132
|
+
const t = p[0];
|
|
133
|
+
p[0] = p[1];
|
|
134
|
+
p[1] = t;
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/** Decodes to [lat, lng] tuples. */
|
|
140
|
+
export const decode = (str, o) => decodeWith(str, o, 0);
|
|
141
|
+
|
|
142
|
+
/** Decodes to a flat Float64Array: [lat0, lng0, lat1, lng1, ...]. */
|
|
143
|
+
export const decodeFlat = (str, o) => decodeWith(str, o, 1);
|
|
144
|
+
|
|
145
|
+
// The 2D fast loop, or null when the input needs slowDecode. A separate,
|
|
146
|
+
// self-contained function because V8 optimized it better that way: with the
|
|
147
|
+
// option and type checks in the same function, 10 point lines decoded about
|
|
148
|
+
// 15% slower.
|
|
149
|
+
export function decodeLoop(str, f, sw, flat) {
|
|
150
|
+
const len = str.length, a = +sw;
|
|
151
|
+
let i = 0, n = 0, lat = 0, lng = 0, bad = 0, c, v, s, out;
|
|
152
|
+
if (flat) {
|
|
153
|
+
// Every value ends with exactly one character below code 95.
|
|
154
|
+
for (; i < len; i++) n += (str.charCodeAt(i) - 95) >>> 31;
|
|
155
|
+
out = new Float64Array(n & ~1);
|
|
156
|
+
i = n = 0;
|
|
157
|
+
} else out = len < 64 ? [] : Array(len >> 1);
|
|
158
|
+
// One value is one or more 5-bit chunks. `bad` collects every character
|
|
159
|
+
// code: anything outside 0..63 after the -63 shift sets a high bit, and
|
|
160
|
+
// so does a 7th chunk in one value (25 - s < 0). NaN past the end of
|
|
161
|
+
// a truncated string ends the value and leaves i past len.
|
|
162
|
+
while (i < len) {
|
|
163
|
+
c = str.charCodeAt(i++) - 63;
|
|
164
|
+
bad |= c;
|
|
165
|
+
v = c & 31;
|
|
166
|
+
for (s = 5; c >= 32; s += 5) {
|
|
167
|
+
c = str.charCodeAt(i++) - 63;
|
|
168
|
+
bad |= c | (25 - s);
|
|
169
|
+
v |= (c & 31) << s;
|
|
170
|
+
}
|
|
171
|
+
lat += (v >>> 1) ^ -(v & 1);
|
|
172
|
+
c = str.charCodeAt(i++) - 63;
|
|
173
|
+
bad |= c;
|
|
174
|
+
v = c & 31;
|
|
175
|
+
for (s = 5; c >= 32; s += 5) {
|
|
176
|
+
c = str.charCodeAt(i++) - 63;
|
|
177
|
+
bad |= c | (25 - s);
|
|
178
|
+
v |= (c & 31) << s;
|
|
179
|
+
}
|
|
180
|
+
lng += (v >>> 1) ^ -(v & 1);
|
|
181
|
+
if (flat) {
|
|
182
|
+
out[n + a] = lat / f;
|
|
183
|
+
out[n + 1 - a] = lng / f;
|
|
184
|
+
n += 2;
|
|
185
|
+
} else out[n++] = [lat / f, lng / f];
|
|
186
|
+
}
|
|
187
|
+
if (bad & ~63 || i != len) return null;
|
|
188
|
+
if (out.length != n) out.length = n;
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Encoded characters for every zigzag value below 1024, so one or two
|
|
193
|
+
// characters cost one string concatenation instead of a loop. Built by a
|
|
194
|
+
// pure call, so bundles that never encode can drop it.
|
|
195
|
+
const CHARS = /* @__PURE__ */ Array.from({ length: 1024 }, (_, z) => chars(z));
|
|
196
|
+
|
|
197
|
+
export function chars(z) {
|
|
198
|
+
let s = '';
|
|
199
|
+
for (; z >= 32; z >>>= 5) s += String.fromCharCode((z & 31) + 95);
|
|
200
|
+
return s + String.fromCharCode(z + 63);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const encodeWith = (src, o, flat) => {
|
|
204
|
+
const f = opts(o);
|
|
205
|
+
return (st.dims == 2 && f <= 1e6 && (flat ? src != null && !(src.length % 2) : Array.isArray(src)) ? encodeLoop(src, f, +st.swap, flat) : null) ?? slowEncode(src, f, flat);
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
/** Encodes [lat, lng] tuples, or objects with lat and lng. */
|
|
209
|
+
export const encode = (points, o) => encodeWith(points, o, 0);
|
|
210
|
+
|
|
211
|
+
/** Encodes a flat array of numbers: [lat0, lng0, lat1, lng1, ...]. */
|
|
212
|
+
export const encodeFlat = (values, o) => encodeWith(values, o, 1);
|
|
213
|
+
|
|
214
|
+
// The 2D fast loop, or null when the input needs slowEncode.
|
|
215
|
+
function encodeLoop(src, f, a, flat) {
|
|
216
|
+
const n = flat ? src.length >> 1 : src.length;
|
|
217
|
+
let s = '', i = 0, la = 0, lb = 0, x, y, p, q, z, pt;
|
|
218
|
+
try {
|
|
219
|
+
for (; i < n; i++) {
|
|
220
|
+
if (flat) {
|
|
221
|
+
x = src[i * 2 + a];
|
|
222
|
+
y = src[i * 2 + 1 - a];
|
|
223
|
+
} else {
|
|
224
|
+
pt = src[i];
|
|
225
|
+
x = pt[a];
|
|
226
|
+
y = pt[1 - a];
|
|
227
|
+
}
|
|
228
|
+
// Anything but numbers goes the slow way, which coerces numeric
|
|
229
|
+
// strings and rejects null. The range check is also false for NaN.
|
|
230
|
+
if (typeof x != 'number' || typeof y != 'number' || !((x *= f) < LIMIT && x > -LIMIT && (y *= f) < LIMIT && y > -LIMIT)) return null;
|
|
231
|
+
// Round half away from zero. floor(|x| + 0.5) is exact here except for
|
|
232
|
+
// |x| = 0.49999999999999994, where the addition rounds up to 1, so any
|
|
233
|
+
// |x| < 0.5 is set to 0 afterwards. Math.round would be exact on its own,
|
|
234
|
+
// but it measured 40% slower on JavaScriptCore.
|
|
235
|
+
p = x < 0 ? -((0.5 - x) | 0) : (x + 0.5) | 0;
|
|
236
|
+
q = y < 0 ? -((0.5 - y) | 0) : (y + 0.5) | 0;
|
|
237
|
+
if (x < 0.5 && x > -0.5) p = 0;
|
|
238
|
+
if (y < 0.5 && y > -0.5) q = 0;
|
|
239
|
+
z = p - la;
|
|
240
|
+
z = (z << 1) ^ (z >> 31);
|
|
241
|
+
s += z < 1024 ? CHARS[z] : chars(z);
|
|
242
|
+
z = q - lb;
|
|
243
|
+
z = (z << 1) ^ (z >> 31);
|
|
244
|
+
s += z < 1024 ? CHARS[z] : chars(z);
|
|
245
|
+
la = p;
|
|
246
|
+
lb = q;
|
|
247
|
+
}
|
|
248
|
+
} catch {
|
|
249
|
+
// A null point: let slowEncode report it.
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
return s;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Helpers built on top of an entry point's own decode and encode, so every
|
|
256
|
+
// entry uses its fastest paths. Entries call these with /* @__PURE__ */, so
|
|
257
|
+
// bundlers drop the ones nobody imports.
|
|
258
|
+
const lngLat = (o) => ({ ...(typeof o == 'number' ? { precision: o } : o), order: 'lnglat' });
|
|
259
|
+
|
|
260
|
+
/** {lat, lng} objects, the shape Google Maps and Leaflet take. */
|
|
261
|
+
export const latLngs = (decode) => (str, o) => decode(str, o).map(([lat, lng]) => ({ lat, lng }));
|
|
262
|
+
|
|
263
|
+
export const toGeo = (decode) => (str, o) => ({ type: 'LineString', coordinates: decode(str, lngLat(o)) });
|
|
264
|
+
|
|
265
|
+
export const fromGeo = (encode) => (g, o) => {
|
|
266
|
+
if (g?.type == 'Feature') g = g.geometry;
|
|
267
|
+
return g?.type == 'LineString' ? encode(g.coordinates, lngLat(o)) : fail('input', 'Expected a LineString');
|
|
268
|
+
};
|