@odla-ai/chapter 0.25.1 → 0.25.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@odla-ai/chapter",
3
- "version": "0.25.1",
3
+ "version": "0.25.3",
4
4
  "description": "A leader/follower foundation for branded membership sites: shared CRM, admin, auth, payments, booking, and explicit record delivery from one defineChapter config.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://odla.ai/docs/packages/chapter",
@@ -49,8 +49,24 @@ runtime and data rollback remain proven.
49
49
 
50
50
  ## Phase 0 — Freeze the operating baseline
51
51
 
52
- Create or extend root `MIGRATION.md`; never replace its history. Record state
53
- `inventoried` only after the human approves the baseline.
52
+ Use odla PM as the migration's durable coordination state; do not create a
53
+ parallel migration diary. If the odla app already exists, begin by listing
54
+ doing tasks, open bugs, open goals, and recent decisions for the `appId` from
55
+ `odla.config.mjs`. Read the active task, its linked goal, and their comments
56
+ before inspecting code.
57
+
58
+ If the app is not registered yet, choose the intended stable `appId`, keep
59
+ Phase 0/early provisioning evidence in focused commits and checkpoint
60
+ handoffs, and rerun the inventory when a fresh agent resumes. Old branches,
61
+ git history, unrelated deployments, and earlier experiments are only leads to
62
+ verify. Immediately after the first provision registers the app, create PM
63
+ goals/tasks/decisions and backfill the approved baseline evidence; PM is
64
+ authoritative from then on.
65
+
66
+ Use one conformance goal per acceptance outcome, parallel tasks for independent
67
+ tracks, decisions for product/data/identity/route/rollback choices, and bugs
68
+ for defects. Comments carry the source commit, immutable deployment version,
69
+ verification command/result, and rollback checkpoint. Never put secrets in PM.
54
70
 
55
71
  ### Inventory the product
56
72
 
@@ -173,7 +189,8 @@ Before deleting old schema/rules/provisioning:
173
189
  and prove the parity test fails before trusting a green result;
174
190
  6. fail on missing fields, widened rules, cardinality changes, renamed natural
175
191
  keys, new client-readable data, or unapproved seed differences;
176
- 7. record every intentional delta and migration mapping in `MIGRATION.md`.
192
+ 7. record every intentional delta and migration mapping as a PM decision, and
193
+ attach the comparator evidence to the linked conformance goal/task.
177
194
 
178
195
  `createChapterIntegration()` inserts the group seed only when absent. Existing
179
196
  runtime owner edits do not update from later config changes. Compare the current
@@ -188,9 +205,9 @@ At minimum audit:
188
205
  - per-field and request-body caps;
189
206
  - explicit chapter-mode account decision and outbound effects of
190
207
  `create`/`invite`;
191
- - stock `JoinIsland` generates a fresh `submissionId` on each invocation, so an
192
- ambiguous retry after a lost response is not idempotent even though a
193
- concurrent click is disabled;
208
+ - stock `JoinIsland` keeps one `submissionId` across an ambiguous lost-response
209
+ retry. Prove the replay returns the original canonical application id, that
210
+ the id can resume the journey, and that no second row or side effect exists;
194
211
  - `profileFields` now defaults to `[]`; enumerate the small account/admin
195
212
  signals that may be mirrored into backend-only Clerk private metadata rather
196
213
  than relying on implicit projection. Keep the application row and CRM
@@ -420,10 +437,15 @@ fixture. Compare markup/behavior and the Phase 0 screenshots before deletion.
420
437
  `renderHeader` when the header belongs inside the Chapter scope. Chapter mode
421
438
  defaults to Dashboard, People, and Settings; move former global Billing,
422
439
  Calendar, Email, and per-record operations into nested tabs.
423
- - Preserve a distinctive People summary, rail, and record heading with
424
- `collectionSection`'s `renderSummary`, `renderMaster`, and
425
- `renderDetailHeader` slots. Replace specialized record tabs rather than
426
- flattening them into global navigation.
440
+ - Preserve distinctive People summary content, list presentation, record
441
+ heading, and specialized panels with `collectionSection`'s `renderSummary`,
442
+ `renderMaster`, `renderDetailHeader`, and record-tab slots. These slots
443
+ customize content; they do not fix pane geometry.
444
+ - Operational usability is not pixel parity with a cramped legacy admin. At
445
+ desktop widths, the unselected People collection must use the full workspace
446
+ width; after a record opens it becomes master/detail. This is the
447
+ `collapseClosedDetail` default. Set it to `false` only when the empty detail
448
+ pane contains intentional, useful content approved by the human.
427
449
  - Application-backed pipeline changes must use a lifecycle adapter that invokes
428
450
  the authoritative application endpoints. Prove approve/refund/manual
429
451
  transition side effects; a raw CRM `setStage` is not parity.
@@ -448,6 +470,9 @@ At 390, 768, 1280, and 1440 pixels in every theme, compare:
448
470
  - wordmark, text baseline, theme control, active state, and hover/focus;
449
471
  - join fields/errors, payment and slot picker, Clerk sign-in containment;
450
472
  - member cards/actions and every admin section/table/drawer;
473
+ - at 1280 and 1440, every unselected collection table uses the full content
474
+ width: no empty detail pane and no wide table squeezed into a narrow rail;
475
+ after selection, both master and detail remain usable;
451
476
  - no clipped labels, card text escape, accidental document scroll, or
452
477
  horizontal overflow;
453
478
  - loading, empty, error, unauthorized, 404, and reduced-motion states.
@@ -459,16 +484,21 @@ not visual parity.
459
484
 
460
485
  ### Clerk
461
486
 
462
- Use the same Clerk application/workspace. Chapter claim mode requires session
463
- claims for both email and role; hub table mode uses lowercase `admins` rows.
464
- Prove existing allowed/forbidden users, role ladder, super-admin behavior,
465
- malformed/expired sessions, sign-out, and return targets.
466
-
467
- If the legacy verifier enforces JWT `aud` or `azp`, keep that host verifier in
468
- front of Chapter. This Chapter release verifies issuer but does not expose or
469
- enforce the CLI-provisioned Clerk audience. Add wrong-audience and
470
- wrong-authorized-party fixtures; do not cut over auth until the legacy contract
471
- still rejects them.
487
+ For the one website being converted, retain that website's existing Clerk
488
+ application/workspace unless the human approves an identity migration. A
489
+ leader and follower are different websites and use different Clerk
490
+ applications, publishable keys, issuers, roles, and local session tokens. A
491
+ Clerk JWT never authenticates a cross-site delivery.
492
+
493
+ Chapter claim mode requires session claims for both email and role; hub table
494
+ mode uses lowercase `admins` rows. Prove signed-out, allowed, forbidden,
495
+ provisional, member, admin, super-admin, malformed, expired, wrong-issuer,
496
+ sign-out, and return-target behavior. If the site's verifier intentionally
497
+ enforces JWT `aud` or `azp`, retain that check with a host verifier until
498
+ Chapter exposes the same policy and add wrong-audience/wrong-authorized-party
499
+ fixtures. If it never enforced those claims, mark those two cases `n/a` only
500
+ after the full matrix is recorded; do not call their absence an auth success or
501
+ use it to skip the remaining authorization tests.
472
502
 
