@duoquote/polytini 0.0.0-stage → 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 (80) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +119 -2
  3. package/dist/deckgl.cjs +250 -0
  4. package/dist/flexible.cjs +229 -0
  5. package/dist/google.cjs +232 -0
  6. package/dist/leaflet-auto.cjs +209 -0
  7. package/dist/leaflet.cjs +231 -0
  8. package/dist/mapbox.cjs +185 -0
  9. package/dist/maplibre.cjs +185 -0
  10. package/dist/node.cjs +322 -0
  11. package/dist/presets.cjs +65 -0
  12. package/dist/turf.cjs +267 -0
  13. package/dist/types/cli.d.cts +2 -0
  14. package/dist/types/deckgl.d.cts +72 -0
  15. package/dist/types/flexible.d.cts +92 -0
  16. package/dist/types/geojson.jsr.d.cts +111 -0
  17. package/dist/types/google.d.cts +48 -0
  18. package/dist/types/google.jsr.d.cts +72 -0
  19. package/dist/types/index.d.cts +109 -0
  20. package/dist/types/leaflet-auto.d.cts +4 -0
  21. package/dist/types/leaflet-auto.jsr.d.cts +2 -0
  22. package/dist/types/leaflet.d.cts +39 -0
  23. package/dist/types/leaflet.jsr.d.cts +15 -0
  24. package/dist/types/mapbox.d.cts +50 -0
  25. package/dist/types/mapbox.jsr.d.cts +5 -0
  26. package/dist/types/maplibre.d.cts +54 -0
  27. package/dist/types/maplibre.jsr.d.cts +92 -0
  28. package/dist/types/openlayers.d.cts +23 -0
  29. package/dist/types/openlayers.jsr.d.cts +42 -0
  30. package/dist/types/presets.d.cts +70 -0
  31. package/dist/types/turf.d.cts +33 -0
  32. package/dist/types/turf.jsr.d.cts +46 -0
  33. package/dist/types/wasm.d.cts +42 -0
  34. package/dist/web.cjs +231 -0
  35. package/package.json +198 -4
  36. package/src/browser.js +15 -0
  37. package/src/bun.js +4 -0
  38. package/src/cli-lib.js +160 -0
  39. package/src/cli.js +7 -0
  40. package/src/core.js +268 -0
  41. package/src/deckgl.js +176 -0
  42. package/src/deno.js +12 -0
  43. package/src/error.js +15 -0
  44. package/src/fast.js +179 -0
  45. package/src/flexible.js +283 -0
  46. package/src/google.js +70 -0
  47. package/src/leaflet-auto.js +11 -0
  48. package/src/leaflet.js +44 -0
  49. package/src/mapbox.js +10 -0
  50. package/src/maplibre.js +57 -0
  51. package/src/node.js +17 -0
  52. package/src/openlayers.js +172 -0
  53. package/src/presets.js +242 -0
  54. package/src/text.js +111 -0
  55. package/src/turf.js +80 -0
  56. package/src/wasm-bytes.js +2 -0
  57. package/src/wasm.js +235 -0
  58. package/src/web.js +9 -0
  59. package/types/cli.d.ts +2 -0
  60. package/types/deckgl.d.ts +72 -0
  61. package/types/flexible.d.ts +92 -0
  62. package/types/geojson.jsr.d.ts +111 -0
  63. package/types/google.d.ts +48 -0
  64. package/types/google.jsr.d.ts +72 -0
  65. package/types/index.d.ts +109 -0
  66. package/types/leaflet-auto.d.ts +4 -0
  67. package/types/leaflet-auto.jsr.d.ts +2 -0
  68. package/types/leaflet.d.ts +39 -0
  69. package/types/leaflet.jsr.d.ts +15 -0
  70. package/types/mapbox.d.ts +50 -0
  71. package/types/mapbox.jsr.d.ts +5 -0
  72. package/types/maplibre.d.ts +54 -0
  73. package/types/maplibre.jsr.d.ts +92 -0
  74. package/types/openlayers.d.ts +23 -0
  75. package/types/openlayers.jsr.d.ts +42 -0
  76. package/types/presets.d.ts +70 -0
  77. package/types/turf.d.ts +33 -0
  78. package/types/turf.jsr.d.ts +46 -0
  79. package/types/wasm.d.ts +42 -0
  80. package/wasm/polytini.wasm +0 -0
