geontfy 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 theabbie
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,300 @@
1
- # Temporary Holding Version
1
+ # geontfy
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
+ OpenStreetMap Geohash Proximity PubSub Utility
4
+
5
+ Turn geographic regions into exact-match pub/sub topics. Plan subscriptions and
6
+ publications, filter spatial false positives, and suppress repeated event IDs.
7
+ TypeScript, ESM and CommonJS; Node 18+; no runtime dependencies. The core also
8
+ uses browser-compatible APIs and does not import Node modules.
9
+
10
+ This package calculates routing. Your application owns the broker, credentials,
11
+ subscriber identity, notification UI, persistence, and delivery policy. No network
12
+ requests happen unless you explicitly use a boundary provider or transport.
13
+
14
+ ## Publisher chooses the radius
15
+
16
+ ```ts
17
+ import { createGeontfy, createReceiver } from 'geontfy';
18
+
19
+ const geo = createGeontfy({ precision: 6 });
20
+ const subscription = geo.subscribe('road-alerts', { lat: 12.9716, lon: 77.5946 });
21
+ const publication = geo.publish({
22
+ id: 'road-closure-2026-001',
23
+ topicId: 'road-alerts',
24
+ position: { lat: 12.972, lon: 77.595 },
25
+ radiusMeters: 1500,
26
+ data: { title: 'Road closure', detailsUrl: 'https://example.org/alerts/001' },
27
+ });
28
+
29
+ const receiver = createReceiver();
30
+ const shouldDisplay = await receiver.accept(subscription, publication.event);
31
+ ```
32
+
33
+ Subscribe the device to `subscription.topics`; send `publication.event` to each
34
+ `publication.topics` entry. Keep the receiver alive across incoming messages.
35
+ Call `accept` before displaying an alert. A successful call claims the event ID;
36
+ it is not an acknowledgement that your UI displayed it.
37
+
38
+ The default `publisher-region` mode subscribes a location to its precision-P
39
+ geohash and every ancestor, including a world cell. At P=6 that is seven topics
40
+ per logical topic ID. The publisher covers its radius with disjoint cells. A
41
+ covered location matches exactly one publication topic.
42
+
43
+ ## Subscriber chooses the region
44
+
45
+ ```ts
46
+ import { circle, createGeontfy } from 'geontfy';
47
+
48
+ const geo = createGeontfy({ mode: 'subscriber-region', precision: 6 });
49
+ const subscription = geo.subscribe(
50
+ 'road-alerts',
51
+ circle({ lat: 12.9716, lon: 77.5946 }, 1500),
52
+ );
53
+ const publication = geo.publish({
54
+ id: 'road-closure-2026-001',
55
+ topicId: 'road-alerts',
56
+ position: { lat: 12.972, lon: 77.595 },
57
+ data: { title: 'Road closure' },
58
+ });
59
+ ```
60
+
61
+ Here subscribers use the region's disjoint cover. Publishers send point events
62
+ to every ancestor. A covered point matches exactly one subscription topic.
63
+ Subscribers can also pass GeoJSON `Polygon` or `MultiPolygon` geometries,
64
+ including holes and disconnected components.
65
+
66
+ | Mode | Subscriber | Publisher | Topics on the point side |
67
+ | --- | --- | --- | --- |
68
+ | `publisher-region` | Position | Position plus radius in meters | P + 1 subscriptions |
69
+ | `subscriber-region` | Circle or polygon | Position, radius omitted or zero | P + 1 publications |
70
+
71
+ These are distinct protocols. Namespace, mode, precision and topic ID are part
72
+ of each physical topic. All participants must agree on them. Region-to-region
73
+ intersection is deliberately unsupported: simply fanning out two independently
74
+ compressed covers can miss matches or deliver duplicates. Passing a region to
75
+ the default subscriber or a positive event radius in the reverse mode throws.
76
+ Use separate channels when an application needs both directions.
77
+
78
+ ## Covering and precision
79
+
80
+ Geohash interleaves longitude and latitude bits. It is a binary spatial
81
+ hierarchy; each full character adds five bits and has 32 children, rather than
82
+ four quadtree children. A length-6 cell is approximately 1.22 km east–west by
83
+ 0.61 km north–south at the equator; east–west width decreases with latitude.
84
+
85
+ `coverRegion(region, options)` traverses this hierarchy, rejects exterior cells,
86
+ stops at contained cells, and retains intersecting boundary cells at precision
87
+ P. It recursively merges complete sets of 32 siblings. The result is prefix-free
88
+ and maximally compact for that retained P-level cell union. It is not a claim
89
+ of global minimum subscriptions: one world topic would minimize count by
90
+ broadcasting everything. Precision trades filtering traffic against topic count.
91
+
92
+ Circle/cell classification uses extrema of spherical distance over each cell,
93
+ not a sampled polygon approximation of a circle. Distances use a mean-radius
94
+ sphere (6,371,008.8 meters), not an ellipsoidal surveying model. Radius comparisons
95
+ have a one-micrometer numerical tolerance. Zero radius means the same normalized
96
+ position. Longitude 180 normalizes to -180; either pole has a canonical longitude.
97
+ Circles crossing the date line or enclosing poles are supported.
98
+
99
+ GeoJSON coordinates use `[longitude, latitude]`; position objects use
100
+ `{ lat, lon }`. Polygons use straight longitude/latitude segments as in GeoJSON,
101
+ not geodesic edges. Supply topologically valid polygons: structural validation
102
+ checks coordinates and closed, nondegenerate rings, but does not repair
103
+ self-intersections or invalid hole topology. Split date-line-crossing polygons
104
+ into a MultiPolygon before use, following [RFC 7946](https://www.rfc-editor.org/rfc/rfc7946.html).
105
+ Edges jumping more than 180 degrees are rejected. Polygon boundaries, including
106
+ hole edges, count as inside. Boundaries touching a pole include that geographic
107
+ pole regardless of its input longitude.
108
+
109
+ The empty geohash represents the world, encoded as `world` in broker topics.
110
+ This allows a whole-world radius to use one publication topic. Precision is an
111
+ integer from 1 to 12. Very high precision or complex boundaries may be expensive.
112
+
113
+ ```ts
114
+ const geo = createGeontfy({
115
+ namespace: 'myapp',
116
+ precision: 6,
117
+ maxCells: 2048,
118
+ maxVisited: 100_000,
119
+ maxTopics: 2000,
120
+ });
121
+ ```
122
+
123
+ Budgets throw instead of returning incomplete covers. `maxVisited` counts
124
+ visited cells, `maxCells` limits the final compact cover, and `maxTopics` limits
125
+ each individual plan. Geometry accepts up to 100,000 coordinates; computational
126
+ cost also scales with vertex count. Reduce/simplify very detailed boundaries
127
+ upstream if necessary, taking responsibility for the changed boundary.
128
+
129
+ Topic IDs and namespaces accept 1–80 ASCII letters, digits, underscores or
130
+ hyphens. Data must be finite, acyclic JSON. Plans snapshot input data; treat the
131
+ returned plans as immutable. Give each logical event a stable, unique ID within
132
+ its namespace, mode and topic ID. Reuse that ID on retries, not on new events.
133
+
134
+ ## FCM integration
135
+
136
+ ```ts
137
+ import {
138
+ createFcmTransport,
139
+ dispatch,
140
+ fromFcmData,
141
+ reconcileSubscriptions,
142
+ } from 'geontfy';
143
+
144
+ const transport = createFcmTransport(message => messaging.send(message));
145
+ const result = await dispatch(publication, transport);
146
+
147
+ const updated = await reconcileSubscriptions(previousTopics, subscription, {
148
+ async subscribe(topic) {
149
+ const response = await messaging.subscribeToTopic([deviceToken], topic);
150
+ if (response.failureCount) throw response.errors[0].error;
151
+ },
152
+ async unsubscribe(topic) {
153
+ const response = await messaging.unsubscribeFromTopic([deviceToken], topic);
154
+ if (response.failureCount) throw response.errors[0].error;
155
+ },
156
+ });
157
+
158
+ const envelope = fromFcmData(incomingMessage.data);
159
+ const shouldDisplay = await receiver.accept(subscription, envelope);
160
+ ```
161
+
162
+ `messaging` is your initialized Firebase Admin SDK instance, held on your server.
163
+ Client apps receive and filter the data; they do not receive server credentials.
164
+ The bridge only requires a `send` function, so Firebase is not a dependency.
165
+ It emits data-only messages: display alerts only after spatial filtering and
166
+ ID suppression. Automatic notification display would show edge-cell false
167
+ positives before filtering. Background execution restrictions still apply.
168
+ [FCM message types](https://firebase.google.com/docs/cloud-messaging/customize-messages/set-message-type)
169
+
170
+ FCM permits 2,000 topics per app instance across all interests, not per geontfy
171
+ plan. Account for the union of your subscriptions, other app topics, and temporary
172
+ old/new overlap during movement. Topic delivery favors throughput over latency;
173
+ topics are appropriate for public information, not access control. Physical topic
174
+ names reveal coarse location. [FCM topic limits](https://firebase.google.com/docs/cloud-messaging/topic-messaging)
175
+
176
+ The bridge enforces a conservative 2,048-byte UTF-8 serialized data budget and
177
+ FCM-safe topic names. Keep event payloads small; send an authenticated content
178
+ reference when needed. It does not add TTL, priority, collapse keys, platform
179
+ options or automatic retries. Wrap the send function to apply your delivery
180
+ policy. [FCM payload limits](https://firebase.google.com/docs/cloud-messaging/error-codes)
181
+
182
+ `dispatch` sends sequentially and returns `{ succeeded, failed }`. A success
183
+ means the transport accepted the send, not that devices received it. Retry only
184
+ failed topics with the original event ID:
185
+
186
+ ```ts
187
+ await dispatch({
188
+ ...publication,
189
+ topics: result.failed.map(failure => failure.topic),
190
+ }, transport);
191
+ ```
192
+
193
+ The generic `PublishTransport.publish(topic, event)` works with other exact-match
194
+ brokers. `SubscriptionTransport` has independent `subscribe`/`unsubscribe`
195
+ methods. Adapters must reject when the underlying operation fails, including SDK
196
+ responses that resolve with per-item failures.
197
+
198
+ `reconcileSubscriptions` adds new topics before removing old ones. If any addition
199
+ fails, it leaves all old topics subscribed. It returns the best-known `active`
200
+ topics and operation-specific failures so the app can persist state and retry.
201
+ A lost transport acknowledgement leaves actual broker state uncertain. It cannot
202
+ make movement atomic or share reference counts across independently managed
203
+ interests; reconcile the union for the whole device when interests overlap.
204
+
205
+ ## Delivery guarantees
206
+
207
+ The one-match property applies to a single point/region pair, stable matching
208
+ configuration and a fully applied subscription plan. A point has one ancestor
209
+ at each depth; a prefix-free cover contains at most one of them. Conservative
210
+ covering ensures an in-region point has that match. Exact filtering then removes
211
+ boundary-cell candidates outside the requested region.
212
+
213
+ That spatial property is not exactly-once network delivery. FCM may delay or
214
+ discard messages, and does not guarantee ordering. Devices can be offline or
215
+ moving while subscriptions change. For alerts that must not be missed, persist
216
+ an event log and implement authenticated catch-up alongside push.
217
+ [FCM delivery behavior](https://firebase.google.com/docs/cloud-messaging/customize-messages/collapsible-message-types)
218
+
219
+ `createReceiver` filters before claiming an event ID. Its default in-memory store
220
+ suppresses repeated IDs for 24 hours, up to 10,000 entries, evicting the oldest
221
+ entry when full. Restart, eviction or expiry permits duplicates again. Share one
222
+ receiver across overlapping interests on a device to suppress duplicate display.
223
+ If each interest should process an event separately, give it its own receiver.
224
+
225
+ Inject `{ claim(key): boolean | Promise<boolean> }` via `dedupe` for persistence
226
+ or multi-process consumers. `claim` must atomically return true only for a new
227
+ key, with your own expiry policy. Claiming before display can lose a display if
228
+ the process crashes afterward; transactional inbox/processing semantics belong
229
+ in the application. Malformed envelopes throw; callers should catch and reject
230
+ them. Spatial matching is not authentication or authorization.
231
+
232
+ ## OpenStreetMap boundaries
233
+
234
+ No OSM API or key is needed for coordinates, circles, distance or geohashes.
235
+ OSM provides geographic data, not a proximity pub/sub service. Bring an existing
236
+ GeoJSON boundary, inject a custom `BoundaryProvider`, or use the optional
237
+ Nominatim-compatible lookup adapter:
238
+
239
+ ```ts
240
+ import { createGeontfy, createNominatimProvider } from 'geontfy';
241
+
242
+ const geo = createGeontfy({
243
+ mode: 'subscriber-region',
244
+ boundaryProvider: createNominatimProvider({
245
+ endpoint: 'https://your-nominatim-provider.example/',
246
+ userAgent: 'myapp/1.0 (contact@example.com)',
247
+ headers: { Authorization: `Bearer ${providerApiKey}` },
248
+ }),
249
+ });
250
+
251
+ const boundary = await geo.lookupBoundary('R12345');
252
+ const subscription = geo.subscribe('local-alerts', boundary);
253
+ ```
254
+
255
+ The relation ID above is illustrative. Choose a real OSM way (`W…`) or relation
256
+ (`R…`) representing the desired administrative/neighbourhood boundary. Tags such
257
+ as `boundary=administrative` and `place=neighbourhood` do not guarantee a polygon;
258
+ a place may be a node. The adapter rejects non-polygon or missing results rather
259
+ than inventing a boundary. It looks up known IDs, not arbitrary place searches.
260
+ [Nominatim lookup API](https://nominatim.org/release-docs/latest/api/Lookup/)
261
+
262
+ Configure the endpoint and any provider-specific headers at initialization.
263
+ Providers differ in authentication requirements. The adapter serializes requests,
264
+ coalesces concurrent identical lookups, uses a bounded 24-hour in-memory cache,
265
+ and times out after 10 seconds. You can configure `fetch`, `minIntervalMs`,
266
+ `timeoutMs`, `cacheTtlMs`, and `maxCacheEntries`. Cache entries are copied on return.
267
+ There is no automatic retry or cross-process rate limiter.
268
+
269
+ No public service is selected by default. If you deliberately choose
270
+ `https://nominatim.openstreetmap.org/`, you must comply with its
271
+ [usage policy](https://operations.osmfoundation.org/policies/nominatim/): at most
272
+ one request per second across the entire application, identifying requests,
273
+ caching, attribution, and no systematic/bulk boundary harvesting. The adapter's
274
+ per-instance limiter is insufficient across multiple instances. The public
275
+ service restricts generic geocoding platforms and large-scale usage; use your
276
+ own instance or a suitable provider. The public endpoint rejects configured
277
+ intervals below one second. Browser integrations may require a server proxy for
278
+ headers and centralized limits. Display OpenStreetMap contributor attribution
279
+ and comply with the applicable ODbL terms when using OSM-derived data.
280
+
281
+ ## Development
282
+
283
+ ```sh
284
+ npm ci --ignore-scripts --registry=https://registry.npmjs.org
285
+ npm run build
286
+ npm run check
287
+ npm test
288
+ npm pack --dry-run
289
+ ```
290
+
291
+ Tests exercise both routing directions, deterministic randomized coverage,
292
+ prefix splits, date-line and polar circles, polygon holes and disconnected
293
+ regions, false positives, deduplication, partial transport failures, mocked OSM
294
+ lookups, FCM serialization, and packaged ESM/CommonJS entry points.
295
+ No live FCM or OSM calls are made by the tests.
296
+
297
+ The existing publish workflow uses npm trusted publishing and requires npm-side
298
+ configuration after the first manual publication. No package has been published
299
+ as part of implementation. All publish commands should explicitly target
300
+ `https://registry.npmjs.org`; `publishConfig.registry` also selects that registry.