473
503
  When Chapter needs server-side account/role operations, set the named
474
504
  app-readable `clerk_secret_key` through:
@@ -608,6 +638,7 @@ Keep both rollback capabilities through the approved observation window
608
638
  webhook, job, and secret only in a separate human-approved change with a fresh
609
639
  journey afterward.
610
640
 
611
- Close `MIGRATION.md` only when every applicable track is `primary-prod` or
612
- `retired`, the observation window passes, and the human confirms the existing
613
- product—not merely a Chapter canary—has been converted.
641
+ Mark the migration goals met and tasks done only when every applicable track is
642
+ `primary-prod` or `retired`, the observation window passes, evidence is attached
643
+ in PM, and the human confirms the existing product—not merely a Chapter
644
+ canary—has been converted.
@@ -67,9 +67,19 @@ consumer, not a visual identity to rename.
67
67
 
68
68
  ## Phase 0 — Resolve the product and brand brief
69
69
 
70
- Write `PRODUCT.md` before code. Record decisions rather than inventing business
71
- facts. Ask the human only for missing choices that change money, identity,
72
- outbound communication, authorization, or the public brand.
70
+ Record decisions rather than inventing business facts. Ask the human only for
71
+ missing choices that change money, identity, outbound communication,
72
+ authorization, or the public brand. Do not create a parallel product or
73
+ migration diary.
74
+
75
+ PM requires a registered, co-owned odla app. Before Phase 3 registration, use a
76
+ focused branch/commit and checkpoint handoff for the approved brief and rerun
77
+ the Phase 0 checks when a fresh agent resumes. Immediately after provision
78
+ registers the app, create PM conformance goals and track tasks, record these
79
+ product/brand/identity decisions, and backfill the earlier evidence. PM is
80
+ authoritative from then on; start every later session by listing doing tasks,
81
+ open bugs/goals, and recent decisions for the `appId` in
82
+ `odla.config.mjs`. Never put secrets in PM.
73
83
 
74
84
  | Decision | Required answer |
75
85
  | --- | --- |
@@ -158,7 +168,6 @@ Recommended minimum tree:
158
168
 
159
169
  ```text
160
170
  .
161
- ├── PRODUCT.md
162
171
  ├── package.json
163
172
  ├── index.html
164
173
  ├── vite.config.mjs
@@ -344,9 +353,8 @@ the private profile write and records `clerkPrivateMetadataSyncedAt`.
344
353
  `copy` is a recursive partial of `ChapterCopy`. `defineChapter()` resolves it
345
354
  to a complete `chapter.copy`, which is the voice source for packaged join,
346
355
  member, and admin surfaces. Put plain text in `copy`; use render slots for
347
- markup or a different composition. Include the voice constraints from
348
- `PRODUCT.md` in a contract test, such as banned punctuation or required
349
- terminology.
356
+ markup or a different composition. Include the approved voice constraints in a
357
+ contract test, such as banned punctuation or required terminology.
350
358
 
351
359
  In this release, `prices.currency` and `prices.interval` record intent but do
352
360
  not control the group row, public join config, or Stripe charge. The Stripe
@@ -376,6 +384,32 @@ Snapshot these resolved values in `chapter-contract.test.ts`:
376
384
  schema/rules/seeds/probes, using the fixed clock because the integration seed
377
385
  carries the timestamp.
378
386
 
387
+ ### When this site is a leader or follower
388
+
389
+ Model the network as website nodes joined by directed delivery edges. Every
390
+ website keeps its own `appId`, ODLA tenant/key, CRM config, Clerk application,
391
+ issuer, roles, and users. A leader edge is one `network.targets[]` record with
392
+ the follower id/name/origin, optional vault secret name, and a per-record-type
393
+ field allowlist. The follower declares compatible CRM types and fields; it does
394
+ not need the leader's Clerk configuration.
395
+
396
+ The leader browser authenticates only to the leader. Its Worker authorizes the
397
+ local admin, reads the edge's share secret from the leader vault, and sends a
398
+ versioned `{ version, type, hubRecordId, input }` payload to the follower. The
399
+ follower validates that share secret and its local CRM config, then writes with
400
+ its own `ODLA_API_KEY`. Never send either website's Clerk JWT or ODLA key across
401
+ the edge. Pipeline, account, billing, and roles remain authoritative locally.
402
+
403
+ Conformance must prove:
404
+
405
+ - the target metadata returned to the browser contains no secret;
406
+ - only allowlisted fields leave the leader;
407
+ - unknown follower types/fields fail before a write;
408
+ - wrong share secret returns `401` and writes nothing;
409
+ - retry updates the provenance-matched follower record instead of duplicating;
410
+ - neither Clerk token nor either `ODLA_API_KEY` appears in the cross-site
411
+ request or client bundle.
412
+
379
413
  ## Phase 3 — Provisioning and Worker shell
380
414
 
381
415
  ```js
@@ -448,6 +482,10 @@ separate browser-owned booking-consent checkpoint for availability plus
448
482
  create/reschedule/cancel access. A grant created for the retired read-only
449
483
  mirror must be reconnected. No OAuth code or token passes through the agent.
450
484
 
485
+ The app now exists. Initialize PM, backfill the approved Phase 0–2 decisions
486
+ and evidence, create linked tasks/goals for the remaining tracks, and read that
487
+ state before continuing.
488
+
451
489
  ## Phase 4 — Build the four application surfaces
452
490
 
453
491
  Import the public site's application theme once. For the admin application,
@@ -517,12 +555,12 @@ from raw `redirect_status` or `reschedule` parameters. When the host stores the
517
555
  application capability elsewhere, provide `initialState` from trusted server
518
556
  state or a `loadResume` adapter.
519
557
 
520
- `JoinIsland` disables its button while one request is pending, but creates a new
521
- `submissionId` for every submit invocation. A retry after the server committed
522
- but the response was lost can therefore create another application. If that is
523
- unacceptable, stop and fix/upgrade the package or use a reviewed host adapter
524
- that keeps one stable id across logical retries. Do not label the stock behavior
525
- fully idempotent.
558
+ `JoinIsland` disables its button while one request is pending and keeps one
559
+ stable `submissionId` for the logical form journey. Prove a retry after the
560
+ server committed but the response was lost returns the same canonical
561
+ application id, that the id can be resumed, and that no second application or
562
+ side effect exists. A `duplicate: true` response or unchanged row count alone
563
+ is not sufficient proof.
526
564
 
527
565
  ### Members
528
566
 
@@ -564,6 +602,13 @@ anchors; record details are record-tab anchors. Do not promote those tabs into
564
602
  the global site header. Use `chrome="standalone"` only for an admin-only product
565
603
  that has no host shell.
566
604
 