package/src/node.js ADDED
@@ -0,0 +1,17 @@
1
+ // Node entry: the core plus the Buffer fast paths in fast.js.
2
+ /* @ts-self-types="../types/index.d.ts" */
3
+ import { Buffer } from 'node:buffer';
4
+ import { fast } from './fast.js';
5
+ import { latLngs, toGeo, fromGeo } from './core.js';
6
+
7
+ export { PolylineError } from './core.js';
8
+ // On V8 12 (Node 22 and 23), a pre-sized array of 100,000 points made decode
9
+ // about 40% slower than appending. Probably because the big array lands in
10
+ // old space and every young point stored into it goes through the write
11
+ // barrier, but I haven't profiled the GC to confirm it. V8 13
12
+ // and 14 (Node 24 on, and what Bun reports) were 25% faster pre-sized, so
13
+ // only V8 12 appends, from 32,768 points.
14
+ export const { decode, decodeFlat, encode, encodeFlat } = fast(Buffer, process.versions.v8?.startsWith('12.') ? 32768 : Infinity);
15
+ export const decodeLatLng = latLngs(decode);
16
+ export const toGeoJSON = toGeo(decode);
17
+ export const fromGeoJSON = fromGeo(encode);
@@ -0,0 +1,172 @@
1
+ // OpenLayers: a faster drop-in for ol/format/Polyline.
2
+ //
3
+ // import Polyline from 'ol/format/Polyline.js';
4
+ // import LineString from 'ol/geom/LineString.js';
5
+ // import { createPolylineFormat } from '@duoquote/polytini/openlayers';
6
+ // const FastPolyline = createPolylineFormat({ Polyline, LineString });
7
+ // const format = new FastPolyline({ factor: 1e6 });
8
+ //
9
+ // The factory takes ol's classes from you instead of importing ol, so
10
+ // polytini has no runtime dependency on it. The class it returns extends
11
+ // the Polyline class you pass and replaces only the two text-level methods,
12
+ // readGeometryFromText and writeGeometryText. Everything else is ol's: the
13
+ // constructor options (factor, geometryLayout), projections, readFeature,
14
+ // readFeatures, writeFeature, writeFeatures and the `decimals` write option.
15
+ //
16
+ // The output is the same as ol's for every input, with one exception: ol's
17
+ // writeGeometry flips XY and writes the deltas into the geometry's own flat
18
+ // coordinates when there is no projection transform (and no `decimals`), so
19
+ // a second writeGeometry of the same geometry gives a wrong string. This
20
+ // class never changes the geometry.
21
+ //
22
+ // What "the same" means in detail:
23
+ // - Coordinates come out as [x, y] = [lng, lat], then Z and M, as plain
24
+ // arrays, and every value, M included, is divided by the factor. A factor
25
+ // of 0 or no factor means 1e5, like ol.
26
+ // - Rounding is ol's, not Google's. ol rounds with
27
+ // `value < 0 ? Math.ceil(value - 0.5) : Math.round(value)`. That is half
28
+ // away from zero for every value except -0.49999999999999994 (the largest
29
+ // double below 0.5, negated), where `value - 0.5` rounds to -1 in floating
30
+ // point, so ol writes -1 where Google's algorithm, and polytini's own
31
+ // encode, write 0. (Values of 2^52 and more differ too, but those are past
32
+ // ol's 32-bit limit anyway.) A drop-in should give the same strings as the
33
+ // format it replaces, so this class rounds like ol.
34
+ // - ol never throws on bad input. Strings that are not plain valid polylines
35
+ // (characters outside '?' to '~', a value cut off at the end, a point with
36
+ // fewer values than the layout has, or a value of more than 30 bits) and
37
+ // geometries with values that do not fit 32-bit deltas (NaN, Infinity, or
38
+ // deltas of 2^29 units or more) are handed to ol's own code, so they give
39
+ // exactly what ol gives, odd results included: a NaN for a missing value,
40
+ // and 32-bit wrap-around for very large values.
41
+ /* @ts-self-types="../types/openlayers.jsr.d.ts" */
42
+ import { chars, LIMIT } from './core.js';
43
+
44
+ const STRIDE = { XY: 2, XYZ: 3, XYM: 3, XYZM: 4 };
45
+
46
+ // Encoded characters for zigzag values below 1024.
47
+ const CHARS = [];
48
+ for (let z = 0; z < 1024; z++) CHARS[z] = chars(z);
49
+
50
+ /**
51
+ * Decodes to ol's flat coordinates ([lng, lat, ...rest] per point), or
52
+ * returns null when the string is anything but a plain valid polyline with
53
+ * a whole number of points and values of at most 6 characters. On those
54
+ * strings ol's 32-bit math is exact, so the result is identical to ol's.
55
+ */
56
+ function decodeFlat(str, stride, f) {
57
+ if (!(stride >= 2 && stride <= 4)) return null;
58
+ const len = str.length, sum = [0, 0, 0, 0];
59
+ let i = 0, n = 0, bad = 0, d, c, v, s;
60
+ // Long lines are counted first (every value ends with exactly one
61
+ // character below code 95) and get one array of the right size: growing
62
+ // an array of a few hundred thousand doubles was slower than the extra
63
+ // pass. Short ones grow by appending, which was faster for them.
64
+ if (len > 50000) for (; i < len; i++) n += (str.charCodeAt(i) - 95) >>> 31;
65
+ const out = n ? new Array(n) : [];
66
+ i = n = 0;
67
+ while (i < len) {
68
+ for (d = 0; d < stride; d++) {
69
+ // Past the end, charCodeAt gives NaN: the value ends and i passes len.
70
+ c = str.charCodeAt(i++) - 63;
71
+ bad |= c;
72
+ v = c & 31;
73
+ for (s = 5; c >= 32; s += 5) {
74
+ c = str.charCodeAt(i++) - 63;
75
+ bad |= c;
76
+ v |= (c & 31) << s;
77
+ }
78
+ bad |= 30 - s;
79
+ sum[d] += (v >>> 1) ^ -(v & 1);
80
+ }
81
+ out[n++] = sum[1] / f;
82
+ out[n++] = sum[0] / f;
83
+ if (stride > 2) out[n++] = sum[2] / f;
84
+ if (stride > 3) out[n++] = sum[3] / f;
85
+ }
86
+ return bad & ~63 || i != len ? null : out;
87
+ }
88
+
89
+ /**
90
+ * Encodes ol flat coordinates without changing them, rounding like ol.
91
+ * Returns null when a delta is not finite or too large for 32-bit math, or
92
+ * the length is not a whole number of points.
93
+ */
94
+ function encodeFlat(flat, stride, f) {
95
+ const n = flat.length, last = [0, 0, 0, 0];
96
+ if (n % stride) return null;
97
+ let s = '', k = 0, d, v, z;
98
+ for (; k < n; k += stride) {
99
+ for (d = 0; d < stride; d++) {
100
+ v = flat[k + (d < 2 ? 1 - d : d)] * f;
101
+ v = v < 0 ? Math.ceil(v - 0.5) : Math.round(v);
102
+ z = v - last[d];
103
+ last[d] = v;
104
+ if (!(z < LIMIT && z > -LIMIT)) return null;
105
+ z = (z << 1) ^ (z >> 31);
106
+ s += z < 1024 ? CHARS[z] : chars(z);
107
+ }
108
+ }
109
+ return s;
110
+ }
111
+
112
+ // The projection step of ol's format, done with the geometry's own
113
+ // transform() so nothing from ol has to be imported. Returns null when ol
114
+ // has to do it itself: tile-pixel projections, which ol handles specially.
115
+ const projections = (options, write) => {
116
+ const fp = options?.featureProjection, dp = options?.dataProjection;
117
+ const tile = (p) => typeof p == 'object' && p?.getUnits?.() == 'tile-pixels';
118
+ if (tile(fp) || tile(dp)) return null;
119
+ // Equal codes need nothing. Different but equivalent projections
120
+ // (EPSG:3857 and EPSG:900913) go through transform(), which copies the
121
+ // values unchanged, so the numbers are the same as ol's.
122
+ return fp && dp && fp !== dp ? (write ? [fp, dp] : [dp, fp]) : [];
123
+ };
124
+
125
+ /**
126
+ * Makes the drop-in class from ol's own. Pass `{ Polyline, LineString }`
127
+ * (ol/format/Polyline.js and ol/geom/LineString.js), or the `ol` namespace
128
+ * of the full build.
129
+ */
130
+ export function createPolylineFormat(ol) {
131
+ const Base = ol?.Polyline ?? ol?.format?.Polyline, LineString = ol?.LineString ?? ol?.geom?.LineString;
132
+ if (typeof Base != 'function' || typeof LineString != 'function') {
133
+ throw new TypeError('createPolylineFormat needs { Polyline, LineString } from ol');
134
+ }
135
+ /** Drop-in for ol/format/Polyline: same options and output, faster, and it never changes the geometry it writes. */
136
+ return class Polyline extends Base {
137
+ constructor(options) {
138
+ super(options);
139
+ options = options || {};
140
+ // ol keeps these as private fields; keep our own copies.
141
+ this.polyFactor_ = options.factor ? options.factor : 1e5;
142
+ this.polyLayout_ = options.geometryLayout ? options.geometryLayout : 'XY';
143
+ }
144
+
145
+ readGeometryFromText(text, options) {
146
+ options = this.adaptOptions(options);
147
+ const layout = this.polyLayout_, p = projections(options, false);
148
+ const flat = p && decodeFlat(text, STRIDE[layout], this.polyFactor_);
149
+ if (!flat) return super.readGeometryFromText(text, options);
150
+ const geometry = new LineString(flat, layout);
151
+ return p.length ? geometry.transform(p[0], p[1]) : geometry;
152
+ }
153
+
154
+ writeGeometryText(geometry, options) {
155
+ options = this.adaptOptions(options);
156
+ const p = projections(options, true);
157
+ let flat = geometry.getFlatCoordinates();
158
+ const stride = geometry.getStride(), f = this.polyFactor_;
159
+ if (p) {
160
+ if (p.length) flat = geometry.clone().transform(p[0], p[1]).getFlatCoordinates();
161
+ // ol's `decimals`: round every value to that many places first.
162
+ if (options?.decimals !== undefined) {
163
+ const power = Math.pow(10, options.decimals);
164
+ flat = flat.map((c) => Math.round(c * power) / power);
165
+ }
166
+ }
167
+ // Anything else goes to ol's own writer, on a copy: it writes the
168
+ // deltas into the geometry it encodes.
169
+ return (p && encodeFlat(flat, stride, f)) ?? super.writeGeometryText(geometry.clone(), options);
170
+ }
171
+ };
172
+ }
package/src/presets.js ADDED
@@ -0,0 +1,242 @@
1
+ // Option presets for routing engines and APIs that use the Google encoded
2
+ // polyline format. Each preset is a plain options object for encode, decode,
3
+ // encodeFlat, decodeFlat, toGeoJSON and fromGeoJSON:
4
+ //
5
+ // import { decode } from '@duoquote/polytini';
6
+ // import { osrm6 } from '@duoquote/polytini/presets';
7
+ // decode(route.geometry, osrm6); // [[lng, lat], ...]
8
+ //
9
+ // This module imports nothing, so it adds no bytes to the codec, and a
10
+ // bundler keeps only the presets you import.
11
+ //
12
+ // How the values were chosen:
13
+ //
14
+ // - precision: the engine's documented precision, checked against its
15
+ // encoder source where the source is public. Presets use `precision`
16
+ // rather than `factor`, so spreading a preset and adding `factor` (for
17
+ // example GraphHopper's points_encoded_multiplier) still works, because
18
+ // factor takes priority over precision.
19
+ // - order: the order of the engine's own unencoded coordinates (GeoJSON or
20
+ // coordinate arrays), so decoded output can be compared with, or used in
21
+ // place of, what the engine returns when you ask it for plain coordinates.
22
+ // The encoded string always stores latitude first; order only changes the
23
+ // tuples you pass in and get back. Override it with a spread, for example
24
+ // { ...valhalla, order: 'latlng' }.
25
+ // - dimensions and zFactor: only for engines that put a third value in the
26
+ // string. Those engines only add it when asked, so each has a 2D preset
27
+ // for the default response and a "3d" preset for the elevation response.
28
+ // A 3D preset on a 2D string throws in strict mode when the value count is
29
+ // not a multiple of 3, and gives wrong points when it is, so pick the
30
+ // preset that matches the request.
31
+ //
32
+ // Rounding: polytini rounds half away from zero, like Google's description
33
+ // and like OSRM and Valhalla (C++ std::round / round). Java's Math.round,
34
+ // used by GraphHopper and openrouteservice, rounds halves toward positive
35
+ // infinity, and some engines floor. This only matters when encoding:
36
+ // decoding gives the engine's exact values for every preset. The core has
37
+ // no rounding option, so where an engine rounds differently, encoding a
38
+ // point with its preset can give a string that differs from the engine's
39
+ // own output by one unit in the last place for some inputs. Each preset
40
+ // below says when that happens.
41
+ //
42
+ // Not covered here, because they are not the Google algorithm:
43
+ // - HERE flexible polyline (a header with precision and a third dimension
44
+ // type, and a different character table). Use '@duoquote/polytini/flexible'.
45
+ // - Bing Maps point compression (each latitude and longitude pair is
46
+ // combined into one value, and it uses a different character table):
47
+ // https://learn.microsoft.com/en-us/bingmaps/rest-services/elevations/point-compression-algorithm
48
+ //
49
+ // Sources were read on 2026-11-26. Commits are the default branch heads on
50
+ // that date.
51
+ /* @ts-self-types="../types/presets.d.ts" */
52
+
53
+ /**
54
+ * Google Maps Platform: the format's own definition, precision 5.
55
+ * https://developers.google.com/maps/documentation/utilities/polylinealgorithm
56
+ *
57
+ * order 'latlng': Google's decoders return latitude first:
58
+ * google.maps.geometry.encoding.decodePath returns Array<LatLng>
59
+ * (https://developers.google.com/maps/documentation/javascript/reference/geometry),
60
+ * and Directions API locations are {lat, lng}. The Routes API can also
61
+ * return GeoJSON ([lng, lat]) with polylineEncoding: GEO_JSON_LINESTRING
62
+ * (https://developers.google.com/maps/documentation/routes/traffic_on_polylines);
63
+ * use { ...google, order: 'lnglat' } to compare with that.
64
+ */
65
+ export const google = { precision: 5, order: 'latlng' };
66
+
67
+ /**
68
+ * OSRM, geometries=polyline (the default), precision 5.
69
+ * Docs: https://github.com/Project-OSRM/osrm-backend/blob/578a12065917e02bf14bb4568f12a2d3c388ba15/docs/http.md
70
+ * ("polyline with precision 5 in [latitude,longitude] encoding"; also
71
+ * http://project-osrm.org/docs/v5.24.0/api/).
72
+ * Encoder: include/engine/polyline_compressor.hpp at the same commit.
73
+ * OSRM stores coordinates as integers at 1e6 and encodes
74
+ * std::round(fixed * 0.1), which rounds half away from zero, as polytini
75
+ * does.
76
+ *
77
+ * order 'lnglat': geometries=geojson returns a GeoJSON LineString, and
78
+ * waypoint, maneuver and intersection locations are [longitude, latitude].
79
+ * The tests check the public demo server's polyline against its GeoJSON.
80
+ */
81
+ export const osrm = { precision: 5, order: 'lnglat' };
82
+
83
+ /** OSRM, geometries=polyline6: as `osrm`, precision 6. */
84
+ export const osrm6 = { precision: 6, order: 'lnglat' };
85
+
86
+ /**
87
+ * Valhalla, precision 6. The native JSON response has trip.legs[].shape;
88
+ * trace_attributes, height and linear_cost_factors also use precision 6.
89
+ * Docs: https://github.com/valhalla/valhalla/blob/4d8b2061b566412ce61eb8a2001b7cfa2392356a/docs/docs/api/decoding.md
90
+ * ("Valhalla APIs use six digits of decimal precision") and
91
+ * docs/docs/api/route/api-reference.md at the same commit.
92
+ * Encoder: valhalla/midgard/encoded.h at the same commit,
93
+ * round(value * 1e6), half away from zero, latitude first.
94
+ *
95
+ * order 'lnglat': Valhalla's only plain coordinate line output is
96
+ * format=osrm with shape_format=geojson, which is [lng, lat]. Request
97
+ * coordinates are {lat, lon} objects, and the JavaScript example in
98
+ * decoding.md returns [lat, lng]; use { ...valhalla, order: 'latlng' } to
99
+ * match that example.
100
+ *
101
+ * With format=osrm the geometry is polyline6 by default (use this preset or
102
+ * osrm6), or polyline5 with shape_format=polyline5 (use `osrm`).
103
+ */
104
+ export const valhalla = { precision: 6, order: 'lnglat' };
105
+
106
+ /**
107
+ * Stadia Maps routing, which runs Valhalla: precision 6, legs[].shape.
108
+ * https://docs.stadiamaps.com/tutorials/getting-directions-in-javascript-from-geospatial-apis-maplibre
109
+ * ("Our polylines have 6 digits of precision, not 5"; the example decodes
110
+ * leg.shape with polyline.toGeoJSON(shape, 6)). Same values as `valhalla`.
111
+ */
112
+ export const stadia = { precision: 6, order: 'lnglat' };
113
+
114
+ /**
115
+ * GraphHopper, points_encoded=true (the default) and elevation=false (the
116
+ * default): paths[].points and paths[].snapped_waypoints.
117
+ * Docs: https://github.com/graphhopper/graphhopper/blob/ce72e96197eb16fcc3ab4f18fdd543fa270be9d5/docs/web/api-doc.md
118
+ * Encoder: ResponsePathSerializer.encodePolyline in
119
+ * web-api/src/main/java/com/graphhopper/jackson/ResponsePathSerializer.java
120
+ * at the same commit.
121
+ *
122
+ * Latitude and longitude use the points_encoded_multiplier parameter,
123
+ * default 1e5 (web-bundle/.../RouteResource.java), which any value of 1 or
124
+ * more can change. The response echoes it as paths[].points_encoded_multiplier
125
+ * since GraphHopper 9.0 (commit 322be2aa43, "polyline multiplier"). For a
126
+ * response with another multiplier use
127
+ * { ...graphhopper, factor: path.points_encoded_multiplier }.
128
+ * GraphHopper's /navigate endpoint (Mapbox compatible) always uses
129
+ * polyline6; use `mapbox6` there.
130
+ *
131
+ * Rounding: Math.round since GraphHopper 9.0 (commit 4a5dbeb3ff, "encoded
132
+ * polyline algorithm: closer to Google spec"); 8.0 and earlier used
133
+ * Math.floor. Math.round rounds halves toward positive infinity, so a
134
+ * scaled value of exactly -2.5 becomes -2 in GraphHopper and -3 in
135
+ * polytini. Only negative values exactly halfway between two steps differ.
136
+ * The floor of older versions differs from rounding about half the time.
137
+ * Decoding is exact for all versions.
138
+ *
139
+ * order 'lnglat': with points_encoded=false, points is a GeoJSON
140
+ * LineString with [lon, lat, elevation] order.
141
+ */
142
+ export const graphhopper = { precision: 5, order: 'lnglat' };
143
+
144
+ /**
145
+ * GraphHopper with elevation=true: a third value per point, elevation in
146
+ * meters times 100 (hard coded, it does not follow
147
+ * points_encoded_multiplier), so centimeters. Decodes to
148
+ * [lng, lat, elevation]. Same encoder and rounding notes as `graphhopper`:
149
+ * a negative elevation exactly halfway between two centimeters (such as
150
+ * -0.125 m) encodes one centimeter higher in GraphHopper than in polytini.
151
+ */
152
+ export const graphhopper3d = { precision: 5, dimensions: 3, zFactor: 100, order: 'lnglat' };
153
+
154
+ /**
155
+ * openrouteservice, /v2/directions/{profile}/json: routes[].geometry,
156
+ * precision 5. ORS uses its own encoder, not GraphHopper's, and the
157
+ * multiplier is fixed.
158
+ * Docs: https://github.com/GIScience/openrouteservice/blob/65fb57b1d6716ef5147af5d62909402eb51a85f4/docs/api-reference/endpoints/directions/geometry-decoding.md
159
+ * and requests-and-return-types.md in the same folder.
160
+ * Encoder: ors-engine/src/main/java/org/heigit/ors/util/PolylineEncoder.java
161
+ * at the same commit: Math.round(lat * 1e5) and Math.round(lng * 1e5), with
162
+ * the same negative halfway difference as `graphhopper`.
163
+ *
164
+ * order 'lnglat': the geojson endpoint returns a LineString, and request
165
+ * coordinates are longitude/latitude pairs.
166
+ */
167
+ export const openrouteservice = { precision: 5, order: 'lnglat' };
168
+
169
+ /**
170
+ * openrouteservice with elevation=true ("elevation also gets encoded for
171
+ * json response encoded polyline", RouteRequest.java): a third value,
172
+ * elevation in meters times 100. Decodes to [lng, lat, elevation].
173
+ *
174
+ * Rounding: ORS floors the elevation, (long) Math.floor(z * 100), where
175
+ * polytini rounds, so polytini can encode one centimeter more than ORS.
176
+ * That includes some whole-centimeter values, because the multiplication
177
+ * is not exact: 1027.1 * 100 is 102709.99999999999, which ORS stores as
178
+ * 1027.09 m. Latitude and longitude follow the `openrouteservice` notes.
179
+ * Decoding is exact.
180
+ */
181
+ export const openrouteservice3d = { precision: 5, dimensions: 3, zFactor: 100, order: 'lnglat' };
182
+
183
+ /**
184
+ * Mapbox Directions, geometries=polyline (the default), precision 5.
185
+ * Docs: https://docs.mapbox.com/api/navigation/directions/
186
+ * ("polyline (default, a polyline with a precision of five decimal
187
+ * places)"). The encoder is not public; the tests check the response
188
+ * fixtures in mapbox/mapbox-java (MIT).
189
+ *
190
+ * order 'lnglat': geometries=geojson returns a LineString, and waypoint,
191
+ * maneuver and intersection locations are [longitude, latitude].
192
+ */
193
+ export const mapbox = { precision: 5, order: 'lnglat' };
194
+
195
+ /** Mapbox Directions, geometries=polyline6: as `mapbox`, precision 6. */
196
+ export const mapbox6 = { precision: 6, order: 'lnglat' };
197
+
198
+ /**
199
+ * Strava API v3: map.polyline and map.summary_polyline on activities,
200
+ * routes and segments, precision 5.
201
+ * Docs: https://developers.strava.com/docs/reference/ (PolylineMap). The
202
+ * docs do not state the precision; the example summary_polyline there
203
+ * starts at 37.82822, -122.26348 at precision 5, next to the example's
204
+ * start_latlng [37.83, -122.26]. The encoder is not public.
205
+ *
206
+ * order 'latlng': Strava's own coordinates (LatLng, start_latlng, the
207
+ * latlng stream) are [latitude, longitude] arrays.
208
+ */
209
+ export const strava = { precision: 5, order: 'latlng' };
210
+
211
+ /**
212
+ * OpenTripPlanner 2: legGeometry.points in the GraphQL APIs, precision 5.
213
+ * Encoder: street/src/main/java/org/opentripplanner/street/geometry/PolylineEncoder.java
214
+ * and application/src/main/java/org/opentripplanner/api/model/geometry/EncodedPolyline.java
215
+ * in opentripplanner/OpenTripPlanner at 14bcee2a04d0c4a012f524b84b0814595130bf99.
216
+ *
217
+ * Rounding: OTP floors, (int) Math.floor(coordinate * 1e5), so encoding
218
+ * with this preset can give a value one step (1e-5 degrees) higher than
219
+ * OTP's for any point that is not on the 1e-5 grid. Decoding is exact.
220
+ *
221
+ * order 'latlng': OTP has no plain coordinate line output; places and
222
+ * steps give lat and lon as separate fields. The preset keeps the string's
223
+ * own latitude first order.
224
+ */
225
+ export const otp = { precision: 5, order: 'latlng' };
226
+
227
+ /** Every preset, keyed by its export name. */
228
+ export const presets = {
229
+ google,
230
+ osrm,
231
+ osrm6,
232
+ valhalla,
233
+ stadia,
234
+ graphhopper,
235
+ graphhopper3d,
236
+ openrouteservice,
237
+ openrouteservice3d,
238
+ mapbox,
239
+ mapbox6,
240
+ strava,
241
+ otp,
242
+ };
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.jsr.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';