@antiphony/shared 0.1.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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -0
  3. package/dist/cjs/api-codecs.cjs +971 -0
  4. package/dist/cjs/api-codecs.d.cts +542 -0
  5. package/dist/cjs/errors/index.cjs +56 -0
  6. package/dist/cjs/errors/index.d.cts +45 -0
  7. package/dist/cjs/index.cjs +1276 -0
  8. package/dist/cjs/index.d.cts +11 -0
  9. package/dist/cjs/nsid.cjs +37 -0
  10. package/dist/cjs/nsid.d.cts +42 -0
  11. package/dist/cjs/observability/index.cjs +58 -0
  12. package/dist/cjs/observability/index.d.cts +1 -0
  13. package/dist/cjs/observability/report-error.cjs +58 -0
  14. package/dist/cjs/observability/report-error.d.cts +48 -0
  15. package/dist/cjs/types/api.cjs +726 -0
  16. package/dist/cjs/types/api.d.cts +494 -0
  17. package/dist/cjs/types/audio.cjs +835 -0
  18. package/dist/cjs/types/audio.d.cts +1149 -0
  19. package/dist/cjs/types/blob.cjs +23 -0
  20. package/dist/cjs/types/blob.d.cts +45 -0
  21. package/dist/cjs/types/channels.cjs +170 -0
  22. package/dist/cjs/types/channels.d.cts +262 -0
  23. package/dist/cjs/types/records.cjs +407 -0
  24. package/dist/cjs/types/records.d.cts +840 -0
  25. package/dist/cjs/types/storage.cjs +414 -0
  26. package/dist/cjs/types/storage.d.cts +197 -0
  27. package/dist/cjs/types/views.cjs +820 -0
  28. package/dist/cjs/types/views.d.cts +9806 -0
  29. package/dist/cjs/utils/index.cjs +8 -0
  30. package/dist/cjs/utils/index.d.cts +7 -0
  31. package/dist/esm/api-codecs.d.ts +542 -0
  32. package/dist/esm/api-codecs.js +6 -0
  33. package/dist/esm/chunk-24KIXQZK.js +6 -0
  34. package/dist/esm/chunk-3WZJXJNU.js +378 -0
  35. package/dist/esm/chunk-5EHV73BA.js +20 -0
  36. package/dist/esm/chunk-72G3LBUQ.js +1 -0
  37. package/dist/esm/chunk-7LW2FHLD.js +48 -0
  38. package/dist/esm/chunk-7V44CPRR.js +132 -0
  39. package/dist/esm/chunk-BUNMR4ZO.js +127 -0
  40. package/dist/esm/chunk-EA4OONDV.js +380 -0
  41. package/dist/esm/chunk-F2CANZZ7.js +40 -0
  42. package/dist/esm/chunk-ORMEWXMH.js +33 -0
  43. package/dist/esm/chunk-TIZRJORN.js +24 -0
  44. package/dist/esm/chunk-XDBKR6LW.js +32 -0
  45. package/dist/esm/errors/index.d.ts +45 -0
  46. package/dist/esm/errors/index.js +2 -0
  47. package/dist/esm/index.d.ts +11 -0
  48. package/dist/esm/index.js +12 -0
  49. package/dist/esm/nsid.d.ts +42 -0
  50. package/dist/esm/nsid.js +2 -0
  51. package/dist/esm/observability/index.d.ts +1 -0
  52. package/dist/esm/observability/index.js +3 -0
  53. package/dist/esm/observability/report-error.d.ts +48 -0
  54. package/dist/esm/observability/report-error.js +2 -0
  55. package/dist/esm/types/api.d.ts +494 -0
  56. package/dist/esm/types/api.js +5 -0
  57. package/dist/esm/types/audio.d.ts +1149 -0
  58. package/dist/esm/types/audio.js +5 -0
  59. package/dist/esm/types/blob.d.ts +45 -0
  60. package/dist/esm/types/blob.js +2 -0
  61. package/dist/esm/types/channels.d.ts +262 -0
  62. package/dist/esm/types/channels.js +162 -0
  63. package/dist/esm/types/records.d.ts +840 -0
  64. package/dist/esm/types/records.js +3 -0
  65. package/dist/esm/types/storage.d.ts +197 -0
  66. package/dist/esm/types/storage.js +26 -0
  67. package/dist/esm/types/views.d.ts +9806 -0
  68. package/dist/esm/types/views.js +4 -0
  69. package/dist/esm/utils/index.d.ts +7 -0
  70. package/dist/esm/utils/index.js +2 -0
  71. package/package.json +82 -0