605
+ The People collection uses the full workspace width until a record is selected,
606
+ then becomes master/detail. Keep the default
607
+ `collectionSection({ collapseClosedDetail: true })`; set it to `false` only
608
+ when an intentional empty-detail panel contains useful approved content. At
609
+ 1280 and 1440 pixels, verify a wide collection table is not squeezed into a
610
+ narrow rail beside an empty pane.
611
+
567
612
  The router must serve and reload `/`, every public page, `/join`, `/members/`,
568
613
  and `/admin/` without accidentally sending API paths to the SPA. Chapter
569
614
  terminates unknown `/api/*` paths as JSON 404s before the static asset fallback.
@@ -571,8 +616,10 @@ terminates unknown `/api/*` paths as JSON 404s before the static asset fallback.
571
616
  ## Phase 5 — Configure Clerk and bootstrap authority
572
617
 
573
618
  At this step, read Clerk's current agent-facing CLI documentation. Use one
574
- Clerk application with development and production instances; do not create a
575
- second application for production.
619
+ Clerk application with development and production instances **for this
620
+ website**; do not create a second application merely for this site's production
621
+ environment. A leader and a follower are separate websites and use separate
622
+ Clerk applications, issuers, users, and roles.
576
623
 
577
624
  For default chapter claim auth, the session token must include both:
