From d41f773c3c15262230b5905efc11d7e41c5637cd Mon Sep 17 00:00:00 2001 From: Derek J <127624400+heyderekj@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:19:28 -0600 Subject: [PATCH 1/3] sdk 0.4.0: typed records, React and CommonJS entries, pinned CDN URLs Types - ChurchRecord.fields is a typed ChurchFields (string | null, string[], ServiceTimes with slots), so apps read fields without casts. New types: ChurchFields, ChurchField, ServiceTimes, ServiceSlot. - Types resolve under every moduleResolution, including node10, through top-level main/types and typesVersions. The type test now installs the package into a throwaway app and checks bundler, node16, nodenext and node10. - React 19: onchurch-* event props are typed, HTML props come from React's own types, and fieldMap/strings/lookup are typed. Unknown camelCase props such as maxResults are now type errors. Vue templates get typed @church-* events; global JSX (React 18, Preact) gets typed on props. Entries - @heresmychurch/lookup/react exports useChurchLookup (React is an optional peer). The registry hook is now generated from it. - Every entry also builds to .cjs with .d.cts types behind a require condition, so Jest loads it without transforms. Client and element - timeout option (15 s default) fails with LookupError code "timeout"; a caller's abort still rejects with AbortError. - On local dev hosts, warn once when client is unset or a chosen church found no fields to fill. - Core size budget is now 5.5 KB gzipped (was 5 KB). Publishing - Each release is also served at /sdk//, immutable for a year. copy-assets writes it once and never replaces it; site/sdk/0.3.0 and 0.4.0 are committed so pinned versions stay deployed. Docs use the pinned URL, and a test keeps it matching the package version. - package.json gains repository, homepage, bugs, keywords, engines and publishConfig.access; LICENSE and CHANGELOG ship in the tarball. - CI workflow runs pnpm test and pnpm typecheck. Docs: README events, properties, client options and React/Vue usage; widget docs get React 19, React 18 and Vue tabs; README sizes corrected. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 23 +++ docs/_skill.md | 6 +- docs/quickstart.md | 17 +- docs/react.md | 2 + docs/service-times.md | 2 +- docs/widget.md | 31 +++- .../src/hooks/use-church-lookup.ts | 1 + examples/shadcn-demo/src/lib/lookup-core.ts | 93 +++++++++-- packages/sdk/CHANGELOG.md | 33 ++++ packages/sdk/LICENSE | 21 +++ packages/sdk/README.md | 39 ++++- packages/sdk/package.json | 147 ++++++++++++++++-- packages/sdk/scripts/build.mjs | 27 ++-- packages/sdk/src/client.ts | 78 +++++++++- packages/sdk/src/core.ts | 2 +- packages/sdk/src/dev.ts | 10 ++ packages/sdk/src/element.ts | 8 +- packages/sdk/src/jsx.d.ts | 27 +++- packages/sdk/src/react.d.ts | 8 - packages/sdk/src/react.ts | 19 +++ packages/sdk/src/use-church-lookup.ts | 84 ++++++++++ packages/sdk/src/vue.d.ts | 8 +- packages/sdk/test/cdn.test.ts | 19 +++ packages/sdk/test/client.test.ts | 41 ++++- packages/sdk/test/size.test.ts | 3 +- packages/sdk/test/ssr.test.ts | 14 +- packages/sdk/test/types.test.ts | 71 +++++++-- packages/sdk/test/types/consumer-react.tsx | 33 ++++ packages/sdk/test/types/consumer-vue.ts | 11 ++ packages/sdk/test/types/consumer.ts | 13 +- packages/sdk/tsconfig.build.json | 4 +- pnpm-lock.yaml | 24 +++ registry/hooks/use-church-lookup.ts | 1 + registry/lib/lookup-core.ts | 93 +++++++++-- scripts/build-registry.mjs | 21 ++- scripts/copy-assets.mjs | 31 +++- site/SKILL.md | 6 +- site/_headers | 3 + site/docs/quickstart.html | 14 +- site/docs/quickstart.md | 17 +- site/docs/react.html | 1 + site/docs/react.md | 2 + site/docs/search-index.json | 2 +- site/docs/service-times.html | 2 +- site/docs/service-times.md | 2 +- site/docs/widget.html | 27 +++- site/docs/widget.md | 35 ++++- site/llms-full.txt | 56 +++++-- site/r/church-consent.json | 2 +- site/r/church-lookup.json | 4 +- site/r/lookup-strings.json | 2 +- site/r/use-church-lookup.json | 4 +- site/sdk/0.3.0/element.js | 47 ++++++ site/sdk/0.3.0/lookup.js | 1 + site/sdk/0.3.0/service-times.js | 28 ++++ site/sdk/0.3.0/strings-de.js | 1 + site/sdk/0.3.0/strings-es.js | 1 + site/sdk/0.3.0/strings-fr.js | 1 + site/sdk/0.3.0/strings-pl.js | 1 + site/sdk/0.3.0/strings-pt.js | 1 + site/sdk/0.4.0/element.js | 47 ++++++ site/sdk/0.4.0/lookup.js | 1 + site/sdk/0.4.0/service-times.js | 28 ++++ site/sdk/0.4.0/strings-de.js | 1 + site/sdk/0.4.0/strings-es.js | 1 + site/sdk/0.4.0/strings-fr.js | 1 + site/sdk/0.4.0/strings-pl.js | 1 + site/sdk/0.4.0/strings-pt.js | 1 + 68 files changed, 1253 insertions(+), 153 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 packages/sdk/CHANGELOG.md create mode 100644 packages/sdk/LICENSE create mode 100644 packages/sdk/src/dev.ts delete mode 100644 packages/sdk/src/react.d.ts create mode 100644 packages/sdk/src/react.ts create mode 100644 packages/sdk/src/use-church-lookup.ts create mode 100644 packages/sdk/test/cdn.test.ts create mode 100644 packages/sdk/test/types/consumer-react.tsx create mode 100644 packages/sdk/test/types/consumer-vue.ts create mode 100644 site/sdk/0.3.0/element.js create mode 100644 site/sdk/0.3.0/lookup.js create mode 100644 site/sdk/0.3.0/service-times.js create mode 100644 site/sdk/0.3.0/strings-de.js create mode 100644 site/sdk/0.3.0/strings-es.js create mode 100644 site/sdk/0.3.0/strings-fr.js create mode 100644 site/sdk/0.3.0/strings-pl.js create mode 100644 site/sdk/0.3.0/strings-pt.js create mode 100644 site/sdk/0.4.0/element.js create mode 100644 site/sdk/0.4.0/lookup.js create mode 100644 site/sdk/0.4.0/service-times.js create mode 100644 site/sdk/0.4.0/strings-de.js create mode 100644 site/sdk/0.4.0/strings-es.js create mode 100644 site/sdk/0.4.0/strings-fr.js create mode 100644 site/sdk/0.4.0/strings-pl.js create mode 100644 site/sdk/0.4.0/strings-pt.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..cbe5d1d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + version: 10 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + - run: pnpm install --frozen-lockfile + # Registry copies are current, worker tests, then the SDK build with its size, SSR and type checks. + - run: pnpm test + - run: pnpm typecheck diff --git a/docs/_skill.md b/docs/_skill.md index 33f5f98..43ee86c 100644 --- a/docs/_skill.md +++ b/docs/_skill.md @@ -13,8 +13,8 @@ Lookup by Here's My Church is a church search box for forms. People type a few l ## Steps 1. Load the element once, near the end of the page or in the app's root layout: - `` - For a service-times editor, also load `https://lookup.heresmychurch.com/service-times.js`. + `` + For a service-times editor, also load `https://lookup.heresmychurch.com/sdk/0.4.0/service-times.js`. 2. Add the field inside the form, above the fields it fills: `` - `name`: the chosen church's ID submits with the form. Save it. @@ -26,7 +26,7 @@ Lookup by Here's My Church is a church search box for forms. People type a few l 3. Inputs named for the church already fill: `church_city`, `churchWebsite`, `church[phone]`, or `autocomplete="section-church tel"`. Tag any other input with `data-hmc-field`. Valid names only: name, street, city, region, regionName, postalCode, country, countryName, latitude, longitude, phone, email, website, denomination, serviceTimes, languages, ministries, pastorName, id. On a form that's only about the church, `fill="auto"` also fills plain names (city, state, zip, phone, website). Empty fields fill; typed values are kept unless the element has `overwrite`. -4. Frameworks: it's a standard custom element. In React or Vue, attach `church-select` (detail.result.id), `church-clear` and `church-error` listeners in an effect. In Next.js, import `@heresmychurch/lookup/element` from a `"use client"` file. Inputs are filled through the native setter plus `input`/`change` events, so controlled inputs stay in sync. Types: `import type {} from "@heresmychurch/lookup/react"` or `/vue`. +4. Frameworks: it's a standard custom element. Listen for `church-select` (detail.result.id), `church-clear` and `church-error`: in React 19 as `onchurch-select` (and so on) props, in Vue as `@church-select`, in React 18 with addEventListener in an effect. In Next.js, import `@heresmychurch/lookup/element` from a `"use client"` file. Inputs are filled through the native setter plus `input`/`change` events, so controlled inputs stay in sync. Types: `import type {} from "@heresmychurch/lookup/react"` or `/vue`. 5. While testing, set `client="lookup-demo"`: shared corrections are checked but never sent. In production, set `client` to the app's name. 6. Styling: set `--hmc-accent`, `--hmc-radius`, `--hmc-border`, `--hmc-input-border`, `--hmc-bg`, `--hmc-text` on `church-lookup`, or rely on shadcn-style tokens (`--background`, `--foreground`, `--accent`, `--border`, `--radius`) already on the page. diff --git a/docs/quickstart.md b/docs/quickstart.md index fdd445c..ab395ab 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -10,8 +10,8 @@ Add a church search field to the form in this project where people enter a churc ## Steps 1. Load the widget once on the page: - - (Service times editor, optional: https://lookup.heresmychurch.com/service-times.js) + + (Service times editor, optional: https://lookup.heresmychurch.com/sdk/0.4.0/service-times.js) 2. Put inside the form, above the fields it fills. - `name` submits the chosen church's ID with the form. Store it so you can look the church up again. - Add `required` if a church must be chosen. @@ -21,8 +21,9 @@ Add a church search field to the form in this project where people enter a churc name, street, city, region, regionName, postalCode, country, countryName, latitude, longitude, phone, email, website, denomination, serviceTimes, languages, ministries, pastorName, id Don't create new inputs unless I ask. Don't rename existing ones. -4. React or Vue: the element is a custom element. Listen for `church-select` and `church-clear` events - with addEventListener in an effect; values are set the way typing sets them, so controlled inputs stay in sync. +4. React or Vue: the element is a custom element. React 19: pass onchurch-select and onchurch-clear props. + React 18: add `church-select` and `church-clear` listeners with addEventListener in an effect. + Vue: @church-select and @church-clear. Values are set the way typing sets them, so controlled inputs stay in sync. Types: import type {} from "@heresmychurch/lookup/react" (or /vue). 5. While testing, add client="lookup-demo" so corrections people share are checked but never sent. Remove it (or set your app's name) before shipping. @@ -41,9 +42,11 @@ Or set it up yourself. There's no key to request. ## 1. Add the script ```html - + ``` +That URL is pinned to version 0.4.0 and never changes, so an update can't change your form until you change the number. To always get the latest release instead, load `https://lookup.heresmychurch.com/element.js`. See the [changelog](https://github.com/harvouscom/lookup/blob/main/packages/sdk/CHANGELOG.md) for what's in each version. + ## 2. Put the search box in your form Fields named for the church, like `church_city`, fill on their own. Tag any others with `data-hmc-field`. Give it a `name` and the chosen church's ID submits with the form. @@ -57,10 +60,10 @@ Fields named for the church, like `church_city`, fill on their own. Tag any othe - + ``` ```javascript title="client only" -import { createLookup } from "https://lookup.heresmychurch.com/lookup.js"; +import { createLookup } from "https://lookup.heresmychurch.com/sdk/0.4.0/lookup.js"; const lookup = createLookup({ client: "my-app" }); const { results } = await lookup.search("grace comm"); diff --git a/docs/react.md b/docs/react.md index f6cbfb7..bff063f 100644 --- a/docs/react.md +++ b/docs/react.md @@ -31,6 +31,8 @@ Add a church picker to this React + shadcn/ui app using Lookup by Here's My Chur Check: type "grac", pick a church, the tagged fields fill and handleSubmit receives church_id. ::: +Not on shadcn/ui? Use the element with `onchurch-select` props in React 19 (see [the widget](/docs/widget#in-your-form)), or build your own picker with `useChurchLookup` from `@heresmychurch/lookup/react` once the package is on npm. + ## Install ```bash diff --git a/docs/service-times.md b/docs/service-times.md index d8cb0c2..1831ace 100644 --- a/docs/service-times.md +++ b/docs/service-times.md @@ -15,7 +15,7 @@ Wrap a service-times field in `` to edit it as rows of day - + ``` When `` fills a `serviceTimes` field inside ``, the rows update with it. diff --git a/docs/widget.md b/docs/widget.md index 56aa4c9..bbee1d6 100644 --- a/docs/widget.md +++ b/docs/widget.md @@ -75,7 +75,7 @@ It also asks for smarter results when people pause. Change the options below to ## In your form -It's a real form field. Give it a `name` and the chosen church's ID submits with your form, so you can store the ID and look the church up again later. React and Vue get types for the tag and its events. +It's a real form field. Give it a `name` and the chosen church's ID submits with your form, so you can store the ID and look the church up again later. React and Vue get types for the tag and its events. React 19 adds `onchurch-select` and other `onchurch-*` props as event listeners; React 18 needs them added in an effect. :::tabs Form example ```html title="html form" @@ -86,10 +86,25 @@ It's a real form field. Give it a `name` and the chosen church's ID submits with ``` -```tsx title="react" +```tsx title="react 19" +"use client"; // Next.js: load the element in a client component. +import "@heresmychurch/lookup/element"; +import type {} from "@heresmychurch/lookup/react"; // types the props and onchurch-* events + +function ChurchField({ onChange }) { + return ( + onChange(e.detail.result.id)} + onchurch-clear={() => onChange("")} + /> + ); +} +``` +```tsx title="react 18" "use client"; // Next.js: load the element in a client component. import "@heresmychurch/lookup/element"; -import type {} from "@heresmychurch/lookup/react"; function ChurchField({ onChange }) { const ref = useRef(null); @@ -107,6 +122,16 @@ function ChurchField({ onChange }) { return ; } ``` +```vue title="vue" + + + +``` ::: ## Fields diff --git a/examples/shadcn-demo/src/hooks/use-church-lookup.ts b/examples/shadcn-demo/src/hooks/use-church-lookup.ts index 7768b7a..daa2f20 100644 --- a/examples/shadcn-demo/src/hooks/use-church-lookup.ts +++ b/examples/shadcn-demo/src/hooks/use-church-lookup.ts @@ -1,5 +1,6 @@ "use client" +// Generated from packages/sdk/src/use-church-lookup.ts by scripts/build-registry.mjs. MIT. // useChurchLookup: Lookup's search engine as a React hook, for building your own church picker. // The debounce, settled search, "Show more", stale-result handling and record loading all live in // @/lib/lookup-core, the same engine the element uses. diff --git a/examples/shadcn-demo/src/lib/lookup-core.ts b/examples/shadcn-demo/src/lib/lookup-core.ts index 37969a9..5f01f4c 100644 --- a/examples/shadcn-demo/src/lib/lookup-core.ts +++ b/examples/shadcn-demo/src/lib/lookup-core.ts @@ -1,7 +1,19 @@ -// Lookup by Here's My Church, headless core v0.3.0. Generated from @heresmychurch/lookup +// Lookup by Here's My Church, headless core v0.4.0. Generated from @heresmychurch/lookup // (packages/sdk/src) by scripts/build-registry.mjs. MIT. https://lookup.heresmychurch.com/docs /* eslint-disable */ +// ── dev.ts ── +// Setup hints for developers. Each prints once, and only on a local development host (localhost, +// 127.0.0.1, *.localhost, *.test), so production consoles and servers stay quiet. +const said: Record = {}; + +export function devWarn(message: string): void { + const host = typeof location == "object" ? location.hostname : ""; + if (said[message] || !/^(localhost|127\.0\.0\.1|\[::1\])$|\.(localhost|test)$/.test(host)) return; + said[message] = 1; + console.warn("Lookup: " + message); +} + // ── client.ts ── // @heresmychurch/lookup core client. No dependencies. @@ -56,13 +68,58 @@ export interface SearchResponse { attribution: string; } +/** One weekly service. */ +export interface ServiceSlot { + /** 0 is Sunday, 6 is Saturday. */ + dayOfWeek: number; + /** 24-hour "HH:MM", such as "09:30". */ + startTime: string; +} + +export interface ServiceTimes { + /** The listed text, such as "Sun 9:00 AM; Wed 7:00 PM", or null when there is none. */ + raw: string | null; + /** The services read from `raw`. Empty when it couldn't be read; `raw` still holds the text. */ + slots: ServiceSlot[]; + /** Whether every part of `raw` was read into `slots`. */ + parsed: boolean; +} + +/** A church's details. Every key is always present, with null or [] when the directory has nothing. */ +export interface ChurchFields { + name: string; + street: string | null; + city: string | null; + /** A region code, such as "TX" or "ON". */ + region: string; + /** The region's name, such as "Texas". */ + regionName: string; + postalCode: string | null; + /** An ISO country code, such as "US". */ + country: string; + countryName: string; + latitude: number; + longitude: number; + phone: string | null; + email: string | null; + website: string | null; + denomination: string | null; + serviceTimes: ServiceTimes; + languages: string[]; + ministries: string[]; + pastorName: string | null; +} + +/** A field name in a church record, as data-hmc-field takes. */ +export type ChurchField = keyof ChurchFields | "id"; + export interface ChurchRecord { id: string; - /** Only with { follow: false }: this listing merged into another. Load that ID instead. */ + /** Only with { follow: false }: this listing merged into another. Load that ID instead; nothing else is set. */ movedTo?: string; /** The ID you asked for, when it merged into this church. Store this record's `id` instead. */ movedFrom?: string; - fields: Record & { name: string; serviceTimes: { raw: string | null } }; + fields: ChurchFields; missing: string[]; completeness: number; /** When someone last confirmed the listing (ms since 1970), or null if never. */ @@ -102,7 +159,7 @@ export class LookupError extends Error { status: number; /** Seconds to wait before trying again, on a 429 or 503. */ retryAfter?: number; - /** A stable reason: invalid, not_found, rate_limited, overloaded, unavailable, … */ + /** A stable reason: invalid, not_found, rate_limited, overloaded, unavailable, timeout, … */ code?: string; constructor(status: number, message: string, retryAfter?: number, code?: string) { super(message); @@ -118,17 +175,35 @@ export interface LookupOptions { /** Your tool's name, such as "my-chms". Self-declared; shown to reviewers as declared. */ client?: string; fetch?: typeof fetch; + /** Give up on a request after this many milliseconds, with a LookupError whose code is "timeout". Defaults to 15000; 0 waits forever. */ + timeout?: number; } export function createLookup(opts: LookupOptions = {}) { const base = (opts.baseUrl ?? "https://lookup.heresmychurch.com").replace(/\/+$/, "") + "/v1"; const f = opts.fetch ?? fetch.bind(globalThis); + const timeout = opts.timeout ?? 15000; + if (!opts.client) devWarn('set client="my-app" so Here\'s My Church knows which tool is asking. Use "lookup-demo" while testing.'); async function get(path: string, signal?: AbortSignal, init?: RequestInit): Promise { - const res = await f(base + path, { signal, ...init }); - const body = await res.json().catch(() => ({})); - if (!res.ok) throw new LookupError(res.status, body.error ?? res.statusText, Number(res.headers.get("retry-after")) || undefined, body.code); - return body; + // One signal for the caller's abort and the timeout. A caller's abort still rejects with AbortError. + const ctl = new AbortController(); + const stop = () => ctl.abort(); + const timer = timeout > 0 ? setTimeout(stop, timeout) : 0; + if (signal?.aborted) stop(); + signal?.addEventListener("abort", stop); + try { + const res = await f(base + path, { ...init, signal: ctl.signal }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new LookupError(res.status, body.error ?? res.statusText, Number(res.headers.get("retry-after")) || undefined, body.code); + return body; + } catch (e) { + // Aborted, but not by the caller: the timeout fired. + throw ctl.signal.aborted && !signal?.aborted ? new LookupError(0, "Timed out", undefined, "timeout") : e; + } finally { + clearTimeout(timer); + signal?.removeEventListener("abort", stop); + } } const post = (path: string, body: unknown, keepalive?: boolean) => @@ -370,7 +445,7 @@ export const MAX_RESULTS = 50; /** A record field as the text a form field should hold, or null when the directory has nothing. */ export function fieldValue(record: ChurchRecord, field: string): string | null { - const v = field === "id" ? record.id : record.fields[field]; + const v = field === "id" ? record.id : (record.fields as unknown as Record)[field]; if (v == null) return null; if (Array.isArray(v)) return v.length ? v.join(", ") : null; if (typeof v === "object") return (v as { raw?: string | null }).raw ?? null; diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md new file mode 100644 index 0000000..ac6c496 --- /dev/null +++ b/packages/sdk/CHANGELOG.md @@ -0,0 +1,33 @@ +# Changelog + +All notable changes to `@heresmychurch/lookup`. Versions follow [semver](https://semver.org); while the version is 0.x, a minor release can change behavior, so pin the exact version you test against. + +## 0.4.0 + +- React: `useChurchLookup` ships in `@heresmychurch/lookup/react`, so React apps without shadcn/ui get the headless core as a hook. React is an optional peer dependency, needed only for that entry. +- React 19 types for ``: `onchurch-select`, `onchurch-fill` and the other event props are typed (React 19 adds them as listeners), the usual HTML props come from React's own types, and the object properties `fieldMap`, `strings` and `lookup` are typed. Breaking, types only: an unknown camelCase prop such as `maxResults` is now a type error instead of passing silently. Use `max-results`. +- Vue: `@church-select` and the other events are typed in templates. Preact and React 18 (global JSX) get typed `on` props too. +- CommonJS build: every entry has a `.cjs` file and `.d.cts` types behind a `require` condition, so Jest and other `require()` setups load the package with no transforms. +- Client `timeout` option: a request with no answer after 15 seconds (by default) fails with a `LookupError` whose `code` is `"timeout"`. A caller's own abort still rejects with `AbortError`. +- Setup hints: on a local development host, the console says once when `client` isn't set, or when a chosen church found no fields to fill. Production consoles stay quiet. +- The headless core's size budget is now 5.5 KB gzipped (it was 5 KB), for the timeout and setup hints. +- Types: `ChurchRecord.fields` is now a typed `ChurchFields`, so `record.fields.city` is `string | null` and `record.fields.languages` is `string[]` with no casts. New exported types: `ChurchFields`, `ChurchField`, `ServiceTimes` and `ServiceSlot`. +- Types resolve under every TypeScript `moduleResolution`, including the older `"node"` (node10) that many existing apps and Jest setups use. +- Pinned script URLs: each release is also served at `https://lookup.heresmychurch.com/sdk//element.js` (and `lookup.js`, `service-times.js`), cached for a year and never changed. The unversioned URLs keep tracking the latest release. +- Package metadata for npm: repository, homepage, keywords, license file and public access. + +## 0.3.0 + +- "Show more" in the results, with `limit` and `max-results`. +- Inputs named for the church (`church_city`, `churchWebsite`, `autocomplete="section-church tel"`) fill with no tags. `fill="auto"` also fills plain names like `city`; `@heresmychurch/lookup/fields` exposes the matcher. +- New attributes: `density`, `max-results`, `min-chars`, `debounce`, `lat`, `lng`, `semantic="off"`, `show-distance="off"`, `fill`. New `church-error` event. +- Sharing fixes back is checked by default; "Still correct" shows only for stale listings; report closed, duplicate or moved; add a church that isn't listed (`church-add`, `church-added`). +- Type declarations ship compiled, so apps need no special TypeScript settings. + +## 0.2.0 + +- `@heresmychurch/lookup/core`: the headless controller, fill planning and consent rules, with no side effects on import. +- `` is a real form field: `name` submits the church ID, `value` prefills it, `required` validates, and form reset and restore work. +- Spanish, French, German, Portuguese and Polish text, loaded on demand. +- Types for React, Vue, Preact and Solid. +- The shadcn/ui registry: `ChurchLookup`, `useChurchLookup` and `ChurchConsent`. diff --git a/packages/sdk/LICENSE b/packages/sdk/LICENSE new file mode 100644 index 0000000..557f043 --- /dev/null +++ b/packages/sdk/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Here's My Church contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/sdk/README.md b/packages/sdk/README.md index a6948d8..12b7101 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -8,9 +8,11 @@ Not published to npm yet. Until it is, load the element from the API: - + ``` +Script URLs under `/sdk//` never change. Drop the version (`https://lookup.heresmychurch.com/element.js`) to always get the latest release. What changed in each version is in [CHANGELOG.md](CHANGELOG.md). + Selecting a church fills empty fields marked with `data-hmc-field`. Values go through the native setter plus `input` and `change` events, so React controlled inputs update. Add `overwrite` to replace fields that already have values. Fields: `name, street, city, region, regionName, postalCode, country, countryName, latitude, longitude, phone, email, website, denomination, serviceTimes, languages, ministries, pastorName, id`. @@ -19,15 +21,17 @@ Events: `church-select` (`detail.result`) and `church-fill` (`detail.record`, `d Theming: on a page styled with [Sensible UI](https://sensibleui.com) by [Cam Pak](https://github.com/cameronapak), or anything else using shadcn/ui-style tokens (`--background`, `--foreground`, `--popover`, `--border`, `--input`, `--ring`, `--accent`, `--muted-foreground`, `--radius`), the element picks up the theme automatically. To set it directly, use `--hmc-text`, `--hmc-bg`, `--hmc-popover`, `--hmc-popover-text`, `--hmc-border`, `--hmc-input-border`, `--hmc-accent`, `--hmc-active-bg`, `--hmc-active-text`, `--hmc-muted`, `--hmc-radius` and `--hmc-z`, or the parts `label`, `input`, `clear`, `popup`, `listbox`, `option`, `option-name`, `option-detail`, `option-distance`, `more`, `corrected`, `note`, `retry`, `footer` and `consent`. -Attributes: `label`, `placeholder`, `name`, `value`, `required`, `disabled`, `region`, `country`, `near`, `lat`, `lng`, `geo="off"`, `limit` (per page), `max-results` (Show more reaches up to 50), `density="comfortable"`, `icons="none"`, `show-distance="off"`, `min-chars`, `debounce`, `semantic="off"`, `form` (id of the form to fill), `fill` (`auto`, `tagged` or `off`), `overwrite`, `fill-on-load`, `lang`, `contribute="off"`, `client`, `base-url`. Events: `church-results`, `church-select`, `church-fill`, `church-clear`, `church-error`, `church-contribute`, `church-confirm`. +Attributes: `label`, `placeholder`, `name`, `value`, `required`, `disabled`, `region`, `country`, `near`, `lat`, `lng`, `geo="off"`, `limit` (per page), `max-results` (Show more reaches up to 50), `density="comfortable"`, `icons="none"`, `show-distance="off"`, `min-chars`, `debounce`, `semantic="off"`, `form` (id of the form to fill), `fill` (`auto`, `tagged` or `off`), `overwrite`, `fill-on-load`, `lang`, `contribute="off"`, `client`, `base-url`. Events: `church-results`, `church-select`, `church-fill`, `church-clear`, `church-error`, `church-contribute`, `church-confirm`, `church-add`, `church-added`. + +Properties: `value` (the chosen church's ID), `selected` (its search result), `fieldMap` (a record field to an element or selector, for fields outside the form, such as `{ website: "#site-url" }`), `strings` (text to change) and `lookup` (your own client, such as one with a custom `fetch`). -Fields: inputs named for the church (`church_city`, `churchWebsite`, `autocomplete="section-church tel"`) fill with no setup; tag others with `data-hmc-field`. The element is about 12 KB gzipped, and safe to import during server rendering (it registers itself only in a browser). +Fields: inputs named for the church (`church_city`, `churchWebsite`, `autocomplete="section-church tel"`) fill with no setup; tag others with `data-hmc-field`. The element is about 15 KB gzipped, and safe to import during server rendering (it registers itself only in a browser). Service times: wrap the field in `` to edit it as rows of day, time and an optional label, the same way Here's My Church does. The field keeps the canonical string, such as `Sun 9:00 AM (Main Service); Wed 7:00 PM`, and autofill updates the rows. Text it can't read stays visible rather than being dropped. ```html - + ``` Client only, at most 2 KB gzipped: @@ -37,9 +41,13 @@ import { createLookup } from "@heresmychurch/lookup"; const lookup = createLookup({ client: "my-tool" }); const { results } = await lookup.search("grace comm"); const church = await lookup.getChurch(results[0].id); +church.fields.city; // string | null +church.fields.languages; // string[] ``` -Headless core, at most 4 KB gzipped, for building your own UI. No side effects on import: nothing is registered. `state.hasMore` says a "Show more" row belongs after the results, and `more()` appends the next page. +Every key in `fields` is always present and typed (`ChurchFields`), with `null` or `[]` when the directory has nothing. + +Headless core, at most 5.5 KB gzipped, for building your own UI. No side effects on import: nothing is registered. `state.hasMore` says a "Show more" row belongs after the results, and `more()` appends the next page. ```js import { createLookupController, findTargets, fillTargets } from "@heresmychurch/lookup/core"; @@ -50,7 +58,26 @@ const record = await ctl.choose(0); fillTargets(record, findTargets(form, (el) => matchField(el))); ``` -Types ship as compiled `.d.ts` files, so no special TypeScript settings are needed. +Types ship as compiled `.d.ts` files and resolve under every TypeScript `moduleResolution`, so no special settings are needed. There's a CommonJS build too, so Jest and other `require()` setups load it without transforms. + +Client options: `client` (your app's name), `baseUrl`, `fetch`, and `timeout` (milliseconds before a request fails with a `LookupError` whose `code` is `"timeout"`; 15000 by default, 0 to wait forever). + +While you develop on `localhost` (or `*.localhost`, `*.test`), the console says once if `client` isn't set, or if a chosen church found no fields to fill. Production stays quiet. + +React 19: `import type {} from "@heresmychurch/lookup/react"` types ``, including event props, which React 19 adds as listeners: + +```tsx + setChurchId(e.detail.result.id)} onchurch-clear={() => setChurchId("")} /> +``` + +To build your own picker, `useChurchLookup` from the same entry is the headless core as a hook. Needs React 18 or later: + +```tsx +import { useChurchLookup } from "@heresmychurch/lookup/react"; +const { results, search, choose, open } = useChurchLookup({ client: "my-app" }); +``` + +Vue: `import type {} from "@heresmychurch/lookup/vue"` types the tag and `@church-select` and the other events in templates. React and shadcn/ui: add the registry component instead of the element. It copies `ChurchLookup` (Command and Popover), `useChurchLookup` and this core into your app, and works with React Hook Form. diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 202521e..44ed519 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -1,56 +1,169 @@ { "name": "@heresmychurch/lookup", - "version": "0.3.0", + "version": "0.4.0", "description": "Church typeahead and autofill from the Here's My Church directory: a small client and a element.", + "keywords": [ + "church", + "churches", + "autocomplete", + "typeahead", + "autofill", + "address", + "web-component", + "custom-element", + "form", + "heres-my-church" + ], + "homepage": "https://lookup.heresmychurch.com/docs", + "repository": { + "type": "git", + "url": "git+https://github.com/harvouscom/lookup.git", + "directory": "packages/sdk" + }, + "bugs": { + "url": "https://github.com/harvouscom/lookup/issues" + }, "license": "MIT", "type": "module", "sideEffects": [ "./dist/element.js", + "./dist/element.cjs", "./dist/service-times.js", - "./dist/strings-*.js" + "./dist/service-times.cjs", + "./dist/strings-*.js", + "./dist/strings-*.cjs" ], + "main": "./dist/index.cjs", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" + "import": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } }, "./core": { - "types": "./dist/core.d.ts", - "default": "./dist/core.js" + "import": { + "types": "./dist/core.d.ts", + "default": "./dist/core.js" + }, + "require": { + "types": "./dist/core.d.cts", + "default": "./dist/core.cjs" + } }, "./fields": { - "types": "./dist/fields.d.ts", - "default": "./dist/fields.js" + "import": { + "types": "./dist/fields.d.ts", + "default": "./dist/fields.js" + }, + "require": { + "types": "./dist/fields.d.cts", + "default": "./dist/fields.cjs" + } }, "./element": { - "types": "./dist/element.d.ts", - "default": "./dist/element.js" + "import": { + "types": "./dist/element.d.ts", + "default": "./dist/element.js" + }, + "require": { + "types": "./dist/element.d.cts", + "default": "./dist/element.cjs" + } }, "./service-times": { - "types": "./dist/service-times.d.ts", - "default": "./dist/service-times.js" + "import": { + "types": "./dist/service-times.d.ts", + "default": "./dist/service-times.js" + }, + "require": { + "types": "./dist/service-times.d.cts", + "default": "./dist/service-times.cjs" + } }, "./react": { - "types": "./dist/react.d.ts" + "import": { + "types": "./dist/react.d.ts", + "default": "./dist/react.js" + }, + "require": { + "types": "./dist/react.d.cts", + "default": "./dist/react.cjs" + } }, "./vue": { "types": "./dist/vue.d.ts" }, "./strings/*": { - "types": "./dist/strings-*.d.ts", - "default": "./dist/strings-*.js" + "import": { + "types": "./dist/strings-*.d.ts", + "default": "./dist/strings-*.js" + }, + "require": { + "types": "./dist/strings-*.d.cts", + "default": "./dist/strings-*.cjs" + } + } + }, + "typesVersions": { + "*": { + "core": [ + "./dist/core.d.ts" + ], + "fields": [ + "./dist/fields.d.ts" + ], + "element": [ + "./dist/element.d.ts" + ], + "service-times": [ + "./dist/service-times.d.ts" + ], + "react": [ + "./dist/react.d.ts" + ], + "vue": [ + "./dist/vue.d.ts" + ], + "strings/*": [ + "./dist/strings-*.d.ts" + ] } }, "files": [ - "dist" + "dist", + "CHANGELOG.md" ], + "engines": { + "node": ">=18" + }, + "publishConfig": { + "access": "public" + }, "scripts": { "build": "node scripts/build.mjs", - "test": "node scripts/build.mjs && vitest run" + "test": "node scripts/build.mjs && vitest run", + "prepublishOnly": "pnpm test" + }, + "peerDependencies": { + "react": ">=18" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + } }, "devDependencies": { + "@types/react": "^19.2.2", "esbuild": "^0.25.0", "happy-dom": "^18.0.0", + "react": "^19.2.0", "vitest": "~3.2.0" } } diff --git a/packages/sdk/scripts/build.mjs b/packages/sdk/scripts/build.mjs index 42fe265..6b20fe4 100644 --- a/packages/sdk/scripts/build.mjs +++ b/packages/sdk/scripts/build.mjs @@ -1,4 +1,5 @@ -// Bundle and minify the client and the element, emit type declarations, then report gzipped sizes. +// Bundle and minify each entry as ES modules and as CommonJS (for Jest and other require() setups), +// emit type declarations for both, then report gzipped sizes. import { build } from "esbuild"; import { execFileSync } from "node:child_process"; import { copyFileSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -7,22 +8,26 @@ import { gzipSync } from "node:zlib"; rmSync("dist", { recursive: true, force: true }); // Assignment semantics for class fields: uninitialized fields emit nothing instead of a defineProperty each. -const common = { bundle: true, minify: true, format: "esm", target: "es2020", legalComments: "none", tsconfigRaw: { compilerOptions: { useDefineForClassFields: false } } }; -await build({ ...common, entryPoints: ["src/index.ts"], outfile: "dist/index.js" }); -await build({ ...common, entryPoints: ["src/core.ts"], outfile: "dist/core.js" }); -await build({ ...common, entryPoints: ["src/fields.ts"], outfile: "dist/fields.js" }); -await build({ ...common, entryPoints: ["src/element.ts"], outfile: "dist/element.js" }); -await build({ ...common, entryPoints: ["src/service-times.ts"], outfile: "dist/service-times.js" }); -for (const l of ["es", "fr", "de", "pt", "pl"]) await build({ ...common, entryPoints: [`src/strings-${l}.ts`], outfile: `dist/strings-${l}.js` }); +const common = { bundle: true, minify: true, target: "es2020", legalComments: "none", logLevel: "error", tsconfigRaw: { compilerOptions: { useDefineForClassFields: false } } }; +const entries = ["index", "core", "fields", "element", "service-times", "react", ...["es", "fr", "de", "pt", "pl"].map((l) => `strings-${l}`)]; +for (const name of entries) { + // The React entry uses the app's React, and is a client module for the Next.js app router. + const extra = name === "react" ? { external: ["react"], banner: { js: '"use client";' } } : {}; + await build({ ...common, ...extra, entryPoints: [`src/${name}.ts`], format: "esm", outfile: `dist/${name}.js` }); + await build({ ...common, ...extra, entryPoints: [`src/${name}.ts`], format: "cjs", outfile: `dist/${name}.cjs` }); +} // Declarations. tsc keeps the source's ".ts" import specifiers, which consumers can't resolve without // allowImportingTsExtensions, so point them at the ".js" files next to each .d.ts. const tsc = createRequire(import.meta.url).resolve("typescript/bin/tsc"); execFileSync(process.execPath, [tsc, "-p", "tsconfig.build.json"], { stdio: "inherit" }); -for (const f of ["jsx.d.ts", "react.d.ts", "vue.d.ts"]) copyFileSync(`src/${f}`, `dist/${f}`); +for (const f of ["jsx.d.ts", "vue.d.ts"]) copyFileSync(`src/${f}`, `dist/${f}`); for (const f of readdirSync("dist").filter((f) => f.endsWith(".d.ts"))) { const src = readFileSync(`dist/${f}`, "utf8"); - writeFileSync(`dist/${f}`, src.replace(/((?:from|import\()\s*["']\.\/[\w-]+?)(?:\.d)?\.ts(["'])/g, "$1.js$2").replace('path="../src/', 'path="./')); + const out = src.replace(/((?:from|import\()\s*["']\.\/[\w-]+?)(?:\.d)?\.ts(["'])/g, "$1.js$2").replace('path="../src/', 'path="./'); + writeFileSync(`dist/${f}`, out); + // The same types for require(), pointing at the .cjs side. jsx.d.ts is global and shared by both. + if (f !== "jsx.d.ts" && f !== "vue.d.ts") writeFileSync(`dist/${f.replace(/\.d\.ts$/, ".d.cts")}`, out.replace(/((?:from|import\()\s*["']\.\/(?!jsx\.)[\w-]+)\.js(["'])/g, "$1.cjs$2")); } -for (const f of ["dist/index.js", "dist/core.js", "dist/fields.js", "dist/element.js", "dist/service-times.js"]) console.log(f, gzipSync(readFileSync(f)).length, "bytes gzipped"); +for (const f of ["index", "core", "fields", "element", "service-times", "react"]) console.log(`dist/${f}.js`, gzipSync(readFileSync(`dist/${f}.js`)).length, "bytes gzipped"); diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index a1f4b8e..0234480 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -1,4 +1,5 @@ // @heresmychurch/lookup core client. No dependencies. +import { devWarn } from "./dev.ts"; export interface SearchOptions { near?: string; @@ -51,13 +52,58 @@ export interface SearchResponse { attribution: string; } +/** One weekly service. */ +export interface ServiceSlot { + /** 0 is Sunday, 6 is Saturday. */ + dayOfWeek: number; + /** 24-hour "HH:MM", such as "09:30". */ + startTime: string; +} + +export interface ServiceTimes { + /** The listed text, such as "Sun 9:00 AM; Wed 7:00 PM", or null when there is none. */ + raw: string | null; + /** The services read from `raw`. Empty when it couldn't be read; `raw` still holds the text. */ + slots: ServiceSlot[]; + /** Whether every part of `raw` was read into `slots`. */ + parsed: boolean; +} + +/** A church's details. Every key is always present, with null or [] when the directory has nothing. */ +export interface ChurchFields { + name: string; + street: string | null; + city: string | null; + /** A region code, such as "TX" or "ON". */ + region: string; + /** The region's name, such as "Texas". */ + regionName: string; + postalCode: string | null; + /** An ISO country code, such as "US". */ + country: string; + countryName: string; + latitude: number; + longitude: number; + phone: string | null; + email: string | null; + website: string | null; + denomination: string | null; + serviceTimes: ServiceTimes; + languages: string[]; + ministries: string[]; + pastorName: string | null; +} + +/** A field name in a church record, as data-hmc-field takes. */ +export type ChurchField = keyof ChurchFields | "id"; + export interface ChurchRecord { id: string; - /** Only with { follow: false }: this listing merged into another. Load that ID instead. */ + /** Only with { follow: false }: this listing merged into another. Load that ID instead; nothing else is set. */ movedTo?: string; /** The ID you asked for, when it merged into this church. Store this record's `id` instead. */ movedFrom?: string; - fields: Record & { name: string; serviceTimes: { raw: string | null } }; + fields: ChurchFields; missing: string[]; completeness: number; /** When someone last confirmed the listing (ms since 1970), or null if never. */ @@ -97,7 +143,7 @@ export class LookupError extends Error { status: number; /** Seconds to wait before trying again, on a 429 or 503. */ retryAfter?: number; - /** A stable reason: invalid, not_found, rate_limited, overloaded, unavailable, … */ + /** A stable reason: invalid, not_found, rate_limited, overloaded, unavailable, timeout, … */ code?: string; constructor(status: number, message: string, retryAfter?: number, code?: string) { super(message); @@ -113,17 +159,35 @@ export interface LookupOptions { /** Your tool's name, such as "my-chms". Self-declared; shown to reviewers as declared. */ client?: string; fetch?: typeof fetch; + /** Give up on a request after this many milliseconds, with a LookupError whose code is "timeout". Defaults to 15000; 0 waits forever. */ + timeout?: number; } export function createLookup(opts: LookupOptions = {}) { const base = (opts.baseUrl ?? "https://lookup.heresmychurch.com").replace(/\/+$/, "") + "/v1"; const f = opts.fetch ?? fetch.bind(globalThis); + const timeout = opts.timeout ?? 15000; + if (!opts.client) devWarn('set client="my-app" so Here\'s My Church knows which tool is asking. Use "lookup-demo" while testing.'); async function get(path: string, signal?: AbortSignal, init?: RequestInit): Promise { - const res = await f(base + path, { signal, ...init }); - const body = await res.json().catch(() => ({})); - if (!res.ok) throw new LookupError(res.status, body.error ?? res.statusText, Number(res.headers.get("retry-after")) || undefined, body.code); - return body; + // One signal for the caller's abort and the timeout. A caller's abort still rejects with AbortError. + const ctl = new AbortController(); + const stop = () => ctl.abort(); + const timer = timeout > 0 ? setTimeout(stop, timeout) : 0; + if (signal?.aborted) stop(); + signal?.addEventListener("abort", stop); + try { + const res = await f(base + path, { ...init, signal: ctl.signal }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new LookupError(res.status, body.error ?? res.statusText, Number(res.headers.get("retry-after")) || undefined, body.code); + return body; + } catch (e) { + // Aborted, but not by the caller: the timeout fired. + throw ctl.signal.aborted && !signal?.aborted ? new LookupError(0, "Timed out", undefined, "timeout") : e; + } finally { + clearTimeout(timer); + signal?.removeEventListener("abort", stop); + } } const post = (path: string, body: unknown, keepalive?: boolean) => diff --git a/packages/sdk/src/core.ts b/packages/sdk/src/core.ts index 099fe6f..a778da3 100644 --- a/packages/sdk/src/core.ts +++ b/packages/sdk/src/core.ts @@ -20,7 +20,7 @@ export const MAX_RESULTS = 50; /** A record field as the text a form field should hold, or null when the directory has nothing. */ export function fieldValue(record: ChurchRecord, field: string): string | null { - const v = field === "id" ? record.id : record.fields[field]; + const v = field === "id" ? record.id : (record.fields as unknown as Record)[field]; if (v == null) return null; if (Array.isArray(v)) return v.length ? v.join(", ") : null; if (typeof v === "object") return (v as { raw?: string | null }).raw ?? null; diff --git a/packages/sdk/src/dev.ts b/packages/sdk/src/dev.ts new file mode 100644 index 0000000..1d26352 --- /dev/null +++ b/packages/sdk/src/dev.ts @@ -0,0 +1,10 @@ +// Setup hints for developers. Each prints once, and only on a local development host (localhost, +// 127.0.0.1, *.localhost, *.test), so production consoles and servers stay quiet. +const said: Record = {}; + +export function devWarn(message: string): void { + const host = typeof location == "object" ? location.hostname : ""; + if (said[message] || !/^(localhost|127\.0\.0\.1|\[::1\])$|\.(localhost|test)$/.test(host)) return; + said[message] = 1; + console.warn("Lookup: " + message); +} diff --git a/packages/sdk/src/element.ts b/packages/sdk/src/element.ts index 7f87135..dc5103c 100644 --- a/packages/sdk/src/element.ts +++ b/packages/sdk/src/element.ts @@ -4,6 +4,7 @@ import { createLookup, type AddResult, type ChurchRecord, type FieldStatus, type Lookup, type LookupError, type Meta, type NewChurch, type SearchResult } from "./client.ts"; import { addUrl, applyFill, changeFor, consentDiff, contributable, createLookupController, fieldValue, findTargets, isStale, mergeAddress, newChurchFrom, planFill, suggestUrl, type ControllerState, type FillChange } from "./core.ts"; import { setNativeValue, type FieldTarget } from "./dom.ts"; +import { devWarn } from "./dev.ts"; import { matchField } from "./fields.ts"; import { LANGS, registry, stringsFor, type Strings } from "./strings.ts"; @@ -177,7 +178,8 @@ export class ChurchLookup extends Base { private loadLang(): void { const lang = this.uiLang; if (!LANGS.includes(lang) || registry()[lang]) return; - import(/* @vite-ignore */ new URL(`./strings-${lang}.js`, import.meta.url).href).catch(() => { /* stay in English */ }); + // import.meta.url is missing in the CommonJS build (Jest): stay in English unless a language file is imported. + try { import(/* @vite-ignore */ new URL(`./strings-${lang}.js`, import.meta.url).href).catch(() => { /* stay in English */ }); } catch { /* stay in English */ } } disconnectedCallback(): void { @@ -488,7 +490,9 @@ export class ChurchLookup extends Base { /** Fill the form, unless fill="off": then church-fill still carries the record, with no changes. */ private fillFrom(record: ChurchRecord): void { const off = this.getAttribute("fill") === "off"; - const { changes, empty } = off ? { changes: [], empty: [] } : planFill(record, this.targets(), { overwrite: this.hasAttribute("overwrite") }); + const targets = off ? null : this.targets(); + if (targets && !targets.size) devWarn('no fields to fill. Add data-hmc-field="city" (and so on) to inputs, or name them like church_city.'); + const { changes, empty } = targets ? planFill(record, targets, { overwrite: this.hasAttribute("overwrite") }) : { changes: [], empty: [] }; if (!this.dispatchEvent(new CustomEvent("church-fill", { detail: { record, changes }, cancelable: true, bubbles: true, composed: true })) || off) return; applyFill(changes); this.say(this.t.filled(changes.length, empty)); diff --git a/packages/sdk/src/jsx.d.ts b/packages/sdk/src/jsx.d.ts index 92c2ef5..4c3d93e 100644 --- a/packages/sdk/src/jsx.d.ts +++ b/packages/sdk/src/jsx.d.ts @@ -1,8 +1,10 @@ // Types for in any setup: the DOM tag and its events, and JSX for React <= 18, // Preact and Solid through the global JSX namespace. React 19 and Vue: also import the matching // "@heresmychurch/lookup/react" or "@heresmychurch/lookup/vue" types. -import type { ChurchRecord, NewChurch, SearchResult } from "./client.ts"; +import type { ChurchRecord, Lookup, NewChurch, SearchResult } from "./client.ts"; +import type { FieldTarget } from "./dom.ts"; import type { ChurchErrorDetail, ChurchLookup, FillChange } from "./element.ts"; +import type { Strings } from "./strings.ts"; export interface ChurchLookupEventMap { /** `more` is true when the results came from "Show more". */ @@ -64,10 +66,31 @@ export interface ChurchLookupAttributes { ref?: unknown; } +/** + * Event handlers as props, such as onchurch-select. React 19 and Preact add an `on` prop on a + * custom element as a listener for that event, so `onchurch-fill={(e) => e.detail.record}` is typed. + */ +export type ChurchLookupEventProps = { + [K in keyof ChurchLookupEventMap as `on${K}`]?: (event: ChurchLookupEventMap[K]) => void; +}; + +/** + * Properties that take objects. React 19 and Preact set these on the element instead of as attributes + * when the element is already defined, so import "@heresmychurch/lookup/element" before rendering. + */ +export interface ChurchLookupProperties { + /** Fill fields the matcher wouldn't find: record field to an element or a CSS selector. */ + fieldMap?: Record; + /** Text to change, in any language. */ + strings?: Partial; + /** Bring your own client, such as one with a custom fetch or timeout. */ + lookup?: Lookup | null; +} + declare global { interface HTMLElementTagNameMap { "church-lookup": ChurchLookup } interface HTMLElementEventMap extends ChurchLookupEventMap {} namespace JSX { - interface IntrinsicElements { "church-lookup": ChurchLookupAttributes & Record } + interface IntrinsicElements { "church-lookup": ChurchLookupAttributes & ChurchLookupEventProps & Record } } } diff --git a/packages/sdk/src/react.d.ts b/packages/sdk/src/react.d.ts deleted file mode 100644 index 997b96e..0000000 --- a/packages/sdk/src/react.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// React 19 types for . Add `import type {} from "@heresmychurch/lookup/react";` once. -import type { ChurchLookupAttributes } from "./jsx.d.ts"; - -declare module "react" { - namespace JSX { - interface IntrinsicElements { "church-lookup": ChurchLookupAttributes & Record } - } -} diff --git a/packages/sdk/src/react.ts b/packages/sdk/src/react.ts new file mode 100644 index 0000000..dbc3889 --- /dev/null +++ b/packages/sdk/src/react.ts @@ -0,0 +1,19 @@ +// @heresmychurch/lookup/react: useChurchLookup, the search engine as a hook for your own picker, and +// React 19 types for : its attributes, onchurch-* event props and object properties. +// For the types alone, add `import type {} from "@heresmychurch/lookup/react";` once. +import type * as React from "react"; +import type { ChurchLookup } from "./element.ts"; +import type { ChurchLookupAttributes, ChurchLookupEventProps, ChurchLookupProperties } from "./jsx.d.ts"; + +export { useChurchLookup, type UseChurchLookup, type UseChurchLookupOptions } from "./use-church-lookup.ts"; + +type Own = Omit & ChurchLookupEventProps & ChurchLookupProperties; + +/** Props for in React 19: its own, plus the usual HTML ones (id, className, style, aria-*). */ +export type ChurchLookupProps = Own & Omit, keyof Own> & { class?: string; ref?: React.Ref }; + +declare module "react" { + namespace JSX { + interface IntrinsicElements { "church-lookup": ChurchLookupProps } + } +} diff --git a/packages/sdk/src/use-church-lookup.ts b/packages/sdk/src/use-church-lookup.ts new file mode 100644 index 0000000..3427bd9 --- /dev/null +++ b/packages/sdk/src/use-church-lookup.ts @@ -0,0 +1,84 @@ +"use client" + +// useChurchLookup: Lookup's search engine as a React hook, for building your own church picker. +// The debounce, settled search, "Show more", stale-result handling and record loading all live in +// the headless core, the same engine the element uses. +import * as React from "react" + +import { + createLookupController, + type ChurchRecord, + type ControllerState, + type Lookup, + type SearchParams, + type SearchResult, +} from "./core.ts" + +export interface UseChurchLookupOptions extends SearchParams { + /** Your app's name, sent with requests. Use "lookup-demo" while testing. */ + client?: string + /** Point at another Lookup server. Defaults to https://lookup.heresmychurch.com. */ + baseUrl?: string + /** Bring your own client, such as one with a custom fetch. */ + lookup?: Lookup + /** Results arrived. `more` is true when they came from more(). `state` is the search state now. */ + onResults?: (detail: { query: string; results: SearchResult[]; settled: boolean; more: boolean }, state: Readonly) => void + /** A search or "Show more" failed. */ + onError?: (error: unknown, query: string) => void + /** A church is about to be chosen. Return false to cancel. */ + onSelect?: (result: SearchResult) => boolean | void +} + +export interface UseChurchLookup extends ControllerState { + /** Call with what the person typed. */ + search: (text: string) => void + /** Choose a result by index (the highlighted one by default) and load its full record. */ + choose: (index?: number) => Promise + /** Show the next page of results. Resolves to the rows it added. */ + more: () => Promise + /** Search the current text again, such as after an error. */ + retry: () => void + /** Mark a church as chosen without searching, such as a saved one. */ + select: (result: SearchResult | null) => void + move: (dir: 1 | -1) => void + highlight: (index: number) => void + setOpen: (open: boolean) => void + reset: () => void + /** The underlying client, for getChurch, meta, contribute and confirm. */ + lookup: Lookup +} + +export function useChurchLookup(options: UseChurchLookupOptions = {}): UseChurchLookup { + const opts = React.useRef(options) + opts.current = options + const ctl = React.useMemo(() => { + const c = createLookupController({ + lookup: opts.current.lookup, + client: opts.current.client, + baseUrl: opts.current.baseUrl, + // Every SearchParams key passes through, read when each search runs. + params: () => opts.current, + onChange: (s) => setState({ ...s }), + onResults: (d) => opts.current.onResults?.(d, c.state), + onError: (e, q) => opts.current.onError?.(e, q), + onSelect: (r) => opts.current.onSelect?.(r), + }) + return c + }, []) + const [state, setState] = React.useState(() => ({ ...ctl.state })) + React.useEffect(() => () => ctl.destroy(), [ctl]) + + return { + ...state, + search: ctl.input, + choose: ctl.choose, + more: ctl.more, + retry: ctl.retry, + select: ctl.select, + move: ctl.move, + highlight: ctl.highlight, + setOpen: (open) => (open ? ctl.open() : ctl.close()), + reset: ctl.reset, + lookup: ctl.lookup, + } +} diff --git a/packages/sdk/src/vue.d.ts b/packages/sdk/src/vue.d.ts index 204e3eb..49edca2 100644 --- a/packages/sdk/src/vue.d.ts +++ b/packages/sdk/src/vue.d.ts @@ -1,8 +1,12 @@ // Vue types for . Add `import type {} from "@heresmychurch/lookup/vue";` once, and tell // Vue's compiler it's a custom element: compilerOptions.isCustomElement = (tag) => tag.startsWith("church-"). +// Events type-check in templates too: @church-select="(e) => e.detail.result". import type { DefineComponent } from "vue"; -import type { ChurchLookupAttributes } from "./jsx.d.ts"; +import type { ChurchLookupAttributes, ChurchLookupEventMap } from "./jsx.d.ts"; + +type Camel = S extends `${infer A}-${infer B}` ? `${A}${Capitalize>}` : S; +type ChurchLookupVueEvents = { [K in keyof ChurchLookupEventMap as `on${Capitalize>}`]?: (event: ChurchLookupEventMap[K]) => void }; declare module "vue" { - interface GlobalComponents { "church-lookup": DefineComponent } + interface GlobalComponents { "church-lookup": DefineComponent } } diff --git a/packages/sdk/test/cdn.test.ts b/packages/sdk/test/cdn.test.ts new file mode 100644 index 0000000..2c48240 --- /dev/null +++ b/packages/sdk/test/cdn.test.ts @@ -0,0 +1,19 @@ +// Pinned script URLs (/sdk//element.js) in the docs and README must name the package's +// version, so a release can't leave the docs pointing at an older one. +import { readdirSync, readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; + +const root = process.cwd(); +const { version } = JSON.parse(readFileSync(`${root}/package.json`, "utf8")); +const docs = [ + `${root}/README.md`, + ...readdirSync(`${root}/../../docs`).filter((f) => f.endsWith(".md")).map((f) => `${root}/../../docs/${f}`), +]; + +describe("pinned script URLs", () => { + it.each(docs.map((f) => [f.replace(/^.*\/(packages\/sdk|docs)\//, "$1/"), f]))("%s names the current version", (_, file) => { + const text = readFileSync(file, "utf8"); + for (const [, v] of text.matchAll(/heresmychurch\.com\/sdk\/(\d+\.\d+\.\d+[^/]*)\//g)) expect(v).toBe(version); + for (const [, v] of text.matchAll(/pinned to version (\d+\.\d+\.\d+)/g)) expect(v).toBe(version); + }); +}); diff --git a/packages/sdk/test/client.test.ts b/packages/sdk/test/client.test.ts index b656278..a220bef 100644 --- a/packages/sdk/test/client.test.ts +++ b/packages/sdk/test/client.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { createLookup, LookupError } from "../src/client.ts"; const fake = (body: unknown, status = 200, headers: Record = {}) => { @@ -59,4 +59,43 @@ describe("client", () => { await lookup.contribute("R-1", [{ field: "phone", value: "1" }]); expect(sent[2]!.init.keepalive).toBeUndefined(); }); + + // A fetch that answers only when aborted, the way a hung request behaves. + const hang = (() => (_: string, init?: RequestInit) => new Promise((_r, reject) => { + init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError"))); + })) as unknown as () => typeof globalThis.fetch; + it("times out with a LookupError", async () => { + const err = await createLookup({ fetch: hang(), timeout: 20 }).search("grace").catch((e) => e); + expect(err).toBeInstanceOf(LookupError); + expect(err).toMatchObject({ status: 0, code: "timeout" }); + }); + it("still rejects with AbortError when the caller aborts", async () => { + const ctl = new AbortController(); + const p = createLookup({ fetch: hang(), timeout: 5000 }).search("grace", { signal: ctl.signal }).catch((e) => e); + ctl.abort(); + expect(await p).toMatchObject({ name: "AbortError" }); + }); +}); + +describe("setup hints", () => { + afterEach(() => vi.unstubAllGlobals()); + it("warns once on a dev host when client is missing", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.stubGlobal("location", { hostname: "localhost" }); + vi.resetModules(); + const { createLookup: fresh } = await import("../src/client.ts"); + fresh(); fresh(); fresh({ client: "my-app" }); + expect(warn).toHaveBeenCalledTimes(1); + expect(String(warn.mock.calls[0]![0])).toMatch(/client="my-app"/); + warn.mockRestore(); + }); + it("stays quiet in production", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + vi.stubGlobal("location", { hostname: "www.example.org" }); + vi.resetModules(); + const { createLookup: fresh } = await import("../src/client.ts"); + fresh(); + expect(warn).not.toHaveBeenCalled(); + warn.mockRestore(); + }); }); diff --git a/packages/sdk/test/size.test.ts b/packages/sdk/test/size.test.ts index d6c1dbe..d82cbf4 100644 --- a/packages/sdk/test/size.test.ts +++ b/packages/sdk/test/size.test.ts @@ -7,7 +7,8 @@ const gz = (f: string) => gzipSync(readFileSync(`${process.cwd()}/dist/${f}`)).l describe("bundle size", () => { it("core client is at most 2 KB gzipped", () => expect(gz("index.js")).toBeLessThanOrEqual(2048)); - it("headless core is at most 5 KB gzipped", () => expect(gz("core.js")).toBeLessThanOrEqual(5120)); + it("headless core is at most 5.5 KB gzipped", () => expect(gz("core.js")).toBeLessThanOrEqual(5632)); + it("React hook is at most 5.5 KB gzipped", () => expect(gz("react.js")).toBeLessThanOrEqual(5632)); it("field matching is at most 1 KB gzipped", () => expect(gz("fields.js")).toBeLessThanOrEqual(1024)); it("element is at most 15 KB gzipped", () => expect(gz("element.js")).toBeLessThanOrEqual(15360)); it("service-times editor is at most 6 KB gzipped", () => expect(gz("service-times.js")).toBeLessThanOrEqual(6144)); diff --git a/packages/sdk/test/ssr.test.ts b/packages/sdk/test/ssr.test.ts index 5492d14..74856e1 100644 --- a/packages/sdk/test/ssr.test.ts +++ b/packages/sdk/test/ssr.test.ts @@ -1,11 +1,23 @@ // @vitest-environment node // Run after `node scripts/build.mjs`, which `pnpm test` does. Server rendering (Next.js, Nuxt, Astro) // imports these files with no DOM; they must load without throwing and register nothing. +import { createRequire } from "node:module"; import { describe, expect, it } from "vitest"; +const require = createRequire(import.meta.url); + describe("importing without a DOM", () => { it("has no HTMLElement here", () => expect(typeof HTMLElement).toBe("undefined")); - it.each(["index", "core", "fields", "element", "service-times", "strings-es"])("loads dist/%s.js", async (f) => { + it.each(["index", "core", "fields", "element", "service-times", "react", "strings-es"])("loads dist/%s.js", async (f) => { await expect(import(`../dist/${f}.js`)).resolves.toBeTruthy(); }); + // The CommonJS build, for Jest and other require() setups. + it.each(["index", "core", "fields", "element", "service-times", "react", "strings-es"])("requires dist/%s.cjs", (f) => { + expect(require(`../dist/${f}.cjs`)).toBeTruthy(); + }); + it("exports the same names from both builds", async () => { + for (const f of ["index", "core", "fields", "element", "react"]) { + expect(Object.keys(require(`../dist/${f}.cjs`)).sort(), f).toEqual(Object.keys(await import(`../dist/${f}.js`)).filter((k) => k !== "default").sort()); + } + }); }); diff --git a/packages/sdk/test/types.test.ts b/packages/sdk/test/types.test.ts index c4f5d5a..347f785 100644 --- a/packages/sdk/test/types.test.ts +++ b/packages/sdk/test/types.test.ts @@ -1,28 +1,81 @@ // Run after `node scripts/build.mjs`, which `pnpm test` does. Checks the published types work for an -// app: every export has a declaration, and none import ".ts" files an app can't resolve. +// app: every export has a declaration, none import ".ts" files an app can't resolve, and an app finds +// them under each moduleResolution TypeScript offers, including the older "node" (node10). import { execFileSync } from "node:child_process"; -import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { createRequire } from "node:module"; -import { describe, expect, it } from "vitest"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; const root = process.cwd(); const pkg = JSON.parse(readFileSync(`${root}/package.json`, "utf8")); +const tsc = createRequire(import.meta.url).resolve("typescript/bin/tsc"); + +// A throwaway app with the package in node_modules the way an install puts it: package.json and dist. +const app = mkdtempSync(join(tmpdir(), "lookup-types-")); +const installed = join(app, "node_modules/@heresmychurch/lookup"); +mkdirSync(installed, { recursive: true }); +copyFileSync(`${root}/package.json`, join(installed, "package.json")); +cpSync(`${root}/dist`, join(installed, "dist"), { recursive: true }); +copyFileSync(`${root}/test/types/consumer.ts`, join(app, "consumer.ts")); +copyFileSync(`${root}/test/types/consumer-react.tsx`, join(app, "consumer-react.tsx")); +copyFileSync(`${root}/test/types/consumer-vue.ts`, join(app, "consumer-vue.ts")); +// React from this package's dev dependencies, as an app would have its own. +mkdirSync(join(app, "node_modules/@types"), { recursive: true }); +symlinkSync(`${root}/node_modules/react`, join(app, "node_modules/react"), "dir"); +symlinkSync(`${root}/node_modules/@types/react`, join(app, "node_modules/@types/react"), "dir"); +// A stand-in for Vue's types: just what vue.d.ts augments. +mkdirSync(join(app, "node_modules/vue"), { recursive: true }); +writeFileSync(join(app, "node_modules/vue/package.json"), JSON.stringify({ name: "vue", types: "index.d.ts" })); +writeFileSync(join(app, "node_modules/vue/index.d.ts"), "export type DefineComponent

