@odla-ai/chapter 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -156,12 +156,29 @@ These bite silently — a smoke test won't catch them:
156
156
  ready), `"none"` skips it — all need `clerk_secret_key` in the tenant vault. A
157
157
  site that wants server-side create must set `account: "create"`; inheriting the
158
158
  default silently changes the model.
159
- - **What lands on the Clerk account.** Both models write `public_metadata` as
160
- `{ applicationId, profile }`, where `profile` is every configured
159
+ - **What lands on the Clerk account (and its `public_metadata` is
160
+ client-readable).** Both models write `public_metadata` as
161
+ `{ applicationId, profile }`. By default `profile` is every configured
161
162
  `application.required`/`optional` field Clerk doesn't already carry natively
162
- (so *not* email/firstName/lastName), plus `focus`. It follows your field names —
163
- `applicantProfile(chapter, fields)` is exported if you want to assert the exact
164
- shape in a test before deleting a local override.
163
+ (so *not* email/firstName/lastName), plus `focus` **which means free-text or
164
+ third-party fields like `message` or `referral` are exposed to the browser
165
+ unless you curate.** Set `application: { profileFields: ["phone", "state",
166
+ "focus", ...] }` to an allowlist and everything else stays db-only. Array fields
167
+ (`focus`) are clamped to `maxArrayLen` (default 100) and non-primitive elements
168
+ dropped, so a client can't post an unbounded array into metadata.
169
+ `applicantProfile(chapter, fields)` is exported to assert the exact shape in a
170
+ test before deleting a local override. (Default is back-compat today; expected
171
+ to tighten at 1.0.)
172
+ - **Email + input validation.** The field literally named `email` is checked
173
+ against a permissive email shape (400 on `"notanemail"`, so it fails cleanly
174
+ here rather than at the downstream Clerk create) — set
175
+ `application: { validateEmail: false }` to opt out; `isValidEmail` is exported.
176
+ A valid application is never newly rejected.
177
+ - **CRM enrichment.** `projectApplicant` writes the base identity/contact person.
178
+ To carry more of the application into the CRM, list `application: { crmFields:
179
+ [...] }` — each must be a field on your crm person type, else that field is
180
+ dropped and the base person still projects (it is never lost). Stage mirroring,
181
+ billing snapshots and Clerk-identity linking stay yours as host routes.
165
182
  - **Disclaimer acknowledgement.** A truthy `disclaimerAck` on the submit body
166
183
  (boolean or the string a plain form posts) stamps `disclaimerAckAt` from the
167
184
  *server* clock; no ack leaves the attr absent, and a client-supplied
@@ -219,6 +236,20 @@ These bite silently — a smoke test won't catch them:
219
236
  per-person comms, people list, role changes, approve and refund are out of
220
237
  scope** — they are yours as host routes via the seam. Don't plan around them
221
238
  shipping.
239
+ - **`onboardingInvite` is a template with no built-in caller.** It is seeded into
240
+ the group's email settings (so you can edit its copy) but chapter never fires
241
+ it, because the moment it would fire — approval — is a host route (approval is
242
+ out of scope, above). Send it from your own approve handler via `sendTemplated`;
243
+ the seed existing does not mean the built-ins send it.
244
+ - **Server-side Clerk is exported, even though the admin *routes* aren't.** A role
245
+ change is your host route — but you don't hand-roll the Clerk REST calls for it.
246
+ Beside `createClerkUser`/`createClerkInvitation`/`canChangeRole`, chapter exports
247
+ the odla→Clerk write half: `clerkGetUserByEmail`, `clerkGetUser`, `clerkListUsers`
248
+ (auto-paginated — never a silent 100-user cap), and `clerkSetRole`. Two
249
+ load-bearing semantics: an absent `public_metadata.role` reads as the lowest rung
250
+ (`"provisional"`), and `clerkSetRole` merge-`PATCH`es only `{ role }` so it never
251
+ clobbers a separately-written `public_metadata.profile`. All take an injectable
252
+ `fetch` and the vault `clerk_secret_key`.
222
253
 
223
254
  ### Verify from the types, not this file
224
255
 
