@volter/twin-googlemaps 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.
Files changed (39) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +96 -0
  3. package/dist/src/cli.d.ts +2 -0
  4. package/dist/src/cli.js +23 -0
  5. package/dist/src/googlemaps-auth.d.ts +31 -0
  6. package/dist/src/googlemaps-auth.js +37 -0
  7. package/dist/src/googlemaps-budget.d.ts +61 -0
  8. package/dist/src/googlemaps-budget.js +142 -0
  9. package/dist/src/googlemaps-capabilities.d.ts +3 -0
  10. package/dist/src/googlemaps-capabilities.js +648 -0
  11. package/dist/src/googlemaps-conformance.d.ts +8 -0
  12. package/dist/src/googlemaps-conformance.js +18 -0
  13. package/dist/src/googlemaps-connector.d.ts +94 -0
  14. package/dist/src/googlemaps-connector.js +243 -0
  15. package/dist/src/googlemaps-data.d.ts +87 -0
  16. package/dist/src/googlemaps-data.js +370 -0
  17. package/dist/src/googlemaps-perform-harness.d.ts +5 -0
  18. package/dist/src/googlemaps-perform-harness.js +17 -0
  19. package/dist/src/googlemaps-server.d.ts +14 -0
  20. package/dist/src/googlemaps-server.js +25 -0
  21. package/dist/src/googlemaps-twin.d.ts +2 -0
  22. package/dist/src/googlemaps-twin.js +1116 -0
  23. package/dist/src/googlemaps-types.d.ts +45 -0
  24. package/dist/src/googlemaps-types.js +1 -0
  25. package/dist/src/index.d.ts +11 -0
  26. package/dist/src/index.js +65 -0
  27. package/package.json +52 -0
  28. package/src/cli.ts +22 -0
  29. package/src/googlemaps-auth.ts +52 -0
  30. package/src/googlemaps-budget.ts +168 -0
  31. package/src/googlemaps-capabilities.ts +766 -0
  32. package/src/googlemaps-conformance.ts +24 -0
  33. package/src/googlemaps-connector.ts +250 -0
  34. package/src/googlemaps-data.ts +399 -0
  35. package/src/googlemaps-perform-harness.ts +17 -0
  36. package/src/googlemaps-server.ts +33 -0
  37. package/src/googlemaps-twin.ts +1110 -0
  38. package/src/googlemaps-types.ts +47 -0
  39. package/src/index.ts +124 -0