= { new (): { $props: P } };\nexport interface GlobalComponents {}\n"); +afterAll(() => rmSync(app, { recursive: true, force: true })); + +function typecheck(moduleResolution: string, module: string, type: "module" | "commonjs", files = ["consumer.ts"]) { + writeFileSync(join(app, "package.json"), JSON.stringify({ type })); + const compilerOptions = { target: "ES2022", module, moduleResolution, lib: ["ES2022", "DOM", "DOM.Iterable"], types: [], strict: true, noEmit: true, skipLibCheck: false, jsx: "react-jsx" }; + writeFileSync(join(app, "tsconfig.json"), JSON.stringify({ compilerOptions, files })); + try { execFileSync(process.execPath, [tsc, "-p", "tsconfig.json"], { cwd: app, stdio: "pipe" }); return ""; } + catch (e) { return String((e as { stdout?: Buffer }).stdout ?? e); } +} describe("published types", () => { it("has a declaration file for every export", () => { - for (const [path, entry] of Object.entries<{ types: string }>(pkg.exports)) { - const file = entry.types.replace("*", "es"); - expect(existsSync(`${root}/${file}`), `${path} -> ${file}`).toBe(true); - expect(file.startsWith("./dist/"), path).toBe(true); + type Entry = { types: string; default?: string }; + for (const [path, entry] of Object.entries(pkg.exports)) { + for (const e of "import" in entry ? [entry.import, entry.require] : [entry]) { + for (const file of [e.types, e.default].filter(Boolean).map((f) => f!.replace("*", "es"))) { + expect(existsSync(`${root}/${file}`), `${path} -> ${file}`).toBe(true); + expect(file.startsWith("./dist/"), path).toBe(true); + } + } } }); + it("maps every export for node10 through typesVersions", () => { + const mapped = Object.keys(pkg.typesVersions["*"]).map((k) => `./${k}`); + expect(mapped.sort()).toEqual(Object.keys(pkg.exports).filter((k) => k !== ".").sort()); + expect(existsSync(`${root}/${pkg.types}`)).toBe(true); + }); it("imports .js files, never .ts", () => { for (const f of readdirSync(`${root}/dist`).filter((f) => f.endsWith(".d.ts"))) { expect(readFileSync(`${root}/dist/${f}`, "utf8"), f).not.toMatch(/(from|import\()\s*["']\.\/[^"']*\.ts["']/); } }); - it("type-checks in an app without allowImportingTsExtensions", () => { - const tsc = createRequire(import.meta.url).resolve("typescript/bin/tsc"); + it("type-checks in an app with the original settings (self-reference)", () => { expect(() => execFileSync(process.execPath, [tsc, "-p", "test/types/tsconfig.json"], { cwd: root, stdio: "pipe" })).not.toThrow(); }, 60_000); + it.each([ + ["bundler", "esnext", "module"], + ["node16", "node16", "module"], + ["nodenext", "nodenext", "module"], + ["node10", "commonjs", "commonjs"], + ] as const)("type-checks in an app with moduleResolution %s", (mr, m, type) => { + expect(typecheck(mr, m, type)).toBe(""); + }, 60_000); + it("types React 19 props, events and the hook", () => { + expect(typecheck("bundler", "esnext", "module", ["consumer-react.tsx"])).toBe(""); + }, 60_000); + it("types Vue template events", () => { + expect(typecheck("bundler", "esnext", "module", ["consumer-vue.ts"])).toBe(""); + }, 60_000); }); diff --git a/packages/sdk/test/types/consumer-react.tsx b/packages/sdk/test/types/consumer-react.tsx new file mode 100644 index 0000000..78a78bc --- /dev/null +++ b/packages/sdk/test/types/consumer-react.tsx @@ -0,0 +1,33 @@ +// Type-checked by types.test.ts: React 19 props on and the useChurchLookup hook. +import { useChurchLookup, type ChurchLookupProps } from "@heresmychurch/lookup/react"; +import type { ChurchLookup } from "@heresmychurch/lookup/element"; +import { createRef } from "react"; + +export function Picker() { + const ref = createRef(); + const { results, search } = useChurchLookup({ client: "types-test", limit: 5 }); + void search; + return ( +

+ e.detail.result.id.toUpperCase()} + onchurch-fill={(e) => e.detail.record.fields.city?.toUpperCase()} + onchurch-error={(e) => e.detail.status} + /> + {results.map((r) =>

{r.name}

)} + {/* @ts-expect-error a typo'd camelCase prop is an error, not silently passed through */} + + + ); +} +const props: ChurchLookupProps = { label: "Church" }; +void props; diff --git a/packages/sdk/test/types/consumer-vue.ts b/packages/sdk/test/types/consumer-vue.ts new file mode 100644 index 0000000..abed7b4 --- /dev/null +++ b/packages/sdk/test/types/consumer-vue.ts @@ -0,0 +1,11 @@ +// Type-checked by types.test.ts: Vue's GlobalComponents entry carries typed event props. +import type {} from "@heresmychurch/lookup/vue"; +import type { GlobalComponents } from "vue"; + +type Props = InstanceType["$props"]; +const props: Props = { + label: "Church", + onChurchSelect: (e) => e.detail.result.id, + onChurchFill: (e) => e.detail.record.fields.city, +}; +void props; diff --git a/packages/sdk/test/types/consumer.ts b/packages/sdk/test/types/consumer.ts index 9ef2a03..55d422d 100644 --- a/packages/sdk/test/types/consumer.ts +++ b/packages/sdk/test/types/consumer.ts @@ -1,6 +1,6 @@ // Type-checked by types.test.ts the way an app would see the package: through its exports, with no // allowImportingTsExtensions and full library checking. -import { createLookup, LookupError, type SearchResponse } from "@heresmychurch/lookup"; +import { createLookup, LookupError, type ChurchField, type ChurchRecord, type SearchResponse } from "@heresmychurch/lookup"; import { createLookupController, findTargets, type ControllerState } from "@heresmychurch/lookup/core"; import { matchField } from "@heresmychurch/lookup/fields"; import "@heresmychurch/lookup/element"; @@ -20,3 +20,14 @@ el.addEventListener("church-select", (e) => e.detail.result.id); el.addEventListener("church-fill", (e) => e.detail.record.fields.name); const err = new LookupError(429, "slow down", 60); void [res, err.retryAfter, el.value]; + +// Record fields are typed, so an app reads them without casts. +declare const rec: ChurchRecord; +const city: string | null = rec.fields.city; +const lat: number = rec.fields.latitude; +const langs: string[] = rec.fields.languages; +const day: number | undefined = rec.fields.serviceTimes.slots[0]?.dayOfWeek; +const field: ChurchField = "pastorName"; +// @ts-expect-error not a record field +rec.fields.nope; +void [city, lat, langs, day, field]; diff --git a/packages/sdk/tsconfig.build.json b/packages/sdk/tsconfig.build.json index 0422be3..334d973 100644 --- a/packages/sdk/tsconfig.build.json +++ b/packages/sdk/tsconfig.build.json @@ -16,7 +16,8 @@ "declaration": true, "emitDeclarationOnly": true, "rootDir": "src", - "outDir": "dist" + "outDir": "dist", + "jsx": "react-jsx" }, "files": [ "src/index.ts", @@ -24,6 +25,7 @@ "src/fields.ts", "src/element.ts", "src/service-times.ts", + "src/react.ts", "src/strings-es.ts", "src/strings-fr.ts", "src/strings-de.ts", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d265582..996c855 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -32,12 +32,18 @@ importers: packages/sdk: devDependencies: + '@types/react': + specifier: 19.2.2 + version: 19.2.2 esbuild: specifier: ^0.25.0 version: 0.25.4 happy-dom: specifier: ^18.0.0 version: 18.0.1 + react: + specifier: 19.2.0 + version: 19.2.0 vitest: specifier: ~3.2.0 version: 3.2.7(@types/node@20.19.43)(happy-dom@18.0.1) @@ -900,6 +906,9 @@ packages: '@types/node@20.19.43': resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==} + '@types/react@19.2.2': + resolution: {integrity: sha512-6mDvHUFSjyT2B2yeNx2nUgMxh9LtOWvkhIU3uePn2I2oyNymUAX1NIsdgviM4CH+JSrp2D2hsMvJOkxY+0wNRA==} + '@types/unist@3.0.3': resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==} @@ -1002,6 +1011,9 @@ packages: resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} engines: {node: '>=18'} + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} @@ -1186,6 +1198,10 @@ packages: property-information@7.2.0: resolution: {integrity: sha512-IAtzIB6sUiWaJYrX9smp3V46pBGbBeLFRGdh25kg1334VcBlD8HzhPeNIWQH9zhGmo2itIe25EHt9dQP7G5hmg==} + react@19.2.0: + resolution: {integrity: sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==} + engines: {node: '>=0.10.0'} + regex-recursion@6.0.2: resolution: {integrity: sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==} @@ -2048,6 +2064,10 @@ snapshots: dependencies: undici-types: 6.21.0 + '@types/react@19.2.2': + dependencies: + csstype: 3.2.3 + '@types/unist@3.0.3': {} '@types/whatwg-mimetype@3.0.2': {} @@ -2146,6 +2166,8 @@ snapshots: cookie@1.1.1: {} + csstype@3.2.3: {} + debug@4.4.3: dependencies: ms: 2.1.3 @@ -2378,6 +2400,8 @@ snapshots: property-information@7.2.0: {} + react@19.2.0: {} + regex-recursion@6.0.2: dependencies: regex-utilities: 2.3.0 diff --git a/registry/hooks/use-church-lookup.ts b/registry/hooks/use-church-lookup.ts index 7768b7a..daa2f20 100644 --- a/registry/hooks/use-church-lookup.ts +++ b/registry/hooks/use-church-lookup.ts @@ -1,5 +1,6 @@ "use client" +// Generated from packages/sdk/src/use-church-lookup.ts by scripts/build-registry.mjs. MIT. // useChurchLookup: Lookup's search engine as a React hook, for building your own church picker. // The debounce, settled search, "Show more", stale-result handling and record loading all live in // @/lib/lookup-core, the same engine the element uses. diff --git a/registry/lib/lookup-core.ts b/registry/lib/lookup-core.ts index 37969a9..5f01f4c 100644 --- a/registry/lib/lookup-core.ts +++ b/registry/lib/lookup-core.ts @@ -1,7 +1,19 @@ -// Lookup by Here's My Church, headless core v0.3.0. Generated from @heresmychurch/lookup +// Lookup by Here's My Church, headless core v0.4.0. Generated from @heresmychurch/lookup // (packages/sdk/src) by scripts/build-registry.mjs. MIT. https://lookup.heresmychurch.com/docs /* eslint-disable */ +// ── dev.ts ── +// Setup hints for developers. Each prints once, and only on a local development host (localhost, +// 127.0.0.1, *.localhost, *.test), so production consoles and servers stay quiet. +const said: Record = {}; + +export function devWarn(message: string): void { + const host = typeof location == "object" ? location.hostname : ""; + if (said[message] || !/^(localhost|127\.0\.0\.1|\[::1\])$|\.(localhost|test)$/.test(host)) return; + said[message] = 1; + console.warn("Lookup: " + message); +} + // ── client.ts ── // @heresmychurch/lookup core client. No dependencies. @@ -56,13 +68,58 @@ export interface SearchResponse { attribution: string; } +/** One weekly service. */ +export interface ServiceSlot { + /** 0 is Sunday, 6 is Saturday. */ + dayOfWeek: number; + /** 24-hour "HH:MM", such as "09:30". */ + startTime: string; +} + +export interface ServiceTimes { + /** The listed text, such as "Sun 9:00 AM; Wed 7:00 PM", or null when there is none. */ + raw: string | null; + /** The services read from `raw`. Empty when it couldn't be read; `raw` still holds the text. */ + slots: ServiceSlot[]; + /** Whether every part of `raw` was read into `slots`. */ + parsed: boolean; +} + +/** A church's details. Every key is always present, with null or [] when the directory has nothing. */ +export interface ChurchFields { + name: string; + street: string | null; + city: string | null; + /** A region code, such as "TX" or "ON". */ + region: string; + /** The region's name, such as "Texas". */ + regionName: string; + postalCode: string | null; + /** An ISO country code, such as "US". */ + country: string; + countryName: string; + latitude: number; + longitude: number; + phone: string | null; + email: string | null; + website: string | null; + denomination: string | null; + serviceTimes: ServiceTimes; + languages: string[]; + ministries: string[]; + pastorName: string | null; +} + +/** A field name in a church record, as data-hmc-field takes. */ +export type ChurchField = keyof ChurchFields | "id"; + export interface ChurchRecord { id: string; - /** Only with { follow: false }: this listing merged into another. Load that ID instead. */ + /** Only with { follow: false }: this listing merged into another. Load that ID instead; nothing else is set. */ movedTo?: string; /** The ID you asked for, when it merged into this church. Store this record's `id` instead. */ movedFrom?: string; - fields: Record & { name: string; serviceTimes: { raw: string | null } }; + fields: ChurchFields; missing: string[]; completeness: number; /** When someone last confirmed the listing (ms since 1970), or null if never. */ @@ -102,7 +159,7 @@ export class LookupError extends Error { status: number; /** Seconds to wait before trying again, on a 429 or 503. */ retryAfter?: number; - /** A stable reason: invalid, not_found, rate_limited, overloaded, unavailable, … */ + /** A stable reason: invalid, not_found, rate_limited, overloaded, unavailable, timeout, … */ code?: string; constructor(status: number, message: string, retryAfter?: number, code?: string) { super(message); @@ -118,17 +175,35 @@ export interface LookupOptions { /** Your tool's name, such as "my-chms". Self-declared; shown to reviewers as declared. */ client?: string; fetch?: typeof fetch; + /** Give up on a request after this many milliseconds, with a LookupError whose code is "timeout". Defaults to 15000; 0 waits forever. */ + timeout?: number; } export function createLookup(opts: LookupOptions = {}) { const base = (opts.baseUrl ?? "https://lookup.heresmychurch.com").replace(/\/+$/, "") + "/v1"; const f = opts.fetch ?? fetch.bind(globalThis); + const timeout = opts.timeout ?? 15000; + if (!opts.client) devWarn('set client="my-app" so Here\'s My Church knows which tool is asking. Use "lookup-demo" while testing.'); async function get(path: string, signal?: AbortSignal, init?: RequestInit): Promise { - const res = await f(base + path, { signal, ...init }); - const body = await res.json().catch(() => ({})); - if (!res.ok) throw new LookupError(res.status, body.error ?? res.statusText, Number(res.headers.get("retry-after")) || undefined, body.code); - return body; + // One signal for the caller's abort and the timeout. A caller's abort still rejects with AbortError. + const ctl = new AbortController(); + const stop = () => ctl.abort(); + const timer = timeout > 0 ? setTimeout(stop, timeout) : 0; + if (signal?.aborted) stop(); + signal?.addEventListener("abort", stop); + try { + const res = await f(base + path, { ...init, signal: ctl.signal }); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new LookupError(res.status, body.error ?? res.statusText, Number(res.headers.get("retry-after")) || undefined, body.code); + return body; + } catch (e) { + // Aborted, but not by the caller: the timeout fired. + throw ctl.signal.aborted && !signal?.aborted ? new LookupError(0, "Timed out", undefined, "timeout") : e; + } finally { + clearTimeout(timer); + signal?.removeEventListener("abort", stop); + } } const post = (path: string, body: unknown, keepalive?: boolean) => @@ -370,7 +445,7 @@ export const MAX_RESULTS = 50; /** A record field as the text a form field should hold, or null when the directory has nothing. */ export function fieldValue(record: ChurchRecord, field: string): string | null { - const v = field === "id" ? record.id : record.fields[field]; + const v = field === "id" ? record.id : (record.fields as unknown as Record)[field]; if (v == null) return null; if (Array.isArray(v)) return v.length ? v.join(", ") : null; if (typeof v === "object") return (v as { raw?: string | null }).raw ?? null; diff --git a/scripts/build-registry.mjs b/scripts/build-registry.mjs index a4fb7da..a7ff591 100644 --- a/scripts/build-registry.mjs +++ b/scripts/build-registry.mjs @@ -2,6 +2,8 @@ // 1. registry/lib/lookup-core.ts: the SDK's headless core (client, fill, fields, consent, strings) as // one file, so `shadcn add` gives people the code itself. Generated; edit packages/sdk/src instead. // registry/lib/lookup-strings.ts: the other languages, registered when imported. +// registry/hooks/use-church-lookup.ts: the SDK's useChurchLookup (packages/sdk/src/use-church-lookup.ts), +// importing the core above. Generated too. // 2. examples/shadcn-demo/src: verbatim copies of the registry files, so the demo runs what ships. // 3. site/r/*.json: `shadcn build` over registry.json. // @@ -25,7 +27,7 @@ function libSource() { return `// Lookup by Here's My Church, headless core v${version}. Generated from @heresmychurch/lookup // (packages/sdk/src) by scripts/build-registry.mjs. MIT. https://lookup.heresmychurch.com/docs /* eslint-disable */ -${["client.ts", "dom.ts", "strings.ts", "fields.ts", "core.ts"].map((f) => `\n// ── ${f} ──\n${strip(src(f))}`).join("")}`; +${["dev.ts", "client.ts", "dom.ts", "strings.ts", "fields.ts", "core.ts"].map((f) => `\n// ── ${f} ──\n${strip(src(f))}`).join("")}`; } /** Every language file, each in its own block so their helpers don't collide. */ @@ -43,14 +45,27 @@ import { registerStrings, type Strings } from "@/lib/lookup-core" ${body}`; } +/** The hook, pointed at the registry's copy of the core. */ +function hookSource() { + const code = src("use-church-lookup.ts"); + const out = code + .replace('from "./core.ts"', 'from "@/lib/lookup-core"') + .replace("// the headless core, the same engine", "// @/lib/lookup-core, the same engine") + .replace(/^(\/\/ useChurchLookup:)/m, "// Generated from packages/sdk/src/use-church-lookup.ts by scripts/build-registry.mjs. MIT.\n$1"); + if (out.includes("./core.ts")) throw new Error("use-church-lookup.ts: core import not rewritten"); + return out; +} + /** Each generated file and what it should hold. The demo gets the registry files as they are. */ function outputs() { const lib = libSource(); const strings = stringsSource(); - const files = new Map([["registry/lib/lookup-core.ts", lib], ["registry/lib/lookup-strings.ts", strings]]); - for (const f of ["components/church-lookup.tsx", "components/church-consent.tsx", "hooks/use-church-lookup.ts"]) { + const hook = hookSource(); + const files = new Map([["registry/lib/lookup-core.ts", lib], ["registry/lib/lookup-strings.ts", strings], ["registry/hooks/use-church-lookup.ts", hook]]); + for (const f of ["components/church-lookup.tsx", "components/church-consent.tsx"]) { files.set(`examples/shadcn-demo/src/${f}`, readFileSync(`registry/${f}`, "utf8")); } + files.set("examples/shadcn-demo/src/hooks/use-church-lookup.ts", hook); files.set("examples/shadcn-demo/src/lib/lookup-core.ts", lib); files.set("examples/shadcn-demo/src/lib/lookup-strings.ts", strings); return files; diff --git a/scripts/copy-assets.mjs b/scripts/copy-assets.mjs index 8c54228..b75ac3f 100644 --- a/scripts/copy-assets.mjs +++ b/scripts/copy-assets.mjs @@ -1,7 +1,28 @@ // Copy the built SDK into the Worker's static assets, so /element.js, /lookup.js, /service-times.js and // the language files next to element.js serve the current build. -import { copyFileSync } from "node:fs"; -copyFileSync("packages/sdk/dist/element.js", "site/element.js"); -copyFileSync("packages/sdk/dist/index.js", "site/lookup.js"); -copyFileSync("packages/sdk/dist/service-times.js", "site/service-times.js"); -for (const l of ["es", "fr", "de", "pt", "pl"]) copyFileSync(`packages/sdk/dist/strings-${l}.js`, `site/strings-${l}.js`); +// +// Each release is also kept at /sdk// for sites that pin a version. Those files are served as +// immutable, so they're written once and never replaced: commit site/sdk// with the release, +// since a deploy only serves what's in site/. Changing the SDK without bumping its version leaves the +// pinned copy as it was and says so. +import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs"; + +const { version } = JSON.parse(readFileSync("packages/sdk/package.json", "utf8")); +const files = [ + ["element.js", "element.js"], + ["index.js", "lookup.js"], + ["service-times.js", "service-times.js"], + ...["es", "fr", "de", "pt", "pl"].map((l) => [`strings-${l}.js`, `strings-${l}.js`]), +]; + +for (const [from, to] of files) copyFileSync(`packages/sdk/dist/${from}`, `site/${to}`); + +const pinned = `site/sdk/${version}`; +if (!existsSync(pinned)) { + mkdirSync(pinned, { recursive: true }); + for (const [from, to] of files) copyFileSync(`packages/sdk/dist/${from}`, `${pinned}/${to}`); + console.log(`${pinned}/ written. Commit it: pinned versions must stay deployed.`); +} else { + const changed = files.filter(([from, to]) => !readFileSync(`packages/sdk/dist/${from}`).equals(readFileSync(`${pinned}/${to}`))).map(([, to]) => to); + if (changed.length) console.warn(`${pinned}/ kept as released; the build differs in ${changed.join(", ")}. Bump packages/sdk's version to pin this build.`); +} diff --git a/site/SKILL.md b/site/SKILL.md index 33f5f98..43ee86c 100644 --- a/site/SKILL.md +++ b/site/SKILL.md @@ -13,8 +13,8 @@ Lookup by Here's My Church is a church search box for forms. People type a few l ## Steps 1. Load the element once, near the end of the page or in the app's root layout: - `` - For a service-times editor, also load `https://lookup.heresmychurch.com/service-times.js`. + `` + For a service-times editor, also load `https://lookup.heresmychurch.com/sdk/0.4.0/service-times.js`. 2. Add the field inside the form, above the fields it fills: `` - `name`: the chosen church's ID submits with the form. Save it. @@ -26,7 +26,7 @@ Lookup by Here's My Church is a church search box for forms. People type a few l 3. Inputs named for the church already fill: `church_city`, `churchWebsite`, `church[phone]`, or `autocomplete="section-church tel"`. Tag any other input with `data-hmc-field`. Valid names only: name, street, city, region, regionName, postalCode, country, countryName, latitude, longitude, phone, email, website, denomination, serviceTimes, languages, ministries, pastorName, id. On a form that's only about the church, `fill="auto"` also fills plain names (city, state, zip, phone, website). Empty fields fill; typed values are kept unless the element has `overwrite`. -4. Frameworks: it's a standard custom element. In React or Vue, attach `church-select` (detail.result.id), `church-clear` and `church-error` listeners in an effect. In Next.js, import `@heresmychurch/lookup/element` from a `"use client"` file. Inputs are filled through the native setter plus `input`/`change` events, so controlled inputs stay in sync. Types: `import type {} from "@heresmychurch/lookup/react"` or `/vue`. +4. Frameworks: it's a standard custom element. Listen for `church-select` (detail.result.id), `church-clear` and `church-error`: in React 19 as `onchurch-select` (and so on) props, in Vue as `@church-select`, in React 18 with addEventListener in an effect. In Next.js, import `@heresmychurch/lookup/element` from a `"use client"` file. Inputs are filled through the native setter plus `input`/`change` events, so controlled inputs stay in sync. Types: `import type {} from "@heresmychurch/lookup/react"` or `/vue`. 5. While testing, set `client="lookup-demo"`: shared corrections are checked but never sent. In production, set `client` to the app's name. 6. Styling: set `--hmc-accent`, `--hmc-radius`, `--hmc-border`, `--hmc-input-border`, `--hmc-bg`, `--hmc-text` on `church-lookup`, or rely on shadcn-style tokens (`--background`, `--foreground`, `--accent`, `--border`, `--radius`) already on the page. diff --git a/site/_headers b/site/_headers index b723db5..e1f0d92 100644 --- a/site/_headers +++ b/site/_headers @@ -1,3 +1,6 @@ +/sdk/* + Access-Control-Allow-Origin: * + Cache-Control: public, max-age=31536000, immutable /element.js Access-Control-Allow-Origin: * Cache-Control: public, max-age=300 diff --git a/site/docs/quickstart.html b/site/docs/quickstart.html index 93d1089..3a4b595 100644 --- a/site/docs/quickstart.html +++ b/site/docs/quickstart.html @@ -60,8 +60,8 @@

