@proveanything/smartlinks 2.1.18 → 2.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/adminViews.d.ts +19 -0
  2. package/dist/adminViews.js +16 -0
  3. package/dist/api/ai.d.ts +15 -5
  4. package/dist/api/ai.js +15 -9
  5. package/dist/api/aiGuide.d.ts +110 -0
  6. package/dist/api/aiGuide.js +162 -0
  7. package/dist/api/appObjects.d.ts +21 -0
  8. package/dist/api/appObjects.js +33 -1
  9. package/dist/api/authKit.d.ts +37 -1
  10. package/dist/api/authKit.js +51 -0
  11. package/dist/docs/API_SUMMARY.md +510 -40
  12. package/dist/docs/admin-lists-and-pickers.md +140 -0
  13. package/dist/docs/admin-views.md +22 -0
  14. package/dist/docs/app-data-storage.md +277 -276
  15. package/dist/docs/auth-kit.md +872 -741
  16. package/dist/docs/comms.md +686 -644
  17. package/dist/docs/customer-guide.md +70 -0
  18. package/dist/docs/headless-providers.md +112 -112
  19. package/dist/docs/server-functions.md +69 -1
  20. package/dist/docs/ui-utils.md +123 -121
  21. package/dist/docs/user-groups.md +175 -168
  22. package/dist/headless.js +38 -2
  23. package/dist/http.js +4 -0
  24. package/dist/index.d.ts +2 -2
  25. package/dist/live.d.ts +88 -0
  26. package/dist/live.js +357 -0
  27. package/dist/openapi.yaml +888 -34
  28. package/dist/testing/index.d.ts +22 -0
  29. package/dist/testing/index.js +31 -0
  30. package/dist/types/appManifest.d.ts +214 -1
  31. package/dist/types/appOptions.d.ts +32 -0
  32. package/dist/types/appOptions.js +3 -0
  33. package/dist/types/authKit.d.ts +193 -4
  34. package/dist/types/comms.d.ts +41 -2
  35. package/dist/types/headless.d.ts +49 -1
  36. package/dist/types/iframeResponder.d.ts +1 -1
  37. package/dist/types/index.d.ts +1 -0
  38. package/dist/types/index.js +1 -0
  39. package/docs/API_SUMMARY.md +510 -40
  40. package/docs/admin-lists-and-pickers.md +140 -0
  41. package/docs/admin-views.md +22 -0
  42. package/docs/app-data-storage.md +277 -276
  43. package/docs/auth-kit.md +872 -741
  44. package/docs/comms.md +686 -644
  45. package/docs/customer-guide.md +70 -0
  46. package/docs/headless-providers.md +112 -112
  47. package/docs/server-functions.md +69 -1
  48. package/docs/ui-utils.md +123 -121
  49. package/docs/user-groups.md +175 -168
  50. package/openapi.yaml +888 -34
  51. package/package.json +1 -1
  52. package/scripts/doctor.mjs +454 -428
  53. package/scripts/lib/keyed-app-data.mjs +21 -0
@@ -19,6 +19,15 @@ export interface TestSlImpl {
19
19
  listTypes?(): any;
20
20
  adjust?(id: string, by: Record<string, number>, opts?: any): any;
21
21
  aggregate?(params?: any): any;
22
+ all?(recordType: string): any;
23
+ };
24
+ /** ctx.sl.userGroups.members(keys) — defaults to the `people` option. */
25
+ userGroups?: {
26
+ members?(keys?: string[]): any;
27
+ };
28
+ /** ctx.sl.appOptions.get(source, opts) — defaults to the in-memory one (records by convention, `valueLists`). */
29
+ appOptions?: {
30
+ get?(source: string, opts?: any): any;
22
31
  };
23
32
  /** ctx.sl.transaction(ops, { idempotencyKey }) — defaults to the in-memory one (all or none, replay by key). */
24
33
  transaction?(ops: any[], opts?: any): any;
@@ -111,6 +120,19 @@ export interface CreateFunctionTestContextOptions {
111
120
  knownInteractionTypes?: string[];
112
121
  /** Share one in-memory store between several contexts (e.g. concurrent callers in one test). */
113
122
  memory?: FunctionTestMemory;
123
+ /** People `ctx.sl.userGroups.members` answers from: who is in which user group (by key). */
124
+ people?: Array<{
125
+ userId: string;
126
+ name?: string | null;
127
+ email?: string | null;
128
+ userGroups: string[];
129
+ }>;
130
+ /** Value lists `ctx.sl.appOptions.get('list:<id>')` answers from, by list id (as the admin saved them). */
131
+ valueLists?: Record<string, Array<{
132
+ code: string;
133
+ label?: string;
134
+ active?: boolean;
135
+ }>>;
114
136
  }
115
137
  /** The harness's in-memory platform state (when no impl is injected). */
