@mccaskie-labs/workbench-places 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # @mccaskie-labs/workbench-places
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - README: the form tool's Address field uses the place search and the places route. The first version through the trusted publisher.
8
+
9
+ ## 0.1.0
10
+
11
+ ### Minor Changes
12
+
13
+ - First release: the Philippine place list (every barangay of the PSA's October 2026 PSGC, with cities that are their own province placed in the province around them), barangay-first place search ("san isidro laur" to San Isidro, Laur, Nueva Ecija) that runs in the project for free, `createGeocoder` for the Gateway's new `POST /v1/geocode` (Geoapify), and `placesRoute`, the project route a page's address box calls.
package/README.md CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # @mccaskie-labs/workbench-places
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
+ Places for Workbench apps. It's one building block that the form tool's Address field uses now and the Maps tool will use later. Nothing in it is specific to forms or to maps.
4
+
5
+ - **The Philippine place list** (`/ph`): every region, province, city, municipality and barangay, from the PSA's Philippine Standard Geographic Code (PSGC). `searchBarangays("san isidro laur")` returns `San Isidro, Laur, Nueva Ecija`, best match first. It runs in the project, so it is free. A city that the PSGC counts as its own province (Cebu City, Davao City) is placed in the province around it, which is how people describe it.
6
+ - **The address look-up client** (`/geocode`): `createGeocoder({ gateway, key, environment })` calls the Gateway's `POST /v1/geocode` for full address suggestions, lookups and reverse lookups, using Geoapify. The project's `search` budget pays for it. Call it only from the project's Worker, so the key never reaches a page.
7
+ - **The place route** (`/route`): `placesRoute(request, { lists, geocoder, countries })` answers a page's address box. `kind=place` searches the place lists and `kind=address` asks the look-up. If a lookup can't be made it answers `unavailable: true` instead of failing, and the page offers "Type it in instead".
8
+
9
+ Every result is a `Place`: `{ label, parts, source, code?, lat?, lng?, precision }`. In the Philippines `parts.suburb` is the barangay, `parts.city` the city or municipality and `parts.state` the province. In Australia `parts.suburb` is the suburb and `parts.state` is NSW, VIC and so on.
10
+
11
+ ## Updating the Philippine list
12
+
13
+ The PSA publishes a new PSGC every three months. Download `barangay_flat.json` from the MIT-licensed [`barangay`](https://pypi.org/project/barangay/) package, run `node scripts/psgc.mjs <path> <release date>`, then bump this package.
14
+
15
+ ## Used by
16
+
17
+ - The form tool's Address field (`workbench-forms` 0.19.0): its barangay-and-town search reads `searchPlaceLists`, and its suggestions come through `placesRoute`.
@@ -0,0 +1,53 @@
1
+ import type { Place } from "./types.ts";
2
+ export interface GeocoderOptions {
3
+ /** The Gateway's address, such as https://gateway.mccaskielabs.dev. */
4
+ gateway: string;
5
+ /** The project's Gateway key. */
6
+ key: string;
7
+ /** "staging" or "production": the key's own environment. */
8
+ environment: string;
9
+ /** For tests; the global fetch by default. */
10
+ fetch?: typeof fetch;
11
+ }
12
+ export interface SuggestRequest {
13
+ /** What has been typed so far: 3 to 200 characters. */
14
+ text: string;
15
+ /** Where the address may be: 1 to 5 two-letter country codes. */
16
+ countries: readonly string[];
17
+ /** 1 to 10, 5 by default. */
18
+ limit?: number;
19
+ /** Near this point first. */
20
+ near?: {
21
+ lat: number;
22
+ lng: number;
23
+ };
24
+ /**
25
+ * One opaque value per person per box (up to 64 characters), so the
26
+ * Gateway can group their typing for its rate limit. Never stored with the text.
27
+ */
28
+ session?: string;
29
+ /** What the look-up is for, as X-Workbench-Job (forms.address by default). */
30
+ job?: string;
31
+ }
32
+ export interface ReverseRequest {
33
+ lat: number;
34
+ lng: number;
35
+ countries: readonly string[];
36
+ job?: string;
37
+ }
38
+ /** The Gateway refused or couldn't answer: its error code (budget_exceeded, rate_limited, vendor_paused and so on). */
39
+ export declare class GeocodeError extends Error {
40
+ readonly code: string;
41
+ readonly status?: number | undefined;
42
+ readonly name = "GeocodeError";
43
+ constructor(code: string, message: string, status?: number | undefined);
44
+ }
45
+ export interface Geocoder {
46
+ suggest(req: SuggestRequest): Promise<Place[]>;
47
+ /** The best match for a whole address, or null. */
48
+ lookup(req: Omit<SuggestRequest, "limit" | "session">): Promise<Place | null>;
49
+ reverse(req: ReverseRequest): Promise<Place | null>;
50
+ }
51
+ /** The Gateway's results as places, dropping anything malformed. */
52
+ export declare function placesFromWire(body: unknown): Place[];
53
+ export declare function createGeocoder(o: GeocoderOptions): Geocoder;
@@ -0,0 +1,76 @@
1
+ // The client for the Gateway's address look-up (POST /v1/geocode): full
2
+ // address suggestions as someone types, an address to a point, and a point
3
+ // to an address, from Geoapify. Called only from the project's own Worker
4
+ // with its Gateway key (the `search` scope and budget), never from a page, so
5
+ // the key never reaches a browser. It imports nothing.
6
+ /** The Gateway refused or couldn't answer: its error code (budget_exceeded, rate_limited, vendor_paused and so on). */
7
+ export class GeocodeError extends Error {
8
+ code;
9
+ status;
10
+ name = "GeocodeError";
11
+ constructor(code, message, status) {
12
+ super(message);
13
+ this.code = code;
14
+ this.status = status;
15
+ }
16
+ }
17
+ const PRECISIONS = new Set(["address", "street", "suburb", "city", "region"]);
18
+ const text = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
19
+ /** The Gateway's results as places, dropping anything malformed. */
20
+ export function placesFromWire(body) {
21
+ const out = [];
22
+ for (const r of body?.results ?? []) {
23
+ const label = text(r?.label);
24
+ const country = text(r?.parts?.country);
25
+ if (!label || !country)
26
+ continue;
27
+ const parts = { country: country.toUpperCase() };
28
+ for (const k of ["line1", "line2", "suburb", "city", "state", "region", "postcode"]) {
29
+ const v = text(r.parts?.[k]);
30
+ if (v)
31
+ parts[k] = v;
32
+ }
33
+ const place = { label, parts, source: "lookup", precision: PRECISIONS.has(String(r.precision)) ? r.precision : "address" };
34
+ if (typeof r.lat === "number" && typeof r.lng === "number" && Number.isFinite(r.lat) && Number.isFinite(r.lng)) {
35
+ place.lat = r.lat;
36
+ place.lng = r.lng;
37
+ }
38
+ out.push(place);
39
+ }
40
+ return out;
41
+ }
42
+ export function createGeocoder(o) {
43
+ const go = o.fetch ?? fetch;
44
+ const base = o.gateway.replace(/\/+$/, "");
45
+ const call = async (job, body) => {
46
+ let res;
47
+ try {
48
+ res = await go(`${base}/v1/geocode`, {
49
+ method: "POST",
50
+ headers: { Authorization: `Bearer ${o.key}`, "X-Workbench-Env": o.environment, "X-Workbench-Job": job, "Content-Type": "application/json", Accept: "application/json" },
51
+ body: JSON.stringify(body),
52
+ });
53
+ }
54
+ catch {
55
+ throw new GeocodeError("network", "Couldn't reach the Gateway");
56
+ }
57
+ const data = await res.json().catch(() => undefined);
58
+ if (!res.ok) {
59
+ const e = data?.error;
60
+ throw new GeocodeError(typeof e?.code === "string" ? e.code : "upstream_error", typeof e?.message === "string" ? e.message : `The Gateway answered ${res.status}`, res.status);
61
+ }
62
+ return placesFromWire(data);
63
+ };
64
+ return {
65
+ suggest: (r) => call(r.job ?? "forms.address", {
66
+ job: "suggest",
67
+ text: r.text,
68
+ countries: [...r.countries],
69
+ limit: r.limit ?? 5,
70
+ ...(r.near ? { lat: r.near.lat, lng: r.near.lng } : {}),
71
+ ...(r.session ? { session: r.session } : {}),
72
+ }),
73
+ lookup: async (r) => (await call(r.job ?? "forms.address", { job: "lookup", text: r.text, countries: [...r.countries], limit: 1, ...(r.near ? { lat: r.near.lat, lng: r.near.lng } : {}) }))[0] ?? null,
74
+ reverse: async (r) => (await call(r.job ?? "forms.address", { job: "reverse", lat: r.lat, lng: r.lng, countries: [...r.countries], limit: 1 }))[0] ?? null,
75
+ };
76
+ }
@@ -0,0 +1,4 @@
1
+ export type { AddressParts, CountryCode, Place, Precision } from "./types.ts";
2
+ export { createGeocoder, GeocodeError, placesFromWire, type Geocoder, type GeocoderOptions, type ReverseRequest, type SuggestRequest } from "./geocode.ts";
3
+ export { placesRoute, type PlacesRouteOptions } from "./route.ts";
4
+ export { words } from "./normal.ts";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ // @mccaskie-labs/workbench-places: places for Workbench apps, shared by the
2
+ // form tool's Address field now and the Maps tool later, with nothing in it
3
+ // about either. The Philippine place list is in "./ph" (it is large, so only
4
+ // code that needs it imports it), and the Gateway client in "./geocode".
5
+ export { createGeocoder, GeocodeError, placesFromWire } from "./geocode.js";
6
+ export { placesRoute } from "./route.js";
7
+ export { words } from "./normal.js";
@@ -0,0 +1,2 @@
1
+ /** The words of `text`, each reduced for comparing. Barangay is left out ("Brgy. San Isidro" is San Isidro). */
2
+ export declare function words(text: string, short?: boolean): string[];
package/dist/normal.js ADDED
@@ -0,0 +1,28 @@
1
+ // Words reduced to what search compares: lower case, no accents (Ñ is N),
2
+ // punctuation as spaces, and the short forms people type spelt out.
3
+ const SHORT = {
4
+ sto: "santo",
5
+ sta: "santa",
6
+ brgy: "",
7
+ bgy: "",
8
+ barangay: "",
9
+ pob: "poblacion",
10
+ gen: "general",
11
+ mt: "mount",
12
+ st: "saint",
13
+ };
14
+ /** The words of `text`, each reduced for comparing. Barangay is left out ("Brgy. San Isidro" is San Isidro). */
15
+ export function words(text, short = true) {
16
+ const plain = text
17
+ .normalize("NFD")
18
+ .replace(/[̀-ͯ]/g, "")
19
+ .toLowerCase()
20
+ .replace(/[^a-z0-9]+/g, " ")
21
+ .trim();
22
+ if (!plain)
23
+ return [];
24
+ return plain
25
+ .split(" ")
26
+ .map((w) => (short && Object.hasOwn(SHORT, w) ? SHORT[w] : w))
27
+ .filter(Boolean);
28
+ }
@@ -0,0 +1,4 @@
1
+ export declare const PSGC_RELEASE = "2026-10-12";
2
+ export declare const PH_REGIONS: readonly (readonly [string, string])[];
3
+ export declare const PH_PROVINCES: readonly string[];
4
+ export declare const PH_TOWNS: readonly (readonly [string, string, number, number, 0 | 1, string])[];