578
625
 
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/ui/slot-picker.tsx","../src/ui/datetime.ts","../src/ui/members.tsx","../src/ui/reschedule.tsx","../src/ui/join.tsx","../src/ui/payment-step.tsx","../src/ui/form-fields.ts","../src/ui/join-booking.tsx"],"sourcesContent":["// SlotPicker — a pure presentational day-chips + time-grid picker, shared by the\n// join booking step and the member-area reschedule. Ported from the proven\n// reference Preact island; behaviour and DOM shape are unchanged.\n//\n// It holds only the active-day UI state; slot data, selection, and booking are\n// the caller's (the picker is `onPick`-driven). `classes` lets the composing\n// island supply its own CSS contract (join styles `slot-*`, reschedule\n// `msched-*`); the defaults work standalone against those class names.\nimport { useMemo, useState } from \"preact/hooks\";\nimport { dayLabel, groupSlotsByDay, timeLabel } from \"./datetime.js\";\nimport type { Slot } from \"./datetime.js\";\n\n/** CSS class names for the four picker parts — overridable so one component\n * serves several differently-styled surfaces. */\nexport interface SlotPickerClasses {\n days: string;\n day: string;\n times: string;\n time: string;\n}\n\nconst DEFAULT_CLASSES: SlotPickerClasses = {\n days: \"slot-days\",\n day: \"slot-day\",\n times: \"slot-grid\",\n time: \"slot-time\",\n};\n\n/** Props for {@link SlotPicker}. Generic over the slot type so a caller's richer\n * slot object survives through `onPick`. */\nexport interface SlotPickerProps<T extends Slot = Slot> {\n /** Bookable slots, ideally already chronological. */\n slots: readonly T[];\n /** The group's scheduling timezone; all labels render in it. */\n timezone: string;\n /** The currently-selected slot's start, for the pressed state. */\n selectedStartAt?: number;\n /** Called with the full slot object when a time is chosen. */\n onPick: (slot: T) => void;\n /** Called when the active day changes (callers clear their selection). */\n onDayChange?: () => void;\n classes?: SlotPickerClasses;\n}\n\n/** A day-chips + time-grid slot picker. Presentational and `onPick`-driven: it\n * owns only the active-day selection; the caller owns slot data, the chosen\n * slot, and booking. Shared by the join booking step and the member reschedule. */\nexport function SlotPicker<T extends Slot = Slot>(props: SlotPickerProps<T>) {\n const { slots, timezone, selectedStartAt, onPick, onDayChange, classes = DEFAULT_CLASSES } = props;\n const byDay = useMemo(() => groupSlotsByDay(slots, timezone), [slots, timezone]);\n const dayKeys = [...byDay.keys()];\n const [activeDay, setActiveDay] = useState<string | undefined>(dayKeys[0]);\n\n // Keep the active day valid if the slot set changed under us (e.g. a reload\n // after a 409): fall back to the first available day.\n const day = activeDay !== undefined && byDay.has(activeDay) ? activeDay : dayKeys[0];\n const times = (day !== undefined ? byDay.get(day) : undefined) ?? [];\n\n return (\n <>\n <div className={classes.days}>\n {dayKeys.map((key) => {\n const first = byDay.get(key)?.[0];\n return (\n <button\n key={key}\n type=\"button\"\n className={classes.day}\n aria-pressed={key === day}\n onClick={() => {\n setActiveDay(key);\n onDayChange?.();\n }}\n >\n {first ? dayLabel(first.startAt, timezone) : key}\n </button>\n );\n })}\n </div>\n <div className={classes.times}>\n {times.map((s) => (\n <button\n key={s.startAt}\n type=\"button\"\n className={classes.time}\n aria-pressed={selectedStartAt === s.startAt}\n onClick={() => onPick(s)}\n >\n {timeLabel(s.startAt, timezone)}\n </button>\n ))}\n </div>\n </>\n );\n}\n","// Date/timezone formatting for the chapter member islands (join booking, member\n// area). Ported from proven production helpers. Every time renders in the\n// group's SCHEDULING timezone with an explicit abbreviation — never the viewer's\n// unlabeled local zone — so an applicant always sees the time the chapter meant.\n// Pure and framework-free, so it is unit-testable without a DOM.\n\n/** A bookable slot: a start instant in epoch milliseconds. */\nexport interface Slot {\n startAt: number;\n}\n\n/** The timezone's short abbreviation (e.g. \"PST\"); falls back to the id if the\n * runtime can't resolve it. */\nexport function tzShort(tz: string): string {\n try {\n const parts = new Intl.DateTimeFormat(undefined, { timeZone: tz, timeZoneName: \"short\" }).formatToParts(\n new Date(),\n );\n return parts.find((p) => p.type === \"timeZoneName\")?.value ?? tz;\n } catch {\n return tz;\n }\n}\n\n/** DST-safe day bucket key (ISO date in the target zone). Groups slots by the\n * calendar day a viewer in `tz` would see, not by UTC midnight. */\nexport function dayKey(ms: number, tz: string): string {\n return new Date(ms).toLocaleDateString(\"en-CA\", { timeZone: tz });\n}\n\n/** Short day label for a day chip, e.g. \"Mon, Jun 3\". */\nexport function dayLabel(ms: number, tz: string): string {\n return new Date(ms).toLocaleDateString(undefined, { timeZone: tz, weekday: \"short\", month: \"short\", day: \"numeric\" });\n}\n\n/** Time-of-day label for a slot button, e.g. \"2:30 PM\". */\nexport function timeLabel(ms: number, tz: string): string {\n return new Date(ms).toLocaleTimeString(undefined, { timeZone: tz, hour: \"numeric\", minute: \"2-digit\" });\n}\n\n/** Full, human confirmation label, e.g. \"Monday, June 3, 2:30 PM PST\". */\nexport function fullLabel(ms: number, tz: string): string {\n return new Date(ms).toLocaleString(undefined, {\n timeZone: tz,\n weekday: \"long\",\n month: \"long\",\n day: \"numeric\",\n hour: \"numeric\",\n minute: \"2-digit\",\n timeZoneName: \"short\",\n });\n}\n\n/** Currency label from integer cents, e.g. 100000 → \"$1,000\". */\nexport function fmtMoney(cents: number): string {\n return \"$\" + Math.round(cents / 100).toLocaleString();\n}\n\n/** Short date label, e.g. \"Jun 3, 2026\" (used for renewal/refund copy). */\nexport function fmtDate(ms: number): string {\n return new Date(ms).toLocaleDateString(undefined, { month: \"short\", day: \"numeric\", year: \"numeric\" });\n}\n\n/** Bucket slots into an insertion-ordered `Map<dayKey, Slot[]>` for the picker.\n * Input order is preserved within each day, so a server that returns slots\n * chronologically yields chronological chips + times. */\nexport function groupSlotsByDay<T extends Slot>(slots: readonly T[], tz: string): Map<string, T[]> {\n const byDay = new Map<string, T[]>();\n for (const s of slots) {\n const k = dayKey(s.startAt, tz);\n const bucket = byDay.get(k);\n if (bucket) bucket.push(s);\n else byDay.set(k, [s]);\n }\n return byDay;\n}\n","// The member area island. Reads GET /api/me (role + the member's own\n// application, folded server-side) and renders the account header plus, for a\n// provisional member, their application card with book/reschedule; a full member\n// sees the caller-supplied `memberContent`. Ported from the reference members island to\n// Preact, driven by the injected `api` (no Clerk SDK dependency).\nimport type { ComponentChildren } from \"preact\";\nimport { useEffect, useState } from \"preact/hooks\";\nimport { Rescheduler } from \"./reschedule.js\";\nimport { fmtDate, fullLabel } from \"./datetime.js\";\nimport type { ApiFn } from \"./api.js\";\nimport type { MemberApplication } from \"../session.js\";\nimport { formatChapterCopy, type ChapterCopy } from \"../copy.js\";\nimport { useChapterCopy } from \"./copy-context.js\";\n\ninterface Me {\n email: string | null;\n role: string;\n application: MemberApplication | null;\n}\n\n/** Props for {@link MembersArea}. */\nexport interface MembersAreaProps {\n api: ApiFn;\n /** Sign the member out (the host owns Clerk's signOut). */\n signOut: () => void;\n /** Where the \"Admin console\" link points for admins. Default \"/admin/\". */\n adminHref?: string;\n /** Where an accountless member goes to apply. Default \"/join.html\". */\n applyHref?: string;\n /** What a full (non-provisional) member sees below the account header. */\n memberContent?: ComponentChildren;\n /** Resolved member-area copy. */\n copy?: ChapterCopy[\"members\"];\n /** Replace the provisional application card without replacing auth/data load. */\n renderProvisional?: (context: MemberProvisionalRenderContext) => ComponentChildren;\n}\n\n/** Data and actions supplied to a site's provisional-member render slot. */\nexport interface MemberProvisionalRenderContext {\n api: ApiFn;\n application: MemberApplication | null;\n applyHref: string;\n reload: () => Promise<void>;\n defaultContent: ComponentChildren;\n}\n\nfunction card(copy: ChapterCopy[\"members\"], kicker: string, body: ComponentChildren): ComponentChildren {\n return (\n <div className=\"card\">\n <div className=\"card-label\">{copy.provisional.cardLabel}</div>\n <div className=\"meeting-block\">\n <div className=\"meeting-kicker\">{kicker}</div>\n {body}\n </div>\n </div>\n );\n}\n\nfunction ProvisionalCard(props: {\n api: ApiFn;\n application: MemberApplication | null;\n applyHref: string;\n copy: ChapterCopy[\"members\"];\n onReschedule: () => void | Promise<void>;\n}): ComponentChildren {\n const { api, application, applyHref, copy, onReschedule } = props;\n if (!application) {\n return card(\n copy,\n copy.provisional.applicationNeeded,\n <>\n <div className=\"meeting-note\">{copy.provisional.applicationNeededBody}</div>\n <a className=\"apply-link\" href={applyHref}>\n {copy.provisional.apply}\n </a>\n </>,\n );\n }\n if (application.status === \"refunded\") {\n return card(\n copy,\n copy.provisional.refunded,\n <div className=\"meeting-note\">{copy.provisional.refundedBody}</div>,\n );\n }\n const membership = application.paid ? (\n <div className=\"meeting-note\">\n {application.renewalAt\n ? formatChapterCopy(copy.provisional.renews, { date: fmtDate(application.renewalAt) })\n : copy.provisional.active}\n </div>\n ) : null;\n if (application.meetingAt) {\n return card(\n copy,\n copy.provisional.introductionCall,\n <>\n <div className=\"meeting-date\">{fullLabel(application.meetingAt, application.timezone)}</div>\n <div className=\"meeting-note\">{copy.provisional.calendarInvite}</div>\n {application.meetUrl ? (\n <div className=\"meeting-note\">\n <a href={application.meetUrl} target=\"_blank\" rel=\"noopener\">\n {copy.provisional.joinCall}\n </a>\n </div>\n ) : null}\n <Rescheduler\n api={api}\n applicationId={application.id}\n timezone={application.timezone}\n copy={copy.reschedule}\n onRescheduled={onReschedule}\n />\n {membership}\n </>,\n );\n }\n return card(\n copy,\n copy.provisional.bookCall,\n <>\n <div className=\"meeting-note\">{copy.provisional.bookCallBody}</div>\n <Rescheduler\n api={api}\n applicationId={application.id}\n timezone={application.timezone}\n copy={copy.reschedule}\n onRescheduled={onReschedule}\n label={copy.provisional.chooseTime}\n />\n {membership}\n </>,\n );\n}\n\n/** The signed-in member area. Loads /api/me on mount and renders the account\n * header plus the provisional application card or the full-member content. */\nexport function MembersArea(props: MembersAreaProps) {\n const inheritedCopy = useChapterCopy();\n const {\n api,\n signOut,\n adminHref = \"/admin/\",\n applyHref = \"/join.html\",\n memberContent,\n renderProvisional,\n } = props;\n const copy = props.copy ?? inheritedCopy.members;\n const [me, setMe] = useState<Me | null>(null);\n const [error, setError] = useState(false);\n\n const reload = async () => {\n try {\n setMe(await api<Me>(\"/api/me\"));\n } catch {\n setError(true);\n }\n };\n useEffect(() => {\n void reload();\n }, []);\n\n if (error) return <p className=\"meeting-note\">{copy.loadFailed}</p>;\n if (!me) return <p className=\"meeting-note\">{inheritedCopy.common.loading}</p>;\n const role = me.role || \"provisional\";\n\n return (\n <>\n <div className=\"card\">\n <div className=\"member-row\">\n <span className=\"member-email\">{me.email}</span>\n <span className={\"role-badge \" + role}>{role}</span>\n </div>\n <div className=\"account-actions\">\n <button className=\"btn secondary mini\" onClick={signOut}>\n {copy.account.signOut}\n </button>\n {role === \"admin\" ? (\n <a className=\"admin-console-link\" href={adminHref}>\n {copy.account.adminConsole}\n </a>\n ) : null}\n </div>\n </div>\n {role === \"provisional\" ? (() => {\n const defaultContent = (\n <ProvisionalCard\n api={api}\n application={me.application}\n applyHref={applyHref}\n copy={copy}\n onReschedule={reload}\n />\n );\n return renderProvisional?.({\n api,\n application: me.application,\n applyHref,\n reload,\n defaultContent,\n }) ?? defaultContent;\n })() : (\n (memberContent ?? (\n <div className=\"card\">\n <div className=\"card-label\">{copy.full.welcome}</div>\n </div>\n ))\n )}\n </>\n );\n}\n","// In-place reschedule: open a SlotPicker, rebook via /api/schedule/book (the same\n// capability the join flow uses; the application id is the credential). Ported\n// from the reference member-area Rescheduler, driven by the injected `api`.\nimport { useState } from \"preact/hooks\";\nimport { SlotPicker } from \"./slot-picker.js\";\nimport type { Slot } from \"./datetime.js\";\nimport type { ApiFn } from \"./api.js\";\nimport type { ChapterCopy } from \"../copy.js\";\nimport { useChapterCopy } from \"./copy-context.js\";\n\ninterface SlotsResponse {\n schedulingReady?: boolean;\n slots?: Slot[];\n timezone?: string;\n}\n\n/** Props for {@link Rescheduler}. */\nexport interface RescheduleProps {\n api: ApiFn;\n applicationId: string;\n timezone: string;\n /** Called after a successful (re)booking so the caller can refresh /api/me. */\n onRescheduled: () => void | Promise<void>;\n /** Link text to open the picker (e.g. \"Choose a time\" for a first booking). */\n label?: string;\n /** Resolved rescheduling copy. */\n copy?: ChapterCopy[\"members\"][\"reschedule\"];\n}\n\n/** A collapsed \"change your time\" link that expands into a {@link SlotPicker} and\n * rebooks on pick. Degrades to a message when scheduling is unavailable. */\nexport function Rescheduler(props: RescheduleProps) {\n const inheritedCopy = useChapterCopy();\n const copy = props.copy ?? inheritedCopy.members.reschedule;\n const { api, applicationId, timezone, onRescheduled, label = copy.changeTime } = props;\n const [open, setOpen] = useState(false);\n const [slots, setSlots] = useState<Slot[] | null>(null);\n const [tz, setTz] = useState(timezone);\n const [busy, setBusy] = useState(false);\n const [msg, setMsg] = useState<string | null>(null);\n\n const start = async () => {\n setOpen(true);\n setSlots(null);\n setMsg(null);\n try {\n const r = await api<SlotsResponse>(\"/api/schedule/slots\");\n if (r.schedulingReady === false) {\n setSlots([]);\n setMsg(copy.unavailable);\n return;\n }\n setSlots(r.slots ?? []);\n if (r.timezone) setTz(r.timezone);\n } catch {\n setSlots([]);\n setMsg(copy.loadFailed);\n }\n };\n\n const pick = async (slot: Slot) => {\n setBusy(true);\n setMsg(null);\n try {\n await api(\"/api/schedule/book\", { method: \"POST\", body: JSON.stringify({ applicationId, startAt: slot.startAt }) });\n setOpen(false);\n await onRescheduled();\n } catch (e) {\n setMsg(e instanceof Error ? e.message : copy.slotGone);\n } finally {\n setBusy(false);\n }\n };\n\n if (!open) {\n return (\n <p className=\"meeting-note\">\n <a\n href=\"#\"\n onClick={(e) => {\n e.preventDefault();\n void start();\n }}\n >\n {label}\n </a>\n </p>\n );\n }\n return (\n <div className=\"msched\">\n {slots === null ? (\n <p className=\"meeting-note\">{copy.loading}</p>\n ) : slots.length === 0 ? (\n <p className=\"meeting-note\">{msg ?? copy.noTimes}</p>\n ) : (\n <SlotPicker\n slots={slots}\n timezone={tz}\n classes={{ days: \"msched-days\", day: \"msched-day\", times: \"msched-times\", time: \"msched-time\" }}\n onPick={(s) => void pick(s)}\n />\n )}\n {busy ? <p className=\"meeting-note\">{copy.rescheduling}</p> : null}\n {msg && slots && slots.length > 0 ? <p className=\"meeting-note error\">{msg}</p> : null}\n <p className=\"meeting-note\">\n <a\n href=\"#\"\n onClick={(e) => {\n e.preventDefault();\n setOpen(false);\n }}\n >\n {copy.keepTime}\n </a>\n </p>\n </div>\n );\n}\n","// The join island — the signup flow orchestrator. The SITE provides the form\n// fields (as children); this owns the flow: submit → /api/applications →\n// (paymentsReady) the Stripe PaymentStep → (schedulingReady) the SlotPicker\n// booking → confirmation. Faithful to the reference join flow, but the flow +\n// payment + booking are packaged instead of hand-rolled per site.\nimport type { ComponentChildren, JSX } from \"preact\";\nimport { useEffect, useState } from \"preact/hooks\";\nimport { PaymentStep } from \"./payment-step.js\";\nimport { fullLabel } from \"./datetime.js\";\nimport type { ChapterCopy } from \"../copy.js\";\nimport { useChapterCopy } from \"./copy-context.js\";\nimport { collectFormFields } from \"./form-fields.js\";\nimport { JoinBooking } from \"./join-booking.js\";\n\n/** The public join config (the shape `GET /api/join-config` returns). */\nexport interface JoinConfig {\n id: string;\n name: string;\n paymentsReady: boolean;\n refundPolicyText?: string;\n /** Resolved copy for the packaged join flow. */\n copy?: ChapterCopy[\"join\"];\n}\n\n/** Server-validated state used to resume a join journey after a redirect. */\nexport type JoinFlowState =\n | { step: \"form\" }\n | { step: \"payment\"; applicationId: string }\n | { step: \"paymentPending\"; applicationId: string }\n | { step: \"booking\"; applicationId: string }\n | {\n step: \"done\";\n applicationId: string;\n booked: { startAt: number; timezone: string };\n };\n\n/** Canonical flow state supplied to a site's per-step heading render slot. */\nexport interface JoinStepRenderContext {\n state: JoinFlowState;\n applicationId?: string;\n}\n\n/** Submission state supplied to a site's submit-control render slot. */\nexport interface JoinSubmitRenderContext {\n submitting: boolean;\n disabled: boolean;\n}\n\ninterface JoinResumeResponse {\n state: \"payment\" | \"paymentPending\" | \"booking\" | \"done\";\n applicationId: string;\n booked?: { startAt: number; timezone: string };\n}\n\n/** Load canonical server state for a capability-bearing application id. */\nexport async function loadJoinResume(\n applicationId: string,\n fetcher: typeof fetch = fetch,\n): Promise<JoinFlowState> {\n const res = await fetcher(`/api/join/resume?application=${encodeURIComponent(applicationId)}`);\n const data = (await res.json()) as JoinResumeResponse & { error?: string };\n if (!res.ok) throw new Error(data.error ?? \"The application could not be resumed.\");\n if (data.state === \"done\" && data.booked) {\n return { step: \"done\", applicationId: data.applicationId, booked: data.booked };\n }\n if (data.state === \"paymentPending\") {\n return { step: \"paymentPending\", applicationId: data.applicationId };\n }\n if (data.state === \"booking\") {\n return { step: \"booking\", applicationId: data.applicationId };\n }\n return { step: \"payment\", applicationId: data.applicationId };\n}\n\n/** Props for {@link JoinIsland}. */\nexport interface JoinIslandProps {\n config: JoinConfig;\n /** The site's application form fields — inputs with `name` attributes; their\n * values are collected via FormData and posted to /api/applications. */\n children: ComponentChildren;\n /** Where the confirmation links after booking. Default \"/members/\". */\n membersHref?: string;\n /** Resolved join copy. Defaults to `config.copy`, then the nearest provider. */\n copy?: ChapterCopy[\"join\"];\n /** Trusted initial state produced by the server, never raw URL parameters. */\n initialState?: JoinFlowState;\n /** Resolve redirect/query state against the server before resuming the flow. */\n loadResume?: () => Promise<JoinFlowState | null>;\n /** Render a heading or other site-owned framing above each packaged step. */\n renderStepHeader?: (context: JoinStepRenderContext) => ComponentChildren;\n /** Replace the packaged completion card while retaining flow orchestration. */\n renderDone?: (\n context: Extract<JoinFlowState, { step: \"done\" }> & { membersHref: string },\n ) => ComponentChildren;\n /** Replace the submit control without replacing the application form. */\n renderSubmit?: (context: JoinSubmitRenderContext) => ComponentChildren;\n /** Additional host validation gate for the submit action. */\n submitDisabled?: boolean;\n /** Stripe Elements presentation and site-owned payment content. */\n payment?: {\n appearance?: Record<string, unknown>;\n fonts?: readonly Record<string, unknown>[];\n renderPriceLines?: (lines: {\n standardCents: number;\n discountCents: number;\n dueTodayCents: number;\n }) => ComponentChildren;\n children?: ComponentChildren;\n };\n}\n\n/** The signup island. Renders the site's form, then drives payment (when the\n * chapter charges) and booking (when a calendar is connected) to confirmation. */\nexport function JoinIsland(props: JoinIslandProps) {\n const inheritedCopy = useChapterCopy();\n const {\n config,\n children,\n membersHref = \"/members/\",\n renderStepHeader,\n renderDone,\n renderSubmit,\n } = props;\n const copy = props.copy ?? config.copy ?? inheritedCopy.join;\n const [state, setState] = useState<JoinFlowState>(props.initialState ?? { step: \"form\" });\n const [error, setError] = useState<string | null>(null);\n const [submitting, setSubmitting] = useState(false);\n\n useEffect(() => {\n const resolver = props.loadResume ?? (() => {\n if (typeof window === \"undefined\") return Promise.resolve(null);\n const applicationId = new URL(window.location.href).searchParams.get(\"application\");\n return applicationId ? loadJoinResume(applicationId) : Promise.resolve(null);\n });\n let live = true;\n void resolver()\n .then((resumed) => {\n if (live && resumed) setState(resumed);\n })\n .catch(() => {\n if (live) setError(copy.form.unexpectedFailure);\n });\n return () => {\n live = false;\n };\n }, [props.loadResume]);\n\n useEffect(() => {\n if (state.step !== \"paymentPending\") return;\n let live = true;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const poll = async () => {\n try {\n const resumed = props.loadResume\n ? await props.loadResume()\n : await loadJoinResume(state.applicationId);\n if (!live || !resumed) return;\n setState(resumed);\n if (resumed.step === \"paymentPending\") timer = setTimeout(() => void poll(), 1500);\n } catch {\n if (live) timer = setTimeout(() => void poll(), 2500);\n }\n };\n timer = setTimeout(() => void poll(), 1000);\n return () => {\n live = false;\n if (timer) clearTimeout(timer);\n };\n }, [state, props.loadResume]);\n\n const submit = async (e: JSX.TargetedSubmitEvent<HTMLFormElement>) => {\n e.preventDefault();\n if (submitting || props.submitDisabled === true) return;\n setSubmitting(true);\n setError(null);\n try {\n const fields = collectFormFields(new FormData(e.currentTarget));\n fields.submissionId = crypto.randomUUID();\n const res = await fetch(\"/api/applications\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(fields),\n });\n const data = (await res.json()) as { id?: string; error?: string };\n if (!res.ok || !data.id) throw new Error(data.error ?? copy.form.submitFailed);\n setState({\n step: config.paymentsReady ? \"payment\" : \"booking\",\n applicationId: data.id,\n });\n } catch (err) {\n setError(err instanceof Error ? err.message : copy.form.unexpectedFailure);\n } finally {\n setSubmitting(false);\n }\n };\n\n const header = renderStepHeader?.({\n state,\n ...(\"applicationId\" in state ? { applicationId: state.applicationId } : {}),\n });\n if (state.step === \"done\") {\n const body = renderDone?.({ ...state, membersHref }) ?? (\n <div className=\"join-done card\">\n <div className=\"card-label\">{copy.done.label}</div>\n <p className=\"meeting-date\">{fullLabel(state.booked.startAt, state.booked.timezone)}</p>\n <p className=\"meeting-note\">{copy.done.calendarInvite}</p>\n <a className=\"apply-link\" href={membersHref}>\n {copy.done.memberArea}\n </a>\n </div>\n );\n return <>{header}{body}</>;\n }\n if (state.step === \"booking\") {\n return (\n <>\n {header}\n <JoinBooking\n applicationId={state.applicationId}\n copy={copy.booking}\n onBooked={(booked) => {\n setState({ step: \"done\", applicationId: state.applicationId, booked });\n }}\n />\n </>\n );\n }\n if (state.step === \"payment\") {\n return (\n <>\n {header}\n <PaymentStep\n applicationId={state.applicationId}\n refundPolicyText={config.refundPolicyText ?? \"\"}\n copy={copy.payment}\n appearance={props.payment?.appearance}\n fonts={props.payment?.fonts}\n renderPriceLines={props.payment?.renderPriceLines}\n onPaid={() => setState({ step: \"booking\", applicationId: state.applicationId })}\n >\n {props.payment?.children}\n </PaymentStep>\n </>\n );\n }\n if (state.step === \"paymentPending\") {\n return (\n <>\n {header}\n <p className=\"pay-status\" role=\"status\">{copy.payment.pending}</p>\n </>\n );\n }\n const submitDisabled = submitting || props.submitDisabled === true;\n return (\n <>\n {header}\n <form className=\"join-form\" onSubmit={(e) => void submit(e)}>\n {children}\n {error ? <p className=\"join-error\">{error}</p> : null}\n {renderSubmit?.({ submitting, disabled: submitDisabled }) ?? (\n <button className=\"submit-btn\" type=\"submit\" disabled={submitDisabled}>\n {submitting ? copy.form.submitting : copy.form.submit}\n </button>\n )}\n </form>\n </>\n );\n}\n","// The join flow's payment step. Ports the reference card entry into the island:\n// dynamically loads js.stripe.com (NO @stripe/react-stripe-js dep), creates a\n// subscription server-side, and mounts a Stripe Payment Element. The refund-policy\n// checkbox is the gate — checking it starts the (money-creating) subscription\n// call. Client success is advisory only; the webhook is the\n// authoritative writer of paid state (see payments.ts).\nimport type { ComponentChildren } from \"preact\";\nimport { useRef, useState } from \"preact/hooks\";\nimport type { ChapterCopy } from \"../copy.js\";\nimport { useChapterCopy } from \"./copy-context.js\";\n\n// Minimal shapes for the dynamically-loaded js.stripe.com global.\ninterface StripeElementsApi {\n create(type: string): { mount(target: HTMLElement): void };\n}\ninterface StripeApi {\n elements(opts: {\n clientSecret: string;\n appearance?: Record<string, unknown>;\n fonts?: readonly Record<string, unknown>[];\n }): StripeElementsApi;\n confirmPayment(opts: {\n elements: StripeElementsApi;\n confirmParams?: { return_url?: string };\n redirect?: \"if_required\";\n }): Promise<{ error?: { message?: string }; paymentIntent?: { status?: string } }>;\n}\ntype StripeFactory = (publishableKey: string) => StripeApi;\n\nlet loader: Promise<StripeFactory> | null = null;\n\n/** Load js.stripe.com once and resolve the `Stripe` global (browser only). */\nfunction loadStripe(): Promise<StripeFactory> {\n const existing = (globalThis as { Stripe?: StripeFactory }).Stripe;\n if (existing) return Promise.resolve(existing);\n if (!loader) {\n loader = new Promise<StripeFactory>((resolve, reject) => {\n const s = document.createElement(\"script\");\n s.src = \"https://js.stripe.com/v3/\";\n s.onload = () => {\n const fn = (globalThis as { Stripe?: StripeFactory }).Stripe;\n if (fn) resolve(fn);\n else reject(new Error(\"stripe.js unavailable\"));\n };\n s.onerror = () => reject(new Error(\"stripe.js failed to load\"));\n document.head.appendChild(s);\n });\n }\n return loader;\n}\n\n/** Props for {@link PaymentStep}. */\nexport interface PaymentStepProps {\n /** The application to attach the subscription to (the capability). */\n applicationId: string;\n /** Refund-policy copy the applicant must acknowledge to start payment. */\n refundPolicyText: string;\n /** Called once the payment succeeds (or is processing) — advance to booking. */\n onPaid: () => void;\n /** Stripe Elements appearance passed through without Chapter reinterpretation. */\n appearance?: Record<string, unknown>;\n /** Stripe Elements custom-font descriptors. */\n fonts?: readonly Record<string, unknown>[];\n /** Resolved payment-step copy. */\n copy?: ChapterCopy[\"join\"][\"payment\"];\n /** Render the server-returned membership price breakdown. */\n renderPriceLines?: (lines: PaymentPriceLines) => ComponentChildren;\n /** Site-owned trust, security, or explanatory content. */\n children?: ComponentChildren;\n}\n\n/** Server-authoritative membership amounts supplied to the payment price slot. */\nexport interface PaymentPriceLines {\n standardCents: number;\n discountCents: number;\n dueTodayCents: number;\n}\n\ninterface SubResponse {\n clientSecret?: string;\n publishableKey?: string | null;\n lineItems?: PaymentPriceLines;\n}\n\n/** The card-entry step: acknowledge the refund policy → create the subscription\n * → mount Stripe Elements → confirm. */\nexport function PaymentStep(props: PaymentStepProps) {\n const inheritedCopy = useChapterCopy();\n const {\n applicationId,\n refundPolicyText,\n onPaid,\n appearance,\n fonts,\n renderPriceLines,\n children,\n } = props;\n const copy = props.copy ?? inheritedCopy.join.payment;\n const [status, setStatus] = useState<\"idle\" | \"loading\" | \"ready\" | \"confirming\">(\"idle\");\n const [error, setError] = useState<string | null>(null);\n const [lineItems, setLineItems] = useState<PaymentPriceLines | null>(null);\n const mountRef = useRef<HTMLDivElement | null>(null);\n const stripeRef = useRef<StripeApi | null>(null);\n const elementsRef = useRef<StripeElementsApi | null>(null);\n\n const begin = async () => {\n setStatus(\"loading\");\n setError(null);\n try {\n const res = await fetch(\"/api/payments/subscription\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ applicationId, refundPolicyAck: true }),\n });\n const data = (await res.json()) as SubResponse;\n if (!res.ok || !data.clientSecret || !data.publishableKey) throw new Error(copy.setupFailed);\n const stripe = (await loadStripe())(data.publishableKey);\n const elements = stripe.elements({\n clientSecret: data.clientSecret,\n ...(appearance ? { appearance } : {}),\n ...(fonts ? { fonts } : {}),\n });\n const element = elements.create(\"payment\");\n if (mountRef.current) element.mount(mountRef.current);\n stripeRef.current = stripe;\n elementsRef.current = elements;\n setLineItems(data.lineItems ?? null);\n setStatus(\"ready\");\n } catch (e) {\n setStatus(\"idle\");\n setError(e instanceof Error ? e.message : copy.setupFailed);\n }\n };\n\n const pay = async () => {\n const stripe = stripeRef.current;\n const elements = elementsRef.current;\n if (!stripe || !elements) return;\n setStatus(\"confirming\");\n setError(null);\n let returnUrl: string | undefined;\n if (typeof window !== \"undefined\") {\n const next = new URL(window.location.href);\n next.searchParams.set(\"application\", applicationId);\n next.searchParams.set(\"redirect_status\", \"succeeded\");\n returnUrl = next.toString();\n }\n const result = await stripe.confirmPayment({ elements, confirmParams: { return_url: returnUrl }, redirect: \"if_required\" });\n if (result.error) {\n setError(result.error.message ?? copy.incomplete);\n setStatus(\"ready\");\n return;\n }\n const paid = result.paymentIntent?.status;\n if (paid === \"succeeded\" || paid === \"processing\") onPaid();\n else {\n setError(copy.incomplete);\n setStatus(\"ready\");\n }\n };\n\n return (\n <div className=\"join-pay\">\n {/*\n The policy is a block of its own and the checkbox carries the\n affirmative sentence, so what the member agrees to is a statement of\n agreement rather than the policy text itself. A site that wants the\n checkbox labelled only by the policy sets `copy.join.payment.consent`\n to an empty string.\n */}\n <div className=\"compliance-box\">\n <p className=\"compliance-policy\">{refundPolicyText}</p>\n <label className=\"compliance-check\">\n <input\n type=\"checkbox\"\n disabled={status !== \"idle\"}\n onChange={(e) => {\n if (e.currentTarget.checked) void begin();\n }}\n />\n {copy.consent ? <span>{copy.consent}</span> : null}\n </label>\n </div>\n {status === \"loading\" ? <p className=\"pay-status\">{copy.preparing}</p> : null}\n {lineItems && renderPriceLines ? renderPriceLines(lineItems) : null}\n {children}\n <div ref={mountRef} hidden={status === \"idle\" || status === \"loading\"} />\n {status === \"ready\" || status === \"confirming\" ? (\n <button className=\"submit-btn\" disabled={status === \"confirming\"} onClick={() => void pay()}>\n {status === \"confirming\" ? copy.processing : copy.payAndContinue}\n </button>\n ) : null}\n {error ? <p className=\"pay-error\">{error}</p> : null}\n </div>\n );\n}\n","// Turning a submitted form into the JSON body /api/applications receives.\n// Split out of join.tsx so the multi-value rule is unit-testable without\n// mounting the island.\n\n/**\n * Collect a form's fields into a JSON-serializable object.\n *\n * A name that appears once yields its single value; a name that repeats yields\n * an array. Repetition is how a checkbox group (several inputs sharing one\n * `name`) expresses a multi-select, so folding it to a single value would\n * silently discard all but the last box the member ticked.\n *\n * `File` values are dropped: the application body is JSON, and a `File` would\n * serialize to `{}` and land in the row as an empty object.\n */\nexport function collectFormFields(form: FormData): Record<string, unknown> {\n const fields: Record<string, unknown> = {};\n for (const key of new Set(form.keys())) {\n const values = form.getAll(key).filter((v): v is string => typeof v === \"string\");\n if (values.length === 0) continue;\n fields[key] = values.length > 1 ? values : values[0];\n }\n return fields;\n}\n","import type { ComponentChildren } from \"preact\";\nimport { useEffect, useState } from \"preact/hooks\";\nimport type { ChapterCopy } from \"../copy.js\";\nimport type { Slot } from \"./datetime.js\";\nimport { SlotPicker } from \"./slot-picker.js\";\n\ninterface SlotsResponse {\n schedulingReady?: boolean;\n slots?: Slot[];\n timezone?: string;\n}\n\nexport function JoinBooking(props: {\n applicationId: string;\n copy: ChapterCopy[\"join\"][\"booking\"];\n onBooked: (b: { startAt: number; timezone: string }) => void;\n}): ComponentChildren {\n const { applicationId, copy, onBooked } = props;\n const [state, setState] = useState<{ slots: Slot[]; timezone: string } | null>(null);\n const [msg, setMsg] = useState<string | null>(null);\n const [busy, setBusy] = useState(false);\n const [selected, setSelected] = useState<Slot | null>(null);\n\n const load = async () => {\n setMsg(null);\n try {\n const res = await fetch(\"/api/schedule/slots\");\n const data = (await res.json()) as SlotsResponse;\n if (data.schedulingReady === false || !data.slots?.length) {\n setState(null);\n setMsg(copy.unavailable);\n return;\n }\n setState({ slots: data.slots, timezone: data.timezone ?? \"UTC\" });\n } catch {\n setMsg(copy.loadFailed);\n }\n };\n useEffect(() => {\n void load();\n }, []);\n\n const book = async () => {\n if (!selected) return;\n setBusy(true);\n setMsg(null);\n try {\n const res = await fetch(\"/api/schedule/book\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ applicationId, startAt: selected.startAt }),\n });\n const data = (await res.json()) as { startAt?: number; error?: string; code?: string };\n if (res.status === 409 && data.code === \"calendar_slot_unavailable\") {\n setSelected(null);\n setMsg(copy.slotTaken);\n await load();\n return;\n }\n if (!res.ok) throw new Error(data.error ?? copy.failed);\n onBooked({ startAt: data.startAt ?? selected.startAt, timezone: state?.timezone ?? \"UTC\" });\n } catch (e) {\n setMsg(e instanceof Error ? e.message : copy.failed);\n } finally {\n setBusy(false);\n }\n };\n\n if (!state) return <p className=\"slots-status\">{msg ?? copy.loading}</p>;\n return (\n <div className=\"join-book\">\n <SlotPicker\n slots={state.slots}\n timezone={state.timezone}\n selectedStartAt={selected?.startAt}\n onPick={setSelected}\n onDayChange={() => setSelected(null)}\n />\n <div className=\"slot-confirm\" hidden={!selected}>\n <button className=\"submit-btn\" disabled={busy} onClick={() => void book()}>\n {busy ? copy.booking : copy.book}\n </button>\n {msg ? <p className=\"step2-note\">{msg}</p> : null}\n </div>\n </div>\n );\n}\n"],"mappings":";;;;;;AAQA,SAAS,SAAS,gBAAgB;;;ACK3B,SAAS,QAAQ,IAAoB;AAC1C,MAAI;AACF,UAAM,QAAQ,IAAI,KAAK,eAAe,QAAW,EAAE,UAAU,IAAI,cAAc,QAAQ,CAAC,EAAE;AAAA,MACxF,oBAAI,KAAK;AAAA,IACX;AACA,WAAO,MAAM,KAAK,CAAC,MAAM,EAAE,SAAS,cAAc,GAAG,SAAS;AAAA,EAChE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIO,SAAS,OAAO,IAAY,IAAoB;AACrD,SAAO,IAAI,KAAK,EAAE,EAAE,mBAAmB,SAAS,EAAE,UAAU,GAAG,CAAC;AAClE;AAGO,SAAS,SAAS,IAAY,IAAoB;AACvD,SAAO,IAAI,KAAK,EAAE,EAAE,mBAAmB,QAAW,EAAE,UAAU,IAAI,SAAS,SAAS,OAAO,SAAS,KAAK,UAAU,CAAC;AACtH;AAGO,SAAS,UAAU,IAAY,I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AAY,UAAU,CAAC,MAAM,KAAK,OAAO,CAAC,GACvD;AAAA;AAAA,MACA,QAAQ,gBAAAD,KAAC,OAAE,WAAU,cAAc,iBAAM,IAAO;AAAA,MAChD,eAAe,EAAE,YAAY,UAAU,eAAe,CAAC,KACtD,gBAAAA,KAAC,YAAO,WAAU,cAAa,MAAK,UAAS,UAAU,gBACpD,uBAAa,KAAK,KAAK,aAAa,KAAK,KAAK,QACjD;AAAA,OAEJ;AAAA,KACF;AAEJ;","names":["useState","useState","jsx","jsxs","useState","Fragment","jsx","jsxs","useState","useEffect","useState","useState","jsx","jsxs","useState","useEffect","useState","jsx","jsxs","useState","useEffect","Fragment","jsx","jsxs","useState","useEffect"]}