@@ -0,0 +1,971 @@
1
+ 'use strict';
2
+
3
+ var zod = require('zod');
4
+
5
+ // api-codecs.ts
6
+ var BlobRefSchema = zod.z.object({
7
+ /** Discriminator for AT Protocol type system */
8
+ $type: zod.z.literal("blob"),
9
+ /** Content Identifier (CID) or URL pointing to the blob */
10
+ ref: zod.z.string(),
11
+ /** MIME type of the blob (e.g., 'audio/webm') */
12
+ mimeType: zod.z.string(),
13
+ /** Size of the blob in bytes */
14
+ size: zod.z.number()
15
+ });
16
+
17
+ // types/records.ts
18
+ function httpsUrl() {
19
+ return zod.z.string().trim().url().refine((u) => /^https?:\/\//i.test(u), {
20
+ message: "URL must use the http or https scheme"
21
+ });
22
+ }
23
+ var FirestoreTimestampSchema = zod.z.union([
24
+ zod.z.custom((data) => {
25
+ return data && typeof data === "object" && (typeof data.toDate === "function" || "seconds" in data && "nanoseconds" in data);
26
+ }),
27
+ zod.z.string(),
28
+ zod.z.number(),
29
+ zod.z.date()
30
+ ]).transform((data, ctx) => {
31
+ let date;
32
+ if (data instanceof Date) {
33
+ date = data;
34
+ } else if (typeof data === "string") {
35
+ date = new Date(data);
36
+ } else if (typeof data === "number") {
37
+ date = new Date(data);
38
+ } else if (typeof data.toDate === "function") {
39
+ date = data.toDate();
40
+ } else {
41
+ const timestamp = data;
42
+ date = new Date(timestamp.seconds * 1e3 + timestamp.nanoseconds / 1e6);
43
+ }
44
+ if (Number.isNaN(date.getTime())) {
45
+ ctx.addIssue({
46
+ code: zod.z.ZodIssueCode.custom,
47
+ message: "FirestoreTimestamp coerced to Invalid Date"
48
+ });
49
+ return zod.z.NEVER;
50
+ }
51
+ return date;
52
+ });
53
+ zod.z.object({
54
+ /** Unique Firebase UID */
55
+ id: zod.z.string(),
56
+ /** Public handle (e.g. @brad). Optional for Lite Users. */
57
+ handle: zod.z.string().min(3).max(20).regex(/^[a-zA-Z0-9_]+$/).nullable().optional(),
58
+ /** User stated intent (e.g. "Podcaster", "Listener") */
59
+ usageIntent: zod.z.string().nullable().optional(),
60
+ /**
61
+ * Domain for federated handle support.
62
+ * Defaults to 'voxpop.com'.
63
+ */
64
+ domain: zod.z.string().default("voxpop.com"),
65
+ /**
66
+ * Display Name (e.g. "Brad Thorson"). Nullable: Firestore stores `null`
67
+ * when the user clears this field via the settings form, and the schema
68
+ * must match storage reality or `UserRecordSchema.parse` (in
69
+ * `getUserRecordByUid`) will throw.
70
+ */
71
+ displayName: zod.z.string().max(50).nullable().optional(),
72
+ /** Short bio/description — nullable for the same reason as displayName. */
73
+ bio: zod.z.string().max(160).nullable().optional(),
74
+ /** URL to avatar image — nullable for the same reason as displayName. */
75
+ avatarUrl: zod.z.string().url().nullable().optional(),
76
+ /** Optional personal website surfaced on the public profile. */
77
+ website: httpsUrl().nullable().optional(),
78
+ /** Up to 5 additional public links (label + URL) shown under the bio. */
79
+ links: zod.z.array(zod.z.object({
80
+ label: zod.z.string().min(1).max(40),
81
+ url: httpsUrl()
82
+ })).max(5).optional(),
83
+ /** When true and a Bluesky identity is linked, surfaces it on the public profile. */
84
+ showBlueskyPublicly: zod.z.boolean().optional(),
85
+ /** Server timestamp of creation */
86
+ createdAt: FirestoreTimestampSchema,
87
+ /** Individual account tier — free or creator_pro */
88
+ tier: zod.z.enum(["free", "creator_pro"]).default("free"),
89
+ /** Account status. Deactivated accounts retain data but are excluded from lookups. */
90
+ status: zod.z.enum(["active", "deactivated"]).default("active"),
91
+ /** Timestamp when the account was deactivated (soft deleted) */
92
+ deactivatedAt: FirestoreTimestampSchema.optional(),
93
+ /**
94
+ * Denormalized org memberships — { orgId: role } for fast lookup.
95
+ * Source of truth is organizations/{orgId}/members/{userId}.
96
+ * Kept in sync by Cloud Function trigger.
97
+ */
98
+ orgMemberships: zod.z.record(zod.z.string(), zod.z.enum(["owner", "admin", "member"])).optional()
99
+ });
100
+ var PromptRecordSchema = zod.z.object({
101
+ /** Unique Prompt ID */
102
+ id: zod.z.string(),
103
+ /** ID of the User who created this prompt. Always a user ID, never an org ID. @see UserRecord */
104
+ authorId: zod.z.string(),
105
+ /** Organization context this prompt belongs to (null = personal/no org) */
106
+ orgId: zod.z.string().nullable().optional(),
107
+ /** The main text of the question/prompt */
108
+ title: zod.z.string().min(3),
109
+ /** Optional extra context */
110
+ description: zod.z.string().nullable().optional(),
111
+ /** User who created this prompt (differs from authorId when org-owned) */
112
+ createdBy: zod.z.string().optional(),
113
+ /** URL to the recorded audio file (GCS) */
114
+ audioUrl: zod.z.string().url().or(zod.z.literal("")),
115
+ /** AT Protocol blob reference (future replacement for audioUrl) */
116
+ audio: BlobRefSchema.optional(),
117
+ /**
118
+ * AT Protocol URI returned by the publisher after a successful
119
+ * `repo.putRecord` against the author's PDS — e.g.
120
+ * `at://did:plc:abc123/com.voxpop.audio.prompt/3kj4...`. Optional,
121
+ * no migration: existing rows leave it unset. Format-validated so
122
+ * malformed strings surface at the schema-parse boundary rather than
123
+ * being silently stored.
124
+ */
125
+ atprotoUri: zod.z.string().regex(/^at:\/\/.+/).optional(),
126
+ /** Server timestamp of creation */
127
+ createdAt: FirestoreTimestampSchema,
128
+ /**
129
+ * Life-cycle status.
130
+ * - `live`: Visible and accepting replies.
131
+ * - `archived`: Visible but closed for new replies.
132
+ * - `deleted`: Soft deleted.
133
+ */
134
+ status: zod.z.enum(["live", "archived", "deleted"]).default("live"),
135
+ /** AI Enrichment Fields */
136
+ aiStatus: zod.z.enum(["pending", "complete", "error"]).optional(),
137
+ aiError: zod.z.string().optional(),
138
+ aiSummary: zod.z.string().optional(),
139
+ aiLabels: zod.z.array(zod.z.string()).optional(),
140
+ transcription: zod.z.string().optional(),
141
+ /** Pre-computed waveform peaks (normalized 0–1) for instant audio visualization */
142
+ waveformPeaks: zod.z.array(zod.z.number()).optional(),
143
+ /** Social Share Video Fields */
144
+ socialVideoUrl: zod.z.string().url().optional(),
145
+ socialVideoStoragePath: zod.z.string().optional(),
146
+ socialVideoStatus: zod.z.enum(["pending", "complete", "error"]).optional(),
147
+ socialVideoError: zod.z.string().optional(),
148
+ /** The audio URL/path used to generate the current video (for cache invalidation) */
149
+ socialVideoSourceAudio: zod.z.string().optional()
150
+ });
151
+ var ReplyRecordSchema = zod.z.object({
152
+ /** Unique Reply ID */
153
+ id: zod.z.string(),
154
+ /** The Prompt being replied to. @see PromptRecord */
155
+ promptId: zod.z.string(),
156
+ /** The User who replied. @see UserRecord */
157
+ authorId: zod.z.string(),
158
+ /** URL to the recorded audio file (GCS) */
159
+ audioUrl: zod.z.string().url(),
160
+ /** AT Protocol blob reference (future replacement for audioUrl) */
161
+ audio: BlobRefSchema.optional(),
162
+ /** Server timestamp of creation */
163
+ createdAt: FirestoreTimestampSchema,
164
+ /**
165
+ * Life-cycle status.
166
+ * - `live`: Visible and accepting replies.
167
+ * - `archived`: Visible but closed for new replies.
168
+ * - `deleted`: Soft deleted.
169
+ */
170
+ status: zod.z.enum(["live", "archived", "deleted"]).default("live"),
171
+ /**
172
+ * Pre-computed waveform peaks (normalized 0–1) for instant audio
173
+ * visualization. **Stays on canonical** (does NOT move to the
174
+ * enrichment doc) — produced by a plain ffmpeg pass at ingestion,
175
+ * not an AI step; a self-hoster without paid-tier AI still needs
176
+ * this on every reply for the audio player. See
177
+ * `specs/ai-enrichment-split.md` § 5.
178
+ */
179
+ waveformPeaks: zod.z.array(zod.z.number()).optional(),
180
+ /**
181
+ * Duration of the audio in seconds, computed server-side from
182
+ * ffmpeg. **Stays on canonical** (same reasoning as `waveformPeaks`
183
+ * above — ingestion ffmpeg output, not an AI enrichment). See
184
+ * `specs/ai-enrichment-split.md` § 5.
185
+ */
186
+ audioDurationSec: zod.z.number().optional()
187
+ });
188
+ zod.z.object({
189
+ id: zod.z.string(),
190
+ /** Private notes by the prompt author about this reply. */
191
+ notes: zod.z.string().optional(),
192
+ // === AI-enrichment fields (sole source of truth post Stage 4) ===
193
+ //
194
+ // These lifted off canonical in Stage 4 of `specs/ai-enrichment-split.md`.
195
+ // Writers (`functions/`) route AI updates here via the split-write
196
+ // helper in `functions/src/services/replyEnrichmentDualWrite.ts`;
197
+ // readers source them via the hydrator's enrichment branch (see
198
+ // `packages/core/services/hydration.ts`).
199
+ // --- AI core (Gemini-generated) ---
200
+ aiStatus: zod.z.enum(["pending", "complete", "error", "skipped_too_short"]).optional(),
201
+ aiError: zod.z.string().optional(),
202
+ aiSummary: zod.z.string().optional(),
203
+ aiLabels: zod.z.array(zod.z.string()).optional(),
204
+ transcription: zod.z.string().optional(),
205
+ sentiment: zod.z.enum(["Positive", "Negative", "Neutral"]).optional(),
206
+ /** Must match the widened enum in `ReplyRecordSchema.energyLevel`. */
207
+ energyLevel: zod.z.enum(["High", "Low", "Neutral"]).optional(),
208
+ engagementScore: zod.z.number().min(1).max(10).optional(),
209
+ // --- Voice isolation (ElevenLabs, paid tier) ---
210
+ /** Noise-reduced audio URL — replaces `audioUrl` for downstream players when present. PUBLIC. */
211
+ enhancedAudioUrl: zod.z.string().url().optional(),
212
+ /** Storage path companion to `enhancedAudioUrl` — private. */
213
+ enhancedStoragePath: zod.z.string().optional(),
214
+ // --- Social-share video (paid tier) ---
215
+ //
216
+ // All `socialVideo*` fields are creator-only. The URL points at the
217
+ // generated artifact (a video file the creator can download and post
218
+ // to social media); the reply detail page does NOT render it.
219
+ socialVideoUrl: zod.z.string().url().optional(),
220
+ socialVideoStoragePath: zod.z.string().optional(),
221
+ socialVideoStatus: zod.z.enum(["pending", "complete", "error"]).optional(),
222
+ socialVideoError: zod.z.string().optional(),
223
+ /** The audio URL/path used to generate the current video (for cache invalidation). */
224
+ socialVideoSourceAudio: zod.z.string().optional()
225
+ });
226
+ zod.z.object({
227
+ /** Composite key `${viewerUid}_${targetUid}`. */
228
+ id: zod.z.string(),
229
+ /** Per-viewer CRM notes about the target. */
230
+ notes: zod.z.string().optional(),
231
+ /** Per-viewer freeform tags about the target. */
232
+ tags: zod.z.array(zod.z.string()).optional(),
233
+ // === Identity-merge: alias set ===
234
+ //
235
+ // Other identifiers the viewer has declared to be the SAME person as
236
+ // this entry's `targetUid`. vCard/URI-aligned: each entry is a
237
+ // scheme-prefixed identifier, so one field generalizes across networks
238
+ // AND across the future contact-sync import (which carries phone/email):
239
+ // "uid:<firebaseUid>" | "did:plc:…" | "handle:bob.bsky.social"
240
+ // | "tel:+15551234567" | "mailto:x@example.com"
241
+ // Mirrors vCard 4.0's `UID` + `CLIENTPIDMAP`/`PID` source-tracking
242
+ // (RFC 6350) — the standard answer to "the same person from multiple
243
+ // sources". See `specs/people-lexicon-prior-art.md`. The People
244
+ // read-path collapses any replier whose "uid:<uid>" appears here into
245
+ // this primary entry. Empty until the merge feature is used.
246
+ aliases: zod.z.array(zod.z.string()).optional(),
247
+ lastUpdated: FirestoreTimestampSchema.optional()
248
+ });
249
+ zod.z.object({
250
+ sipUri: zod.z.string(),
251
+ sipUsername: zod.z.string(),
252
+ sipSecret: zod.z.string(),
253
+ provider: zod.z.enum(["twilio", "plivo", "internal"])
254
+ });
255
+ zod.z.object({
256
+ /** User's personal phone number (E.164) */
257
+ phoneNumber: zod.z.string(),
258
+ /** Line type from Twilio Lookup v2 */
259
+ lineType: zod.z.string().nullable(),
260
+ /** Carrier name from Twilio Lookup v2 */
261
+ carrier: zod.z.string().nullable(),
262
+ /** free = shared Twilio number (ForwardedFrom routing), paid = dedicated number */
263
+ tier: zod.z.enum(["free", "paid"]),
264
+ /** The VoxPop Twilio number calls forward to (E.164) */
265
+ voxpopNumber: zod.z.string(),
266
+ /** Twilio Phone Number SID (paid tier only) */
267
+ twilioNumberSid: zod.z.string().nullable().optional(),
268
+ /** Forwarding verification state */
269
+ verificationStatus: zod.z.enum(["pending", "verifying", "verified", "failed"]).default("pending"),
270
+ /** Last verification attempt timestamp */
271
+ lastVerificationAt: FirestoreTimestampSchema.optional(),
272
+ /** Number of verification attempts */
273
+ verificationAttempts: zod.z.number().default(0),
274
+ /** Reason for verification failure */
275
+ failureReason: zod.z.string().nullable().optional(),
276
+ /** Whether call forwarding is active */
277
+ enabled: zod.z.boolean().default(false),
278
+ createdAt: FirestoreTimestampSchema,
279
+ updatedAt: FirestoreTimestampSchema
280
+ });
281
+ var ConnectorTypeSchema = zod.z.enum(["telephony"]);
282
+ var ConnectorStatusSchema = zod.z.object({
283
+ /** Coarse, generic lifecycle the control-plane UI can render without
284
+ * connector-specific knowledge. */
285
+ state: zod.z.enum(["unconfigured", "pending", "active", "error", "disabled"]).default("unconfigured"),
286
+ detail: zod.z.string().nullable().optional(),
287
+ /** Opaque, connector-specific status detail (e.g. telephony's
288
+ * `{ verificationStatus, verificationAttempts, failureReason }`). Connector-
289
+ * owned like the rest of `status` — never user-writable. Nullable so a doc
290
+ * that stored `data: null` round-trips without a parse error. */
291
+ data: zod.z.record(zod.z.unknown()).nullable().optional(),
292
+ updatedAt: FirestoreTimestampSchema.optional()
293
+ });
294
+ var ConnectorConfigRecordSchema = zod.z.object({
295
+ connectorType: ConnectorTypeSchema,
296
+ /** The owning user. Org-scoping (ownerId as an orgId) is a later step. */
297
+ ownerId: zod.z.string(),
298
+ /** Opaque, connector-specific blob. Core does not interpret this. */
299
+ settings: zod.z.record(zod.z.unknown()).default({}),
300
+ /** Reference into a secret store (e.g. Secret Manager key). Never a raw secret. */
301
+ secretRef: zod.z.string().nullable().optional(),
302
+ enabled: zod.z.boolean().default(false),
303
+ status: ConnectorStatusSchema.default({ state: "unconfigured" }),
304
+ createdAt: FirestoreTimestampSchema,
305
+ updatedAt: FirestoreTimestampSchema
306
+ });
307
+ zod.z.object({
308
+ id: zod.z.string(),
309
+ ownerId: zod.z.string(),
310
+ /** The caller number this rule matches (E.164). Format-enforced at the
311
+ * record level so any writer (API, future contact-sync/callback) can't
312
+ * persist a malformed number. */
313
+ e164: zod.z.string().regex(/^\+[1-9]\d{6,14}$/, "Must be an E.164 phone number"),
314
+ /** Display label, e.g. "Mom" / "Delta Airlines". null = unlabeled. */
315
+ label: zod.z.string().nullable().optional(),
316
+ /** `allow` = ring through; `screen` = async voicemail. */
317
+ action: zod.z.enum(["allow", "screen"]),
318
+ /** Provenance. `manual` = user-created; the others are future writers. */
319
+ source: zod.z.enum(["manual", "contact-sync", "callback"]),
320
+ /** null = permanent; a date = self-expiring exception. */
321
+ expiresAt: FirestoreTimestampSchema.nullable().optional(),
322
+ createdAt: FirestoreTimestampSchema
323
+ });
324
+ var OrganizationRecordSchema = zod.z.object({
325
+ id: zod.z.string(),
326
+ /** Display name of the organization */
327
+ name: zod.z.string().min(3).max(50),
328
+ /**
329
+ * Unique handle for the organization (e.g. voxpop.com/@mypodcast).
330
+ * Used for public URLs.
331
+ */
332
+ slug: zod.z.string().min(3).max(30).regex(/^[a-z0-9-]+$/),
333
+ /** URL to avatar/logo */
334
+ avatarUrl: zod.z.string().url().optional(),
335
+ /** URL to the podcast RSS feed */
336
+ rssFeedUrl: zod.z.string().url().optional(),
337
+ /** External website URL */
338
+ websiteUrl: httpsUrl().optional(),
339
+ /** Description or tagline */
340
+ description: zod.z.string().optional(),
341
+ /** Owner ID (User ID) */
342
+ ownerId: zod.z.string(),
343
+ /** Server timestamp of creation */
344
+ createdAt: FirestoreTimestampSchema,
345
+ /** Verified domain (e.g., "acme.com") — enables auto-join, enterprise features */
346
+ domain: zod.z.string().nullable().optional(),
347
+ /** Whether the domain has been verified via DNS TXT record */
348
+ domainVerified: zod.z.boolean().default(false),
349
+ /** DNS verification token (stored server-side until verification completes) */
350
+ domainVerificationToken: zod.z.string().optional(),
351
+ /** Billing email — required for paid orgs, where invoices go */
352
+ billingEmail: zod.z.string().email().nullable().optional(),
353
+ /**
354
+ * Tier determines isolation and feature set. Orgs are meant to be paid
355
+ * (business or enterprise); free/pro exist on the enum for the individual track.
356
+ * Default is provisionally `business` (the entry paid tier) — it's assigned at
357
+ * creation with no subscription behind it yet, so it stays provisional until billing
358
+ * promotes/reconciles the org. See docs/tech-debt.md "Org tier billing reconciliation".
359
+ */
360
+ tier: zod.z.enum(["free", "pro", "business", "enterprise"]).default("business"),
361
+ /** Stripe Customer ID */
362
+ stripeCustomerId: zod.z.string().optional(),
363
+ /** Subscription Status */
364
+ subscriptionStatus: zod.z.enum(["active", "trialing", "past_due", "canceled", "unpaid"]).optional()
365
+ });
366
+ var OrganizationMemberRecordSchema = zod.z.object({
367
+ orgId: zod.z.string(),
368
+ userId: zod.z.string(),
369
+ /** Role in the organization */
370
+ role: zod.z.enum(["owner", "admin", "member"]),
371
+ /** Server timestamp of joining */
372
+ joinedAt: FirestoreTimestampSchema,
373
+ invitedBy: zod.z.string().optional()
374
+ });
375
+ var OrgInviteRecordSchema = zod.z.object({
376
+ id: zod.z.string(),
377
+ orgId: zod.z.string(),
378
+ /** Email the invite was sent to */
379
+ email: zod.z.string().email(),
380
+ /** Role to assign on acceptance */
381
+ role: zod.z.enum(["admin", "member"]),
382
+ /** User ID of who sent the invite */
383
+ invitedBy: zod.z.string(),
384
+ /** Invite lifecycle status */
385
+ status: zod.z.enum(["pending", "accepted", "expired", "revoked"]).default("pending"),
386
+ /** Server timestamp of creation */
387
+ createdAt: FirestoreTimestampSchema,
388
+ /** When this invite expires */
389
+ expiresAt: FirestoreTimestampSchema
390
+ });
391
+ var ProfileViewBasicSchema = zod.z.object({
392
+ id: zod.z.string(),
393
+ handle: zod.z.string().nullable().optional(),
394
+ // `displayName` and `bio` are `.nullable()` — Firestore stores `null` for
395
+ // empty values on these fields (see users-dependencies.ts), and Zod's
396
+ // `.optional()` alone rejects `null`. This hit dashboard rendering on the
397
+ // Phase 3.1 HTTP cutover, when transport-layer Zod validation started
398
+ // actually exercising the wire shape. Consumers already use truthy
399
+ // checks / `??` / `||`, so widening the type to include `null` is safe.
400
+ displayName: zod.z.string().nullable().optional(),
401
+ avatarUrl: zod.z.string().nullable().optional(),
402
+ bio: zod.z.string().nullable().optional(),
403
+ /** Personal website link surfaced on the public profile. */
404
+ website: zod.z.string().nullable().optional(),
405
+ /** Public links (label + URL) shown under the bio. */
406
+ links: zod.z.array(zod.z.object({
407
+ label: zod.z.string(),
408
+ url: zod.z.string()
409
+ })).optional(),
410
+ /**
411
+ * AT Protocol identity, surfaced on the public profile only when the user
412
+ * opts in (`UserRecord.showBlueskyPublicly === true`). Projection happens
413
+ * in the user dependency layer; this schema simply allows the field.
414
+ */
415
+ bluesky: zod.z.object({
416
+ handle: zod.z.string(),
417
+ did: zod.z.string()
418
+ }).optional(),
419
+ stats: zod.z.object({
420
+ followers: zod.z.number().default(0),
421
+ following: zod.z.number().default(0),
422
+ prompts: zod.z.number().default(0)
423
+ }).optional(),
424
+ badges: zod.z.array(zod.z.string()).optional(),
425
+ isVerified: zod.z.boolean().optional(),
426
+ createdAt: FirestoreTimestampSchema.optional()
427
+ });
428
+ var ProfileViewDetailedSchema = ProfileViewBasicSchema.extend({
429
+ /** AT Protocol Identity link */
430
+ bluesky: zod.z.object({
431
+ handle: zod.z.string(),
432
+ did: zod.z.string()
433
+ }).optional(),
434
+ usageIntent: zod.z.string().nullable().optional(),
435
+ /** Hydrated RSS Data (fetched from sub-collection) */
436
+ rssSummary: zod.z.object({
437
+ title: zod.z.string().optional(),
438
+ description: zod.z.string().optional(),
439
+ items: zod.z.array(zod.z.object({
440
+ title: zod.z.string().optional(),
441
+ link: zod.z.string().optional(),
442
+ content: zod.z.string().optional(),
443
+ pubDate: zod.z.string().optional()
444
+ })).optional(),
445
+ lastFetchedAt: FirestoreTimestampSchema.optional()
446
+ }).optional(),
447
+ promptAudioUrl: zod.z.string().optional(),
448
+ /** @deprecated Use stats.prompts from ProfileViewBasic instead */
449
+ totalPrompts: zod.z.number().optional(),
450
+ totalReplies: zod.z.number().optional(),
451
+ favoritePromptId: zod.z.string().optional()
452
+ });
453
+ var ProfileViewSelfSchema = ProfileViewDetailedSchema.extend({
454
+ phoneNumber: zod.z.string().nullable().optional(),
455
+ email: zod.z.string().optional(),
456
+ lastSeenAt: FirestoreTimestampSchema.optional(),
457
+ lastActiveAt: FirestoreTimestampSchema.optional(),
458
+ unreadReplyCount: zod.z.number().default(0),
459
+ newReplierCount: zod.z.number().default(0),
460
+ /**
461
+ * Account tier from UserRecord — surfaced on the self profile so the
462
+ * client can gate paid features (e.g. the Performance dashboard tab).
463
+ * Optional for legacy docs without the field; consumers should treat
464
+ * missing as `'free'`.
465
+ */
466
+ tier: zod.z.enum(["free", "creator_pro"]).optional(),
467
+ /**
468
+ * Surfaces the linked Bluesky identity (handle + DID) on the public profile
469
+ * when true. Persisted on UserRecord; exposed in self/detailed views so the
470
+ * settings form can render the toggle's current state.
471
+ */
472
+ showBlueskyPublicly: zod.z.boolean().optional(),
473
+ settings: zod.z.object({
474
+ notifications: zod.z.boolean().optional(),
475
+ theme: zod.z.string().optional()
476
+ }).optional()
477
+ });
478
+ var ProfileViewAdminSchema = ProfileViewSelfSchema.extend({
479
+ blockedUsers: zod.z.array(zod.z.string()).optional(),
480
+ followers: zod.z.array(zod.z.string()).optional(),
481
+ following: zod.z.array(zod.z.string()).optional(),
482
+ reportCount: zod.z.number().optional(),
483
+ isBanned: zod.z.boolean().optional()
484
+ });
485
+ var ProfileViewSchema = ProfileViewAdminSchema;
486
+ var PromptViewSchema = zod.z.object({
487
+ /** AT Protocol URI (e.g. at://did:plc.../app.../123) */
488
+ uri: zod.z.string().optional(),
489
+ /** IPFS Content ID */
490
+ cid: zod.z.string().optional(),
491
+ /** The raw prompt data */
492
+ record: PromptRecordSchema,
493
+ /** The hydrated author profile */
494
+ author: ProfileViewSchema,
495
+ /** Total number of replies */
496
+ replyCount: zod.z.number().default(0),
497
+ likeCount: zod.z.number().default(0),
498
+ updatedAt: FirestoreTimestampSchema.optional(),
499
+ lastReplyAt: FirestoreTimestampSchema.optional(),
500
+ tags: zod.z.array(zod.z.string()).optional(),
501
+ visibility: zod.z.enum(["public", "private", "unlisted", "archived"]).default("public"),
502
+ analytics: zod.z.object({
503
+ views: zod.z.number().default(0),
504
+ listens: zod.z.number().default(0),
505
+ /**
506
+ * Mean engagementScore (1–10) across this prompt's `status: 'live'`
507
+ * replies that completed AI enrichment. `null` when no such replies
508
+ * exist (0 would alias a valid bottom-of-range score). Derived in
509
+ * hydration from the prompt doc's `engagementScoreSum / Count`.
510
+ */
511
+ avgEngagementScore: zod.z.number().nullable().optional(),
512
+ /**
513
+ * Counts of `status: 'live'` AI-enriched replies grouped by sentiment.
514
+ * Keys lowercase by convention; source enum
515
+ * (`Positive | Neutral | Negative`) is mapped at the write site.
516
+ */
517
+ sentimentBreakdown: zod.z.object({
518
+ positive: zod.z.number(),
519
+ neutral: zod.z.number(),
520
+ negative: zod.z.number()
521
+ }).optional()
522
+ }).optional(),
523
+ moderation: zod.z.object({
524
+ flagged: zod.z.boolean().default(false),
525
+ reason: zod.z.string().optional()
526
+ }).optional(),
527
+ // AI Enrichment Fields (Hydrated from Record but hidden from Record Schema)
528
+ aiLabels: zod.z.array(zod.z.string()).optional(),
529
+ aiSummary: zod.z.string().optional(),
530
+ aiStatus: zod.z.enum(["pending", "complete", "error"]).optional(),
531
+ aiError: zod.z.string().optional(),
532
+ transcription: zod.z.string().optional()
533
+ });
534
+ var PromptViewPublicSchema = PromptViewSchema.omit({
535
+ analytics: true,
536
+ moderation: true,
537
+ aiLabels: true,
538
+ aiSummary: true,
539
+ aiStatus: true,
540
+ aiError: true,
541
+ transcription: true
542
+ }).extend({
543
+ author: ProfileViewBasicSchema
544
+ });
545
+ var ReplyViewSchema = zod.z.object({
546
+ record: ReplyRecordSchema,
547
+ author: ProfileViewSchema,
548
+ recipient: ProfileViewSchema,
549
+ /** GCS Storage Path for audio file */
550
+ storagePath: zod.z.string().optional(),
551
+ duration: zod.z.number().optional(),
552
+ updatedAt: FirestoreTimestampSchema.optional(),
553
+ isRead: zod.z.boolean(),
554
+ readBy: zod.z.array(zod.z.string()).default([]),
555
+ isDeleted: zod.z.boolean().default(false),
556
+ reactions: zod.z.record(zod.z.string(), zod.z.number()).optional(),
557
+ moderation: zod.z.object({
558
+ flagged: zod.z.boolean().default(false),
559
+ reason: zod.z.string().optional()
560
+ }).optional(),
561
+ // AI Enrichment Fields (Hydrated from Record but hidden from Record Schema)
562
+ aiLabels: zod.z.array(zod.z.string()).optional(),
563
+ aiSummary: zod.z.string().optional(),
564
+ aiStatus: zod.z.enum(["pending", "complete", "error", "skipped_too_short"]).optional(),
565
+ aiError: zod.z.string().optional(),
566
+ transcription: zod.z.string().optional(),
567
+ sentiment: zod.z.enum(["Positive", "Negative", "Neutral"]).optional(),
568
+ /** Must match the widened enum in `ReplyRecordSchema.energyLevel`. */
569
+ energyLevel: zod.z.enum(["High", "Low", "Neutral"]).optional(),
570
+ engagementScore: zod.z.number().min(1).max(10).optional(),
571
+ // === Voice-isolation enrichment (lifted; see specs/ai-enrichment-split.md) ===
572
+ //
573
+ // `enhancedAudioUrl` is the only one of these the public view keeps —
574
+ // it replaces `audioUrl` for downstream players when present.
575
+ // `enhancedStoragePath` is private (storage paths are server-side
576
+ // bookkeeping).
577
+ enhancedAudioUrl: zod.z.string().url().optional(),
578
+ enhancedStoragePath: zod.z.string().optional(),
579
+ // === Social-share video enrichment (lifted; creator-only) ===
580
+ //
581
+ // All `socialVideo*` fields are stripped by `toReplyViewPublic` —
582
+ // the URL points at a generated artifact the creator may share to
583
+ // social media, NOT at content the reply page should render. Status /
584
+ // error / source-audio are job-tracking state.
585
+ socialVideoUrl: zod.z.string().url().optional(),
586
+ socialVideoStoragePath: zod.z.string().optional(),
587
+ socialVideoStatus: zod.z.enum(["pending", "complete", "error"]).optional(),
588
+ socialVideoError: zod.z.string().optional(),
589
+ socialVideoSourceAudio: zod.z.string().optional(),
590
+ /** @private Confirmed listener phone number (never exposed publicly) */
591
+ listenerPhoneNumber: zod.z.string().regex(/^\+[1-9]\d{1,14}$/).optional(),
592
+ /**
593
+ * @private Per-viewer private notes about this reply (CRM enrichment).
594
+ * Lifted into the view from `enrichments/replies/{id}.notes` by the
595
+ * hydrator when the viewer is the prompt author. Never populated for
596
+ * non-author viewers; defensively stripped by `toReplyViewPublic`.
597
+ */
598
+ notes: zod.z.string().optional()
599
+ });
600
+ var ReplyViewPublicSchema = ReplyViewSchema.omit({
601
+ listenerPhoneNumber: true,
602
+ notes: true,
603
+ // AI cluster — only `transcription` survives.
604
+ aiStatus: true,
605
+ aiError: true,
606
+ aiSummary: true,
607
+ aiLabels: true,
608
+ sentiment: true,
609
+ energyLevel: true,
610
+ engagementScore: true,
611
+ // Voice isolation — keep enhancedAudioUrl, strip the path.
612
+ enhancedStoragePath: true,
613
+ // Social-video — entire cluster is creator-only.
614
+ socialVideoUrl: true,
615
+ socialVideoStoragePath: true,
616
+ socialVideoStatus: true,
617
+ socialVideoError: true,
618
+ socialVideoSourceAudio: true
619
+ });
620
+ var OrganizationViewSchema = zod.z.object({
621
+ record: OrganizationRecordSchema,
622
+ memberCount: zod.z.number().default(1),
623
+ currentUserRole: zod.z.enum(["owner", "admin", "member"]).optional()
624
+ });
625
+ zod.z.object({
626
+ record: OrganizationMemberRecordSchema,
627
+ profile: ProfileViewBasicSchema
628
+ });
629
+ zod.z.object({
630
+ record: OrgInviteRecordSchema,
631
+ /** Display name of the user who sent the invite */
632
+ inviterName: zod.z.string().optional(),
633
+ /** Name of the organization */
634
+ orgName: zod.z.string()
635
+ });
636
+ zod.z.object({
637
+ promptId: zod.z.string(),
638
+ repliers: zod.z.record(zod.z.string(), zod.z.object({
639
+ firstReplyAt: FirestoreTimestampSchema,
640
+ lastReplyAt: FirestoreTimestampSchema,
641
+ replyCount: zod.z.number()
642
+ }))
643
+ });
644
+ PromptViewSchema.extend({
645
+ replies: zod.z.array(ReplyViewSchema)
646
+ });
647
+ var ReplierSchema = zod.z.object({
648
+ handle: zod.z.string(),
649
+ /** ISO date string */
650
+ lastReplyDate: zod.z.string(),
651
+ /** ISO date string */
652
+ firstReplyAt: zod.z.string(),
653
+ totalReplies: zod.z.number()
654
+ });
655
+ zod.z.discriminatedUnion("type", [
656
+ // Public endpoint (`GET /resolve/:handle`) — project to the basic shape so
657
+ // PII/admin fields (email, phoneNumber, settings, blockedUsers, …) never
658
+ // cross the public API boundary. See `toProfileViewBasic`.
659
+ zod.z.object({ type: zod.z.literal("user"), profile: ProfileViewBasicSchema }),
660
+ zod.z.object({ type: zod.z.literal("org"), org: OrganizationViewSchema })
661
+ ]);
662
+ zod.z.object({
663
+ // Public endpoint (`GET /users/:handle/profile`) — basic shape only, so the
664
+ // owner's PII/admin fields never serialize to anonymous callers.
665
+ profileUser: ProfileViewBasicSchema,
666
+ // Each prompt's nested `author` is the profile owner, hydrated from the
667
+ // wide admin profile (`getPromptsForUser` prefetches via getUserDataByUid).
668
+ // Use the PUBLIC prompt/reply shapes so that nested author PII (email,
669
+ // phoneNumber, settings, …) and owner-only prompt enrichment never leak.
670
+ allPromptsWithReplies: zod.z.array(PromptViewPublicSchema.extend({
671
+ replies: zod.z.array(ReplyViewPublicSchema)
672
+ })),
673
+ repliers: zod.z.array(ReplierSchema)
674
+ });
675
+ var RssSummarySchema = zod.z.object({
676
+ title: zod.z.string().optional(),
677
+ description: zod.z.string().optional(),
678
+ image: zod.z.string().optional(),
679
+ link: zod.z.string().optional(),
680
+ items: zod.z.array(zod.z.object({
681
+ title: zod.z.string().optional(),
682
+ link: zod.z.string().optional(),
683
+ content: zod.z.string().optional(),
684
+ pubDate: zod.z.string().optional()
685
+ })).optional(),
686
+ lastFetchedAt: FirestoreTimestampSchema.optional()
687
+ });
688
+ zod.z.object({
689
+ org: OrganizationViewSchema,
690
+ prompts: zod.z.array(PromptViewSchema),
691
+ rssSummary: RssSummarySchema.nullable()
692
+ });
693
+ zod.z.object({
694
+ profile: ProfileViewBasicSchema,
695
+ totalReplies: zod.z.number(),
696
+ /** ISO date string */
697
+ lastReplyDate: zod.z.string(),
698
+ /** ISO date string */
699
+ firstReplyAt: zod.z.string(),
700
+ /** Phone number for anonymous repliers (from Firebase Auth, only visible to prompt author) */
701
+ phoneNumber: zod.z.string().optional()
702
+ });
703
+
704
+ // types/audio.ts
705
+ var StrongRefSchema = zod.z.object({
706
+ uri: zod.z.string().regex(/^at:\/\/.+/, "Must be an at:// URI"),
707
+ cid: zod.z.string()
708
+ });
709
+ var ReplyRefSchema = zod.z.object({
710
+ root: StrongRefSchema,
711
+ parent: StrongRefSchema
712
+ });
713
+ var AudioEmbedSchema = zod.z.object({
714
+ $type: zod.z.literal("dev.antiphony.embed.audio"),
715
+ /** The audio bytes as a content-addressed storage ref (CID/path). */
716
+ audio: BlobRefSchema,
717
+ /** Duration in MILLISECONDS (platform-wide unit; not seconds). */
718
+ durationMs: zod.z.number().int().min(0).optional(),
719
+ /** User-authored short description (audio analogue of image alt). NOT the transcript. */
720
+ alt: zod.z.string().max(1e4).optional(),
721
+ /** Pre-computed waveform peaks (normalized 0–100) for instant rendering. */
722
+ waveform: zod.z.array(zod.z.number().int().min(0).max(100)).max(1e3).optional()
723
+ });
724
+ var TranscriptSegmentSchema = zod.z.object({
725
+ startMs: zod.z.number().int().min(0),
726
+ endMs: zod.z.number().int().min(0),
727
+ text: zod.z.string()
728
+ }).refine((s) => s.endMs >= s.startMs, {
729
+ message: "endMs must be >= startMs",
730
+ path: ["endMs"]
731
+ });
732
+ var TimedTranscriptSchema = zod.z.object({
733
+ segments: zod.z.array(TranscriptSegmentSchema),
734
+ text: zod.z.string().optional()
735
+ });
736
+ var AudioEmbedViewSchema = zod.z.object({
737
+ $type: zod.z.literal("dev.antiphony.embed.audio#view"),
738
+ url: zod.z.string().url(),
739
+ durationMs: zod.z.number().int().min(0).optional(),
740
+ // `alt`/`waveform` are copied from the stored embed; keep the same bounds
741
+ // so a view can never carry a larger payload than the record allows.
742
+ alt: zod.z.string().max(1e4).optional(),
743
+ waveform: zod.z.array(zod.z.number().int().min(0).max(100)).max(1e3).optional(),
744
+ /** Lifted from the transcript enrichment record; absent until transcription completes. */
745
+ transcript: TimedTranscriptSchema.optional()
746
+ });
747
+ zod.z.object({
748
+ /** Storage id (rkey/doc id). */
749
+ id: zod.z.string(),
750
+ // --- Tenancy + facets (storage-indexed; NOT in the lexicon) ---
751
+ /** Origin app that created this record — the multi-tenant isolation key. */
752
+ originAppId: zod.z.string(),
753
+ /** Authoring user. A queryable facet, not the tenancy boundary. */
754
+ authorId: zod.z.string(),
755
+ /** Optional AT Protocol identity of the author (facet). */
756
+ authorDid: zod.z.string().optional(),
757
+ /** Optional org context (facet). */
758
+ orgId: zod.z.string().nullable().optional(),
759
+ /** Denormalized from `reply` presence: `reply` set ⇒ 'reply', else 'prompt'. */
760
+ kind: zod.z.enum(["prompt", "reply"]),
761
+ // --- Lexicon fields (public contract) ---
762
+ /** User-authored text (bsky-semantic). May be empty for pure-audio posts. NEVER the transcript. */
763
+ text: zod.z.string().max(3e3),
764
+ /** Optional headline; a prompt feature, not the discriminator. */
765
+ title: zod.z.string().max(3e3).optional(),
766
+ /** Audio (or other) attachment. Audio posts carry an `AudioEmbed`. */
767
+ embed: AudioEmbedSchema.optional(),
768
+ /** Present iff this post is a reply (StrongRef root + parent). */
769
+ reply: ReplyRefSchema.optional(),
770
+ /** BCP-47 language tags for the text. */
771
+ langs: zod.z.array(zod.z.string()).max(3).optional(),
772
+ /** Author-applied self-label values (content warnings). Simplified from the
773
+ * lexicon's `com.atproto.label.defs#selfLabels` to the bare value strings. */
774
+ selfLabels: zod.z.array(zod.z.string()).optional(),
775
+ createdAt: FirestoreTimestampSchema
776
+ }).refine(
777
+ // `kind` is denormalized from `reply` presence at write time; enforce the
778
+ // invariant so an inconsistent record can't be written or read silently.
779
+ // A reply has `reply` and no `title`; a prompt has neither a `reply`.
780
+ (r) => r.kind === "reply" ? !!r.reply && r.title === void 0 : !r.reply,
781
+ {
782
+ message: "kind must match reply presence: 'reply' \u21D2 reply set & no title; 'prompt' \u21D2 no reply",
783
+ path: ["kind"]
784
+ }
785
+ );
786
+ zod.z.object({
787
+ id: zod.z.string(),
788
+ /** The post whose audio this transcribes. */
789
+ subject: StrongRefSchema,
790
+ transcript: TimedTranscriptSchema,
791
+ /** BCP-47 language tag of the transcript. */
792
+ lang: zod.z.string().optional(),
793
+ /** Model/provider provenance (the generator is a pluggable port). */
794
+ model: zod.z.string().optional(),
795
+ createdAt: FirestoreTimestampSchema
796
+ });
797
+ zod.z.object({
798
+ handle: zod.z.string().min(3).max(20).optional(),
799
+ usageIntent: zod.z.string().max(100).optional(),
800
+ rssFeed: zod.z.string().url().optional()
801
+ });
802
+ var ViewerStateSchema = zod.z.object({
803
+ /** True when the authenticated caller authored this post. */
804
+ isAuthor: zod.z.boolean().default(false)
805
+ });
806
+ var PostRecordPublicSchema = zod.z.object({
807
+ text: zod.z.string(),
808
+ title: zod.z.string().optional(),
809
+ reply: ReplyRefSchema.optional(),
810
+ langs: zod.z.array(zod.z.string()).optional(),
811
+ selfLabels: zod.z.array(zod.z.string()).optional(),
812
+ createdAt: FirestoreTimestampSchema
813
+ });
814
+ zod.z.object({
815
+ /** at:// URI (or internal ref) identifying the post. */
816
+ uri: zod.z.string(),
817
+ cid: zod.z.string().optional(),
818
+ kind: zod.z.enum(["prompt", "reply"]),
819
+ author: ProfileViewBasicSchema,
820
+ record: PostRecordPublicSchema,
821
+ /** Hydrated audio embed (signed URL + lifted transcript). */
822
+ embed: AudioEmbedViewSchema.optional(),
823
+ viewer: ViewerStateSchema
824
+ });
825
+
826
+ // api-codecs.ts
827
+ var CreateAudioPostRequestSchema = zod.z.object({
828
+ /** User-authored text; may be empty for pure-audio posts. */
829
+ text: zod.z.string().max(3e3).default(""),
830
+ /** Optional headline (prompt feature). */
831
+ title: zod.z.string().max(3e3).optional(),
832
+ /** The uploaded audio attachment. */
833
+ embed: AudioEmbedSchema.optional(),
834
+ /** Present ⇒ this is a reply (StrongRef root + parent). */
835
+ reply: ReplyRefSchema.optional(),
836
+ /** BCP-47 language tags. */
837
+ langs: zod.z.array(zod.z.string()).max(3).optional(),
838
+ /** Author self-label values (content warnings). */
839
+ selfLabels: zod.z.array(zod.z.string()).optional()
840
+ }).refine((d) => !(d.reply && d.title), {
841
+ message: "Replies cannot have a title",
842
+ path: ["title"]
843
+ }).refine((d) => d.text.trim().length > 0 || !!d.embed, {
844
+ message: "Post must have text or an audio embed",
845
+ path: ["text"]
846
+ });
847
+ var CreatePromptRequestSchema = zod.z.object({
848
+ // Bounds chosen so the public prompt hero never needs to clip: title +
849
+ // description sit between the two dots inside an h-dvh, overflow-hidden
850
+ // layout. 80/200 keeps typical content to a few lines on short phones.
851
+ // (Record-level schema stays unbounded so any pre-existing longer values
852
+ // still read cleanly — this only gates new writes.)
853
+ title: zod.z.string().min(3).max(80),
854
+ description: zod.z.string().max(200).optional(),
855
+ audioUrl: zod.z.string().url().or(zod.z.literal("")),
856
+ setAsGreeting: zod.z.union([zod.z.boolean(), zod.z.string().transform((val) => val === "true")]).optional(),
857
+ /** Explicit org context override (normally inferred from auth.currentOrg) */
858
+ orgId: zod.z.string().nullable().optional()
859
+ });
860
+ var UpdateProfileRequestSchema = zod.z.object({
861
+ handle: zod.z.string().min(3).max(20).regex(/^[a-zA-Z0-9_]+$/).optional(),
862
+ displayName: zod.z.string().max(50).optional(),
863
+ bio: zod.z.string().max(160).optional(),
864
+ avatarUrl: zod.z.string().url().nullable().optional(),
865
+ usageIntent: zod.z.string().max(200).nullable().optional(),
866
+ /**
867
+ * Personal website surfaced on the public profile. Accepts a URL, empty
868
+ * string, or null from the client; normalizes empty string → null so the
869
+ * value stored on `UserRecord` (which requires `.url() | null`) round-trips
870
+ * cleanly through `UserRecordSchema.parse` on subsequent reads.
871
+ */
872
+ website: zod.z.union([zod.z.string().url(), zod.z.literal(""), zod.z.null()]).optional().transform((v) => v === "" ? null : v),
873
+ /** Up to 5 public links (label + URL) shown under the bio. */
874
+ links: zod.z.array(zod.z.object({
875
+ label: zod.z.string().min(1).max(40),
876
+ url: zod.z.string().url()
877
+ })).max(5).optional(),
878
+ /** When true, surfaces the linked Bluesky identity on the public profile. */
879
+ showBlueskyPublicly: zod.z.boolean().optional()
880
+ });
881
+ var FcmTokenRequestSchema = zod.z.object({
882
+ // FCM registration tokens are typically ~163–200 chars; Google's docs
883
+ // don't publish a hard max but 4096 is a safe upper bound that prevents
884
+ // multi-MB payloads while accommodating any plausible FCM token format.
885
+ token: zod.z.string().min(1).max(4096)
886
+ });
887
+ var BadgeResetRequestSchema = zod.z.object({
888
+ type: zod.z.enum(["new_replier", "unread_reply"])
889
+ });
890
+ var CreateOrgRequestSchema = zod.z.object({
891
+ name: zod.z.string().min(3).max(50),
892
+ slug: zod.z.string().min(3).max(30).regex(/^[a-z0-9-]+$/),
893
+ avatarUrl: zod.z.string().url().optional(),
894
+ rssFeedUrl: zod.z.string().url().optional(),
895
+ websiteUrl: zod.z.string().url().optional(),
896
+ // 500 chars — enough for a multi-sentence blurb, prevents multi-MB writes.
897
+ description: zod.z.string().max(500).optional()
898
+ });
899
+ var UpdateOrgRequestSchema = zod.z.object({
900
+ name: zod.z.string().min(3).max(50).optional(),
901
+ slug: zod.z.string().min(3).max(30).regex(/^[a-z0-9-]+$/).optional(),
902
+ // 500 chars — matches CreateOrgRequestSchema.description.
903
+ description: zod.z.string().max(500).optional(),
904
+ avatarUrl: zod.z.string().url().nullable().optional(),
905
+ rssFeedUrl: zod.z.string().url().nullable().optional(),
906
+ websiteUrl: zod.z.string().url().nullable().optional(),
907
+ billingEmail: zod.z.string().email().nullable().optional(),
908
+ // 253 chars — the DNS spec maximum for a fully-qualified domain name.
909
+ domain: zod.z.string().max(253).nullable().optional()
910
+ });
911
+ var CreateOrgInviteRequestSchema = zod.z.object({
912
+ email: zod.z.string().email(),
913
+ role: zod.z.enum(["admin", "member"])
914
+ });
915
+ var UpdateMemberRoleRequestSchema = zod.z.object({
916
+ role: zod.z.enum(["admin", "member"])
917
+ });
918
+ var SwitchOrgRequestSchema = zod.z.object({
919
+ /** orgId to switch to, or null to switch to personal context */
920
+ orgId: zod.z.string().nullable()
921
+ });
922
+ var ConnectorConfigInputSchema = ConnectorConfigRecordSchema.omit({
923
+ connectorType: true,
924
+ ownerId: true,
925
+ status: true,
926
+ createdAt: true,
927
+ updatedAt: true
928
+ });
929
+ var ConnectorConfigUpdateSchema = ConnectorConfigInputSchema.partial();
930
+ var PersonNotesUpdateSchema = zod.z.object({
931
+ notes: zod.z.string().max(1e4).optional(),
932
+ tags: zod.z.array(zod.z.string().max(64)).max(50).optional()
933
+ });
934
+ var PersonMergeRequestSchema = zod.z.object({
935
+ alternateUid: zod.z.string().min(1)
936
+ });
937
+ var ScreeningRuleInputSchema = zod.z.object({
938
+ e164: zod.z.string().regex(/^\+[1-9]\d{6,14}$/, "Must be an E.164 phone number"),
939
+ label: zod.z.string().max(120).nullable().optional(),
940
+ action: zod.z.enum(["allow", "screen"]),
941
+ expiresAt: zod.z.union([zod.z.string(), zod.z.number()]).nullable().optional().refine((v) => v == null || !Number.isNaN(new Date(v).getTime()), {
942
+ message: "Must be a valid ISO date string or epoch-ms timestamp"
943
+ })
944
+ });
945
+ var ScreeningRuleUpdateSchema = ScreeningRuleInputSchema.partial();
946
+ var UpdateReplyStatusRequestSchema = zod.z.object({
947
+ status: zod.z.enum(["live", "archived", "deleted"])
948
+ });
949
+ var BulkReplyActionRequestSchema = zod.z.object({
950
+ replyIds: zod.z.array(zod.z.string()).min(1).max(100),
951
+ action: zod.z.enum(["markRead", "archive", "delete", "restore"])
952
+ });
953
+
954
+ exports.BadgeResetRequestSchema = BadgeResetRequestSchema;
955
+ exports.BulkReplyActionRequestSchema = BulkReplyActionRequestSchema;
956
+ exports.ConnectorConfigInputSchema = ConnectorConfigInputSchema;
957
+ exports.ConnectorConfigUpdateSchema = ConnectorConfigUpdateSchema;
958
+ exports.CreateAudioPostRequestSchema = CreateAudioPostRequestSchema;
959
+ exports.CreateOrgInviteRequestSchema = CreateOrgInviteRequestSchema;
960
+ exports.CreateOrgRequestSchema = CreateOrgRequestSchema;
961
+ exports.CreatePromptRequestSchema = CreatePromptRequestSchema;
962
+ exports.FcmTokenRequestSchema = FcmTokenRequestSchema;
963
+ exports.PersonMergeRequestSchema = PersonMergeRequestSchema;
964
+ exports.PersonNotesUpdateSchema = PersonNotesUpdateSchema;
965
+ exports.ScreeningRuleInputSchema = ScreeningRuleInputSchema;
966
+ exports.ScreeningRuleUpdateSchema = ScreeningRuleUpdateSchema;
967
+ exports.SwitchOrgRequestSchema = SwitchOrgRequestSchema;
968
+ exports.UpdateMemberRoleRequestSchema = UpdateMemberRoleRequestSchema;
969
+ exports.UpdateOrgRequestSchema = UpdateOrgRequestSchema;
970
+ exports.UpdateProfileRequestSchema = UpdateProfileRequestSchema;
971
+ exports.UpdateReplyStatusRequestSchema = UpdateReplyStatusRequestSchema;