@duoquote/polytini 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +120 -120
  3. package/dist/types/cli.d.cts +2 -2
  4. package/dist/types/deckgl.d.cts +72 -60
  5. package/dist/types/flexible.d.cts +92 -80
  6. package/dist/types/geojson.jsr.d.cts +111 -0
  7. package/dist/types/google.d.cts +48 -48
  8. package/dist/types/google.jsr.d.cts +72 -60
  9. package/dist/types/index.d.cts +109 -87
  10. package/dist/types/leaflet-auto.d.cts +4 -4
  11. package/dist/types/leaflet-auto.jsr.d.cts +2 -2
  12. package/dist/types/leaflet.d.cts +39 -39
  13. package/dist/types/leaflet.jsr.d.cts +15 -13
  14. package/dist/types/mapbox.d.cts +50 -50
  15. package/dist/types/mapbox.jsr.d.cts +5 -0
  16. package/dist/types/maplibre.d.cts +54 -54
  17. package/dist/types/maplibre.jsr.d.cts +92 -0
  18. package/dist/types/openlayers.d.cts +23 -23
  19. package/dist/types/openlayers.jsr.d.cts +42 -0
  20. package/dist/types/presets.d.cts +70 -66
  21. package/dist/types/turf.d.cts +33 -33
  22. package/dist/types/turf.jsr.d.cts +46 -0
  23. package/dist/types/wasm.d.cts +42 -33
  24. package/package.json +200 -200
  25. package/src/browser.js +15 -15
  26. package/src/bun.js +4 -4
  27. package/src/cli-lib.js +160 -160
  28. package/src/cli.js +7 -7
  29. package/src/core.js +268 -268
  30. package/src/deckgl.js +176 -176
  31. package/src/deno.js +12 -12
  32. package/src/error.js +15 -15
  33. package/src/fast.js +179 -179
  34. package/src/flexible.js +283 -283
  35. package/src/google.js +70 -70
  36. package/src/leaflet-auto.js +11 -11
  37. package/src/leaflet.js +44 -44
  38. package/src/mapbox.js +10 -10
  39. package/src/maplibre.js +57 -57
  40. package/src/node.js +17 -17
  41. package/src/openlayers.js +172 -172
  42. package/src/presets.js +242 -242
  43. package/src/text.js +111 -111
  44. package/src/turf.js +80 -80
  45. package/src/wasm-bytes.js +2 -2
  46. package/src/wasm.js +235 -235
  47. package/src/web.js +9 -9
  48. package/types/cli.d.ts +2 -2
  49. package/types/deckgl.d.ts +72 -60
  50. package/types/flexible.d.ts +92 -80
  51. package/types/geojson.jsr.d.ts +111 -0
  52. package/types/google.d.ts +48 -48
  53. package/types/google.jsr.d.ts +72 -60
  54. package/types/index.d.ts +109 -87
  55. package/types/leaflet-auto.d.ts +4 -4
  56. package/types/leaflet-auto.jsr.d.ts +2 -2
  57. package/types/leaflet.d.ts +39 -39
  58. package/types/leaflet.jsr.d.ts +15 -13
  59. package/types/mapbox.d.ts +50 -50
  60. package/types/mapbox.jsr.d.ts +5 -0
  61. package/types/maplibre.d.ts +54 -54
  62. package/types/maplibre.jsr.d.ts +92 -0
  63. package/types/openlayers.d.ts +23 -23
  64. package/types/openlayers.jsr.d.ts +42 -0
  65. package/types/presets.d.ts +70 -66
  66. package/types/turf.d.ts +33 -33
  67. package/types/turf.jsr.d.ts +46 -0
  68. package/types/wasm.d.ts +42 -33
package/src/cli-lib.js CHANGED
@@ -1,160 +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
- }
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.1';
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 CHANGED
@@ -1,7 +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();
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();