package/dist/index.cjs CHANGED
@@ -33,7 +33,12 @@ __export(index_exports, {
33
33
  canTransition: () => canTransition,
34
34
  canceledPatch: () => canceledPatch,
35
35
  chapterDb: () => chapterDb,
36
+ clampArray: () => clampArray,
37
+ clerkGetUser: () => clerkGetUser,
38
+ clerkGetUserByEmail: () => clerkGetUserByEmail,
36
39
  clerkInviteRequest: () => clerkInviteRequest,
40
+ clerkListUsers: () => clerkListUsers,
41
+ clerkSetRole: () => clerkSetRole,
37
42
  clerkUserRequest: () => clerkUserRequest,
38
43
  createChapterIntegration: () => createChapterIntegration,
39
44
  createClerkInvitation: () => createClerkInvitation,
@@ -51,6 +56,7 @@ __export(index_exports, {
51
56
  isAlreadySent: () => isAlreadySent,
52
57
  isReconcilable: () => isReconcilable,
53
58
  isSlotAvailable: () => isSlotAvailable,
59
+ isValidEmail: () => isValidEmail,
54
60
  joinConfig: () => joinConfig,
55
61
  meetingCreateRow: () => meetingCreateRow,
56
62
  meetingRescheduleUpdate: () => meetingRescheduleUpdate,
@@ -482,27 +488,47 @@ function resolveApplication(a) {
482
488
  throw new Error(`defineChapter.application.${name}: must be an array of field-name strings`);
483
489
  }
484
490
  }
491
+ if (a?.profileFields !== void 0 && (!Array.isArray(a.profileFields) || !a.profileFields.every((f) => typeof f === "string" && f !== ""))) {
492
+ throw new Error("defineChapter.application.profileFields: must be an array of field-name strings");
493
+ }
494
+ if (a?.crmFields !== void 0 && (!Array.isArray(a.crmFields) || !a.crmFields.every((f) => typeof f === "string" && f !== ""))) {
495
+ throw new Error("defineChapter.application.crmFields: must be an array of field-name strings");
496
+ }
485
497
  return {
486
498
  required,
487
499
  optional,
488
500
  maxLen: a?.maxLen ?? {},
489
501
  defaultMaxLen: a?.defaultMaxLen ?? 2e3,
490
502
  bodyCap: a?.bodyCap ?? 32768,
491
- requireDisclaimerAck: a?.requireDisclaimerAck ?? false
503
+ requireDisclaimerAck: a?.requireDisclaimerAck ?? false,
504
+ profileFields: a?.profileFields ?? null,
505
+ crmFields: a?.crmFields ?? [],
506
+ maxArrayLen: a?.maxArrayLen ?? 100,
507
+ validateEmail: a?.validateEmail ?? true
492
508
  };
493
509
  }
510
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
511
+ function isValidEmail(value) {
512
+ return typeof value === "string" && EMAIL_RE.test(value);
513
+ }
514
+ function clampArray(value, max) {
515
+ if (!Array.isArray(value)) return value;
516
+ return value.filter((x) => typeof x === "string" || typeof x === "number" || typeof x === "boolean").slice(0, max);
517
+ }
494
518
  function hasDisclaimerAck(fields) {
495
519
  return fields.disclaimerAck === true || fields.disclaimerAck === "true";
496
520
  }
497
521
  var IDENTITY_FIELDS = /* @__PURE__ */ new Set(["email", "firstName", "lastName"]);
498
522
  function applicantProfile(chapter, fields) {
523
+ const app = chapter.application;
524
+ const allowed = (f) => app.profileFields === null || app.profileFields.includes(f);
499
525
  const profile = {};
500
- for (const f of [...chapter.application.required, ...chapter.application.optional]) {
501
- if (IDENTITY_FIELDS.has(f)) continue;
526
+ for (const f of [...app.required, ...app.optional]) {
527
+ if (IDENTITY_FIELDS.has(f) || !allowed(f)) continue;
502
528
  const v = fields[f];
503
529
  if (typeof v === "string" && v.trim() !== "") profile[f] = v.trim();
504
530
  }
505
- if (fields.focus !== void 0) profile.focus = fields.focus;
531
+ if (fields.focus !== void 0 && allowed("focus")) profile.focus = clampArray(fields.focus, app.maxArrayLen);
506
532
  return Object.keys(profile).length > 0 ? profile : void 0;
507
533
  }
508
534
  async function submitApplication(db, chapter, fields, opts) {
@@ -516,6 +542,9 @@ async function submitApplication(db, chapter, fields, opts) {
516
542
  const cap = app.maxLen[f] ?? app.defaultMaxLen;
517
543
  if (typeof v === "string" && v.length > cap) return { ok: false, error: `${f} exceeds ${cap} characters` };
518
544
  }
545
+ if (app.validateEmail && typeof fields.email === "string" && !isValidEmail(fields.email)) {
546
+ return { ok: false, error: "email must be a valid email address" };
547
+ }
519
548
  const acked = hasDisclaimerAck(fields);
520
549
  if (app.requireDisclaimerAck && !acked) {
521
550
  return { ok: false, error: "disclaimerAck is required" };
@@ -525,7 +554,7 @@ async function submitApplication(db, chapter, fields, opts) {
525
554
  for (const f of [...app.required, ...app.optional]) {
526
555
  if (typeof fields[f] === "string") row[f] = fields[f].trim();
527
556
  }
528
- if (fields.focus !== void 0) row.focus = fields.focus;
557
+ if (fields.focus !== void 0) row.focus = clampArray(fields.focus, app.maxArrayLen);
529
558
  if (opts.groupId) row.groupId = opts.groupId;
530
559
  if (acked) row.disclaimerAckAt = opts.now;
531
560
  const { duplicate } = await db.transact(
@@ -867,7 +896,7 @@ async function projectSharedRecord(deps, person) {
867
896
  return upsertPerson(deps, { email: person.email, input: sharedPersonInput(person), mutationId: `share:${person.hubRecordId}` });
868
897
  }
869
898
  async function projectApplicant(deps, applicant) {
870
- const input = sharedPersonInput({
899
+ const base = sharedPersonInput({
871
900
  email: applicant.email,
872
901
  firstName: applicant.firstName,
873
902
  lastName: applicant.lastName,
@@ -875,7 +904,14 @@ async function projectApplicant(deps, applicant) {
875
904
  linkedin: applicant.linkedin,
876
905
  hubRecordId: applicant.applicationId
877
906
  });
878
- return upsertPerson(deps, { email: applicant.email, input, mutationId: `apply:${applicant.applicationId}` });
907
+ const mutationId = `apply:${applicant.applicationId}`;
908
+ const extra = applicant.extra ?? {};
909
+ if (Object.keys(extra).length === 0) return upsertPerson(deps, { email: applicant.email, input: base, mutationId });
910
+ try {
911
+ return await upsertPerson(deps, { email: applicant.email, input: { ...base, ...extra }, mutationId });
912
+ } catch {
913
+ return upsertPerson(deps, { email: applicant.email, input: base, mutationId });
914
+ }
879
915
  }
880
916
 
881
917
  // src/clerk.ts
@@ -940,6 +976,53 @@ async function createClerkUser(secretKey, input, fetchImpl = fetch) {
940
976
  return { ...healed, refreshed };
941
977
  }
942
978
 
979
+ // src/clerk-roles.ts
980
+ var CLERK_API = "https://api.clerk.com";
981
+ var DEFAULT_ROLE = "provisional";
982
+ var PAGE = 100;
983
+ function toRecord(u) {
984
+ if (typeof u.id !== "string") return null;
985
+ const pm = u.public_metadata ?? {};
986
+ const role = typeof pm.role === "string" && pm.role ? pm.role : DEFAULT_ROLE;
987
+ const email = u.email_addresses?.[0]?.email_address;
988
+ return { id: u.id, email: typeof email === "string" ? email : void 0, role, publicMetadata: pm };
989
+ }
990
+ async function clerkGet(path, secretKey, fetchImpl) {
991
+ const res = await fetchImpl(`${CLERK_API}${path}`, { headers: { authorization: `Bearer ${secretKey}` } });
992
+ if (!res.ok) throw new Error(`clerk GET ${path} \u2192 ${res.status}`);
993
+ return res.json();
994
+ }
995
+ async function clerkGetUserByEmail(secretKey, email, fetchImpl = fetch) {
996
+ const data = await clerkGet(`/v1/users?email_address=${encodeURIComponent(email)}&limit=1`, secretKey, fetchImpl).catch(() => null);
997
+ const user = Array.isArray(data) ? data[0] : void 0;
998
+ return user ? toRecord(user) : null;
999
+ }
1000
+ async function clerkGetUser(secretKey, id2, fetchImpl = fetch) {
1001
+ const data = await clerkGet(`/v1/users/${encodeURIComponent(id2)}`, secretKey, fetchImpl).catch(() => null);
1002
+ return data ? toRecord(data) : null;
1003
+ }
1004
+ async function clerkListUsers(secretKey, fetchImpl = fetch) {
1005
+ const out = [];
1006
+ for (let offset = 0; ; offset += PAGE) {
1007
+ const data = await clerkGet(`/v1/users?limit=${PAGE}&offset=${offset}`, secretKey, fetchImpl);
1008
+ const page = Array.isArray(data) ? data : [];
1009
+ for (const u of page) {
1010
+ const record = toRecord(u);
1011
+ if (record) out.push(record);
1012
+ }
1013
+ if (page.length < PAGE) break;
1014
+ }
1015
+ return out;
1016
+ }
1017
+ async function clerkSetRole(secretKey, id2, role, fetchImpl = fetch) {
1018
+ const res = await fetchImpl(`${CLERK_API}/v1/users/${encodeURIComponent(id2)}/metadata`, {
1019
+ method: "PATCH",
1020
+ headers: { authorization: `Bearer ${secretKey}`, "content-type": "application/json" },
1021
+ body: JSON.stringify({ public_metadata: { role } })
1022
+ });
1023
+ return res.ok;
1024
+ }
1025
+
943
1026
  // src/session.ts
944
1027
  function applicationSummary(app) {
945
1028
  return {