@duoquote/geotini 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/CHANGELOG.md ADDED
@@ -0,0 +1,88 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ The first release of `@duoquote/geotini`: an encoder and decoder for the geotini format, version 1, as SPEC.md now means to freeze it.
6
+
7
+ - `encode` and `decode` for GeoJSON geometries, `[lng, lat]`: Point, MultiPoint, LineString, MultiLineString, Polygon with holes, MultiPolygon and GeometryCollection, nested up to 32 deep, empties included, with optional Z and M. Precision 0 to 15, rounded half away from zero like Google's polyline algorithm, and decoded to exactly the numbers polytini gives.
8
+ - `encodeLine` and `decodeLine` for a single line in `[lat, lng]` order. `encodeLine(points)` writes the same string as `encode` of that LineString.
9
+ - Options: `precision`, `zPrecision`, `mPrecision`, `checksum` (`true` for a CRC-32C in 6 characters, `'short'` for 12 bits of it in 2) and `favor` (`'size'` or `'speed'`).
10
+ - `favor: 'size'` is the canonical encoder the format defines (SPEC.md section 16.4): the same string for the same geometry and settings in every implementation and every release. `canonical(str)` gives that string for any valid string, and `canonical(str, { to })` gives it at settings you fix, which is what a cache key needs.
11
+ - `decode(str, { checksum: true })` and `decodeLine(str, { checksum: true })` refuse a string that has no check.
12
+ - `maxLength` and `maxPositions` on `decode`, `decodeLine` and `canonical` limit how long a string may be and how much it may hold. The defaults are 2^24 characters and 2^20 positions. `maxLength` counts UTF-8 bytes, as every implementation does (SPEC.md section 14): a string with a character outside ASCII, which is `BAD_CHARACTER` anyway, is `LIMIT_EXCEEDED` when its bytes are more than the limit. It counted UTF-16 units before, so `decode('é', { maxLength: 1 })` was `BAD_CHARACTER` here and `LIMIT_EXCEEDED` in Rust.
13
+ - `encodeValue`, `decodeValue`, `encodeLineValue`, `decodeLineValue`, `canonicalValue`, `toValue` and `fromValue`: the binary form of the format (SPEC.md section 23), the bits of a string in a `Uint8Array` three quarters as long. On both codecs.
14
+ - `GeotiniError` with a stable `code` for every refusal rule, the same codes as SPEC.md section 14 and every other implementation.
15
+ - `@duoquote/geotini/reference`: the plain, bit-by-bit codec, which decodes the same strings to the same numbers and refuses the same ones with the same codes. Its encoder is the canonical one, and it has `inspect(str)` for a string's header fields and coding choices.
16
+ - Adapters, each its own import, none importing its library: `/leaflet`, `/maplibre`, `/mapbox`, `/openlayers`, `/deckgl`, `/turf` and `/google`. Every function of theirs that reads strings takes `decode`'s options (`checksum`, `maxLength`, `maxPositions`) in the options object it already has; the OpenLayers format takes them in its constructor as `decode`.
17
+ - `/mongodb`: `toDocument` and `fromDocument` keep a geometry as its canonical string next to a GeoJSON field for MongoDB's 2dsphere index, the geometry's box (the default), its centroid or the geometry in 2D. The box is built for MongoDB's sphere: great-circle edges, the antimeridian, caps round the poles, and slices for boxes near half the sphere. `key`, `indexSpec`, `indexGeometry` and the `geoWithin`, `geoIntersects` and `near` filters go with them. No driver is imported. Tested against MongoDB 7.0 and 9.0 with the Node driver 6.0 and 7.9: every box and centroid of 2,602 vectors and 11,967 real geometries was accepted, and holds its geometry as MongoDB reads it. On those real geometries, documents with a centroid field took 0.22 of the BSON of plain GeoJSON documents and 0.33 of the space on disk, with a box 0.32 and 0.39 (integrations/mongodb).
18
+ - `/redis`: `createStore` keeps canonical strings in keys or a hash with each centroid in a GEO set, written in one MULTI, and searches it with GEOSEARCH; `cacheKey` and `cached` key a cache by the canonical string at settings the caller fixes. It takes a node-redis (4 and newer) or ioredis (5 and newer) client. Tested against Redis 6.2, 7.4 and 8.12 and Valkey. The strings took 0.22 of the memory of GeoJSON text on the same geometries (integrations/redis).
19
+ - `binary: true` on `/mongodb`'s `key` and `toDocument` and on `/redis`'s `createStore` keeps the binary value instead of the string: BSON Binary in MongoDB, where `fromDocument` reads either form by its BSON type, and bytes in Redis, read back with buffer replies on ioredis and node-redis 4 and newer. On the same 11,967 geometries a value field took 0.78 of the string field's BSON in MongoDB, and the values 0.82 of the strings' memory in Redis with a key each (0.77 in hashes of 100 fields). The filters, `key` and `set` take a value as input too. The two imports grew by about 0.9 KB gzipped with the codec's value functions, and their budgets with them.
20
+
21
+ ### The format freeze
22
+
23
+ The format got its last changes before this release, after two audits of the spec. Nothing was published before, so no string in the wild is affected. Strings from development builds aren't compatible, though: some are refused now, and at precisions 0 to 4 and 7 the first position reads differently. What changed:
24
+
25
+ - One canonical encoder. The default, `'size'` and `'speed'` encoders used to be normative all three, and SPEC.md didn't fully define any of them. Now SPEC.md defines one encoder completely, in integers, and `favor: 'size'` is that encoder. It costs all six predictors for each geometry and every Rice parameter for each block, and takes the cheapest. On 106,522 geometries and 34,318 lines of the research datasets its strings are 1.0% and 1.7% smaller than the default's, and encoding takes 5 to 17 times as long (5 on buildings, 17 on GPS tracks). The `'size'` encoder it replaced took 2.5 to 11 times. The default and `'speed'` encoders write what they wrote before, apart from the changes below, but they aren't normative any more and may change between releases.
26
+ - Canonical decoding. A valid string is now its geometry, its header options and its coding choices (the predictor of each geometry, the Rice parameter of each block, the predictor bit of Z and of M), and nothing else. Any other second spelling is refused with `NON_CANONICAL`: `wide` on a string that doesn't need it, `openRings` without an open ring or on a type without rings, `hasZ` on a string without a position, a predictor on a geometry or a Z with nothing to predict, and an open path that ends on its first point. In a test, 4,000,000 damaged copies of valid strings left 1,050,438 that still decoded, and every one came out the same, bit for bit, when written again from those three.
27
+ - `canonical(str)` is new, on both codecs.
28
+ - One string per line. `encodeLine` and `encode` were two encoders, and on 32 of 102,954 real lines they wrote different strings for the same points. Now they write the same string at every setting.
29
+ - `checksum: 'short'` is new: the 12 most significant bits of the CRC-32C in 2 characters. It catches every single wrong character in a string of up to 24 characters. In longer strings and for other damage it's 12 bits against chance: about 1 damaged string in 25,000 got through in our test, where the full check let none through.
30
+ - The check is verified first. A decoder now reads the whole 17-bit header, verifies the check, and only then judges the type, the precision and the options, so damage there is `CHECKSUM` too. `decodeLine` gives `WRONG_TYPE` after that.
31
+ - A check can be required. Swapping the first two characters of a checked string can give a valid string without a check, and no check can catch that from the inside. `decode(str, { checksum: true })` refuses a string without one. Of 7.4 million damaged strings, 531 got past the full check that way and none with the option set.
32
+ - Positions with M and no Z (`hasM` without `hasZ`) are reserved, and refused with `UNSUPPORTED_VERSION`. No encoder here ever wrote them.
33
+ - The long form of a Rice parameter can now write -1 and -2, the sparse and the all-zero block, from any earlier parameter. Before, -2 could only follow a parameter of 2 or less and -1 one of 3 or less, so at precision 6 or 7 a block of 16 points that didn't move still cost a few bits per point. Synthetic 1 Hz logs with stops got up to 1.6% smaller at precision 6 and 7, and real GPS tracks up to 0.3%. Most tracks don't change, and nothing changes at precision 5.
34
+ - The short codes for a first position moved to where people live, at precisions 0 to 4 and 7 (5 and 6 already were). A Point at precision 3 in Europe, Asia or Africa north of 8° S is 9 characters where it was 10. At precision 4 a Point is 10 characters and not 11 when its latitude is from 23° to 52.7° or its longitude from -10° to 49.4°; before, that took a place west of 120.6° W or south of 60.3° S. It isn't free: a precision-3 Point in the Americas south of 15° S got one character longer. The precision-7 geometries of the research data are 0.45% smaller.
35
+ - The slope and ortho predictors work in wide strings. They were refused there with `BAD_MODE`, so buildings at precision 8, or in projected metres, fell back to plain differences. Buildings and streets are now 4 to 6% smaller at precision 8 and in projected metres. The gain fades with precision: 2% for buildings at precision 10, nothing at 12. The step arithmetic stays 32-bit; only adding a step to its position is exact.
36
+ - A path that starts beyond 90 degrees of latitude gets a planar ortho frame. Projected buildings at precision 2 went from 1% to 6% smaller than plain differences.
37
+ - Strings with Z or M, and wide strings, are always written by the canonical encoder, so they get all six predictors where the old one tried three. The 3D and 4D tracks of the research data are 2.1% smaller, and they encode about 2.5 times faster, wide buildings about twice.
38
+ - The slope-fold predictor writes every step. Steps of more than 2^29 units back made it fail, and the encoder fell back to another predictor.
39
+ - Error codes: `BAD_MODE` is gone. A count that's larger than the rest of the string can hold is `TRUNCATED` now, so every cut of a valid string gets the same code, and `COUNT_TOO_LARGE` is left for a count the format can't write at all. `LIMIT_EXCEEDED` is new, for a decoder's own limits: `maxLength` and `maxPositions`, and 2^28 characters whatever the caller says.
40
+ - The fast encoders take any input whose rounded integers fit 32 bits and whose first position is on the globe. The old test was on the squares of the coordinates, and sent some of those inputs to the slow encoder.
41
+ - Decoding takes the time it took before the freeze: 1.01, 1.00 and 1.00 of it on Node, Bun and Deno, as the geometric mean over eleven kinds of input in paired runs in fresh processes. One kind is slower by more than the spread of those runs, a mix of collections and short lines, by 2 to 5%: the new refusals cost a few tests per path and per geometry, and that's where they show.
42
+ - The bundles grew: everything from 26,059 to 28,087 bytes gzipped, `decode` alone from 11,131 to 11,927 and `encode` alone from 13,453 to 16,086. The decoder has the new refusals and both checks. The canonical encoder costs all six predictors and writes wide strings and Z and M as well, and it replaced two smaller encoders. The budgets in `scripts/size.js` went up with them.
43
+
44
+ ### After two audits of the release candidate
45
+
46
+ Two more audits read the frozen format and this package. Neither found a reason to change the format, and no string decodes differently. What they found here:
47
+
48
+ - The fast encoder threw `RangeError: offset is out of bounds` once a string passed about 0.7 million characters: a MultiPolygon of 41,123 buildings, or a MultiPoint of 89,634 points. After one failure every later string over 4,096 bytes failed too, until a small one reset the buffer. `encode` with any `favor`, `encodeLine` and `canonical` were all affected. The output buffer was shrunk while its old contents were still copied into it. `test/long.test.js` now writes more than a megabyte and then encodes again.
49
+ - Options are validated. `zPrecision: -1` and `mPrecision: -0.5` were accepted, `checksum: 'none'` or any other truthy value switched the full check on, and `favor: 'fast'` meant the default. The two codecs also disagreed on some of them. Now an option that's given must be one of its values or the call throws a `RangeError`, the same in both codecs. Left out, `undefined` or `null` still means the default.
50
+ - `decode`, `decodeLine` and `canonical` take `maxLength` and `maxPositions`, and both have defaults: 2^24 characters and 2^20 positions. A valid string of a million characters can hold 24 million positions, which took 1.8 GB on Node, and a string half as long again with Z ran Node out of memory. With the defaults a call builds at most about 95 MB (115 MB on Bun). So a larger geometry of your own needs the option now: `decode(str, { maxPositions: Infinity })`. `maxPositions` counts lines, rings, polygons and geometries as well, because empty ones take memory too, and a string is refused where a count says it holds too much, before the positions are read. A string of up to 43,690 characters can't hold enough to pass the default and isn't counted at all. The adapters decode with the default limits and don't take the options yet: for a larger geometry, call `decode` yourself and give them the GeoJSON.
51
+ - `canonical(str, { to })` writes the canonical string at settings you fix. `canonical(str)` keeps the string's own precisions and kind of check, so one geometry has many canonical strings, 48 for a Point and 12,288 for one with Z and M, and the sender picks which. The docs said "one string per geometry", and that only holds at fixed settings. `to` is a precision or the options of `encode`.
52
+ - The allocation rule counts values. A path could reserve its whole array when `2m <= bitsLeft`, the same for positions of 2, 3 or 4 values. It's now one value per bit left: `v * m <= bitsLeft` (SPEC.md section 15). Here that only changes refused strings with Z or M: a megabyte of them made the decoder reserve 17 MB before and 2 MB now. A decoder that keeps a path as flat doubles reserved 97 MB for such a megabyte with Z and M, and reserves at most 48 MB under the new rule.
53
+ - Decoded positions with Z or M are built at their final length. They were `[x, y]` with Z and M pushed on, and V8 keeps room for 17 more numbers in an array that grows by `push`: 216 bytes a position, against 80 with Z and 88 with Z and M now. Lines with Z decode faster on Node and Deno with it: one of 100,000 positions takes 0.54 to 0.57 of the time by the median pass and 0.83 to 0.86 by the fastest pass, and 3D tracks take 0.94. Bun measured no change.
54
+ - The reference codec reads bits from the string as it needs them. It unpacked every string into an array with one element per bit before it read the header, 104 MB for a megabyte, and did it twice for a string with a check. It had no length limit either (23 million characters threw the engine's `RangeError`, not a `GeotiniError`), and its encoder overflowed the stack from 124,720 paths. It now has the limits of the main codec, and loops where it spread arrays.
55
+ - The conformance vectors went from 8,947 normative cases to 9,386. Z was never at precision 15 in them and M only at 0, 1 and 3, because the generator dropped inputs an encoder refused without saying so. Now every Z and every M precision from 0 to 15 is there and the generator stops if one is missing. The 110 cases the two audits proposed are in, and cases can carry what a caller asks of a decoder (`checksum`, `maxLength`, `maxPositions`), 130 of them.
56
+ - Wrong numbers in the docs, each replaced by a measurement. The short check doesn't miss "1 damaged string in 4,096 whatever the change": SPEC.md section 12 now has the rate for each kind of damage, from `scripts/damage.js`. A check costs 4 or 5 characters (short) and 8 or 9 (full) only on a string with the short header, and exactly 2 and 6 on any other. Unix seconds fit as M with up to 5 decimals, where the docs asked for `mPrecision: 0`. `favor: 'speed'` strings aren't "3 to 4% larger" everywhere: nothing on points, 2 to 4% on buildings and streets, 11 to 23% on driving routes. Strings of `favor: 'size'` don't decode "about 2%" slower on tracks: it's 3 to 17% on GPS tracks on Node and up to 19% on Bun. `require()` needs Node 22.12, not 22.0.
57
+ - Decoding speed against the release candidate, as the geometric mean over 15 kinds of input in paired runs in fresh processes: 0.966 on Node, 1.005 on Bun and 0.959 on Deno by the median pass, where under 1 is faster. Without the two kinds with Z it's 1.008, 1.002 and 1.003. Two runs of the same code differ by about 1% there. Points on Deno are the one kind that moved more: 2% slower.
58
+ - The bundles grew with the limits and `canonical`'s target: everything from 28,087 to 28,960 bytes gzipped, `decode` alone from 11,927 to 12,497, `encode` alone from 16,086 to 16,188, and the reference codec from 10,241 to 10,846. The budgets in `scripts/size.js` went up with them.
59
+
60
+ ### The binary form
61
+
62
+ The format got a second way to keep what a string holds, for places that take bytes. No string changed. The four vector files of strings are byte for byte what they were, once the new `binary` fields are taken out, and `node vectors/generate.mjs --check --text` checks that.
63
+
64
+ - A binary value is the bits of a string 8 to a byte, with fewer than 8 zero bits of padding. Every valid string has exactly one value and every valid value one string. On our data a value is 0.750 to 0.775 of its string: 7 bytes for the 9 or 10 characters of a Point at precision 5.
65
+ - `encodeValue`, `decodeValue`, `encodeLineValue`, `decodeLineValue` and `canonicalValue` are the functions without `Value` for a `Uint8Array`. They take the same options and refuse with the same codes. `maxLength` counts bytes, and no value gets `BAD_CHARACTER`. They take a `Uint8Array` from another realm too: they refused one with a `TypeError` before, because of `instanceof`. A `Uint8Array` of 2^32 bytes or more is `LIMIT_EXCEEDED`; `decodeValue` without options used to wrap its length to 32 bits, and took one of 2^32 + 1 bytes for one of 1 byte, past every limit, with a copy of 4 GiB.
66
+ - `toValue(str)` and `fromValue(bytes)` turn one form into the other, exactly. They take a decode, because nothing marks where padding starts: the bytes `00` and `c0` both end in two zero bits, and one is the string `A` and the other `wA`. A string or value that's refused is refused by the conversion with the same code.
67
+ - A value's check is of its bytes: the CRC-32C in 4 bytes, or 16 bits of it in 2. It can't be the string's check, which covers characters whose number a decoder only knows after reading the geometry, and the check has to be verified first. The short one catches every single wrong byte in a value of up to 1,139 bytes. With the check required, none of 22.2 million damaged values got past the full check and 27 of 21.5 million got past the short one (`node scripts/damage-bytes.js`, SPEC.md section 23.2).
68
+ - A value has no marker. A byte of one would be 14% of a Point. So the characters of a string given as bytes can decode as a value: 4 of the 6,470 test strings did, and 5 to 6% of random Points at precision 5. WKB can't: it starts with `00` or `01`, and it's always refused, with `TRAILING_DATA` when nothing else was asked of the decoder. A required check refuses every string's characters, at the price of 4 bytes on a Point (`node scripts/foreign-bytes.js`, SPEC.md section 23.7).
69
+ - Compressed, the form gains nothing: on 27 sets, a column of values was between 0.7% smaller and 4.7% larger than the column of strings under gzip, up to 9.7% larger under brotli and up to 16% under zstd, most of all for short geometries. It's for bytes that are stored as they are.
70
+ - Decoding a value against decoding its string, in paired runs in fresh processes: 0.88 of the time on Node, 0.95 on Bun and 0.89 on Deno as the geometric mean over 15 kinds of input, where under 1 is faster. Points took 0.62 on Node, lines of 3 to 17 points 0.74 and buildings 0.77 to 0.82. Long lines take about the same time: 0.98 to 1.01 with both forms decoded in turn in one process, and 0.92 to 1.11 in the paired runs, on a machine where two runs of the same code differed by that much. Before `decodeValue` had its own short paths for a Point and for a line it was slower than `decode` on Bun, 1.11 to 1.27 on points, short lines and rings.
71
+ - Decoding and encoding strings takes what it took: 1.003 and 0.999 of the time on Node as the geometric mean of the same 15, 0.998 and 1.005 on Bun, and 1.001 and 1.012 on Deno. One case stood out, encoding Points on Deno at 1.13, and it was 1.00 in a second run of 15 rounds: two runs of the same code differ by a quarter there. The decoders of strings aren't touched, and the encoders ask one variable whether to hand out bytes.
72
+ - `encodeValue` takes the time of `encode` on Node and Bun (0.99 and 0.97). On Deno it's slower for small geometries, 6.5 times for Points and 1.2 times for short lines, because a new `Uint8Array` took 0.5 to 1 microsecond there, even one of 7 bytes. Node takes that long too from 65 bytes up, and Bun 9 to 100 nanoseconds. The arrays are still the caller's own, each with its buffer. Handing out views into a shared buffer took 32 to 80 nanoseconds in the same test, and it isn't done.
73
+ - The bundles: everything went from 28,957 to 31,888 bytes gzipped and the reference codec from 10,846 to 11,488. `import { decodeValue }` alone is 11,593, less than `decode` at 12,512, since it has no base64. An import of the fast codec that uses no function for values grew by 9 to 45 bytes. The reference codec's `decode` alone grew by 174, from 5,763 to 5,937, because its reader takes both forms.
74
+ - The vectors got a `binary` field on every case of `decode.json` and of the two encode files, 9,766 values in all with the canonical ones, and two files of their own: `binary-decode.json` with 46 cases and `binary-invalid.json` with 5,980. Four audits of the binary form added 8 and 50 of them, for rules no case had pinned: the bounds rule one over and exactly at each count, with and without a check, a 1 in the padding before a check that holds, a read into the check, and `canonicalValue` at a target. A Python decoder for values was written from SPEC.md section 23 alone, without this package or the vectors. It passed every case there was on its first run, and passes the 14 added since (`reimpl/decode_bin.py`).
75
+ - Checked with 3,000,000 random, changed and cut values and strings, on which both codecs and the Python decoder give the same geometry or the same code, and each form turned into the other and back is itself. And with 81 ways to get a rule of the binary form wrong: the vectors catch 80, two of them only since 14 cases were added for them, and the last one can't change a result.
76
+
77
+ ### Earlier fixes
78
+
79
+ The codec started as a port of an earlier internal one. What changed on the way, before the freeze:
80
+
81
+ - Errors: the fast decoder threw `INVALID` for most refusals. It now reports the specific code, the one a decoder reading bit by bit would report, and the reference codec uses the same names. On 1,000,000 random, mutated and cut strings, decoded in random order through `decode` and `decodeLine` with valid strings decoded in between, the two codecs agreed on every geometry and every code. That test had no strings of the kind in the last item below, where they didn't agree.
82
+ - `decodeLine` applied the bounds rule after allocating the output array. A forged count of 134 million took 140 to 175 ms per string on Bun; now it's refused before anything is allocated.
83
+ - A string can pass that bounds rule at every level at once and still be refused right after its counts: 32 nested GeometryCollections of 1.5 million members each fit in a megabyte, and so does a path of 24 million points. `decode` made `Array(n)` for each count before it read anything, and took 380 MB on Node for the collections, 190 MB for the path and 600 MB for collections around a MultiPolygon, the same on Bun and Deno. Now a collection or a polygon sizes at most 1,024 parts up front, a MultiLineString or MultiPolygon at most 1,024 or one per 32 bits left, and a path at most 65,536 points or one per 2 bits left. The arrays grow if more are written. Those strings now take about 2 MB. Real strings use more bits than that per part and per point, so they keep their exact `Array(n)`: growing instead cost 12% on a MultiPolygon of 3,000 buildings and 20 to 35% on 200,000-point lines on Node. `test/alloc.test.js` checks the memory and the refusal on all three runtimes.
84
+ - A bundle that only imports `encode` no longer includes the base64 decoder and its runtime checks: 13,453 bytes gzipped instead of 14,671.
85
+ - `encodeLine` ignored `zPrecision` and `mPrecision` for `[lat, lng, z]` and `[lat, lng, z, m]` points and used `precision` for all of them, so `{ precision: 5, zPrecision: 2 }` wrote the same string as `{ precision: 5, zPrecision: 5 }`. It now honours both, like `encode`, and writes the same string `encode` writes for that LineString. Lines with only `[lat, lng]` are unchanged.
86
+ - The ortho predictor's cos² scale (SPEC.md section 9.4) truncated `|lat0| * 256 / 90` to 32 bits. At precision 0, for a path whose first latitude is 754,974,720 or more, that wrapped and gave a scale of 0 where the spec gives 16. Strings the encoder wrote there decoded to other points under the reference decoder, and the fast decoder misread such strings from other encoders. Both now compute what the spec says. Only precision 0 can reach that range.
87
+ - `decodeLine` could refuse a string with a code that depended on the previous call. Its fast loops took the end of the string from module state that only `decode` sets, so a refusal inside them was `TRUNCATED` in a fresh process and could be `OUT_OF_RANGE` or `NON_CANONICAL` after decoding a longer string with `decode`. A Go port found it with `LeGIYzfctW8plg2n`. Each loop now uses the end of its own string. The earlier fuzz test missed it because it always called `decode` on the same string just before `decodeLine`.
88
+ - The fast decoder could refuse a string with `TRUNCATED` where SPEC.md section 14 gives `OUT_OF_RANGE`. A Rice-T6 class is too large at a set number of zeros, and in these strings that zero is inside the string, but the decoder only found the refusal after reading past the end. There were four ways in. The slow path (wide strings, and any string with Z or M) read a run of zeros 24 bits at a time and checked for the end of the string before the length of the run. The fast loops read both classes of a pair before checking either, so a run of 36 zeros for y that reached the end hid x's class, and x's quotient, checked past the end, hid y's class. And when x's quotient was 2^31 or more, y's refusal was placed 31 bits too late. A Java port's differential test found it on 3 of 444,385 strings, among them `45APvluqyCgfhZIwnOU__qgB0AAAAEAAGLKnYeLqHQAAAAAA`. On 4,991,630 random, mutated, cut and targeted strings, each decoded through `decode` and `decodeLine`, the two codecs gave different codes for 58,294 strings before the fix and for none after. Valid strings decode as before. `vectors/invalid.json` has 27 new strings for it, 7 of them from an audit of the spec. `test/fuzz.test.js` now also cuts strings where a Rice-T6 value starts and ends them inside a class that's too large, builds strings field by field (header, first position, a Rice parameter anywhere in its range, then runs of zeros around each class limit) and cuts them at every length, and checks that a refusal other than `TRUNCATED` or `TRAILING_DATA` keeps its code when more characters are appended.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Güven Değirmenci
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,332 @@
1
- # Temporary Holding Version
1
+ # geotini for JavaScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@duoquote/geotini` encodes GeoJSON geometries as short, URL-safe strings and decodes them back exactly. Points, lines, polygons with holes, the multi-geometries and collections all work, with optional Z and M values. It has no dependencies and runs on Node 22 and newer, Bun, Deno and in browsers. The format is described in [SPEC.md](https://github.com/Duoquote/geotini/blob/main/SPEC.md).
4
+
5
+ ```sh
6
+ npm i @duoquote/geotini
7
+ ```
8
+
9
+ ```sh
10
+ deno add jsr:@duoquote/geotini
11
+ ```
12
+
13
+ It's ESM with TypeScript types. `require('@duoquote/geotini')` works too on Node 22.12 and newer, which can require an ES module. Node 22.0 to 22.11 need `import`.
14
+
15
+ ## Usage
16
+
17
+ ```js
18
+ import { encode, decode } from '@duoquote/geotini';
19
+
20
+ encode({ type: 'Point', coordinates: [13.40495, 52.52001] });
21
+ // 'DZqSC6hPP'
22
+
23
+ decode('TKxjLqBqz8AWAhCAYVzz5RyEHA');
24
+ // { type: 'Polygon', coordinates: [
25
+ // [[0, 0], [0.001, 0], [0.001, 0.001], [0, 0.001], [0, 0]],
26
+ // [[0.0002, 0.0002], [0.0004, 0.0002], [0.0004, 0.0004], [0.0002, 0.0002]] ] }
27
+
28
+ encode(track, { precision: 6, zPrecision: 1 }); // [lng, lat, elevation] at 0.1 m
29
+ encode(geometry, { favor: 'size' }); // the canonical string, the same in every implementation
30
+
31
+ const checked = encode(geometry, { checksum: true }); // a CRC-32C at the end
32
+ decode(checked, { checksum: true }); // refuses a damaged copy, and a string without a check
33
+ ```
34
+
35
+ Use the last two together. A string says in its first characters whether it has a check, so damage there can turn it into a string without one, and plain `decode(checked)` would read that as if nothing had happened. `{ checksum: true }` on `decode` refuses every string that has no check.
36
+
37
+ For a single line in polyline order, `[lat, lng]`, there's `encodeLine` and `decodeLine`:
38
+
39
+ ```js
40
+ import { encodeLine, decodeLine } from '@duoquote/geotini';
41
+
42
+ encodeLine([[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]]); // 'JXO9tgHjZgAJOtsCSe-KJgFAo4'
43
+ decodeLine('JXO9tgHjZgAJOtsCSe-KJgFAo4'); // [[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]]
44
+ ```
45
+
46
+ ## API
47
+
48
+ | Function | Does |
49
+ |---|---|
50
+ | `encode(geometry, options?)` | A GeoJSON geometry (or a Feature's geometry) to a string. `[lng, lat]`, then `z` and `m`. |
51
+ | `decode(str, options?)` | A string back to a GeoJSON geometry. The precision travels in the string. `checksum: true` refuses a string that has no check, and `maxLength` and `maxPositions` limit how long a string may be and how much it may hold. |
52
+ | `encodeLine(points, options?)` | `[lat, lng]` points to a LineString string, the same one `encode` writes for that LineString. `[lat, lng, z]` and `[lat, lng, z, m]` work too, with the same options as `encode`. |
53
+ | `decodeLine(str, options?)` | A LineString string to `[lat, lng]` points, with the options of `decode`. Other types throw `WRONG_TYPE`. |
54
+ | `canonical(str, options?)` | The canonical string for the geometry `str` decodes to: at the settings `str` has, or at the ones in `options.to`. It reads `str` with the options of `decode`. |
55
+ | `encodeValue(geometry, options?)`, `decodeValue(bytes, options?)` | The same as a `Uint8Array` three quarters as long as the string: see [Binary values](#binary-values). `encodeLineValue`, `decodeLineValue` and `canonicalValue` are the other three. |
56
+ | `toValue(str, options?)`, `fromValue(bytes, options?)` | A string to its binary value, and back. |
57
+ | `GeotiniError` | What decoding throws, with a `code`. |
58
+
59
+ Options are a precision number, or `{ precision, zPrecision, mPrecision, checksum, favor }`:
60
+
61
+ - `precision` is the number of decimals kept, from 0 to 15. The default is 5, about a metre. 6 is about 10 cm, 7 about a centimetre. Rounding is half away from zero, the same as Google's polyline algorithm, so the decoded numbers are exactly what [polytini](https://github.com/Duoquote/polytini) gives for the same points.
62
+ - `zPrecision` and `mPrecision` are the decimals for the third and fourth values. They default to `precision`. A value whose rounded integer passes 2^50 is refused, so a Unix time in seconds fits with up to 5 decimals: it works at the default precision, and at `precision: 6` `encode` throws unless you set `mPrecision`. For whole seconds use `mPrecision: 0`, which also makes the string shorter.
63
+ - `checksum: true` adds a CRC-32C at the end, 6 characters, and `checksum: 'short'` adds 12 bits of it, 2 characters. A string with a check also takes the 3-character header. So at precision 5, 6 or 7 with no other option the full check costs 8 or 9 characters in all and the short one 4 or 5, now and then one less. It's worth it when strings get typed or copied by hand. Without a check, 68% of our test strings with one wrong character still decoded. The full check catches every single wrong character. The short one catches all of them in a string of up to 24 characters, and over all kinds of damage it let about 1 string in 25,000 through.
64
+ - `favor` picks the encoder. `'size'` is the format's canonical encoder: it tries every predictor and every parameter, and its strings are about 1% smaller than the default's, but it takes 5 to 17 times as long. `'speed'` skips the costly predictors for a faster encode, and what that costs in size depends on the data: nothing on points, up to 2.5% on GPS tracks, 2 to 4% on OpenStreetMap buildings and streets, 8% on transit routes, and 11 to 23% on driving routes from a routing engine. All three decode the same way.
65
+
66
+ A check only protects when `decode` requires it. The header says whether a check follows, so an edit to the first characters can turn it into a header without one. That's how every damaged string got past the full check in our test, 531 of 7.4 million. With `decode(str, { checksum: true })` none did, and 277 of 7.1 million got past the short check, each by a chance match of its 12 bits. `node scripts/damage.js` prints the whole table by kind of damage, and SPEC.md section 12 has it.
67
+
68
+ Decoding is strict. A string that isn't valid throws a `GeotiniError` whose `code` says why: `TRUNCATED`, `BAD_CHARACTER`, `TRAILING_DATA`, `CHECKSUM`, `NON_CANONICAL`, `OUT_OF_RANGE`, `UNSUPPORTED_VERSION` and a few more, listed in SPEC.md section 14. The codes are the same in every implementation of the format.
69
+
70
+ ## Limits
71
+
72
+ A string can't expand without bound, but it can expand a lot: up to 24 positions per character. A valid string of a million characters can hold 24 million positions, and decoding one took 1.8 GB of arrays on Node. So `decode`, `decodeLine` and `canonical` have two limits, and a string over either is refused with `LIMIT_EXCEEDED` before the work is done:
73
+
74
+ - `maxLength` is the most characters a string may have. The default is 2^24, about 16.7 million. It counts UTF-8 bytes, as every implementation does, so a character outside ASCII counts 2 to 4: `decode('é', { maxLength: 1 })` is `LIMIT_EXCEEDED`, and at 2 it's `BAD_CHARACTER`.
75
+ - `maxPositions` is the most a string may hold: its positions, plus one for every line, ring, polygon and geometry, because those take memory even when they're empty. The default is 2^20, about a million. A string says how many points each line has before the points come, so one that holds too much is refused at that count.
76
+
77
+ ```js
78
+ decode(str, { maxLength: 4096, maxPositions: 1000 }); // a string from a URL
79
+ decode(big, { maxPositions: 5_000_000 }); // a large geometry of your own
80
+ decode(big, { maxPositions: Infinity }); // no limit
81
+ ```
82
+
83
+ With the defaults one call builds at most about 95 MB on Node and Deno and 115 MB on Bun, whatever the string is. I picked them so that real geometries don't meet them. The largest geometry in the datasets we measure with has 11,573 positions and the longest line 100,000, a tenth of the default. A real geometry takes 1 to 6 characters a position, so one of a million positions is 1 to 7 million characters, under half the default length. For strings from strangers the defaults are still generous, so set both to what your application expects. A string longer than 2^28 characters is refused whatever `maxLength` says, because the decoder keeps bit positions in 32-bit integers.
84
+
85
+ The adapters below take the same options wherever they decode, `checksum` included (see [Adapters](#adapters)).
86
+
87
+ ## Canonical strings
88
+
89
+ An encoder has a few choices: which predictor a geometry uses, and which Rice parameter each block of 16 points gets. So two valid strings can decode to the same geometry, and the default encoder may choose differently in a later release. Nothing else about a string is free. A decoder refuses any other second spelling with `NON_CANONICAL`.
90
+
91
+ When the string itself is the key, use the canonical one. The format defines one canonical encoder down to the last bit, and here it's `favor: 'size'`. For the same geometry and the same settings it writes the same string on every runtime, in every implementation and in every release: the [conformance vectors](https://github.com/Duoquote/geotini/tree/main/vectors) pin about 1,700 of its strings byte for byte. `canonical(str)` gives that string for any valid string:
92
+
93
+ ```js
94
+ import { encode, canonical } from '@duoquote/geotini';
95
+
96
+ const a = encode(polygon); // 'TKxjLqBqz8AWAhCAYVzz5RyEHA'
97
+ const b = encode(polygon, { favor: 'size' }); // 'TKxjLqBqz8ABYgECRc8-ULQIUA'
98
+ canonical(a) === b; // true
99
+ canonical(b) === b; // true: b is canonical
100
+ ```
101
+
102
+ The settings are part of the string, though: the precision of the coordinates, of Z and of M, and the kind of check. `canonical(str)` keeps the ones `str` came with. So the same Point written at precision 5 and at precision 6, or with and without a check, has different canonical strings: 48 of them for a plain Point, and 12,288 for one with Z and M. That's fine for strings you wrote yourself at one setting. For strings from elsewhere a key has to be one string per geometry, so fix the settings in your application and pass them as `to`:
103
+
104
+ ```js
105
+ const KEY = { precision: 6 }; // decided once, for every key
106
+ canonical(a, { to: KEY }) === canonical(b, { to: KEY }); // true exactly when a and b hold the same geometry at 6 decimals
107
+
108
+ // a string from outside: require its check, limit it, and write the key
109
+ canonical(str, { checksum: true, maxPositions: 100_000, to: KEY });
110
+ ```
111
+
112
+ `canonical(str, { to })` is `encode(decode(str), { ...to, favor: 'size' })`. So `to` takes what `encode` takes, a precision or an object, and anything left out is `encode`'s default and not the string's own value: the key above has no check, whatever `str` had. It throws a `RangeError` when the geometry doesn't fit the target, for example a coordinate too large for the precision. A lower precision rounds, so two geometries that only differ below it get the same key.
113
+
114
+ `canonical` runs the slow encoder: about half a microsecond per position here, so 0.4 to 0.6 seconds for a string that holds the default limit of a million positions, and 60 ms for a line of 100,000. Where strangers can call it, set `maxPositions` to what you expect.
115
+
116
+ The canonical encoder doesn't always write the shortest possible string, by the way. It picks the cheapest parameter block by block, and now and then a dearer one would have paid off later.
117
+
118
+ `encodeLine(points)` and `encode` of the LineString with the same positions write the same string, at every setting.
119
+
120
+ ## Binary values
121
+
122
+ A string spends a character on every 6 bits, which is what makes it safe in a URL. Where bytes can be stored as they are, `encodeValue` writes the same bits 8 to a byte:
123
+
124
+ ```js
125
+ import { encodeValue, decodeValue, toValue, fromValue } from '@duoquote/geotini';
126
+
127
+ const value = encodeValue({ type: 'Point', coordinates: [13.40495, 52.52001] });
128
+ // Uint8Array(7) [0x0d, 0x9a, 0x92, 0x0b, 0xa8, 0x4f, 0x3c]. The string, 'DZqSC6hPP', has 9 characters.
129
+
130
+ decodeValue(value); // { type: 'Point', coordinates: [13.40495, 52.52001] }
131
+ fromValue(value); // 'DZqSC6hPP'
132
+ toValue('DZqSC6hPP'); // the same 7 bytes
133
+ ```
134
+
135
+ It isn't a second format. A value holds the bits of its string, every valid string has exactly one value, and both decode to the same numbers. So `encodeValue`, `decodeValue`, `encodeLineValue`, `decodeLineValue` and `canonicalValue` take the options of the functions without `Value` and refuse with the same codes, except that `maxLength` counts bytes and there's no `BAD_CHARACTER`. Any `Uint8Array` goes in, a Node `Buffer`, a view into a larger buffer and one from another realm (an iframe, a `vm` context) included, and a new `Uint8Array` comes out. SPEC.md section 23 has the rules.
136
+
137
+ A value is 0.75 of its string for long geometries and a little more for short ones: 0.753 on buildings, 0.754 on lines of 3 to 17 points, and 0.775 on Points, which are 7 bytes for 9 or 10 characters. That's for a `bytea` or `BLOB` column, a Redis value, a field of MessagePack or Protocol Buffers. It doesn't help where something compresses the data anyway, because a compressor finds the 6 bits in a character on its own. On 27 sets of real geometries, each written as a column both ways and compressed, the values came out between 0.7% smaller and 4.7% larger than the strings with gzip, up to 9.7% larger with brotli and up to 16% larger with zstd. The worst were the short geometries, points of interest and streets of a few points, not the long ones. Over HTTP, in JSON and in URLs, use strings.
138
+
139
+ Three things differ from strings:
140
+
141
+ - The check. A value's check covers its bytes. `checksum: true` is the CRC-32C in 4 bytes, and `'short'` is 16 bits of it in 2, which catches every single wrong byte in a value of up to 1,139 bytes. So `toValue` and `fromValue` compute the check again and don't copy it. As with strings, it only protects when the reader requires it.
142
+ - Converting costs a decode. Nothing in a string or a value marks where its padding starts, so `toValue` and `fromValue` read the whole geometry to know how long the other form is. They also refuse whatever `decode` or `decodeValue` would refuse, with the same code. If you need both forms of the same geometries often, keep both.
143
+ - A value isn't marked. Nothing in it says geotini, and bytes that were never a value can decode as one. The characters of a string given to `decodeValue` are usually refused, but 4 of our 6,470 test strings decoded to some other geometry that way, and Points do it far more often: 5 to 6% of random Points at precision 5, whose first character is a byte that starts a Polygon, and 0.7 to 5.8% of real ones. WKB never does: it starts with a byte `00` or `01`, and no value does unless it's the single byte `00`. WKB as hex text, what PostGIS prints, decoded for about 0.1% of real geometries. Keep values and strings in fields of their own type. Where values come from elsewhere, write them with `checksum` and read them with `{ checksum: true }`, which refuses every string and let none of 13 million random byte sequences through. `node scripts/foreign-bytes.js` prints these numbers.
144
+
145
+ Decoding a value skips base64, and that shows on short geometries. `decodeValue` took 0.62 of `decode`'s time for Points on Node and 0.68 on Deno, 0.72 to 0.74 for lines of 3 to 17 points, and 0.74 to 0.91 for buildings. On Bun the gain is smaller: 0.85 to 0.90 for lines and buildings, and Points came out anywhere from 0.92 to 1.05. Long lines decode in about the same time either way, because base64 is a small part of the work there: 0.98 to 1.01 of it with both forms decoded in turn in one process. The paired runs can't tell them apart. Their ratios were between 0.92 and 1.11 on a machine that was busy with other work, and two runs of the same code differed by as much.
146
+
147
+ `encodeValue` takes the time of `encode` on Node and Bun: 0.99 and 0.97 as geometric means over 15 kinds of input. On Deno it's slower for small geometries, 6.5 times for Points and 1.2 times for short lines and building outlines. A new `Uint8Array` took 0.5 to 1 microsecond there, even one of 7 bytes, which is more than encoding a Point takes. Each call returns an array of its own with its own buffer and not a view into a shared one, and that's what it costs. `toValue` took 0.9 to 1.5 times as long as decoding the string for lines and polygons on Node and Bun, and 2.5 to 3.2 times for Points, where `decode` has a shortcut. These are medians of paired runs in fresh processes on a Linux machine with Node 26, Bun 1.4.5 and Deno 2.9.8.
148
+
149
+ The Rust crate has the binary form too, and so has everything built on it: libgeotini in C, the SQLite and DuckDB extensions and the native PostgreSQL extension. So has the PL/pgSQL version. The Go, Java and Python packages don't have it yet.
150
+
151
+ ## The reference codec
152
+
153
+ `@duoquote/geotini/reference` is the same format written as plainly as I could, one bit at a time, following SPEC.md section by section. It's what the tests check the default codec against. It decodes the same strings to the same numbers and refuses the same strings with the same codes, and it's smaller (11.5 KB gzipped against 31.9 KB), but it's several times slower. Its encoder is the canonical encoder written the plain way, so it writes what `favor: 'size'` writes. It has the functions for binary values too, and `inspect(str)`, which returns a string's header fields and coding choices next to its geometry, a `{ mode }` option to force a predictor, and a `trace` callback that prints each field's bits. `scripts/example.js` uses it to print SPEC.md's worked examples.
154
+
155
+ I made the fast codec the default because it's the one measured against everything else. If bundle size matters more to you than speed and you only decode, the reference is the smaller choice.
156
+
157
+ ## Size and speed
158
+
159
+ Gzipped, bundled with esbuild:
160
+
161
+ | Import | Size |
162
+ |---|--:|
163
+ | everything | 31,888 B |
164
+ | `import { decode }` | 12,512 B |
165
+ | `import { encode }` | 16,233 B |
166
+ | `import { decodeValue }` | 11,593 B |
167
+ | `import { encodeValue, decodeValue }` | 26,922 B |
168
+ | `@duoquote/geotini/reference` | 11,488 B |
169
+
170
+ It's large for a codec because the decoder has a separate loop for each predictor with no function calls inside, which is what made it fast on V8. `encode` is two encoders: the fast one, and the canonical one that also writes every wide string and every string with Z or M. The functions for binary values add about 2.9 KB to "everything" and almost nothing to an import that doesn't use them: `decodeValue` has its own copy of the header and of the two short paths, so that decoding a string costs what it did.
171
+
172
+ Decoding a geometry took 0.15 to 0.16 of the time `JSON.parse` takes for the same geometry as GeoJSON on Node 25 and Deno 2.5, and 0.30 on Bun 1.4.3. Encoding took 0.75 to 0.81 of `JSON.stringify`'s time, and 0.51 to 0.55 with `favor: 'speed'`. A single line decodes at about the speed of a Google polyline with polytini: 1.02 to 1.12 of its time by default and 0.93 to 1.04 with strings written using `favor: 'speed'`. All of these are medians of paired runs in fresh processes on one Windows machine.
173
+
174
+ `favor: 'size'` is the slow one. Against the default encoder it took 5 times as long on buildings, 11 times on country outlines and 17 times on GPS tracks, on all three runtimes. Its strings also decode slower on most data, because the smallest predictor isn't always the fastest one to decode: 10 to 16% on buildings and country outlines and 3 to 17% on GPS tracks on Node, and up to 19% on Bun. Driving routes decode as fast either way. Strings with Z or M and wide strings always come from that encoder, at about 0.4 microseconds per point for 3D tracks and 0.5 for buildings at 8 decimals.
175
+
176
+ ## Adapters
177
+
178
+ Each adapter is its own import and doesn't load its map library: you pass the library in, or the functions call methods on the objects you give them. So none of them adds a dependency, and a bundle that doesn't import an adapter doesn't contain it.
179
+
180
+ Every function that reads strings takes `decode`'s options, `checksum`, `maxLength` and `maxPositions`, in the options object it already has, and they hold for each string. OpenLayers is the exception: there they go in the format's constructor under `decode`. For strings that come from users or from a URL, set them:
181
+
182
+ ```js
183
+ const limits = { checksum: true, maxLength: 4096, maxPositions: 10_000 };
184
+ L.GeoJSON.fromGeotini(str, { ...limits, style: { color: '#c00' } }); // Leaflet
185
+ addGeotiniLayer(map, 'shared', str, { ...limits, layer: { type: 'line' } }); // MapLibre, Mapbox
186
+ new Geotini({ precision: 6, decode: limits }); // OpenLayers
187
+ binaryPaths(strings, { ...limits, z: true }); // deck.gl
188
+ toFeature(str, { ...limits, bbox: true }); // Turf
189
+ toPaths(str, { ...limits, LatLng: google.maps.LatLng }); // Google Maps
190
+ ```
191
+
192
+ A string over a limit throws a `GeotiniError` with `LIMIT_EXCEEDED`, and one without a check under `checksum: true` throws with `CHECKSUM`, as `decode` does. The options the adapter has for itself (`properties`, `layer`, `z`, Leaflet's style options and so on) sit in the same object, and `decode` ignores them.
193
+
194
+ ### Leaflet
195
+
196
+ ```js
197
+ import L from 'leaflet';
198
+ import { install } from '@duoquote/geotini/leaflet';
199
+
200
+ install(L);
201
+ L.GeoJSON.fromGeotini(str).addTo(map); // any geometry type
202
+ L.Polygon.fromGeotini(str, { color: '#c00' }).addTo(map); // Polygon or MultiPolygon, holes included
203
+ L.Polyline.fromGeotini(str).addTo(map); // LineString or MultiLineString
204
+ const back = layer.toGeotini(6); // any layer with toGeoJSON()
205
+ ```
206
+
207
+ Without `install`, the same things are `toLayer(L, str)`, `toLatLngs(str)` and `fromLayer(layer, options)`. A group of several layers encodes as one GeometryCollection string. It reads coordinates with `toGeoJSON(false)`, so Leaflet doesn't round them to 6 decimals first. Leaflet has no M values, so they're left out, and no empty parts: Leaflet 1.9's `toGeoJSON()` throws on a MultiPolygon with an empty polygon in it. Decoder options go with the layer options, `L.Polygon.fromGeotini(str, { color: '#c00', maxPositions: 10_000 })`, and Leaflet keeps them in `layer.options` without using them. Leaflet 1.9 and the Leaflet 2 betas both work; on Leaflet 2 there's no lower-case `L.geotini` factory, because its namespace can't take new properties.
208
+
209
+ ### MapLibre GL and Mapbox GL
210
+
211
+ ```js
212
+ import { addGeotiniLayer, setGeotiniData } from '@duoquote/geotini/maplibre';
213
+
214
+ map.on('load', () => {
215
+ addGeotiniLayer(map, 'parcels', strings, { layer: { paint: { 'fill-color': '#0a7', 'fill-opacity': 0.5 } } });
216
+ });
217
+ setGeotiniData(map, 'parcels', newStrings);
218
+ ```
219
+
220
+ `addGeotiniLayer` adds a GeoJSON source and one layer, a `fill`, `line` or `circle` layer depending on the first geometry, unless `layer.type` says otherwise. For strings of mixed types, add more layers on the same source with a `['geometry-type']` filter. `geotiniData` and `geotiniSource` give the FeatureCollection and the source specification on their own. `@duoquote/geotini/mapbox` has the same functions for Mapbox GL 3.
221
+
222
+ ### OpenLayers
223
+
224
+ ```js
225
+ import GeoJSON from 'ol/format/GeoJSON.js';
226
+ import { createGeotiniFormat } from '@duoquote/geotini/openlayers';
227
+
228
+ const Geotini = createGeotiniFormat({ GeoJSON });
229
+ const format = new Geotini({ precision: 6, featureProjection: 'EPSG:3857' });
230
+ const feature = format.readFeature(str);
231
+ source.addFeature(feature);
232
+ const back = format.writeFeature(feature);
233
+ ```
234
+
235
+ The format is a subclass of ol's GeoJSON format, so projections and every geometry type work the way they do there. It takes the GeoJSON class from you instead of importing ol. Strings hold geometry only, so properties are left out when writing, and `writeFeatures` writes one GeometryCollection string, even for one feature. ol has no empty geometries: an empty Point, LineString, Polygon or MultiPoint reads as no geometry, and drops out of a collection. Decoder options go in the constructor as `decode: { checksum, maxLength, maxPositions }`, apart from encode's options, because `checksum` there means to write a check, and here to require one.
236
+
237
+ ### deck.gl
238
+
239
+ ```js
240
+ import { GeoJsonLayer, PathLayer, SolidPolygonLayer } from '@deck.gl/layers';
241
+ import { geotiniData, binaryPaths, flatPolygons } from '@duoquote/geotini/deckgl';
242
+
243
+ new GeoJsonLayer({ id: 'all', data: geotiniData(strings) });
244
+ new PathLayer({ id: 'outlines', data: binaryPaths(strings), _pathType: 'open', getWidth: 2 });
245
+ new SolidPolygonLayer({ id: 'fill', data: flatPolygons(strings), getPolygon: (d) => d, positionFormat: 'XY' });
246
+ ```
247
+
248
+ `geotiniData` is a FeatureCollection for `GeoJsonLayer`, which draws every type. `binaryPaths` is deck.gl's binary format for `PathLayer`, one typed array for every vertex: each line, and each polygon ring as an outline. `flatPolygons` gives every polygon with its holes as `{ positions, holeIndices }`; deck.gl's binary polygon format has no holes, so this is the way to fill polygons that have them. Both say which string each path or polygon came from, in `featureIds` and `featureId`.
249
+
250
+ ### Turf
251
+
252
+ ```js
253
+ import { toFeature, fromFeature } from '@duoquote/geotini/turf';
254
+
255
+ const area = turf.area(toFeature(str));
256
+ const simpler = fromFeature(turf.simplify(toFeature(str), { tolerance: 0.0001 }), 6);
257
+ ```
258
+
259
+ `toFeature` and `toFeatureCollection` build Features the way Turf does, with optional `properties`, `id` and `bbox`. `fromFeature` and `fromFeatureCollection` encode what Turf gives back.
260
+
261
+ ### Google Maps
262
+
263
+ ```js
264
+ import { toPaths, toPolygons, encodePolygon, addGeoJson } from '@duoquote/geotini/google';
265
+
266
+ const polygon = new google.maps.Polygon({ paths: toPaths(str), map });
267
+ const back = encodePolygon(polygon.getPaths(), 6);
268
+ addGeoJson(map.data, strings); // any geometry type, through the Data layer
269
+ ```
270
+
271
+ `toPaths` covers a LineString, MultiLineString or Polygon, and `toPolygons` a MultiPolygon, one `paths` array per polygon. Paths come out as `{ lat, lng }` literals, or as LatLng objects with `{ LatLng: google.maps.LatLng }`. Google's polygon paths don't repeat the first point at the end, so `toPaths` drops the closing point and `encodePolygon` adds it back, unless the path already ends with its first point. `decodePath` and `encodePath` work like `google.maps.geometry.encoding`'s, for a LineString. `addGeoJson` and `encodeData` go through a `google.maps.Data` layer for every other type.
272
+
273
+ ## Databases
274
+
275
+ Two more imports keep geometries in databases that don't know the format, MongoDB and Redis. Like the map adapters, they import nothing: you pass a client, or they build plain objects for your driver. Each is about 31 KB gzipped, with the codec it imports. [integrations/](https://github.com/Duoquote/geotini/tree/main/integrations) has the details, the storage measured on real data, and recipes for BigQuery and Snowflake.
276
+
277
+ ### MongoDB
278
+
279
+ ```js
280
+ import { toDocument, fromDocument, key, indexSpec, geoIntersects, near } from '@duoquote/geotini/mongodb';
281
+
282
+ await parcels.createIndex(indexSpec()); // { geom_index: '2dsphere' }
283
+ await parcels.createIndex({ geom: 1 }, { unique: true }); // one document per geometry
284
+ await parcels.insertOne({ name, ...toDocument(geometry, { precision: 6 }) });
285
+ const docs = await parcels.find(geoIntersects(viewport)).toArray();
286
+ const g = fromDocument(docs[0], { maxPositions: 100_000 });
287
+ await parcels.find(near([14.42, 50.08], { maxDistance: 500 })).toArray();
288
+ ```
289
+
290
+ MongoDB's 2dsphere index only reads GeoJSON, so `toDocument` gives two fields: `geom`, the canonical string at the settings you pass, and `geom_index`, a small GeoJSON geometry for the index. `index` picks it: `'bbox'` (the default) is the geometry's box as a polygon, `'centroid'` a Point, `'geometry'` the whole geometry in 2D with open rings closed, and `false` none. `field` and `indexField` rename the two. The box is built for MongoDB's sphere: it holds the geometry's great-circle edges, crosses the antimeridian where the geometry does, turns into a cap round a pole, and is cut into slices when it's near half the sphere. A geometry with no positions gets `null`, which no geo query finds, and a position that isn't a longitude and latitude throws a RangeError.
291
+
292
+ The string is always the canonical one (`favor: 'size'`), at `precision`, `zPrecision`, `mPrecision` and `checksum` as given, and a geotini string passed in is written again at those settings, so a unique index on `geom` keeps one document per geometry. `key(input, options)` gives that string alone, for lookups. A string passed in is read with `options.decode`, `decode`'s options.
293
+
294
+ `fromDocument` decodes `geom` (a dotted `field` works) with `decode`'s options, and gives null when the document has none. `geoWithin`, `geoIntersects` and `near` build filters on the index field from a GeoJSON geometry, a Feature or a geotini string. On a box they're a first pass: check the geometries they return yourself, and use `'geometry'` where `$geoWithin` must find everything. `strict: true` reads a Polygon by its winding, for one larger than a hemisphere. `indexGeometry(geometry, index)` gives the index field's geometry on its own.
295
+
296
+ Z and M stay in the string; the index field is 2D.
297
+
298
+ With `binary: true`, `geom` holds the canonical binary value instead of the string (SPEC.md section 23): a `Uint8Array`, which the driver stores as BSON Binary. `key(input, { binary: true })` gives that value, for lookups on a unique index of values. `fromDocument` reads either form, because BSON says whether a field is a string or binary: a string field is decoded as a string, and a Binary (or a Buffer, with `promoteBuffers`) as a value. `key`, `toDocument` and the filters also take a value as their input. On the 11,967 real geometries of [integrations/mongodb](https://github.com/Duoquote/geotini/tree/main/integrations/mongodb), the geometry field as a value took 0.78 of the string's BSON and 0.81 of its space on disk, and documents with a centroid field 0.86 and 0.83 of the same documents with strings. Points gain least: 7 bytes in place of 9 or 10 characters.
299
+
300
+ ### Redis
301
+
302
+ ```js
303
+ import { createStore, cacheKey, cached } from '@duoquote/geotini/redis';
304
+
305
+ const parcels = createStore(client, { prefix: 'parcel:', geoKey: 'parcels:geo', precision: 6 });
306
+ await parcels.set('p1', geometry); // SET parcel:p1 and GEOADD parcels:geo, in one MULTI
307
+ await parcels.get('p1'); // the geometry, or null
308
+ await parcels.search({ lng: 14.42, lat: 50.08, radius: 2, unit: 'km', withGeometry: true });
309
+ const area = await cached(client, str, (g) => String(turf.area(g)), { to: { precision: 6 }, ttl: 3600 });
310
+ ```
311
+
312
+ `client` is a node-redis client (4 and newer) or an ioredis one (5 and newer). A store keeps each geometry as its canonical string in a key of its own (`prefix + id`) or, with `hash`, in fields of one hash, and its centroid in the GEO set `geoKey` (`prefix + 'geo'` unless given, `false` for none). `set` writes both in one MULTI, and `delete` removes both. `getString` and `getMany` read the string, or several geometries with one MGET or HMGET. `search` runs GEOSEARCH (Redis 6.2 and newer) from `{ lng, lat }` or a `member`, by `radius` or a `width` by `height` box, and gives `[{ id, distance }]`, nearest first. `decode` on a store holds `decode`'s options for every string it reads.
313
+
314
+ The centroid is the same as MongoDB's `'centroid'`, with the latitude kept within the ±85.05112878 degrees Redis takes. `geoPoint(geometry)` gives it, and `set(id, geometry, { point })` takes your own.
315
+
316
+ With `binary: true` a store keeps each geometry's canonical binary value (SPEC.md section 23) instead of its string, and `set` returns the `Uint8Array` it wrote. It reads values back as bytes without any setting on the client: `callBuffer` on ioredis, `returnBuffers` on node-redis 4, and a type mapping of blob strings to `Buffer` on node-redis 5 and newer. `getString` converts the value to its string. On the same 11,967 geometries, values took 0.82 of the memory of strings with a key per geometry and 0.77 in hashes of 100 fields: 0.18 and 0.15 of GeoJSON text. Points gain nothing with a key each. I think that's Redis's allocator rounding a value of 7 bytes and one of 10 up to the same size; in hashes of 100 fields they take 0.86.
317
+
318
+ `cacheKey(input, { to })` is the cache key for a geometry: `prefix` ('geotini:cache:') and the canonical string at `to`, the settings your application fixes. `to` is required, since a key at each string's own settings would give one geometry several keys. `cached` reads the key, and otherwise stores `compute(geometry)` there, with `ttl` seconds when given. Values are strings.
319
+
320
+ ## Tests
321
+
322
+ ```sh
323
+ npm test # Node
324
+ npm run test:bun
325
+ npm run test:deno
326
+ ```
327
+
328
+ The suite checks the conformance vectors, exactness against polytini by `Object.is`, every geometry type and predictor mode, every refusal rule with its code, decompression bombs, the two limits and what they count, canonical form on every valid string it can make, and 30,000 random plus mutated and cut strings on which the default and reference codecs must agree, with the limits and without. Binary values get the same: every vector in both forms, each form turned into the other and back, and random, changed and cut values on both codecs.
329
+
330
+ ## License
331
+
332
+ MIT, see [LICENSE](LICENSE).