Quickstart

## Steps 1. Load the widget once on the page: - <script type="module" src="https://lookup.heresmychurch.com/element.js"></script> - (Service times editor, optional: https://lookup.heresmychurch.com/service-times.js) + <script type="module" src="https://lookup.heresmychurch.com/sdk/0.4.0/element.js"></script> + (Service times editor, optional: https://lookup.heresmychurch.com/sdk/0.4.0/service-times.js) 2. Put <church-lookup name="church_id" label="Church"></church-lookup> inside the form, above the fields it fills. - `name` submits the chosen church's ID with the form. Store it so you can look the church up again. - Add `required` if a church must be chosen. @@ -71,8 +71,9 @@

Quickstart

name, street, city, region, regionName, postalCode, country, countryName, latitude, longitude, phone, email, website, denomination, serviceTimes, languages, ministries, pastorName, id Don't create new inputs unless I ask. Don't rename existing ones. -4. React or Vue: the element is a custom element. Listen for `church-select` and `church-clear` events - with addEventListener in an effect; values are set the way typing sets them, so controlled inputs stay in sync. +4. React or Vue: the element is a custom element. React 19: pass onchurch-select and onchurch-clear props. + React 18: add `church-select` and `church-clear` listeners with addEventListener in an effect. + Vue: @church-select and @church-clear. Values are set the way typing sets them, so controlled inputs stay in sync. Types: import type {} from "@heresmychurch/lookup/react" (or /vue). 5. While testing, add client="lookup-demo" so corrections people share are checked but never sent. Remove it (or set your app's name) before shipping. @@ -88,7 +89,8 @@

Quickstart

Or set it up yourself. There's no key to request.

1. Add the script

-
html
<script type="module" src="https://lookup.heresmychurch.com/element.js"></script>

2. Put the search box in your form

+
html
<script type="module" src="https://lookup.heresmychurch.com/sdk/0.4.0/element.js"></script>

That URL is pinned to version 0.4.0 and never changes, so an update can't change your form until you change the number. To always get the latest release instead, load https://lookup.heresmychurch.com/element.js. See the changelog for what's in each version.

+

2. Put the search box in your form

Fields named for the church, like church_city, fill on their own. Tag any others with data-hmc-field. Give it a name and the chosen church's ID submits with the form.

<form action="/signup" method="post">
   <church-lookup name="church_id" label="Your church"></church-lookup>
@@ -97,7 +99,7 @@ 

<input name="website" data-hmc-field="website"> <button>Join</button> </form> -<script type="module" src="https://lookup.heresmychurch.com/element.js"></script>

+

Not on shadcn/ui? Use the element with onchurch-select props in React 19 (see the widget), or build your own picker with useChurchLookup from @heresmychurch/lookup/react once the package is on npm.

Install

bash
pnpm dlx shadcn@latest add https://lookup.heresmychurch.com/r/church-lookup.json

That adds three files, plus shadcn's command and popover if you don't have them. The component is a client component ("use client"), so it works in the Next.js app router.

FileWhat it is
components/church-lookup.tsxChurchLookup, the search box, built from Command and Popover
hooks/use-church-lookup.tsuseChurchLookup, the engine as a hook, for your own UI
lib/lookup-core.tsThe headless core: search, fill and consent rules. Generated from @heresmychurch/lookup/core.

With React Hook Form

diff --git a/site/docs/react.md b/site/docs/react.md index 15bfc5c..09c9112 100644 --- a/site/docs/react.md +++ b/site/docs/react.md @@ -33,6 +33,8 @@ Add a church picker to this React + shadcn/ui app using Lookup by Here's My Chur Check: type "grac", pick a church, the tagged fields fill and handleSubmit receives church_id. ``` +Not on shadcn/ui? Use the element with `onchurch-select` props in React 19 (see [the widget](/docs/widget#in-your-form)), or build your own picker with `useChurchLookup` from `@heresmychurch/lookup/react` once the package is on npm. + ## Install ```bash diff --git a/site/docs/search-index.json b/site/docs/search-index.json index 905ebe7..8a9f0cf 100644 --- a/site/docs/search-index.json +++ b/site/docs/search-index.json @@ -1 +1 @@ -[{"t":"Overview","h":"","u":"/docs","g":"Get started","x":"Church tools keep asking people for the same details. Lookup fills them in from Here's My Church, an open directory of 587,842 churches in 19 countries. Someone types a few letters, picks their church, and the address, website, phone and service times fill in."},{"t":"Overview","h":"What you get","u":"/docs#what-you-get","g":"Get started","x":"- Quickstart: Add the search box to a form in a few minutes, or hand the job to your agent. - Example apps: A church management app, a nonprofit sign-up and a church website builder. - The widget: Every attribute, event and form option, with a live preview. - API: Search and church records over plain HTTP, with open CORS and no key."},{"t":"Overview","h":"How it works","u":"/docs#how-it-works","g":"Get started","x":"1. Search as you type. Prefixes, typos and places like \"church in dallas\" all work, nearby churches first. 2. Fill your form. Pick a church and the empty fields you tagged with data-hmc-field fill in. Anything already typed is left alone. 3. Share fixes back. When someone corrects a detail Lookup filled, they can share it back to Here's My Church, one checked box at a time. Because every pick comes from the same open directory, each app that uses Lookup helps keep church data accurate."},{"t":"Overview","h":"Credits","u":"/docs#credits","g":"Get started","x":"- Here's My Church, the open, crowd-sourced church directory every result comes from. - OpenStreetMap contributors, whose map data many listings started from (ODbL). - Cam Pak and Sensible UI. The widget reads the same design token names Sensible UI uses, so it fits right in on those pages. Lookup was built for the AI for Church hackathon and is open source on GitHub."},{"t":"Quickstart","h":"","u":"/docs/quickstart","g":"Get started","x":"Add Lookup to your app Or set it up yourself. There's no key to request."},{"t":"Quickstart","h":"1. Add the script","u":"/docs/quickstart#1-add-the-script","g":"Get started","x":""},{"t":"Quickstart","h":"2. Put the search box in your form","u":"/docs/quickstart#2-put-the-search-box-in-your-form","g":"Get started","x":"Fields named for the church, like churchcity, fill on their own. Tag any others with data-hmc-field. Give it a name and the chosen church's ID submits with the form. script tag: client only: npm:"},{"t":"Quickstart","h":"3. Try it","u":"/docs/quickstart#3-try-it","g":"Get started","x":"Values are set the way typing sets them, so React and other frameworks see them. Testing: Add client=\"lookup-demo\" while you build. Corrections people share are checked the same way, but never sent to Here's My Church."},{"t":"Quickstart","h":"Next steps","u":"/docs/quickstart#next-steps","g":"Get started","x":"- The widget: Attributes, events, icons and the form field, with a live preview. - Theming: Match your design system with a few CSS variables. - Example apps: Three made-up apps built with Lookup."},{"t":"Example apps","h":"","u":"/docs/examples","g":"Get started","x":"Each one is a made-up app using the real widget and live data, in demo mode so nothing you share is sent. They open full screen on the homepage."},{"t":"Example apps","h":"What each one shows","u":"/docs/examples#what-each-one-shows","g":"Get started","x":"Example · Shows · Kinship, web component · React controlled inputs, church-select and church-clear events, the share panel · Harvest · name and required in a plain form, service times feeding distribution hours · Steeple · Filling a live preview,

When <church-lookup> fills a serviceTimes field inside <church-service-times>, the rows update with it.