116
138
  export interface FunctionTestMemory {
@@ -150,6 +150,7 @@ export function createFunctionTestContext(opts) {
150
150
  return null; Object.assign(r, fields); return Object.assign({}, r); },
151
151
  delete: async (id) => { const r = mem.records.find((x) => x.id === id); if (r)
152
152
  r.deletedAt = new Date().toISOString(); return {}; },
153
+ all: async (recordType) => mem.records.filter((r) => !r.deletedAt && r.recordType === recordType).map((r) => (Object.assign({}, r))),
153
154
  // Numbers in data changed in place, with atLeast / atMost checked after the change (as the platform).
154
155
  adjust: async (id, by = {}, opts = {}) => {
155
156
  var _a, _b;
@@ -282,6 +283,36 @@ export function createFunctionTestContext(opts) {
282
283
  listTypes: gated('records', 'read', recordsFn('listTypes'), 'listTypes'),
283
284
  adjust: gated('records', 'write', recordsFn('adjust'), 'adjust'),
284
285
  aggregate: gated('records', 'read', recordsFn('aggregate'), 'aggregate'),
286
+ all: gated('records', 'read', recordsFn('all'), 'all'),
287
+ },
288
+ userGroups: {
289
+ members: gated('usergroups', 'read', impl.userGroups && impl.userGroups.members ? impl.userGroups.members.bind(impl.userGroups) : async (keys = []) => (opts.people || []).filter((p) => !keys.length || p.userGroups.some((k) => keys.includes(k)))
290
+ .map((p) => { var _a, _b; return ({ userId: p.userId, name: (_a = p.name) !== null && _a !== void 0 ? _a : null, email: (_b = p.email) !== null && _b !== void 0 ? _b : null, userGroups: keys.length ? p.userGroups.filter((k) => keys.includes(k)) : [...p.userGroups] }); }), 'members'),
291
+ },
292
+ // Pickers, in memory: a type's records by the platform's conventions (label from data.label, then
293
+ // name, then title; order from sortOrder), or a value list from `valueLists`.
294
+ appOptions: {
295
+ get: gated('records', 'read', impl.appOptions && impl.appOptions.get ? impl.appOptions.get.bind(impl.appOptions) : (impl.appRecords ? undefined : async (source) => {
296
+ const m = /^(type|list):(.+)$/.exec(String(source || ''));
297
+ if (!m)
298
+ throw Object.assign(new Error('Say what to list: type:<record type> or list:<list id>'), { code: 'BAD_SOURCE' });
299
+ let items;
300
+ if (m[1] === 'list') {
301
+ const values = (opts.valueLists || {})[m[2]];
302
+ if (!values)
303
+ throw Object.assign(new Error(`No list "${m[2]}" (pass it in valueLists)`), { code: 'NO_SUCH_LIST' });
304
+ items = values.map((v, i) => ({ id: v.code, label: v.label || v.code, active: v.active !== false, order: i }));
305
+ }
306
+ else {
307
+ items = mem.records.filter((r) => !r.deletedAt && r.recordType === m[2]).map((r) => {
308
+ var _a, _b, _c, _d, _e;
309
+ const d = r.data || {};
310
+ const order = (_a = d.sortOrder) !== null && _a !== void 0 ? _a : d.order;
311
+ return { id: r.id, label: String((_e = (_d = (_c = (_b = d.label) !== null && _b !== void 0 ? _b : d.name) !== null && _c !== void 0 ? _c : d.title) !== null && _d !== void 0 ? _d : r.ref) !== null && _e !== void 0 ? _e : r.id), active: !['inactive', 'archived'].includes(r.status || 'active'), order: typeof order === 'number' ? order : null };
312
+ }).sort((a, b) => { var _a, _b; return ((_a = a.order) !== null && _a !== void 0 ? _a : Infinity) - ((_b = b.order) !== null && _b !== void 0 ? _b : Infinity) || a.label.localeCompare(b.label); });
313
+ }
314
+ return { items, mode: 'all', version: String(items.length) };
315
+ }), 'get'),
285
316
  },
286
317
  transaction: gated('records', 'write', impl.transaction ? impl.transaction : (impl.appRecords ? undefined : async (ops, opts) => {
287
318
  if (Array.isArray(ops) && ops.some((o) => o && o.op === 'log') && !allowsSl(parsed, 'history', 'write'))
@@ -4,6 +4,7 @@ import type { AppDataDeclaration, AppHeadlessDeclaration } from './headless.js';
4
4
  import type { RealtimeChannelDeclaration } from './realtime.js';
5
5
  import type { AppManifestAdminCards } from './adminCards.js';
6
6
  import type { PaginatedResponse } from './appObjects.js';
7
+ import type { TypedMessage, MessageAbout, EmailAttachmentSpec } from './comms.js';
7
8
  import type { WorkOrdersApi, StockApi, BomsApi, MadeFromApi, OperationsApi } from './operations.js';
8
9
  import type { Booking, BookingSlot, BookingAllocation, CreateBookingInput, UpdateBookingInput, MoveBookingInput, BookingListQueryParams, CreateSlotInput, UpdateSlotInput, SlotListQueryParams, CreateBlockInput, BlockListQueryParams, FreeBusyQuery, FreeBusyResponse, MessageBookersInput, MessageBookersResult } from './bookings.js';
9
10
  /**
@@ -545,6 +546,32 @@ export interface AppHistoryQuery {
545
546
  /** Default 100, at most 1000. */
546
547
  limit?: number;
547
548
  }
549
+ /** `ctx.sl.messages.send` input. Give `contactId` or `to: 'caller'`, and `templateId` or `message`. */
550
+ export interface ServerFunctionMessage {
551
+ contactId?: string;
552
+ /** The person calling this function (their contact, made if they're signed in and have none yet). */
553
+ to?: 'caller';
554
+ templateId?: string;
555
+ message?: TypedMessage;
556
+ channel?: 'preferred' | 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet';
557
+ /** Extra Liquid variables. */
558
+ props?: Record<string, unknown>;
559
+ /** Records to hydrate into the template (`{ booking: 'B-123' }`, `{ productId }` …), as comm/send. */
560
+ include?: Record<string, unknown>;
561
+ about?: MessageAbout;
562
+ /** A label for the log (`'booking-cancelled'`). */
563
+ ref?: string;
564
+ attach?: EmailAttachmentSpec[];
565
+ }
566
+ export type ServerFunctionMessageResult = {
567
+ ok: true;
568
+ channel: 'email' | 'sms' | 'whatsapp' | 'push' | 'wallet';
569
+ messageId?: string;
570
+ attachmentsLeftOut?: string[];
571
+ } | {
572
+ ok: false;
573
+ reason: 'opted_out' | 'no_channel' | 'no_contact' | 'template_not_found';
574
+ };
548
575
  export interface ServerFunctionSl {
549
576
  /**
550
577
  * Work orders: what work is under way (`sl:workorders:read` / `:write`). Any app may read a work
@@ -586,8 +613,41 @@ export interface ServerFunctionSl {
586
613
  }): Promise<any>;
587
614
  /** Totals over THIS app's records: count, sum/avg/min/max of data numbers, grouped by data keys. */
588
615
  aggregate(params?: import('./appObjects.js').AggregateRequest): Promise<import('./appObjects.js').AggregateResponse & Record<string, unknown>>;
616
+ /**
617
+ * Every record of one type, with its data: a set-up list (every machine, with its rate). Up to 5,000
618
+ * (more → `TOO_MANY`: page with `query`). Read from cache for types the manifest declares `small`,
619
+ * cleared on every write. A record type or a declared type id. → mapped records, oldest first.
620
+ */
621
+ all(recordType: string): Promise<any[]>;
589
622
  [method: string]: any;
590
623
  };
624
+ /**
625
+ * Pickers: a small list for "pick a machine" or "pick a hold reason", served from cache and cleared on
626
+ * every write. `source` is `type:<record type or declared type id>` (the app's records of it: label,
627
+ * second line, on/off and order as the manifest's `data` block says) or `list:<list id>` (a value list
628
+ * the app declares in `data.lists`; the entry's `id` is the value's code). Pass the `version` you hold
629
+ * to get `{ unchanged: true }` back; a type of more than 2,000 entries answers `mode: 'search'` and
630
+ * wants `q`. Needs `sl:records:read`. docs/admin-lists-and-pickers.md
631
+ */
632
+ appOptions: {
633
+ get(source: string, opts?: {
634
+ q?: string;
635
+ version?: string;
636
+ }): Promise<import('./appOptions.js').AppOptionsResponse>;
637
+ };
638
+ /**
639
+ * Who is in the collection's user groups, by key (all keyed groups when `keys` is empty): staff lists,
640
+ * and addressing a team. Needs `sl:usergroups:read` and collection authority. At most 500 people,
641
+ * sorted by name; members whose account is gone are left out. docs/user-groups.md
642
+ */
643
+ userGroups: {
644
+ members(keys?: string[]): Promise<Array<{
645
+ userId: string;
646
+ name: string | null;
647
+ email: string | null;
648
+ userGroups: string[];
649
+ }>>;
650
+ };
591
651
  /**
592
652
  * Several record writes that land together or not at all (take 5 from bin A AND add 5 to order line B
593
653
  * AND log the move). Needs `sl:records:write`; THIS app's records in THIS collection only. A failing op
@@ -645,16 +705,39 @@ export interface ServerFunctionSl {
645
705
  eventId: string;
646
706
  }>;
647
707
  };
708
+ /**
709
+ * Messages (`sl:messages:write`): message one person through the platform — a template or a typed
710
+ * message, on their preferred channel (or one you name), logged with this app and what it's `about`, so
711
+ * it shows in Messages and on the contact's Activity and a reply finds its way back. Service messages
712
+ * only (confirmations, reminders, cancellations, updates); the person's opt-outs are respected. Someone
713
+ * who can't be reached is an answer — `{ ok: false, reason }` — not an error. docs/comms.md.
714
+ */
715
+ messages: {
716
+ send(input: ServerFunctionMessage): Promise<ServerFunctionMessageResult>;
717
+ };
648
718
  /**
649
719
  * Platform tools (`tools:<name>` or `tools:<family>.*`, e.g. `tools:pdf.create`, `tools:pdf.*`):
650
720
  * pdf.create, pdf.merge, pdf.fill, pdf.inspect, pdf.render, pdf.decodeBarcodes, pdf.inspectGraphics,
651
- * pdf.preflight, pdf.printReady, pdf.edit, image.transform. Runs as THIS collection whatever the caller
721
+ * pdf.preflight, pdf.printReady, pdf.edit, image.transform, image.ocr, pdf.extract. Runs as THIS collection whatever the caller
652
722
  * (authorised by the declaration, billed to the collection), rate-limited per collection. Returns the
653
723
  * tool's result; a failure throws an Error with `code` (e.g. bad_args, busy, too_many_pages).
654
724
  */
655
725
  tools: {
656
726
  run<T = any>(name: string, args?: Record<string, any>): Promise<T>;
657
727
  };
728
+ /**
729
+ * The collection's files (`sl:assets:read` / `sl:assets:write`, and collection authority): read any
730
+ * asset, save what the function makes as an asset of THIS app, and change or remove only this app's
731
+ * own. read/create/replace carry the file as base64 (up to 7 MB); bigger files go straight to storage
732
+ * with startUpload -> PUT to `sessionUrl` -> finishUpload, and are read by fetching the asset's `url`.
733
+ */
734
+ assets: ServerFunctionAssets;
735
+ /**
736
+ * Ask a model (`sl:ai:write`, any authority): a prompt, files (PDFs, photos, text), and optionally a
737
+ * JSON Schema for a structured answer in `data`. The collection's AI budget is ENFORCED: when it is
738
+ * used up the call throws `AI_BUDGET_EXCEEDED` / `AI_CREDITS_EXHAUSTED` (402) before anything is spent.
739
+ */
740
+ ai: ServerFunctionAi;
658
741
  /** Products, scoped by caller authority + declared capability. */
659
742
  products: any;
660
743
  /** Attestations, scoped by caller authority + declared capability. */
@@ -677,6 +760,136 @@ export interface ServerFunctionSl {
677
760
  data: Pick<AppDataHandle, 'get' | 'getData'>;
678
761
  };
679
762
  }
763
+ /** An asset as server code sees it. `url` is the current file; `assetUrl` the address that never changes. */
764
+ export interface ServerFunctionAsset {
765
+ id: string;
766
+ appId: string | null;
767
+ productId: string | null;
768
+ proofId: string | null;
769
+ name: string;
770
+ assetType: string;
771
+ mimeType: string | null;
772
+ size: number | null;
773
+ width: number | null;
774
+ height: number | null;
775
+ hash: string | null;
776
+ url: string;
777
+ assetUrl: string | null;
778
+ thumbnail: string | null;
779
+ labels: string[];
780
+ metadata: Record<string, any>;
781
+ /** How many earlier files replace() has kept. */
782
+ versions: number;
783
+ status: string;
784
+ createdAt: string;
785
+ updatedAt: string;
786
+ }
787
+ /** A file going into server code's calls: bytes as base64 (or plain text). */
788
+ export type ServerFunctionFileInput = {
789
+ base64: string;
790
+ contentType: string;
791
+ } | {
792
+ text: string;
793
+ contentType?: string;
794
+ };
795
+ /** `ctx.sl.assets` - the collection's files from server code. */
796
+ export interface ServerFunctionAssets {
797
+ get(assetId: string): Promise<ServerFunctionAsset | null>;
798
+ list(params?: {
799
+ productId?: string | null;
800
+ proofId?: string | null;
801
+ appId?: string | null;
802
+ labels?: string | string[];
803
+ assetType?: string;
804
+ limit?: number;
805
+ offset?: number;
806
+ }): Promise<ServerFunctionAsset[]>;
807
+ read(assetId: string, opts?: {
808
+ as?: 'base64';
809
+ }): Promise<{
810
+ id: string;
811
+ name: string;
812
+ contentType: string;
813
+ size: number;
814
+ base64: string;
815
+ }>;
816
+ read(assetId: string, opts: {
817
+ as: 'text';
818
+ }): Promise<{
819
+ id: string;
820
+ name: string;
821
+ contentType: string;
822
+ size: number;
823
+ text: string;
824
+ }>;
825
+ create(input: ServerFunctionFileInput & {
826
+ name: string;
827
+ productId?: string;
828
+ proofId?: string;
829
+ labels?: string[];
830
+ metadata?: Record<string, any>;
831
+ }): Promise<ServerFunctionAsset>;
832
+ /** A new file for one of this app's assets: same id and address, the old file kept as a version. */
833
+ replace(assetId: string, input: ServerFunctionFileInput & {
834
+ name?: string;
835
+ }): Promise<ServerFunctionAsset>;
836
+ update(assetId: string, patch: {
837
+ name?: string;
838
+ labels?: string[];
839
+ metadata?: Record<string, any>;
840
+ }): Promise<ServerFunctionAsset>;
841
+ remove(assetId: string): Promise<{
842
+ id: string;
843
+ deleted: true;
844
+ }>;
845
+ /** A large file: PUT its bytes to `sessionUrl` (declare `network:storage.googleapis.com`), then finishUpload. */
846
+ startUpload(input: {
847
+ name: string;
848
+ contentType: string;
849
+ productId?: string;
850
+ proofId?: string;
851
+ replaceAssetId?: string;
852
+ }): Promise<{
853
+ uploadId: string;
854
+ sessionUrl: string;
855
+ expiresAt: string;
856
+ }>;
857
+ finishUpload(uploadId: string, input?: {
858
+ name?: string;
859
+ metadata?: Record<string, any>;
860
+ }): Promise<ServerFunctionAsset>;
861
+ }
862
+ /** `ctx.sl.ai.generate` - what to ask. */
863
+ export interface ServerFunctionAiRequest {
864
+ prompt?: string;
865
+ system?: string;
866
+ /** Up to 10, 7 MB in all: an asset (needs sl:assets:read), bytes, or text. */
867
+ files?: Array<{
868
+ assetId: string;
869
+ } | {
870
+ base64: string;
871
+ contentType: string;
872
+ } | {
873
+ text: string;
874
+ name?: string;
875
+ }>;
876
+ /** A JSON Schema: the answer is parsed into `data`. */
877
+ schema?: Record<string, any>;
878
+ /** 'fast' (default) is quick and cheap; 'best' thinks harder and costs more. */
879
+ quality?: 'fast' | 'best';
880
+ }
881
+ /** `ctx.sl.ai` - model calls from server code, metered to the collection. */
882
+ export interface ServerFunctionAi {
883
+ generate<T = any>(request: ServerFunctionAiRequest): Promise<{
884
+ text: string;
885
+ data?: T;
886
+ model: string;
887
+ usage: {
888
+ inputTokens: number;
889
+ outputTokens: number;
890
+ };
891
+ }>;
892
+ }
680
893
  /** Identity of whoever invoked a server function. */
681
894
  export interface ServerFunctionCaller {
682
895
  /** Authenticated user id, or `null` for anonymous/public/system invocations. */
@@ -0,0 +1,32 @@
1
+ /** One entry a picker shows. */
2
+ export interface AppOption {
3
+ /** A record's id, or a value list value's code: what a record stores. */
4
+ id: string;
5
+ label: string;
6
+ /** A second line (a machine's stage), when the type declares one. */
7
+ sublabel?: string;
8
+ /** Switched off: hide it for new choices, still show its label on records that carry it. */
9
+ active: boolean;
10
+ /** Its place, when the type or list has one; entries come sorted already. */
11
+ order: number | null;
12
+ }
13
+ export type AppOptionsResponse =
14
+ /** `all`: every entry. `search`: the type is too large to send whole; these match `q`. */
15
+ {
16
+ items: AppOption[];
17
+ version: string;
18
+ mode: 'all' | 'search';
19
+ total?: number;
20
+ unchanged?: undefined;
21
+ }
22
+ /** You already hold this version. */
23
+ | {
24
+ unchanged: true;
25
+ version: string;
26
+ };
27
+ /** A value to save in a value list, in the order to show them. */
28
+ export interface AppOptionValueInput {
29
+ code: string;
30
+ label?: string;
31
+ active?: boolean;
32
+ }
@@ -0,0 +1,3 @@
1
+ // Pickers: the small, cached list behind "pick a machine" or "pick a hold reason".
2
+ // docs/admin-lists-and-pickers.md
3
+ export {};
@@ -435,20 +435,136 @@ export interface UpsertContactResponse {
435
435
  userId: string | null;
436
436
  created: boolean;
437
437
  }
438
+ /** The sign-in screens' look (read by `@proveanything/smartlinks-auth-ui`). */
438
439
  export interface AuthKitBrandingConfig {
439
- logoUrl?: string;
440
+ /** Absent = the SmartLinks logo; `''` = no logo. An https address (or a small data:image URI). */
441
+ logoUrl?: string | null;
440
442
  title?: string;
441
443
  subtitle?: string;
444
+ registerTitle?: string;
445
+ registerSubtitle?: string;
446
+ /** CSS colours, e.g. `#1D4ED8`. Shown only with `inheritHostStyles: false` (else the host page's colours win). */
442
447
  primaryColor?: string;
443
448
  secondaryColor?: string;
444
449
  backgroundColor?: string;
445
- buttonStyle?: string;
450
+ buttonStyle?: 'rounded' | 'square' | 'pill' | string;
446
451
  fontFamily?: string;
452
+ /** Light or dark screens; `auto` follows the visitor's device. Default `light`. A host `theme` prop wins. */
453
+ theme?: 'light' | 'dark' | 'auto';
454
+ /** Use the host page's colours (default true). Turn off for your own colours to show. */
455
+ inheritHostStyles?: boolean;
456
+ minimal?: boolean;
457
+ customCss?: string;
458
+ termsUrl?: string;
459
+ privacyUrl?: string;
460
+ [key: string]: unknown;
461
+ }
462
+ /** A sign-in method id, as `enabledProviders` / `providerOrder` take them. */
463
+ export type AuthKitProvider = 'email' | 'magic-link' | 'phone' | 'whatsapp' | 'google' | 'apple' | 'microsoft' | 'linkedin';
464
+ /** One account email's wording. A field left out keeps the built-in words. Plain words (no scripts). */
465
+ export interface AuthKitEmailTemplate {
466
+ subject?: string;
467
+ header?: string;
468
+ introText?: string;
469
+ buttonText?: string;
470
+ footerText?: string;
471
+ }
472
+ /** The account emails a sign-in sends, by kind. */
473
+ export type AuthKitEmailKind = 'passwordReset' | 'emailVerification' | 'magicLink' | 'memberInvite' | 'invite' | 'addedToCollection' | 'mfaCode' | 'providerLinked';
474
+ /** Wording on the sign-in screens a site may change (auth-ui reads `texts[key]`). */
475
+ export type AuthKitTextKey = 'signInTitle' | 'signInSubtitle' | 'registerTitle' | 'registerSubtitle' | 'emailLabel' | 'passwordLabel' | 'signInButton' | 'registerButton' | 'forgotPassword' | 'noAccount' | 'haveAccount' | 'continueWithEmail' | 'continueWithGoogle' | 'continueWithApple' | 'continueWithMicrosoft' | 'continueWithLinkedIn' | 'continueWithPhone' | 'continueWithWhatsApp' | 'continueWithMagicLink' | 'sendMagicLink' | 'magicLinkSent' | 'inviteOnlyNotice';
476
+ /** Second step at sign-in (TOTP authenticator app, email or text code, recovery codes). */
477
+ export interface AuthKitMfaConfig {
478
+ /** off; optional (people may add one, never asked); risk-based / always (asked at sign-in once they have one). */
479
+ mode?: 'off' | 'optional' | 'risk-based' | 'always';
480
+ /** Switch a method off with `false`. */
481
+ factorsEnabled?: {
482
+ email?: boolean;
483
+ sms?: boolean;
484
+ totp?: boolean;
485
+ recoveryCodes?: boolean;
486
+ };
487
+ minimumFactors?: number;
488
+ trustedDeviceDurationDays?: number;
489
+ enforceForAdmins?: boolean;
447
490
  }
491
+ /**
492
+ * A sign-in (AuthKit) config — the ONE shape every setting lives in. The server validates every write
493
+ * (`INVALID_CONFIG`, 400, with `problems: [{ path, message }]`) and fills defaults; GET
494
+ * {@link authKit.schema} lists every field with its default and what reads it, and
495
+ * {@link authKit.settings} shows what sign-in does now. See `docs/auth-kit.md` → "Setting up sign-in".
496
+ */
448
497
  export interface AuthKitConfig {
449
498
  id: string;
499
+ /** The name staff see. */
500
+ name?: string;
450
501
  branding?: AuthKitBrandingConfig;
451
- enabledProviders?: string[];
502
+ /** Which ways to sign in the screens offer. Absent = the host page's choice. */
503
+ enabledProviders?: AuthKitProvider[];
504
+ /** The order they appear in. */
505
+ providerOrder?: AuthKitProvider[];
506
+ /** `form` (email + password form straight away, default) or `button` ("Continue with email" first). */
507
+ emailDisplayMode?: 'form' | 'button';
508
+ /** How much the screens push creating an account. `none` = no sign-up link. Default `minimal`. */
509
+ signupProminence?: 'none' | 'minimal' | 'balanced' | 'emphasized';
510
+ signupRedirectUrl?: string;
511
+ /** Your own Google OAuth web client id (public; no secret needed). Absent = SmartLinks' Google app. */
512
+ googleClientId?: string;
513
+ googleOAuthFlow?: 'oneTap' | 'popup' | 'redirect';
514
+ /** Site domains registered on your own Google client (open Google directly, not via the SmartLinks proxy). */
515
+ whitelistedGoogleDomains?: string[];
516
+ /** Sign in with Apple: your Services ID / bundle ids. Required for `apple`. */
517
+ appleClientIds?: string[];
518
+ /** Your own LinkedIn app's client id. Its secret goes through {@link authKit.secretEntryLink}, never here. */
519
+ linkedInClientId?: string;
520
+ whatsappPrefillMessage?: string;
521
+ whatsappReply?: {
522
+ enabled?: boolean;
523
+ text?: string;
524
+ cta?: {
525
+ body?: string;
526
+ buttonLabel?: string;
527
+ buttonUrl?: string;
528
+ mediaUrl?: string;
529
+ };
530
+ };
531
+ /** Extra contact fields on the sign-up form. */
532
+ registrationFields?: Array<{
533
+ key: string;
534
+ showDuringRegistration?: boolean;
535
+ placement?: 'inline' | 'after';
536
+ required?: boolean;
537
+ }>;
538
+ collectNameOnPasswordlessSignup?: boolean;
539
+ /** Default `verify-auto-login`. */
540
+ emailVerificationMode?: 'immediate' | 'verify-auto-login' | 'verify-manual-login';
541
+ emailVerificationGracePeriod?: number;
542
+ lockUnverifiedAfterGrace?: boolean;
543
+ /** Offer "Forgot password?" and send reset emails (default true). false → the request answers `PASSWORD_RESET_DISABLED` (403). */
544
+ allowPasswordReset?: boolean;
545
+ /** Second step at sign-in. */
546
+ mfa?: AuthKitMfaConfig;
547
+ /** Where the site sends people after they sign in: your page reads it from {@link authKit.load} in `onAuthSuccess`. */
548
+ afterSignInUrl?: string;
549
+ /** Extra domains emailed links may return to (the collection's own domains are always allowed). */
550
+ allowedRedirectDomains?: string[];
551
+ /** Wording on the screens. */
552
+ texts?: Partial<Record<AuthKitTextKey, string>>;
553
+ /** Wording of the account emails, per email. Preview with {@link authKit.previewEmail}. */
554
+ emailTemplates?: Partial<Record<AuthKitEmailKind, AuthKitEmailTemplate>>;
555
+ /** The account emails' look. The sender is the collection's email settings (verified domain). */
556
+ emailBranding?: {
557
+ logoUrl?: string;
558
+ buttonColor?: string;
559
+ footerHtml?: string;
560
+ };
561
+ /** Where each secret is and a masked hint — never the value. Server-owned. */
562
+ secrets?: Record<string, {
563
+ ref: string;
564
+ hint?: string | null;
565
+ collectionId?: string;
566
+ setAt?: string;
567
+ }>;
452
568
  customCss?: string;
453
569
  termsUrl?: string;
454
570
  privacyUrl?: string;
@@ -539,7 +655,80 @@ export interface AuthKitSetIdentityResponse {
539
655
  * })
540
656
  * ```
541
657
  */
542
- export type AuthKitConfigInput = Partial<Omit<AuthKitConfig, 'id' | 'updatedAt' | 'identity'>> & Record<string, any>;
658
+ export type AuthKitConfigInput = Partial<Omit<AuthKitConfig, 'id' | 'updatedAt' | 'identity' | 'secrets'>> & Record<string, any>;
659
+ /** {@link authKit.schema}: every setting, its default, what reads it, in plain words. */
660
+ export interface AuthKitSchema {
661
+ providers: AuthKitProvider[];
662
+ emailKinds: AuthKitEmailKind[];
663
+ emailFields: Array<keyof AuthKitEmailTemplate>;
664
+ textKeys: AuthKitTextKey[];
665
+ /** Secret names (set through {@link authKit.secretEntryLink}). */
666
+ secrets: string[];
667
+ /** Fields never written through create/update. */
668
+ serverOwned: string[];
669
+ /** where: `screens` (the sign-in UI reads it), `server` (the API enforces it), `both`, `host` (your page reads it from {@link authKit.load}). */
670
+ fields: Array<{
671
+ path: string;
672
+ group: string;
673
+ where: 'screens' | 'server' | 'both' | 'host';
674
+ default: unknown;
675
+ description: string;
676
+ }>;
677
+ }
678
+ /** One thing worth knowing about a sign-in's settings (from {@link authKit.settings}). */
679
+ export interface AuthKitCheck {
680
+ /** `problem`: on but will fail; `warning`: works, probably not meant; `info`: worth knowing. */
681
+ level: 'problem' | 'warning' | 'info';
682
+ code: string;
683
+ message: string;
684
+ /** The setting to change. */
685
+ setting?: string;
686
+ }
687
+ /** {@link authKit.settings}: what sign-in does now. */
688
+ export interface AuthKitSettingsResponse {
689
+ authKitId: string;
690
+ ownLogins: 'own' | 'shared';
691
+ /** As stored (no secret values). */
692
+ config: AuthKitConfig;
693
+ /** Every default filled in. */
694
+ effective: Required<Pick<AuthKitConfig, 'enabledProviders' | 'providerOrder' | 'signUp' | 'allowPasswordReset' | 'emailVerificationMode'>> & AuthKitConfig;
695
+ secrets: Record<string, {
696
+ set: boolean;
697
+ hint?: string | null;
698
+ setAt?: string | null;
699
+ legacy?: boolean;
700
+ }>;
701
+ checks: AuthKitCheck[];
702
+ }
703
+ /** Body of {@link authKit.setup}. */
704
+ export interface AuthKitSetupRequest {
705
+ /** For a new sign-in. */
706
+ name?: string;
707
+ /** Give it its own logins (members of this site only). ONE WAY. Needed for `signUp: 'invite'`. */
708
+ ownLogins?: boolean;
709
+ /** A first settings patch, checked like {@link authKit.update}. No secrets. */
710
+ settings?: AuthKitConfigInput;
711
+ }
712
+ /** Result of {@link authKit.setup}. */
713
+ export interface AuthKitSetupResponse {
714
+ authKit: AuthKitConfig;
715
+ created: boolean;
716
+ ownLogins: 'own' | 'shared';
717
+ /** What this call changed, in plain words (empty when nothing). */
718
+ changed: string[];
719
+ }
720
+ /** Result of {@link authKit.previewEmail}. */
721
+ export interface AuthKitEmailPreview {
722
+ kind: AuthKitEmailKind;
723
+ subject: string;
724
+ html: string;
725
+ }
726
+ /** Result of {@link authKit.secretEntryLink}. */
727
+ export interface AuthKitSecretLink {
728
+ /** A SmartLinks page where the person types the secret. Works once. */
729
+ url: string;
730
+ expiresAt: string;
731
+ }
543
732
  /**
544
733
  * Per-collection account-security policy. The API **enforces** all of this; the
545
734
  * client uses `passwordPolicy` (live checklist) and `session` (idle sign-out) for UX.
@@ -324,8 +324,13 @@ export interface SubscriptionsResolveResponse {
324
324
  export interface TransactionalSendRequest {
325
325
  /** CRM contact UUID */
326
326
  contactId: string;
327
- /** Firestore template ID */
328
- templateId: string;
327
+ /** A saved template's id. Give this or `message`. */
328
+ templateId?: string;
329
+ /**
330
+ * A typed message instead of a template: plain text, Liquid allowed (`{{ contact.firstName }}`).
331
+ * `sms` is the shorter text for SMS and WhatsApp (defaults to `body`).
332
+ */
333
+ message?: TypedMessage;
329
334
  /**
330
335
  * Channel to send on. Defaults to 'preferred', which auto-selects the
331
336
  * contact's best available channel respecting consent, suppression, and
@@ -355,6 +360,17 @@ export interface TransactionalSendRequest {
355
360
  ref?: string;
356
361
  /** App context stored on the comms-events row */
357
362
  appId?: string;
363
+ /**
364
+ * What the message is about: the record it was sent for and the admin screen that shows it, so it is a
365
+ * link in Messages, on the contact's Activity, and on the conversation a reply opens. `appId` defaults
366
+ * to the sending app.
367
+ */
368
+ about?: MessageAbout;
369
+ /**
370
+ * `'service'` (a confirmation, a reminder, an update): an asked-for channel the person turned off, or a
371
+ * suppressed email, is refused (`transactional.opted_out`). Marketing goes out as a campaign.
372
+ */
373
+ category?: 'service';
358
374
  /**
359
375
  * Files to attach (email only; at most 5, 10 MB in all). What can't be made is left out and listed in
360
376
  * `attachmentsLeftOut` — the email still goes.
@@ -391,6 +407,27 @@ export interface TransactionalSendResponse {
391
407
  /** Attachments that couldn't be made, and why (the email went without them) */
392
408
  attachmentsLeftOut?: string[];
393
409
  }
410
+ /** A message written there and then rather than a saved template. */
411
+ export interface TypedMessage {
412
+ subject?: string;
413
+ body: string;
414
+ /** The shorter text for SMS and WhatsApp (defaults to `body`). */
415
+ sms?: string;
416
+ }
417
+ /**
418
+ * What a message is about (docs/comms.md, "What a message is about"). Ids only, never content.
419
+ * `view` and `params` name one of the app's admin views (manifest `adminViews`, docs/admin-views.md).
420
+ */
421
+ export interface MessageAbout {
422
+ appId?: string;
423
+ /** What kind of record: `'booking'`, `'entry'`, `'case'`. */
424
+ type: string;
425
+ id: string;
426
+ view?: string;
427
+ params?: Record<string, string>;
428
+ /** A short label to show without looking the record up: `'Sat 3pm, table for 4'`. */
429
+ label?: string;
430
+ }
394
431
  export interface TransactionalSendError {
395
432
  ok: false;
396
433
  /**
@@ -403,6 +440,8 @@ export interface TransactionalSendError {
403
440
  * - `transactional.whatsapp_missing`
404
441
  * - `transactional.no_push_methods`
405
442
  * - `transactional.no_wallet_methods`
443
+ * - `transactional.opted_out` (category `'service'`: the person turned that channel off, or the email is suppressed)
444
+ * - `transactional.template_or_message` / `transactional.message_invalid` / `transactional.about_invalid`
406
445
  */
407
446
  error: string;
408
447
  }