@@ -0,0 +1,45 @@
1
+ export type GoogleMapsRequest = {
2
+ method: string;
3
+ path: string;
4
+ body?: string;
5
+ root?: string;
6
+ readOnly?: boolean;
7
+ occurredAt?: string;
8
+ headers?: Record<string, string>;
9
+ };
10
+ export type GoogleMapsResponse = {
11
+ status: number;
12
+ body: unknown;
13
+ };
14
+ /** Web-service ("Maps") status enum shared across geocode/directions/etc. */
15
+ export type MapsStatus = 'OK' | 'ZERO_RESULTS' | 'OVER_DAILY_LIMIT' | 'OVER_QUERY_LIMIT' | 'REQUEST_DENIED' | 'INVALID_REQUEST' | 'MAX_ELEMENTS_EXCEEDED' | 'MAX_WAYPOINTS_EXCEEDED' | 'MAX_ROUTE_LENGTH_EXCEEDED' | 'NOT_FOUND' | 'UNKNOWN_ERROR';
16
+ export type LatLng = {
17
+ lat: number;
18
+ lng: number;
19
+ };
20
+ export type Viewport = {
21
+ northeast: LatLng;
22
+ southwest: LatLng;
23
+ };
24
+ export type AddressComponent = {
25
+ long_name: string;
26
+ short_name: string;
27
+ types: string[];
28
+ };
29
+ export type Geometry = {
30
+ location: LatLng;
31
+ location_type: 'ROOFTOP' | 'RANGE_INTERPOLATED' | 'GEOMETRIC_CENTER' | 'APPROXIMATE';
32
+ viewport: Viewport;
33
+ bounds?: Viewport;
34
+ };
35
+ export type GeocodeResult = {
36
+ address_components: AddressComponent[];
37
+ formatted_address: string;
38
+ geometry: Geometry;
39
+ place_id: string;
40
+ types: string[];
41
+ plus_code?: {
42
+ global_code: string;
43
+ compound_code: string;
44
+ };
45
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ export { handleGoogleMapsTwinRequest } from './googlemaps-twin.js';
2
+ export { createGoogleMapsTwinFetch, createGoogleMapsTwinServer, type GoogleMapsTwinFetchOptions } from './googlemaps-server.js';
3
+ export { GOOGLEMAPS_API_BASE, googleMapsRequestForAction, liveGoogleMapsExecute, pullGoogleMapsGeocodes, pullGoogleMapsPlaces, pushGoogleMapsAction, syncGoogleMapsFromReal, } from './googlemaps-connector.js';
4
+ export type { GoogleMapsExecute } from './googlemaps-connector.js';
5
+ export { GOOGLEMAPS_BUDGET_CEILING, GOOGLEMAPS_BUDGET_MAX_RETRY_AFTER_S, GOOGLEMAPS_BUDGET_WINDOW_MS, GOOGLEMAPS_CALL_WEIGHTS, GOOGLEMAPS_RATE_BUDGET, GoogleMapsBudget, GoogleMapsBudgetError, googleMapsBudgetPath, googleMapsCallWeight, splitGoogleMapsPath, } from './googlemaps-budget.js';
6
+ export type { GoogleMapsBudgetErrorKind, GoogleMapsBudgetOptions, GoogleMapsBudgetReservation, GoogleMapsBudgetSnapshot, } from './googlemaps-budget.js';
7
+ export { allPlaces, deterministicDuration, deterministicElevation, deterministicLatLng, deterministicTimeZone, distanceText, durationText, encodePolyline, findPlaceById, findPlaceByLatLng, findPlaceByText, geocodeResultFromPlace, haversineMeters, isZeroResultsQuery, normalizeAddress, stableHash, synthGeocodeResult, viewportAround, } from './googlemaps-data.js';
8
+ export type { CannedPlace } from './googlemaps-data.js';
9
+ export type { AddressComponent, GeocodeResult, Geometry, GoogleMapsRequest, GoogleMapsResponse, LatLng, MapsStatus, Viewport, } from './googlemaps-types.js';
10
+ import { type TwinPack } from '@volter/world-core';
11
+ export declare const pack: TwinPack;
@@ -0,0 +1,65 @@
1
+ export { handleGoogleMapsTwinRequest } from "./googlemaps-twin.js";
2
+ export { createGoogleMapsTwinFetch, createGoogleMapsTwinServer } from "./googlemaps-server.js";
3
+ export { GOOGLEMAPS_API_BASE, googleMapsRequestForAction, liveGoogleMapsExecute, pullGoogleMapsGeocodes, pullGoogleMapsPlaces, pushGoogleMapsAction, syncGoogleMapsFromReal, } from "./googlemaps-connector.js";
4
+ // The client-side rate budget — the fail-closed backstop `liveGoogleMapsExecute` routes every live
5
+ // request through. The mechanism is the kernel's (`@volter/world-core` → rateBudget.ts); these are this
6
+ // vendor's numbers and the typed bindings around them.
7
+ export { GOOGLEMAPS_BUDGET_CEILING, GOOGLEMAPS_BUDGET_MAX_RETRY_AFTER_S, GOOGLEMAPS_BUDGET_WINDOW_MS, GOOGLEMAPS_CALL_WEIGHTS, GOOGLEMAPS_RATE_BUDGET, GoogleMapsBudget, GoogleMapsBudgetError, googleMapsBudgetPath, googleMapsCallWeight, splitGoogleMapsPath, } from "./googlemaps-budget.js";
8
+ export { allPlaces, deterministicDuration, deterministicElevation, deterministicLatLng, deterministicTimeZone, distanceText, durationText, encodePolyline, findPlaceById, findPlaceByLatLng, findPlaceByText, geocodeResultFromPlace, haversineMeters, isZeroResultsQuery, normalizeAddress, stableHash, synthGeocodeResult, viewportAround, } from "./googlemaps-data.js";
9
+ import { registerPack } from '@volter/world-core';
10
+ import { GOOGLEMAPS_RATE_BUDGET as RATE_BUDGET } from "./googlemaps-budget.js";
11
+ import { performGoogleMapsAction, syncGoogleMapsFromRemote } from "./googlemaps-connector.js";
12
+ export const pack = {
13
+ // PROTOCOL 2 (docs/contributing/architecture.md#protocol-2-the-pack-is-a-plugin): the pack is a plugin — its wire, its tree, and its half of the real
14
+ // state system. Moved 2026-09-08. The Google Maps APIs answer questions and accept no writes, so `perform`
15
+ // settles every entry with that reason and only `refresh` ever crosses.
16
+ protocol: '2',
17
+ refresh: { every: '1h', onDemand: { atMost: '60s' } }, // an address's geocode moves rarely; there are no webhooks
18
+ stateSystem: { perform: performGoogleMapsAction, refresh: syncGoogleMapsFromRemote },
19
+ // the round trip seeds one address's geocode — the twin's own door, because the vendor has no writable
20
+ // surface at all
21
+ roundTrip: { method: 'POST', path: '/twin/geocode?key=round-trip', body: { address: '1600 Amphitheatre Parkway, Mountain View, CA', result: { formatted_address: '1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA', geometry: { location: { lat: 37.4224, lng: -122.0842 } }, place_id: 'ChIJ_round_trip', types: ['street_address'] } } },
22
+ // a geocode stands alone — no subject here names another, so there is nothing for rule 5 to follow
23
+ references: [],
24
+ // The LEGACY endpoints this connector calls (Geocoding, Place Details) authenticate with `key=`
25
+ // in the QUERY STRING. Google's newer surfaces (Places API New, Address Validation) accept
26
+ // `X-Goog-Api-Key` instead — if this pack ever pulls through those, the strategy becomes a header
27
+ // and this line is where that is said (googlemaps-auth.ts documents both).
28
+ auth: { in: 'query', name: 'key' },
29
+ parityOrigin: 'http://twin',
30
+ // shapeParity is NOT held, for a structural reason rather than a divergence: the Geocoding API has no
31
+ // inventory to enumerate — you ask it about an address, and nothing lists what you have asked. A refresh
32
+ // into a fresh root therefore has nothing to ask about, so the gate's comparison has no ground here.
33
+ vendor: 'googlemaps',
34
+ // The SAME object googlemaps-budget.ts declares at module load — one source of truth, so
35
+ // registering the pack and importing the connector arm identical numbers.
36
+ rateBudget: RATE_BUDGET,
37
+ transport: 'rest',
38
+ archetype: 'crud',
39
+ bin: 'world-googlemaps',
40
+ // The subject types the twin SERVES over its own API — the R2 resource-level claim.
41
+ // `place` is deliberately NOT here: it is a connector-side projection that only
42
+ // `pullGoogleMapsPlaces` / `syncGoogleMapsFromReal` fold in from a real account through an
43
+ // injected client, and no route reads it back — Place Details answers from the canned
44
+ // corpus (`findPlaceById` over googlemaps-data.ts's PLACES), never from stored state.
45
+ // `geocode` stays because the twin both writes it (POST /twin/geocode) and serves it
46
+ // (the Geocoding route's stateful override); `audit` because GET /twin/audit reads it.
47
+ resources: ['geocode', 'audit'],
48
+ specSource: 'Google Maps Platform web-service APIs (Geocoding, Distance Matrix, Directions, Places + Places API New, Roads, Time Zone, Elevation, Geolocation, Address Validation, Static Maps, Street View Static) — deterministic canned data in faithful response shapes',
49
+ description: 'Google Maps Platform twin — deterministic, offline replicas of the Maps web-service APIs in vendor-faithful response shapes with the real status semantics + API-key gate.',
50
+ // Adoption + interception, moved off the central maps unchanged (descriptor-first back-migration, adding-a-twin.md §3,
51
+ // 2026-08-31): the official Node client, the `@googlemaps/` scope, the
52
+ // GOOGLEMAPS_* credential stem, and maps.googleapis.com — one of several *.googleapis.com
53
+ // hosts kept as separate vendors rather than one 'google' (see webrisk, gemini).
54
+ adoption: {
55
+ // Google's official Maps Platform Python client (googlemaps/google-maps-services-python).
56
+ pypi: ['googlemaps'],
57
+ sdks: ['@googlemaps/google-maps-services-js'],
58
+ scopes: ['@googlemaps/'],
59
+ envStems: ['GOOGLEMAPS'],
60
+ },
61
+ hosts: [{ host: 'maps.googleapis.com' }],
62
+ browserRouting: { apiPathPrefix: '/maps/api/', loaderHost: 'https://maps.googleapis.com' },
63
+ };
64
+ // registered at import: the kernel learns the pack's state system (protocol 2)
65
+ registerPack(pack);
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@volter/twin-googlemaps",
3
+ "version": "0.1.0",
4
+ "description": "Local Google Maps Platform twin built on @volter/world-core.",
5
+ "author": "Volter (https://github.com/volter-ai)",
6
+ "license": "Apache-2.0",
7
+ "files": [
8
+ "src",
9
+ "README.md",
10
+ "LICENSE",
11
+ "!**/*.test.ts",
12
+ "!**/*.test.tsx",
13
+ "dist"
14
+ ],
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/volter-ai/twin.git",
18
+ "directory": "packages/twin/googlemaps"
19
+ },
20
+ "homepage": "https://github.com/volter-ai/twin/tree/main/packages/twin/googlemaps#readme",
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/src/index.d.ts",
25
+ "default": "./dist/src/index.js"
26
+ }
27
+ },
28
+ "bin": {
29
+ "world-googlemaps": "dist/src/cli.js"
30
+ },
31
+ "scripts": {
32
+ "test": "bun test src/*.test.ts",
33
+ "typecheck": "tsc --noEmit",
34
+ "build": "node ../../../scripts/publish/build.mjs",
35
+ "prepack": "node ../../../scripts/publish/prepare-publish.mjs prepack",
36
+ "postpack": "node ../../../scripts/publish/prepare-publish.mjs postpack"
37
+ },
38
+ "peerDependencies": {
39
+ "@volter/world-core": "2.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "@googlemaps/google-maps-services-js": "^3.4.0",
43
+ "@types/bun": "^1.2.20",
44
+ "@types/node": "^24.0.0",
45
+ "@volter/world-core": "2.0.0",
46
+ "@volter/world-tooling": "0.1.0",
47
+ "typescript": "^5.9.0"
48
+ },
49
+ "engines": {
50
+ "node": ">=22.3"
51
+ }
52
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ import { keepProcessAlive } from '@volter/world-core/lifecycle';
3
+ import { hasFlag, optionValue } from '@volter/world-core/args';
4
+ import { createGoogleMapsTwinServer } from './googlemaps-server.ts';
5
+
6
+ const [cmd, ...rest] = process.argv.slice(2);
7
+ const port = Number(optionValue(rest, '--port', '0')) || undefined;
8
+ const root = optionValue(rest, '--root') || undefined;
9
+ const readOnly = hasFlag(rest, '--read-only');
10
+
11
+ if (cmd === 'serve') {
12
+ const server = await createGoogleMapsTwinServer({ readOnly, ...(root ? { root } : {}), ...(port ? { port } : {}) });
13
+ process.stdout.write(`googlemaps twin${readOnly ? ' [read-only]' : ''} at http://127.0.0.1:${server.port}\n`);
14
+ await keepProcessAlive();
15
+ } else if (cmd === 'conformance') {
16
+ const { checkGoogleMapsConformance } = await import('./googlemaps-conformance.ts');
17
+ const report = await checkGoogleMapsConformance({ ...(root ? { root } : {}) });
18
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
19
+ if (!report.ok) process.exitCode = 1;
20
+ } else {
21
+ process.stdout.write('Usage: world-googlemaps serve|conformance [--port N] [--root DIR] [--read-only]\n');
22
+ }
@@ -0,0 +1,52 @@
1
+ import type { GoogleMapsResponse } from './googlemaps-types.ts';
2
+
3
+ /**
4
+ * Google Maps Platform web services authenticate with an API key, passed either
5
+ * as the `key=` query parameter (legacy web-service APIs: Geocoding, Directions,
6
+ * Distance Matrix, Roads, Time Zone, Elevation, Geolocation, Static Maps, Street
7
+ * View) or as the `X-Goog-Api-Key` header (Places API New, Address Validation).
8
+ *
9
+ * Missing/invalid keys yield REQUEST_DENIED in the API's own status envelope
10
+ * (HTTP 200 with `status:"REQUEST_DENIED"` for legacy web services; a 403
11
+ * google.rpc.Status for the New/v1 APIs). A sentinel key lets verifies exercise
12
+ * OVER_QUERY_LIMIT / OVER_DAILY_LIMIT.
13
+ */
14
+
15
+ export type MapsAuthResult =
16
+ | { ok: true; key: string }
17
+ | { ok: false; status: 'REQUEST_DENIED' | 'OVER_QUERY_LIMIT' | 'OVER_DAILY_LIMIT'; message: string };
18
+
19
+ // Referenced so the GoogleMapsResponse type import stays meaningful for callers.
20
+ export type _AuthResponse = GoogleMapsResponse;
21
+
22
+ export function header(headers: Record<string, string> | undefined, name: string): string | undefined {
23
+ if (!headers) return undefined;
24
+ const lower = name.toLowerCase();
25
+ for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === lower) return v;
26
+ return undefined;
27
+ }
28
+
29
+ /** Extract the API key from `key=` query param or the `X-Goog-Api-Key` header. */
30
+ export function extractKey(url: URL, headers: Record<string, string> | undefined): string | undefined {
31
+ return url.searchParams.get('key') ?? header(headers, 'x-goog-api-key') ?? undefined;
32
+ }
33
+
34
+ /**
35
+ * Validate the API key gate. When `headers` is entirely undefined (the in-process
36
+ * handler default used by most internal callers/tests) and no `key=` is present,
37
+ * auth is treated as pre-satisfied so offline flows keep working. When a key is
38
+ * supplied it is validated; the sentinel keys drive the quota error paths.
39
+ */
40
+ export function authenticate(url: URL, headers: Record<string, string> | undefined): MapsAuthResult {
41
+ const key = extractKey(url, headers);
42
+ if (key === undefined) {
43
+ // Implicit auth: only when callers don't model headers at all.
44
+ if (headers === undefined) return { ok: true, key: 'twin-implicit' };
45
+ return { ok: false, status: 'REQUEST_DENIED', message: 'The provided API key is invalid or missing. Pass `key=` or the X-Goog-Api-Key header.' };
46
+ }
47
+ if (!key.trim()) return { ok: false, status: 'REQUEST_DENIED', message: 'The provided API key is empty.' };
48
+ if (key === 'over-query-limit') return { ok: false, status: 'OVER_QUERY_LIMIT', message: 'You have exceeded your rate-limit for this API.' };
49
+ if (key === 'over-daily-limit') return { ok: false, status: 'OVER_DAILY_LIMIT', message: 'You have exceeded your daily request quota for this API.' };
50
+ if (key === 'request-denied') return { ok: false, status: 'REQUEST_DENIED', message: 'This API key is not authorized to use this service or API.' };
51
+ return { ok: true, key };
52
+ }
@@ -0,0 +1,168 @@
1
+ // Google Maps Platform's CLIENT-SIDE RATE BUDGET — the pack's DECLARATION (the numbers) plus the
2
+ // thin typed bindings `liveGoogleMapsExecute` uses. The MECHANISM — the durable token-keyed ledger,
3
+ // the rolling window, reserve-under-lock, the `Retry-After`/429 cooldown, fail-CLOSED on a corrupt
4
+ // ledger — lives ONCE in the vendor-agnostic kernel (`@volter/world-core` → `rateBudget.ts`). Read that
5
+ // module's header for the full rationale AND for the honest list of what the guard does not
6
+ // guarantee (an injected clock or ledger path still defeats it — it guards carelessness, not malice).
7
+ //
8
+ // ── WHY THIS EXISTS: THE MISSING CHOKE POINT ─────────────────────────────────────────────────
9
+ // A ~4.5-day Figma token lockout (2026-07-25) came from a burst of raw vendor calls made OUTSIDE
10
+ // any guarded client. The lesson generalized: a pack with no single construction site for its live
11
+ // client is a pack that CANNOT be protected, because there is nowhere for a guard to sit.
12
+ //
13
+ // This connector took an INJECTED `GoogleMapsExecute` and nothing more. That is excellent for
14
+ // testing — every verify runs offline against a fake — but it meant the pack itself never built a
15
+ // network-calling execute, so a rate budget could only ever be something the CALLER opted into.
16
+ // `liveGoogleMapsExecute` (in `googlemaps-connector.ts`) is the choke point that fixes that: the ONE
17
+ // place in this pack that turns a credential into a function that really talks to
18
+ // maps.googleapis.com, with this budget charged BEFORE every request goes out. The injected-function
19
+ // contract is untouched — the factory is an ADDITION for production callers, not a replacement.
20
+ //
21
+ // ── HOW THE CEILING WAS CHOSEN ───────────────────────────────────────────────────────────────
22
+ // Google DOES publish a scalar for the endpoint this connector leans on hardest: the Geocoding API
23
+ // is documented as rate-limited to 3,000 QPM (queries per minute), counted as the sum of client-side
24
+ // and server-side queries (developers.google.com/maps/documentation/geocoding/usage-and-billing). The
25
+ // per-PROJECT scoping and the 'temporarily blocked' warning come from the Maps Platform FAQ's
26
+ // usage-limits section, not from the Geocoding page — two sources, cited separately (§9, 2026-07-26). Exceeding a product's QPM returns an error, and REPEATEDLY exceeding it can
27
+ // get access "temporarily blocked" — the lockout shape this guard exists to prevent.
28
+ //
29
+ // So: 300 weighted units per 60s, with a geocode priced at 1. That is 300 geocodes a minute — TEN
30
+ // PERCENT of the documented limit — while a careless loop is refused after 300 rather than running
31
+ // until Google blocks the project. The kernel independently caps any declaration at 1,000 units per
32
+ // window and 20 units/second, so modeling the vendor's 3,000 QPM literally was never on the table;
33
+ // 10% is a deliberate choice inside that cap, sized so the legitimate workload (a pull of a few
34
+ // dozen addresses) fits many times over in one window.
35
+ //
36
+ // ── HOW THE WEIGHTS WERE CHOSEN (and what is a judgement call) ────────────────────────────────
37
+ // Google counts REQUESTS, per API method per project, so weight 1 is the faithful price for a call
38
+ // and the geocode endpoint — the one with a VERIFIED, generous 3,000 QPM figure — gets it.
39
+ //
40
+ // Everything else is priced at `defaultWeight` (2) or above, never below, because Google documents
41
+ // that "the rate limit per minute is per API method per project" WITHOUT publishing the per-method
42
+ // numbers for the Places surfaces. An endpoint whose limit we cannot read is an endpoint we must not
43
+ // assume is generous.
44
+ //
45
+ // Place Details is priced at 4 — above default. That is a JUDGEMENT CALL, not a published cost: it
46
+ // is the only endpoint in this connector whose response is unbounded in size (a full place record),
47
+ // and Google publishes no per-minute figure for it. Unknown limit + heaviest response ⇒ dearest
48
+ // price. No billing figure is cited here because none was verified.
49
+ import {
50
+ declareRateBudget,
51
+ rateBudgetPath,
52
+ rateBudgetWeight,
53
+ RateBudget,
54
+ type RateBudgetDeclaration,
55
+ type RateBudgetOptions,
56
+ type RateBudgetReservation,
57
+ type RateBudgetSnapshot,
58
+ } from '@volter/world-core';
59
+
60
+ const VENDOR = 'googlemaps';
61
+
62
+ /** Rolling window, in ms. Spend older than this is pruned. Matches Google's own per-MINUTE quotas. */
63
+ export const GOOGLEMAPS_BUDGET_WINDOW_MS = 60_000;
64
+
65
+ /**
66
+ * Weighted units allowed inside one window. 300 geocodes/60s = 10% of the documented 3,000 QPM.
67
+ */
68
+ export const GOOGLEMAPS_BUDGET_CEILING = 300;
69
+
70
+ /** Seconds. A `Retry-After` above this means the project is throttled hard — fail loudly. */
71
+ export const GOOGLEMAPS_BUDGET_MAX_RETRY_AFTER_S = 300;
72
+
73
+ /** Per-call cost, keyed by the `<METHOD> <path>` this connector is about to request. See the header. */
74
+ export const GOOGLEMAPS_CALL_WEIGHTS = {
75
+ /** `GET /maps/api/geocode/json` — documented 3,000 QPM, the most generous figure Google publishes. */
76
+ geocode: 1,
77
+ /** `GET /maps/api/place/details/json` — unbounded response, NO published per-minute figure. */
78
+ placeDetails: 4,
79
+ /** Anything this pack has not classified. Priced like a read, never free. */
80
+ other: 2,
81
+ } as const;
82
+
83
+ /**
84
+ * THE PACK'S DECLARATION — pure data, the only Google-specific thing in the whole budget. Rules are
85
+ * ordered and first-match-wins, and they are keyed on `"<METHOD> <pathname>"` (not the bare path):
86
+ * Google's quotas are per API METHOD, and a write to a surface is not the same call as a read of it,
87
+ * so the method has to be part of what gets priced.
88
+ *
89
+ * Also exported as `pack.rateBudget` (see index.ts), so `registerPack` arms it too.
90
+ */
91
+ export const GOOGLEMAPS_RATE_BUDGET: RateBudgetDeclaration = {
92
+ windowMs: GOOGLEMAPS_BUDGET_WINDOW_MS,
93
+ ceiling: GOOGLEMAPS_BUDGET_CEILING,
94
+ defaultWeight: GOOGLEMAPS_CALL_WEIGHTS.other,
95
+ maxRetryAfterSeconds: GOOGLEMAPS_BUDGET_MAX_RETRY_AFTER_S,
96
+ rules: [
97
+ { match: '^GET /maps/api/place/details', weight: GOOGLEMAPS_CALL_WEIGHTS.placeDetails },
98
+ { match: '^GET /maps/api/geocode/', weight: GOOGLEMAPS_CALL_WEIGHTS.geocode },
99
+ ],
100
+ reason:
101
+ 'Google documents the Geocoding API as rate-limited to 3,000 QPM (queries per minute), counted as the ' +
102
+ 'sum of client-side and server-side queries, and the Maps Platform FAQ warns that repeatedly exceeding ' +
103
+ 'a product\'s QPM can get access temporarily blocked. 300 weighted units / 60s prices a geocode at 1, so the ceiling is ' +
104
+ '10% of that documented limit — many times a legitimate pull of a few dozen addresses, and a hard stop ' +
105
+ 'for the careless loop that the ~4.5-day Figma lockout (2026-07-25) showed the cost of. Place Details ' +
106
+ 'costs 4 because Google publishes NO per-minute figure for it and its response is the pack\'s largest — ' +
107
+ 'a judgement call, not a published cost.',
108
+ };
109
+
110
+ // Declared at module load, so merely importing this module (which `googlemaps-connector.ts` does) is
111
+ // enough to arm the real ceiling. A budget constructed BEFORE this runs falls back to the kernel's
112
+ // DEFAULT_RATE_BUDGET, which is tighter in call count but prices every endpoint at 2 — cheaper than
113
+ // the weight below for Place Details — so "the fallback is always safer" would be a false comfort.
114
+ // `RateBudget` reads its policy live precisely so this declaration takes effect the moment it lands,
115
+ // and constructing through the subclass below (which imports this module) makes the ordering a
116
+ // non-issue in practice.
117
+ declareRateBudget(VENDOR, GOOGLEMAPS_RATE_BUDGET);
118
+
119
+ /** Split a connector path (which carries its own query string) into pathname + parsed query. */
120
+ export function splitGoogleMapsPath(path: string): { pathname: string; query: Record<string, string> } {
121
+ const q = path.indexOf('?');
122
+ if (q < 0) return { pathname: path, query: {} };
123
+ const query: Record<string, string> = {};
124
+ for (const [k, v] of new URLSearchParams(path.slice(q + 1))) query[k] = v;
125
+ return { pathname: path.slice(0, q), query };
126
+ }
127
+
128
+ /**
129
+ * Price one call. Keyed off the request the connector is ABOUT to make, so an unclassified endpoint
130
+ * still costs `defaultWeight` — an unknown endpoint must never be free.
131
+ */
132
+ export function googleMapsCallWeight(method: string, path: string): number {
133
+ const { pathname, query } = splitGoogleMapsPath(path);
134
+ return rateBudgetWeight(VENDOR, `${(method || 'GET').toUpperCase()} ${pathname}`, query);
135
+ }
136
+
137
+ /** Where Google Maps' ledger lives. API-key-keyed and cwd-independent by default (the quota is per
138
+ * project/key, so a cwd-scoped ledger would hand the same key a fresh allowance in every checkout,
139
+ * worktree and CI matrix leg); pass `root` to opt into world-scoped accounting instead. */
140
+ export function googleMapsBudgetPath(opts: { root?: string; token?: string } | string = {}): string {
141
+ const o = typeof opts === 'string' ? { root: opts } : opts;
142
+ // VENDOR spread LAST: a loosely-typed `{ vendor: 'other', … }` slipping through (TypeScript's
143
+ // excess-property check only catches object literals) must not redirect this pack's ledger to
144
+ // another vendor's file.
145
+ return rateBudgetPath({ ...o, vendor: VENDOR });
146
+ }
147
+
148
+ /** Construction options for Google Maps' budget. The vendor is fixed; everything else may only TIGHTEN. */
149
+ export type GoogleMapsBudgetOptions = Omit<RateBudgetOptions, 'vendor'>;
150
+
151
+ /**
152
+ * Google Maps' budget — the shared kernel guard bound to this vendor's declaration. A real subclass,
153
+ * not an alias, so `budget instanceof GoogleMapsBudget` in `liveGoogleMapsExecute` still means "a
154
+ * budget that accounts against GOOGLEMAPS' ledger under GOOGLEMAPS' ceiling": another vendor's
155
+ * `RateBudget` (with its own, possibly larger, ceiling) is NOT assignable there.
156
+ */
157
+ export class GoogleMapsBudget extends RateBudget {
158
+ constructor(opts: GoogleMapsBudgetOptions = {}) {
159
+ super({ ...opts, vendor: VENDOR });
160
+ }
161
+ }
162
+
163
+ /** The typed refusal. One error class shared with every other vendor's budget; `err.vendor` says
164
+ * which one refused, and `err.kind` says why. */
165
+ export { RateBudgetError as GoogleMapsBudgetError } from '@volter/world-core';
166
+ export type { RateBudgetErrorKind as GoogleMapsBudgetErrorKind } from '@volter/world-core';
167
+ export type GoogleMapsBudgetReservation = RateBudgetReservation;
168
+ export type GoogleMapsBudgetSnapshot = RateBudgetSnapshot;