@odla-ai/crm 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,2184 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ACTIVITY_KINDS: () => ACTIVITY_KINDS,
24
+ CONFIG_KEY: () => CONFIG_KEY,
25
+ CONSENT_STATES: () => CONSENT_STATES,
26
+ CRM_NS: () => CRM_NS,
27
+ CRM_RULES: () => CRM_RULES,
28
+ CRM_SCHEMA: () => CRM_SCHEMA,
29
+ CRM_SLOTS: () => CRM_SLOTS,
30
+ CrmClient: () => CrmClient,
31
+ CrmInputError: () => CrmInputError,
32
+ CrmNotFoundError: () => CrmNotFoundError,
33
+ DEFAULT_LIMIT: () => DEFAULT_LIMIT,
34
+ EMAIL_STATUSES: () => EMAIL_STATUSES,
35
+ MAX_LIMIT: () => MAX_LIMIT,
36
+ RANK_EPSILON: () => RANK_EPSILON,
37
+ RANK_STEP: () => RANK_STEP,
38
+ SORTABLE_COLUMNS: () => SORTABLE_COLUMNS,
39
+ TASK_STATUSES: () => TASK_STATUSES,
40
+ addActivity: () => addActivity,
41
+ addLink: () => addLink,
42
+ addTag: () => addTag,
43
+ applyConsent: () => applyConsent,
44
+ applyConsentEvent: () => applyConsentEvent,
45
+ canEmail: () => canEmail,
46
+ canTransition: () => canTransition,
47
+ channelKey: () => channelKey,
48
+ compileList: () => compileList,
49
+ createCrmRoutes: () => createCrmRoutes,
50
+ createRecord: () => createRecord,
51
+ crmIntegration: () => crmIntegration,
52
+ crmRules: () => crmRules,
53
+ defaultTemplates: () => defaultTemplates,
54
+ defineCrm: () => defineCrm,
55
+ deleteView: () => deleteView,
56
+ emailChannelOps: () => emailChannelOps,
57
+ foldEmailStatus: () => foldEmailStatus,
58
+ getConfig: () => getConfig,
59
+ getRecord: () => getRecord,
60
+ initialStage: () => initialStage,
61
+ linkIdentity: () => linkIdentity,
62
+ lintTemplate: () => lintTemplate,
63
+ listActivities: () => listActivities,
64
+ listChannels: () => listChannels,
65
+ listEmailLog: () => listEmailLog,
66
+ listLinks: () => listLinks,
67
+ listRecords: () => listRecords,
68
+ listTags: () => listTags,
69
+ listTasks: () => listTasks,
70
+ listViews: () => listViews,
71
+ mustGetRecord: () => mustGetRecord,
72
+ needsRebalance: () => needsRebalance,
73
+ normalizeTag: () => normalizeTag,
74
+ prepare: () => prepare,
75
+ rankBetween: () => rankBetween,
76
+ rebalancePlan: () => rebalancePlan,
77
+ rebalanceRanks: () => rebalanceRanks,
78
+ recordCanEmail: () => recordCanEmail,
79
+ removeLink: () => removeLink,
80
+ removeTag: () => removeTag,
81
+ renderTemplate: () => renderTemplate,
82
+ resolveDeps: () => resolveDeps,
83
+ resolveSortColumn: () => resolveSortColumn,
84
+ rowToRecord: () => rowToRecord,
85
+ saveConfig: () => saveConfig,
86
+ saveView: () => saveView,
87
+ searchTextFor: () => searchTextFor,
88
+ sendTemplatedEmail: () => sendTemplatedEmail,
89
+ setArchived: () => setArchived,
90
+ setRank: () => setRank,
91
+ setStage: () => setStage,
92
+ stageIndexOf: () => stageIndexOf,
93
+ templateVars: () => templateVars,
94
+ typeSummary: () => typeSummary,
95
+ updateRecord: () => updateRecord,
96
+ updateTask: () => updateTask,
97
+ updateView: () => updateView
98
+ });
99
+ module.exports = __toCommonJS(index_exports);
100
+
101
+ // src/constants.ts
102
+ var CRM_NS = {
103
+ record: "crm_record",
104
+ tag: "crm_tag",
105
+ link: "crm_link",
106
+ activity: "crm_activity",
107
+ channel: "crm_contact_channel",
108
+ emailLog: "crm_email_log",
109
+ view: "crm_view",
110
+ config: "crm_config"
111
+ };
112
+ var CRM_SLOTS = ["s1", "s2", "s3", "s4", "n1", "n2", "n3", "d1", "d2"];
113
+ var CONSENT_STATES = ["subscribed", "unsubscribed", "bounced", "suppressed"];
114
+ var EMAIL_STATUSES = ["ok", "unsubscribed", "bounced", "suppressed", "none"];
115
+ var ACTIVITY_KINDS = ["note", "task", "call", "meeting", "stage_change", "system"];
116
+ var TASK_STATUSES = ["open", "waiting", "done"];
117
+ var SORTABLE_COLUMNS = [
118
+ "name",
119
+ "primaryEmail",
120
+ "stageIndex",
121
+ "stageChangedAt",
122
+ "rank",
123
+ "score",
124
+ "emailStatus",
125
+ "billingStatus",
126
+ "renewalAt",
127
+ "createdAt",
128
+ "updatedAt"
129
+ ];
130
+ var RESERVED_FIELDS = /* @__PURE__ */ new Set([
131
+ "id",
132
+ "type",
133
+ "primaryEmail",
134
+ "stage",
135
+ "stageIndex",
136
+ "stageChangedAt",
137
+ "rank",
138
+ "score",
139
+ "ownerId",
140
+ "emailStatus",
141
+ "clerkUserId",
142
+ "stripeCustomerId",
143
+ "subscriptionId",
144
+ "billingStatus",
145
+ "renewalAt",
146
+ "mrr",
147
+ "fields",
148
+ "searchText",
149
+ "archived",
150
+ "createdAt",
151
+ "updatedAt",
152
+ "archivedAt",
153
+ ...CRM_SLOTS
154
+ ]);
155
+ var CONFIG_KEY = "default";
156
+ var DEFAULT_LIMIT = 50;
157
+ var MAX_LIMIT = 200;
158
+
159
+ // src/schema.ts
160
+ var a = (type, o = {}) => ({
161
+ type,
162
+ unique: false,
163
+ indexed: false,
164
+ optional: false,
165
+ ...o
166
+ });
167
+ var uniq = (type) => a(type, { unique: true, indexed: true });
168
+ var idx = (type, optional = false) => a(type, { indexed: true, optional });
169
+ var opt = (type) => a(type, { optional: true });
170
+ var CRM_SCHEMA = {
171
+ entities: {
172
+ [CRM_NS.record]: {
173
+ attrs: {
174
+ type: idx("string"),
175
+ name: idx("string"),
176
+ primaryEmail: idx("string", true),
177
+ stage: idx("string", true),
178
+ stageIndex: idx("number", true),
179
+ stageChangedAt: idx("date", true),
180
+ rank: idx("number", true),
181
+ score: idx("number", true),
182
+ ownerId: idx("string", true),
183
+ emailStatus: idx("string", true),
184
+ clerkUserId: a("string", { unique: true, indexed: true, optional: true }),
185
+ stripeCustomerId: idx("string", true),
186
+ subscriptionId: opt("string"),
187
+ billingStatus: idx("string", true),
188
+ renewalAt: idx("date", true),
189
+ mrr: opt("number"),
190
+ s1: idx("string", true),
191
+ s2: idx("string", true),
192
+ s3: idx("string", true),
193
+ s4: idx("string", true),
194
+ n1: idx("number", true),
195
+ n2: idx("number", true),
196
+ n3: idx("number", true),
197
+ d1: idx("date", true),
198
+ d2: idx("date", true),
199
+ fields: a("json"),
200
+ searchText: a("string"),
201
+ archived: idx("boolean"),
202
+ createdAt: idx("date"),
203
+ updatedAt: idx("date"),
204
+ archivedAt: opt("date")
205
+ }
206
+ },
207
+ [CRM_NS.tag]: {
208
+ attrs: {
209
+ key: uniq("string"),
210
+ // `${recordId}:${tag}`
211
+ recordId: idx("string"),
212
+ tag: idx("string"),
213
+ createdAt: idx("date")
214
+ }
215
+ },
216
+ [CRM_NS.link]: {
217
+ attrs: {
218
+ key: uniq("string"),
219
+ // `${fromId}:${relation}:${toId}`
220
+ fromId: idx("string"),
221
+ toId: idx("string"),
222
+ relation: idx("string"),
223
+ createdAt: idx("date")
224
+ }
225
+ },
226
+ [CRM_NS.activity]: {
227
+ attrs: {
228
+ recordId: idx("string"),
229
+ kind: idx("string"),
230
+ body: a("string"),
231
+ status: idx("string", true),
232
+ // tasks: open | waiting | done
233
+ dueAt: idx("date", true),
234
+ waitingOn: opt("string"),
235
+ assigneeId: idx("string", true),
236
+ authorId: idx("string"),
237
+ createdAt: idx("date"),
238
+ completedAt: opt("date"),
239
+ meta: opt("json")
240
+ }
241
+ },
242
+ [CRM_NS.channel]: {
243
+ attrs: {
244
+ key: uniq("string"),
245
+ // `${recordId}:${kind}:${value}`
246
+ recordId: idx("string"),
247
+ kind: a("string"),
248
+ // email | phone
249
+ value: idx("string"),
250
+ // emails lowercased
251
+ isPrimary: a("boolean"),
252
+ consent: idx("string"),
253
+ consentAt: idx("date"),
254
+ consentSource: opt("string"),
255
+ unsubscribeToken: uniq("string"),
256
+ createdAt: idx("date")
257
+ }
258
+ },
259
+ [CRM_NS.emailLog]: {
260
+ attrs: {
261
+ recordId: idx("string", true),
262
+ channelId: opt("string"),
263
+ to: a("string"),
264
+ templateId: idx("string"),
265
+ subject: a("string"),
266
+ transport: a("string"),
267
+ // sent | log-only
268
+ redirected: opt("boolean"),
269
+ dedupeKey: idx("string", true),
270
+ messageId: opt("string"),
271
+ error: opt("string"),
272
+ sentAt: idx("date")
273
+ }
274
+ },
275
+ [CRM_NS.view]: {
276
+ attrs: {
277
+ name: a("string"),
278
+ type: idx("string"),
279
+ ownerId: idx("string", true),
280
+ shared: idx("boolean"),
281
+ filters: a("json"),
282
+ sort: a("json"),
283
+ columns: a("json"),
284
+ createdAt: idx("date"),
285
+ updatedAt: idx("date")
286
+ }
287
+ },
288
+ [CRM_NS.config]: {
289
+ attrs: {
290
+ key: uniq("string"),
291
+ // CONFIG_KEY singleton
292
+ notificationEmail: opt("string"),
293
+ replyTo: opt("string"),
294
+ debugEmail: opt("string"),
295
+ emailTemplates: a("json"),
296
+ // Record<templateId, {subject, text, enabled}>
297
+ settings: a("json"),
298
+ updatedAt: idx("date")
299
+ }
300
+ }
301
+ },
302
+ links: {}
303
+ };
304
+
305
+ // src/rules.ts
306
+ var DENY = { view: "false", create: "false", update: "false", delete: "false" };
307
+ var CRM_RULES = Object.fromEntries(
308
+ Object.values(CRM_NS).map((ns) => [ns, { ...DENY }])
309
+ );
310
+ function crmRules() {
311
+ return Object.fromEntries(Object.entries(CRM_RULES).map(([ns, r]) => [ns, { ...r }]));
312
+ }
313
+
314
+ // src/errors.ts
315
+ var CrmInputError = class extends Error {
316
+ fields;
317
+ constructor(message, fields) {
318
+ super(message);
319
+ this.name = "CrmInputError";
320
+ this.fields = fields;
321
+ }
322
+ };
323
+ var CrmNotFoundError = class extends Error {
324
+ constructor(what) {
325
+ super(`${what} not found`);
326
+ this.name = "CrmNotFoundError";
327
+ }
328
+ };
329
+
330
+ // src/pipeline.ts
331
+ function initialStage(def) {
332
+ return def.pipeline?.stages[0]?.id;
333
+ }
334
+ function stageIndexOf(def, stage) {
335
+ const at = (def.pipeline?.stages ?? []).findIndex((s) => s.id === stage);
336
+ if (at === -1) throw new CrmInputError(`unknown stage "${stage}"`);
337
+ return at;
338
+ }
339
+ function canTransition(def, record, to) {
340
+ const pipeline = def.pipeline;
341
+ if (!pipeline) return "type has no pipeline";
342
+ const stages = new Map(pipeline.stages.map((s) => [s.id, s]));
343
+ if (!stages.has(to)) return `unknown stage "${to}"`;
344
+ const from = record.stage;
345
+ if (from === to) return "already in that stage";
346
+ if (from != null) {
347
+ if (!stages.has(from)) return `record is in unknown stage "${from}"`;
348
+ const declared = pipeline.transitions?.[from];
349
+ if (declared) {
350
+ if (!declared.includes(to)) return `cannot move from "${from}" to "${to}"`;
351
+ } else if (stages.get(from)?.terminal) {
352
+ return `"${from}" is terminal`;
353
+ }
354
+ }
355
+ const gate = pipeline.gates?.[to];
356
+ if (gate) {
357
+ const blocked = gate(record);
358
+ if (blocked) return blocked;
359
+ }
360
+ return null;
361
+ }
362
+
363
+ // src/validate.ts
364
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
365
+ var STRINGISH = /* @__PURE__ */ new Set(["string", "email", "url", "enum"]);
366
+ var bad = (error) => ({ ok: false, error });
367
+ var good = (value) => ({ ok: true, value });
368
+ function coerce(def, raw) {
369
+ if (raw === null) return good(null);
370
+ switch (def.type) {
371
+ case "string":
372
+ return typeof raw === "string" ? good(raw.trim()) : bad("expected a string");
373
+ case "email": {
374
+ if (typeof raw !== "string") return bad("expected an email address");
375
+ const email = raw.trim().toLowerCase();
376
+ return EMAIL_RE.test(email) ? good(email) : bad("not a valid email address");
377
+ }
378
+ case "url": {
379
+ if (typeof raw !== "string") return bad("expected a URL");
380
+ const url = raw.trim();
381
+ try {
382
+ const parsed = new URL(url);
383
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
384
+ return bad("must be an http(s) URL");
385
+ return good(url);
386
+ } catch {
387
+ return bad("not a valid URL");
388
+ }
389
+ }
390
+ case "number":
391
+ return typeof raw === "number" && Number.isFinite(raw) ? good(raw) : bad("expected a number");
392
+ case "boolean":
393
+ return typeof raw === "boolean" ? good(raw) : bad("expected true or false");
394
+ case "date": {
395
+ if (typeof raw === "number" && Number.isFinite(raw)) return good(raw);
396
+ if (typeof raw === "string") {
397
+ const t = Date.parse(raw);
398
+ if (!Number.isNaN(t)) return good(t);
399
+ }
400
+ return bad("expected epoch ms or an ISO date string");
401
+ }
402
+ case "enum":
403
+ return typeof raw === "string" && (def.options ?? []).includes(raw) ? good(raw) : bad(`expected one of: ${(def.options ?? []).join(", ")}`);
404
+ case "json":
405
+ return raw === void 0 ? bad("expected a value") : good(raw);
406
+ }
407
+ }
408
+ var empty = (def, value) => value == null || STRINGISH.has(def.type) && value === "";
409
+ function searchTextFor(def, name, email, fields) {
410
+ const parts = [name];
411
+ if (email) parts.push(email);
412
+ for (const [fieldName, field] of Object.entries(def.fields)) {
413
+ if (fieldName === (def.nameField ?? "name") || fieldName === def.emailField) continue;
414
+ const searchable = field.search ?? STRINGISH.has(field.type);
415
+ const value = fields[fieldName];
416
+ if (searchable && value != null && value !== "") parts.push(String(value));
417
+ }
418
+ return parts.join(" ").toLowerCase();
419
+ }
420
+ function prepare(def, input, existing) {
421
+ const errors = {};
422
+ for (const key of Object.keys(input))
423
+ if (!def.fields[key]) errors[key] = "unknown field";
424
+ const fields = { ...existing?.fields ?? {} };
425
+ for (const [fieldName, field] of Object.entries(def.fields)) {
426
+ const supplied = Object.hasOwn(input, fieldName);
427
+ if (supplied) {
428
+ const coerced = coerce(field, input[fieldName]);
429
+ if (!coerced.ok) {
430
+ errors[fieldName] = coerced.error;
431
+ continue;
432
+ }
433
+ fields[fieldName] = coerced.value;
434
+ }
435
+ const settled = fields[fieldName];
436
+ if (field.required && (existing ? supplied || !(fieldName in fields) : true) && empty(field, settled))
437
+ errors[fieldName] = errors[fieldName] ?? "required";
438
+ }
439
+ const nameField = def.nameField ?? "name";
440
+ const name = fields[nameField];
441
+ if (typeof name !== "string" || name === "") errors[nameField] = errors[nameField] ?? "required";
442
+ let primaryEmail = null;
443
+ if (def.emailField) {
444
+ const email = fields[def.emailField];
445
+ primaryEmail = typeof email === "string" && email !== "" ? email : null;
446
+ }
447
+ if (Object.keys(errors).length > 0) return { ok: false, errors };
448
+ const attrs = {
449
+ name,
450
+ fields,
451
+ searchText: searchTextFor(def, name, primaryEmail, fields)
452
+ };
453
+ if (def.emailField) attrs.primaryEmail = primaryEmail;
454
+ for (const [fieldName, field] of Object.entries(def.fields))
455
+ if (field.slot) attrs[field.slot] = fields[fieldName] ?? null;
456
+ return { ok: true, attrs };
457
+ }
458
+
459
+ // src/config.ts
460
+ var NAME_RE = /^[a-z][a-z0-9_-]*$/;
461
+ var FIELD_RE = /^[a-z][a-zA-Z0-9_]*$/;
462
+ var SLOT_KIND = {
463
+ s1: ["string", "email", "url", "enum"],
464
+ s2: ["string", "email", "url", "enum"],
465
+ s3: ["string", "email", "url", "enum"],
466
+ s4: ["string", "email", "url", "enum"],
467
+ n1: ["number"],
468
+ n2: ["number"],
469
+ n3: ["number"],
470
+ d1: ["date"],
471
+ d2: ["date"]
472
+ };
473
+ function fail(path, message) {
474
+ throw new Error(`defineCrm: ${path} ${message}`);
475
+ }
476
+ function checkType(typeName, def) {
477
+ const at = `types.${typeName}`;
478
+ if (!NAME_RE.test(typeName)) fail(at, "must match /^[a-z][a-z0-9_-]*$/");
479
+ const claimed = /* @__PURE__ */ new Map();
480
+ for (const [fieldName, field] of Object.entries(def.fields)) {
481
+ const fat = `${at}.fields.${fieldName}`;
482
+ if (RESERVED_FIELDS.has(fieldName)) fail(fat, "is a reserved column name");
483
+ if (!FIELD_RE.test(fieldName)) fail(fat, "must match /^[a-z][a-zA-Z0-9_]*$/");
484
+ if (field.type === "enum" && !(field.options && field.options.length > 0))
485
+ fail(fat, "enum fields need non-empty options");
486
+ if (field.type !== "enum" && field.options) fail(fat, "options are for enum fields only");
487
+ if (field.slot) {
488
+ if (!CRM_SLOTS.includes(field.slot)) fail(fat, `unknown slot ${field.slot}`);
489
+ if (!SLOT_KIND[field.slot].includes(field.type))
490
+ fail(fat, `slot ${field.slot} cannot hold a ${field.type} field`);
491
+ const holder = claimed.get(field.slot);
492
+ if (holder) fail(fat, `slot ${field.slot} already claimed by ${holder}`);
493
+ claimed.set(field.slot, fieldName);
494
+ }
495
+ }
496
+ const nameField = def.nameField ?? "name";
497
+ if (!def.fields[nameField]) fail(at, `nameField "${nameField}" is not a declared field`);
498
+ if (def.emailField) {
499
+ const emailDef = def.fields[def.emailField];
500
+ if (!emailDef) fail(at, `emailField "${def.emailField}" is not a declared field`);
501
+ if (emailDef.type !== "email") fail(at, `emailField "${def.emailField}" must have type "email"`);
502
+ }
503
+ checkPipeline(at, def);
504
+ }
505
+ function checkPipeline(at, def) {
506
+ const pipeline = def.pipeline;
507
+ if (!pipeline) return;
508
+ if (pipeline.stages.length === 0) fail(at, "pipeline.stages must not be empty");
509
+ const ids = /* @__PURE__ */ new Set();
510
+ for (const stage of pipeline.stages) {
511
+ if (ids.has(stage.id)) fail(at, `duplicate stage "${stage.id}"`);
512
+ ids.add(stage.id);
513
+ }
514
+ for (const [from, targets] of Object.entries(pipeline.transitions ?? {})) {
515
+ if (!ids.has(from)) fail(at, `transitions from unknown stage "${from}"`);
516
+ for (const to of targets) if (!ids.has(to)) fail(at, `transition to unknown stage "${to}"`);
517
+ }
518
+ for (const gated of Object.keys(pipeline.gates ?? {}))
519
+ if (!ids.has(gated)) fail(at, `gate on unknown stage "${gated}"`);
520
+ for (const hooked of Object.keys(def.onTransition ?? {}))
521
+ if (!ids.has(hooked)) fail(at, `onTransition hook on unknown stage "${hooked}"`);
522
+ }
523
+ function defineCrm(config) {
524
+ if (Object.keys(config.types).length === 0) fail("types", "must declare at least one type");
525
+ for (const [typeName, def] of Object.entries(config.types)) checkType(typeName, def);
526
+ for (const [relName, rel] of Object.entries(config.relations ?? {})) {
527
+ const at = `relations.${relName}`;
528
+ if (!config.types[rel.from]) fail(at, `unknown from-type "${rel.from}"`);
529
+ if (!config.types[rel.to]) fail(at, `unknown to-type "${rel.to}"`);
530
+ if (!rel.label) fail(at, "needs a label");
531
+ }
532
+ for (const [tplName, tpl] of Object.entries(config.templates ?? {})) {
533
+ const at = `templates.${tplName}`;
534
+ if (tpl.class !== "transactional" && tpl.class !== "marketing")
535
+ fail(at, `class must be transactional|marketing`);
536
+ for (const v of tpl.vars) if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(v)) fail(at, `bad var "${v}"`);
537
+ }
538
+ const type = (name) => {
539
+ const def = config.types[name];
540
+ if (!def) throw new CrmInputError(`unknown record type "${name}"`);
541
+ return def;
542
+ };
543
+ return {
544
+ config,
545
+ schema: CRM_SCHEMA,
546
+ rules: CRM_RULES,
547
+ type,
548
+ prepare: (name, input, existing) => prepare(type(name), input, existing),
549
+ canTransition: (name, record, to) => canTransition(type(name), record, to),
550
+ initialStage: (name) => initialStage(type(name)),
551
+ stageIndex: (name, stage) => stageIndexOf(type(name), stage)
552
+ };
553
+ }
554
+
555
+ // src/deps.ts
556
+ function resolveDeps(deps) {
557
+ return {
558
+ crm: deps.crm,
559
+ db: deps.db,
560
+ now: deps.now ?? Date.now,
561
+ newId: deps.newId ?? (() => crypto.randomUUID())
562
+ };
563
+ }
564
+
565
+ // src/query.ts
566
+ function resolveSortColumn(crm, type, field) {
567
+ if (SORTABLE_COLUMNS.includes(field)) return field;
568
+ const slot = crm.type(type).fields[field]?.slot;
569
+ if (slot) return slot;
570
+ throw new CrmInputError(
571
+ `cannot sort by "${field}" \u2014 not a promoted column or a slotted field of ${type}`
572
+ );
573
+ }
574
+ function slotFor(crm, type, field) {
575
+ const slot = crm.type(type).fields[field]?.slot;
576
+ if (!slot) throw new CrmInputError(`cannot filter by "${field}" \u2014 not a slotted field of ${type}`);
577
+ return slot;
578
+ }
579
+ function inOrEq(values) {
580
+ return values.length === 1 ? values[0] : { $in: values };
581
+ }
582
+ function compileList(crm, params, tagRecordIds) {
583
+ crm.type(params.type);
584
+ const and = [{ type: params.type }, { archived: params.archived ?? false }];
585
+ if (params.stage?.length) and.push({ stage: inOrEq(params.stage) });
586
+ if (params.emailStatus?.length) and.push({ emailStatus: inOrEq(params.emailStatus) });
587
+ if (params.billingStatus?.length) and.push({ billingStatus: inOrEq(params.billingStatus) });
588
+ if (params.ownerId) and.push({ ownerId: params.ownerId });
589
+ if (tagRecordIds) and.push({ id: { $in: tagRecordIds } });
590
+ for (const [field, filter] of Object.entries(params.fields ?? {})) {
591
+ if (filter == null) continue;
592
+ const slot = slotFor(crm, params.type, field);
593
+ if (filter.eq !== void 0) and.push({ [slot]: filter.eq });
594
+ if (filter.in !== void 0) and.push({ [slot]: { $in: filter.in } });
595
+ if (filter.gte !== void 0) and.push({ [slot]: { $gte: filter.gte } });
596
+ if (filter.lte !== void 0) and.push({ [slot]: { $lte: filter.lte } });
597
+ }
598
+ const sort = params.sort ?? { field: "createdAt", dir: "desc" };
599
+ if (sort.dir !== "asc" && sort.dir !== "desc") throw new CrmInputError("sort.dir must be asc|desc");
600
+ const column = resolveSortColumn(crm, params.type, sort.field);
601
+ const limit = Math.min(Math.max(params.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);
602
+ const offset = Math.max(params.offset ?? 0, 0);
603
+ const search = params.search?.trim();
604
+ return {
605
+ opts: {
606
+ where: { and },
607
+ order: { [column]: sort.dir },
608
+ limit,
609
+ offset,
610
+ ...search ? { search } : {}
611
+ },
612
+ limit,
613
+ offset
614
+ };
615
+ }
616
+
617
+ // src/rank.ts
618
+ var RANK_STEP = 1024;
619
+ var RANK_EPSILON = 2 ** -20;
620
+ function rankBetween(before, after) {
621
+ if (before == null && after == null) return RANK_STEP;
622
+ if (before == null) return after - RANK_STEP;
623
+ if (after == null) return before + RANK_STEP;
624
+ if (after <= before)
625
+ throw new CrmInputError(`rankBetween: after (${after}) must exceed before (${before})`);
626
+ return before + (after - before) / 2;
627
+ }
628
+ function needsRebalance(before, after) {
629
+ return after - before < RANK_EPSILON;
630
+ }
631
+ function rebalancePlan(orderedIds) {
632
+ return orderedIds.map((id, i) => ({ id, rank: (i + 1) * RANK_STEP }));
633
+ }
634
+
635
+ // src/consent.ts
636
+ var TABLE = {
637
+ subscribed: {
638
+ "unsubscribe.token": "unsubscribed",
639
+ "unsubscribe.oneclick": "unsubscribed",
640
+ "bounce.hard": "bounced",
641
+ "admin.suppress": "suppressed",
642
+ "admin.resubscribe": "subscribed",
643
+ "contact.optin": "subscribed"
644
+ },
645
+ unsubscribed: {
646
+ "unsubscribe.token": "unsubscribed",
647
+ "unsubscribe.oneclick": "unsubscribed",
648
+ "bounce.hard": "bounced",
649
+ "admin.suppress": "suppressed",
650
+ "contact.optin": "subscribed"
651
+ // no admin.resubscribe: undoing an unsubscribe needs the contact's opt-in
652
+ },
653
+ bounced: {
654
+ "unsubscribe.token": "unsubscribed",
655
+ "unsubscribe.oneclick": "unsubscribed",
656
+ "bounce.hard": "bounced",
657
+ "admin.suppress": "suppressed",
658
+ "admin.resubscribe": "subscribed",
659
+ // admin says the address was fixed
660
+ "contact.optin": "subscribed"
661
+ },
662
+ suppressed: {
663
+ // sticky: everything except an explicit admin release keeps suppression
664
+ "unsubscribe.token": "suppressed",
665
+ "unsubscribe.oneclick": "suppressed",
666
+ "bounce.hard": "suppressed",
667
+ "admin.suppress": "suppressed",
668
+ "admin.resubscribe": "subscribed",
669
+ "contact.optin": "suppressed"
670
+ }
671
+ };
672
+ function applyConsentEvent(current, event) {
673
+ const next = TABLE[current]?.[event];
674
+ if (next === void 0)
675
+ return { error: `cannot ${event} a ${current} channel \u2014 requires the contact's own opt-in` };
676
+ return { state: next };
677
+ }
678
+ function canEmail(consent, cls) {
679
+ if (consent === "suppressed" || consent === "bounced") return false;
680
+ if (consent === "unsubscribed") return cls === "transactional";
681
+ return true;
682
+ }
683
+
684
+ // src/template.ts
685
+ var TOKEN_RE = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
686
+ function renderTemplate(template, vars) {
687
+ return template.replace(TOKEN_RE, (_, name) => vars[name] ?? "");
688
+ }
689
+ function templateVars(template) {
690
+ const seen = /* @__PURE__ */ new Set();
691
+ for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1]);
692
+ return [...seen];
693
+ }
694
+ function lintTemplate(template, knownVars) {
695
+ const used = templateVars(template);
696
+ const known = new Set(knownVars);
697
+ return {
698
+ unknown: used.filter((v) => !known.has(v)),
699
+ unused: knownVars.filter((v) => !used.includes(v))
700
+ };
701
+ }
702
+
703
+ // src/channels.ts
704
+ var channelKey = (recordId, kind, value) => `${recordId}:${kind}:${value}`;
705
+ function foldEmailStatus(consent) {
706
+ return consent === null ? "none" : consent === "subscribed" ? "ok" : consent;
707
+ }
708
+ function rowToChannel(row) {
709
+ return row;
710
+ }
711
+ async function listChannels(deps, recordId) {
712
+ const { db } = resolveDeps(deps);
713
+ const result = await db.query({
714
+ [CRM_NS.channel]: { $: { where: { recordId }, order: { createdAt: "asc" }, limit: 100 } }
715
+ });
716
+ return (result[CRM_NS.channel] ?? []).map(rowToChannel);
717
+ }
718
+ function emailChannelOps(deps, recordId, email, existing) {
719
+ const { now, newId } = resolveDeps(deps);
720
+ const ops = [];
721
+ const current = existing.filter((c) => c.kind === "email" && c.isPrimary);
722
+ const match = email ? existing.find((c) => c.kind === "email" && c.value === email) : void 0;
723
+ for (const old of current)
724
+ if (old !== match) ops.push({ t: "update", ns: CRM_NS.channel, id: old.id, attrs: { isPrimary: false } });
725
+ if (email === null) return { ops, emailStatus: "none" };
726
+ if (match) {
727
+ if (!match.isPrimary)
728
+ ops.push({ t: "update", ns: CRM_NS.channel, id: match.id, attrs: { isPrimary: true } });
729
+ return { ops, emailStatus: foldEmailStatus(match.consent) };
730
+ }
731
+ const key = channelKey(recordId, "email", email);
732
+ ops.push({
733
+ t: "update",
734
+ ns: CRM_NS.channel,
735
+ id: { ns: CRM_NS.channel, attr: "key", value: key },
736
+ attrs: {
737
+ key,
738
+ recordId,
739
+ kind: "email",
740
+ value: email,
741
+ isPrimary: true,
742
+ consent: "subscribed",
743
+ consentAt: now(),
744
+ consentSource: "record-write",
745
+ unsubscribeToken: newId(),
746
+ createdAt: now()
747
+ }
748
+ });
749
+ return { ops, emailStatus: "ok" };
750
+ }
751
+ async function applyConsent(deps, opts) {
752
+ const { db, now } = resolveDeps(deps);
753
+ const where = opts.token ? { unsubscribeToken: opts.token } : opts.channelId ? { id: opts.channelId } : null;
754
+ if (!where) throw new CrmInputError("token or channelId required");
755
+ const result = await db.query({ [CRM_NS.channel]: { $: { where, limit: 1 } } });
756
+ const row = (result[CRM_NS.channel] ?? [])[0];
757
+ if (!row) throw new CrmNotFoundError("contact channel");
758
+ const channel = rowToChannel(row);
759
+ const outcome = applyConsentEvent(channel.consent, opts.event);
760
+ if ("error" in outcome) throw new CrmInputError(outcome.error);
761
+ const ops = [
762
+ {
763
+ t: "update",
764
+ ns: CRM_NS.channel,
765
+ id: channel.id,
766
+ attrs: { consent: outcome.state, consentAt: now(), consentSource: opts.event }
767
+ }
768
+ ];
769
+ if (channel.isPrimary && channel.kind === "email")
770
+ ops.push({
771
+ t: "update",
772
+ ns: CRM_NS.record,
773
+ id: channel.recordId,
774
+ attrs: { emailStatus: foldEmailStatus(outcome.state), updatedAt: now() }
775
+ });
776
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
777
+ return { state: outcome.state, recordId: channel.recordId, duplicate };
778
+ }
779
+
780
+ // src/records.ts
781
+ function rowToRecord(row) {
782
+ const record = row;
783
+ return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? "" };
784
+ }
785
+ async function getRecord(deps, id) {
786
+ const { db } = resolveDeps(deps);
787
+ const result = await db.query({ [CRM_NS.record]: { $: { where: { id }, limit: 1 } } });
788
+ const row = (result[CRM_NS.record] ?? [])[0];
789
+ return row ? rowToRecord(row) : null;
790
+ }
791
+ async function mustGetRecord(deps, id) {
792
+ const record = await getRecord(deps, id);
793
+ if (!record) throw new CrmNotFoundError("record");
794
+ return record;
795
+ }
796
+ async function listRecords(deps, params) {
797
+ const { crm, db } = resolveDeps(deps);
798
+ let tagRecordIds;
799
+ if (params.tag) {
800
+ const tag = params.tag.trim().toLowerCase();
801
+ const tagResult = await db.query({ [CRM_NS.tag]: { $: { where: { tag }, limit: 1e3 } } });
802
+ tagRecordIds = (tagResult[CRM_NS.tag] ?? []).map((row) => row["recordId"]);
803
+ if (tagRecordIds.length === 0)
804
+ return { records: [], total: 0, limit: params.limit ?? 0, offset: params.offset ?? 0 };
805
+ }
806
+ const { opts, limit, offset } = compileList(crm, params, tagRecordIds);
807
+ const [result, agg] = await Promise.all([
808
+ db.query({ [CRM_NS.record]: { $: opts } }),
809
+ db.aggregate(
810
+ CRM_NS.record,
811
+ { count: true },
812
+ opts.search ? { where: opts.where, search: opts.search } : { where: opts.where }
813
+ )
814
+ ]);
815
+ return {
816
+ records: (result[CRM_NS.record] ?? []).map(rowToRecord),
817
+ total: agg.count ?? 0,
818
+ limit,
819
+ offset
820
+ };
821
+ }
822
+ function scoreOf(deps, type, candidate) {
823
+ const def = resolveDeps(deps).crm.type(type);
824
+ const wantsScore = def.facets?.rank === "score" || def.facets?.rank === "both";
825
+ if (!wantsScore || !def.scorer) return void 0;
826
+ return def.scorer(candidate);
827
+ }
828
+ async function createRecord(deps, opts) {
829
+ const { crm, db, now, newId } = resolveDeps(deps);
830
+ const prepared = crm.prepare(opts.type, opts.input);
831
+ if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
832
+ const id = newId();
833
+ const at = now();
834
+ const stage = opts.stage ?? crm.initialStage(opts.type);
835
+ const attrs = {
836
+ type: opts.type,
837
+ ...prepared.attrs,
838
+ archived: false,
839
+ rank: at,
840
+ createdAt: at,
841
+ updatedAt: at
842
+ };
843
+ if (opts.ownerId != null) attrs.ownerId = opts.ownerId;
844
+ if (stage != null) {
845
+ attrs.stage = stage;
846
+ attrs.stageIndex = crm.stageIndex(opts.type, stage);
847
+ attrs.stageChangedAt = at;
848
+ }
849
+ const ops = [];
850
+ const email = prepared.attrs["primaryEmail"] ?? null;
851
+ if (crm.type(opts.type).emailField) {
852
+ const channel = emailChannelOps(deps, id, email, []);
853
+ attrs.emailStatus = channel.emailStatus;
854
+ ops.push(...channel.ops);
855
+ } else {
856
+ attrs.emailStatus = "none";
857
+ }
858
+ const candidate = { id, ...attrs };
859
+ const score = scoreOf(deps, opts.type, candidate);
860
+ if (score !== void 0) attrs.score = score;
861
+ ops.unshift({ t: "update", ns: CRM_NS.record, id, attrs });
862
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
863
+ return { id, duplicate, record: { id, ...attrs } };
864
+ }
865
+ async function updateRecord(deps, opts) {
866
+ const { crm, db, now } = resolveDeps(deps);
867
+ const existing = await mustGetRecord(deps, opts.id);
868
+ const prepared = crm.prepare(existing.type, opts.input, existing);
869
+ if (!prepared.ok) throw new CrmInputError("invalid input", prepared.errors);
870
+ const attrs = { ...prepared.attrs, updatedAt: now() };
871
+ if (opts.ownerId !== void 0) attrs.ownerId = opts.ownerId;
872
+ const ops = [];
873
+ if (crm.type(existing.type).emailField) {
874
+ const nextEmail = prepared.attrs["primaryEmail"] ?? null;
875
+ if (nextEmail !== (existing.primaryEmail ?? null)) {
876
+ const channels = await listChannels(deps, existing.id);
877
+ const channel = emailChannelOps(deps, existing.id, nextEmail, channels);
878
+ attrs.emailStatus = channel.emailStatus;
879
+ ops.push(...channel.ops);
880
+ }
881
+ }
882
+ const candidate = { ...existing, ...attrs };
883
+ const score = scoreOf(deps, existing.type, candidate);
884
+ if (score !== void 0) attrs.score = score;
885
+ ops.unshift({ t: "update", ns: CRM_NS.record, id: existing.id, attrs });
886
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
887
+ return { record: { ...existing, ...attrs }, duplicate };
888
+ }
889
+ async function setArchived(deps, opts) {
890
+ const { db, now } = resolveDeps(deps);
891
+ await mustGetRecord(deps, opts.id);
892
+ const at = now();
893
+ const attrs = opts.archived ? { archived: true, archivedAt: at, updatedAt: at } : { archived: false, archivedAt: null, updatedAt: at };
894
+ const { duplicate } = await db.transact(
895
+ [{ t: "update", ns: CRM_NS.record, id: opts.id, attrs }],
896
+ { mutationId: opts.mutationId }
897
+ );
898
+ return { duplicate };
899
+ }
900
+
901
+ // src/stage-rank.ts
902
+ async function setStage(deps, opts) {
903
+ const { crm, db, now, newId } = resolveDeps(deps);
904
+ const record = await mustGetRecord(deps, opts.id);
905
+ const blocked = crm.canTransition(record.type, record, opts.to);
906
+ if (blocked) throw new CrmInputError(blocked);
907
+ const at = now();
908
+ const attrs = {
909
+ stage: opts.to,
910
+ stageIndex: crm.stageIndex(record.type, opts.to),
911
+ stageChangedAt: at,
912
+ updatedAt: at
913
+ };
914
+ const ops = [
915
+ { t: "update", ns: CRM_NS.record, id: record.id, attrs },
916
+ {
917
+ t: "update",
918
+ ns: CRM_NS.activity,
919
+ id: newId(),
920
+ attrs: {
921
+ recordId: record.id,
922
+ kind: "stage_change",
923
+ body: `${record.stage ?? "(none)"} \u2192 ${opts.to}`,
924
+ authorId: opts.authorId,
925
+ createdAt: at
926
+ }
927
+ }
928
+ ];
929
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
930
+ const updated = { ...record, ...attrs };
931
+ return {
932
+ record: updated,
933
+ from: record.stage ?? null,
934
+ duplicate,
935
+ hook: crm.type(record.type).onTransition?.[opts.to]
936
+ };
937
+ }
938
+ async function setRank(deps, opts) {
939
+ const { db, now } = resolveDeps(deps);
940
+ const record = await mustGetRecord(deps, opts.id);
941
+ const neighborIds = [opts.beforeId, opts.afterId].filter((v) => v != null);
942
+ const neighbors = /* @__PURE__ */ new Map();
943
+ if (neighborIds.length > 0) {
944
+ const result = await db.query({
945
+ [CRM_NS.record]: { $: { where: { id: { $in: neighborIds } }, limit: 2 } }
946
+ });
947
+ for (const row of result[CRM_NS.record] ?? []) {
948
+ const neighbor = rowToRecord(row);
949
+ if (neighbor.type !== record.type)
950
+ throw new CrmInputError("neighbors must be records of the same type");
951
+ neighbors.set(neighbor.id, neighbor);
952
+ }
953
+ }
954
+ const rankOf = (id) => {
955
+ if (id == null) return void 0;
956
+ const neighbor = neighbors.get(id);
957
+ if (!neighbor) throw new CrmInputError(`neighbor ${id} not found`);
958
+ if (neighbor.rank == null)
959
+ throw new CrmInputError(`neighbor ${id} has no rank \u2014 run a rebalance first`);
960
+ return neighbor.rank;
961
+ };
962
+ const before = rankOf(opts.beforeId);
963
+ const after = rankOf(opts.afterId);
964
+ const rank = rankBetween(before, after);
965
+ const { duplicate } = await db.transact(
966
+ [{ t: "update", ns: CRM_NS.record, id: record.id, attrs: { rank, updatedAt: now() } }],
967
+ { mutationId: opts.mutationId }
968
+ );
969
+ return {
970
+ rank,
971
+ rebalanceNeeded: before != null && after != null && needsRebalance(before, after),
972
+ duplicate
973
+ };
974
+ }
975
+ async function rebalanceRanks(deps, opts) {
976
+ const { crm, db, now } = resolveDeps(deps);
977
+ crm.type(opts.type);
978
+ const result = await db.query({
979
+ [CRM_NS.record]: {
980
+ $: {
981
+ where: { and: [{ type: opts.type }, { archived: false }] },
982
+ order: { rank: "asc" },
983
+ limit: 1e3
984
+ }
985
+ }
986
+ });
987
+ const ids = (result[CRM_NS.record] ?? []).map((row) => row.id);
988
+ const at = now();
989
+ const ops = rebalancePlan(ids).map(({ id, rank }) => ({
990
+ t: "update",
991
+ ns: CRM_NS.record,
992
+ id,
993
+ attrs: { rank, updatedAt: at }
994
+ }));
995
+ if (ops.length === 0) return { count: 0, duplicate: false };
996
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
997
+ return { count: ops.length, duplicate };
998
+ }
999
+
1000
+ // src/tags-links.ts
1001
+ function normalizeTag(raw) {
1002
+ const tag = raw.trim().toLowerCase();
1003
+ if (tag.length === 0 || tag.length > 64) throw new CrmInputError("tag must be 1\u201364 characters");
1004
+ return tag;
1005
+ }
1006
+ async function addTag(deps, opts) {
1007
+ const { db, now } = resolveDeps(deps);
1008
+ const tag = normalizeTag(opts.tag);
1009
+ await mustGetRecord(deps, opts.recordId);
1010
+ const key = `${opts.recordId}:${tag}`;
1011
+ const { duplicate } = await db.transact(
1012
+ [
1013
+ {
1014
+ t: "update",
1015
+ ns: CRM_NS.tag,
1016
+ id: { ns: CRM_NS.tag, attr: "key", value: key },
1017
+ attrs: { key, recordId: opts.recordId, tag, createdAt: now() }
1018
+ }
1019
+ ],
1020
+ { mutationId: opts.mutationId }
1021
+ );
1022
+ return { tag, duplicate };
1023
+ }
1024
+ async function removeTag(deps, opts) {
1025
+ const { db } = resolveDeps(deps);
1026
+ const tag = normalizeTag(opts.tag);
1027
+ const { duplicate } = await db.transact(
1028
+ [{ t: "delete", ns: CRM_NS.tag, id: { ns: CRM_NS.tag, attr: "key", value: `${opts.recordId}:${tag}` } }],
1029
+ { mutationId: opts.mutationId }
1030
+ );
1031
+ return { duplicate };
1032
+ }
1033
+ async function listTags(deps, recordId) {
1034
+ const { db } = resolveDeps(deps);
1035
+ const result = await db.query({
1036
+ [CRM_NS.tag]: { $: { where: { recordId }, order: { createdAt: "asc" }, limit: 200 } }
1037
+ });
1038
+ return (result[CRM_NS.tag] ?? []).map((row) => row);
1039
+ }
1040
+ async function addLink(deps, opts) {
1041
+ const { crm, db, now } = resolveDeps(deps);
1042
+ const rel = crm.config.relations?.[opts.relation];
1043
+ if (!rel) throw new CrmInputError(`unknown relation "${opts.relation}"`);
1044
+ if (opts.fromId === opts.toId) throw new CrmInputError("cannot link a record to itself");
1045
+ const result = await db.query({
1046
+ [CRM_NS.record]: { $: { where: { id: { $in: [opts.fromId, opts.toId] } }, limit: 2 } }
1047
+ });
1048
+ const byId = new Map((result[CRM_NS.record] ?? []).map((row) => [row.id, rowToRecord(row)]));
1049
+ const from = byId.get(opts.fromId);
1050
+ const to = byId.get(opts.toId);
1051
+ if (!from || !to) throw new CrmInputError("both records must exist");
1052
+ if (from.type !== rel.from || to.type !== rel.to)
1053
+ throw new CrmInputError(
1054
+ `relation "${opts.relation}" links ${rel.from} \u2192 ${rel.to}, got ${from.type} \u2192 ${to.type}`
1055
+ );
1056
+ const key = `${opts.fromId}:${opts.relation}:${opts.toId}`;
1057
+ const { duplicate } = await db.transact(
1058
+ [
1059
+ {
1060
+ t: "update",
1061
+ ns: CRM_NS.link,
1062
+ id: { ns: CRM_NS.link, attr: "key", value: key },
1063
+ attrs: { key, fromId: opts.fromId, toId: opts.toId, relation: opts.relation, createdAt: now() }
1064
+ }
1065
+ ],
1066
+ { mutationId: opts.mutationId }
1067
+ );
1068
+ return { duplicate };
1069
+ }
1070
+ async function removeLink(deps, opts) {
1071
+ const { db } = resolveDeps(deps);
1072
+ const key = `${opts.fromId}:${opts.relation}:${opts.toId}`;
1073
+ const { duplicate } = await db.transact(
1074
+ [{ t: "delete", ns: CRM_NS.link, id: { ns: CRM_NS.link, attr: "key", value: key } }],
1075
+ { mutationId: opts.mutationId }
1076
+ );
1077
+ return { duplicate };
1078
+ }
1079
+ async function listLinks(deps, recordId) {
1080
+ const { db } = resolveDeps(deps);
1081
+ const result = await db.query({
1082
+ [CRM_NS.link]: {
1083
+ $: { where: { or: [{ fromId: recordId }, { toId: recordId }] }, order: { createdAt: "asc" }, limit: 200 }
1084
+ }
1085
+ });
1086
+ return (result[CRM_NS.link] ?? []).map((row) => row);
1087
+ }
1088
+
1089
+ // src/activities.ts
1090
+ var rowToActivity = (row) => row;
1091
+ async function addActivity(deps, opts) {
1092
+ const { db, now, newId } = resolveDeps(deps);
1093
+ if (!ACTIVITY_KINDS.includes(opts.kind)) throw new CrmInputError(`unknown kind "${opts.kind}"`);
1094
+ const body = opts.body.trim();
1095
+ if (!body) throw new CrmInputError("body is required");
1096
+ await mustGetRecord(deps, opts.recordId);
1097
+ const id = newId();
1098
+ const attrs = {
1099
+ recordId: opts.recordId,
1100
+ kind: opts.kind,
1101
+ body,
1102
+ authorId: opts.authorId,
1103
+ createdAt: now()
1104
+ };
1105
+ if (opts.kind === "task") {
1106
+ attrs.status = "open";
1107
+ if (opts.dueAt != null) attrs.dueAt = opts.dueAt;
1108
+ if (opts.assigneeId != null) attrs.assigneeId = opts.assigneeId;
1109
+ if (opts.waitingOn != null) attrs.waitingOn = opts.waitingOn;
1110
+ }
1111
+ if (opts.meta) attrs.meta = opts.meta;
1112
+ const { duplicate } = await db.transact([{ t: "update", ns: CRM_NS.activity, id, attrs }], {
1113
+ mutationId: opts.mutationId
1114
+ });
1115
+ return { id, duplicate };
1116
+ }
1117
+ async function updateTask(deps, opts) {
1118
+ const { db, now } = resolveDeps(deps);
1119
+ const result = await db.query({ [CRM_NS.activity]: { $: { where: { id: opts.id }, limit: 1 } } });
1120
+ const row = (result[CRM_NS.activity] ?? [])[0];
1121
+ if (!row) throw new CrmNotFoundError("activity");
1122
+ const activity = rowToActivity(row);
1123
+ if (activity.kind !== "task") throw new CrmInputError("only tasks can be updated");
1124
+ const attrs = {};
1125
+ if (opts.status !== void 0) {
1126
+ if (!TASK_STATUSES.includes(opts.status)) throw new CrmInputError(`unknown status "${opts.status}"`);
1127
+ attrs.status = opts.status;
1128
+ attrs.completedAt = opts.status === "done" ? now() : null;
1129
+ }
1130
+ if (opts.dueAt !== void 0) attrs.dueAt = opts.dueAt;
1131
+ if (opts.assigneeId !== void 0) attrs.assigneeId = opts.assigneeId;
1132
+ if (opts.waitingOn !== void 0) attrs.waitingOn = opts.waitingOn;
1133
+ if (opts.body !== void 0) {
1134
+ const body = opts.body.trim();
1135
+ if (!body) throw new CrmInputError("body is required");
1136
+ attrs.body = body;
1137
+ }
1138
+ if (Object.keys(attrs).length === 0) throw new CrmInputError("nothing to update");
1139
+ const { duplicate } = await db.transact([{ t: "update", ns: CRM_NS.activity, id: opts.id, attrs }], {
1140
+ mutationId: opts.mutationId
1141
+ });
1142
+ return { activity: { ...activity, ...attrs }, duplicate };
1143
+ }
1144
+ async function listActivities(deps, opts) {
1145
+ const { db } = resolveDeps(deps);
1146
+ const where = opts.kind ? { and: [{ recordId: opts.recordId }, { kind: opts.kind }] } : { recordId: opts.recordId };
1147
+ const result = await db.query({
1148
+ [CRM_NS.activity]: {
1149
+ $: {
1150
+ where,
1151
+ order: { createdAt: "desc" },
1152
+ limit: Math.min(opts.limit ?? 50, 200),
1153
+ offset: opts.offset ?? 0
1154
+ }
1155
+ }
1156
+ });
1157
+ return (result[CRM_NS.activity] ?? []).map(rowToActivity);
1158
+ }
1159
+ async function listTasks(deps, opts = {}) {
1160
+ const { db } = resolveDeps(deps);
1161
+ const and = [{ kind: "task" }];
1162
+ const statuses = opts.status ?? ["open", "waiting"];
1163
+ and.push({ status: statuses.length === 1 ? statuses[0] : { $in: statuses } });
1164
+ if (opts.assigneeId) and.push({ assigneeId: opts.assigneeId });
1165
+ if (opts.dueBefore != null) and.push({ dueAt: { $lte: opts.dueBefore } });
1166
+ const result = await db.query({
1167
+ [CRM_NS.activity]: {
1168
+ $: {
1169
+ where: { and },
1170
+ order: { dueAt: "asc" },
1171
+ limit: Math.min(opts.limit ?? 50, 200),
1172
+ offset: opts.offset ?? 0
1173
+ }
1174
+ }
1175
+ });
1176
+ return (result[CRM_NS.activity] ?? []).map(rowToActivity);
1177
+ }
1178
+
1179
+ // src/views.ts
1180
+ var rowToView = (row) => {
1181
+ const view = row;
1182
+ return { ...view, filters: view.filters ?? {}, columns: view.columns ?? [] };
1183
+ };
1184
+ function checkSpec(deps, spec) {
1185
+ const { crm } = resolveDeps(deps);
1186
+ if (!spec.name.trim()) throw new CrmInputError("view name is required");
1187
+ if (!Array.isArray(spec.columns) || spec.columns.some((c) => typeof c !== "string"))
1188
+ throw new CrmInputError("columns must be a string array");
1189
+ compileList(crm, { type: spec.type, ...spec.filters, sort: spec.sort ?? void 0 });
1190
+ }
1191
+ async function saveView(deps, opts) {
1192
+ const { db, now, newId } = resolveDeps(deps);
1193
+ checkSpec(deps, opts.spec);
1194
+ const id = newId();
1195
+ const at = now();
1196
+ const { duplicate } = await db.transact(
1197
+ [
1198
+ {
1199
+ t: "update",
1200
+ ns: CRM_NS.view,
1201
+ id,
1202
+ attrs: {
1203
+ name: opts.spec.name.trim(),
1204
+ type: opts.spec.type,
1205
+ ownerId: opts.ownerId,
1206
+ shared: opts.spec.shared,
1207
+ filters: opts.spec.filters,
1208
+ sort: opts.spec.sort,
1209
+ columns: opts.spec.columns,
1210
+ createdAt: at,
1211
+ updatedAt: at
1212
+ }
1213
+ }
1214
+ ],
1215
+ { mutationId: opts.mutationId }
1216
+ );
1217
+ return { id, duplicate };
1218
+ }
1219
+ async function mustGetView(deps, id) {
1220
+ const { db } = resolveDeps(deps);
1221
+ const result = await db.query({ [CRM_NS.view]: { $: { where: { id }, limit: 1 } } });
1222
+ const row = (result[CRM_NS.view] ?? [])[0];
1223
+ if (!row) throw new CrmNotFoundError("view");
1224
+ return rowToView(row);
1225
+ }
1226
+ async function updateView(deps, opts) {
1227
+ const { db, now } = resolveDeps(deps);
1228
+ const existing = await mustGetView(deps, opts.id);
1229
+ if (existing.ownerId && existing.ownerId !== opts.ownerId)
1230
+ throw new CrmInputError("only the view's owner may change it");
1231
+ const merged = {
1232
+ name: opts.spec.name ?? existing.name,
1233
+ type: opts.spec.type ?? existing.type,
1234
+ filters: opts.spec.filters ?? existing.filters,
1235
+ sort: opts.spec.sort !== void 0 ? opts.spec.sort : existing.sort,
1236
+ columns: opts.spec.columns ?? existing.columns,
1237
+ shared: opts.spec.shared ?? existing.shared
1238
+ };
1239
+ checkSpec(deps, merged);
1240
+ const attrs = {
1241
+ name: merged.name.trim(),
1242
+ type: merged.type,
1243
+ shared: merged.shared,
1244
+ filters: merged.filters,
1245
+ sort: merged.sort,
1246
+ columns: merged.columns,
1247
+ updatedAt: now()
1248
+ };
1249
+ const { duplicate } = await db.transact([{ t: "update", ns: CRM_NS.view, id: opts.id, attrs }], {
1250
+ mutationId: opts.mutationId
1251
+ });
1252
+ return { view: { ...existing, ...attrs }, duplicate };
1253
+ }
1254
+ async function deleteView(deps, opts) {
1255
+ const { db } = resolveDeps(deps);
1256
+ const existing = await mustGetView(deps, opts.id);
1257
+ if (existing.ownerId && existing.ownerId !== opts.ownerId)
1258
+ throw new CrmInputError("only the view's owner may delete it");
1259
+ const { duplicate } = await db.transact([{ t: "delete", ns: CRM_NS.view, id: opts.id }], {
1260
+ mutationId: opts.mutationId
1261
+ });
1262
+ return { duplicate };
1263
+ }
1264
+ async function listViews(deps, opts) {
1265
+ const { db } = resolveDeps(deps);
1266
+ const visible = { or: [{ shared: true }, { ownerId: opts.viewerId }] };
1267
+ const where = opts.type ? { and: [{ type: opts.type }, visible] } : visible;
1268
+ const result = await db.query({
1269
+ [CRM_NS.view]: { $: { where, order: { createdAt: "asc" }, limit: 200 } }
1270
+ });
1271
+ return (result[CRM_NS.view] ?? []).map(rowToView);
1272
+ }
1273
+
1274
+ // src/config-store.ts
1275
+ function defaultTemplates(crm) {
1276
+ const out = {};
1277
+ for (const [id, spec] of Object.entries(crm.config.templates ?? {})) {
1278
+ out[id] = spec.defaults ? { subject: spec.defaults.subject, text: spec.defaults.text, enabled: true } : { subject: "", text: "", enabled: false };
1279
+ }
1280
+ return out;
1281
+ }
1282
+ var rowToConfig = (row) => {
1283
+ const config = row;
1284
+ return { ...config, emailTemplates: config.emailTemplates ?? {}, settings: config.settings ?? {} };
1285
+ };
1286
+ async function getConfig(deps) {
1287
+ const { db } = resolveDeps(deps);
1288
+ const result = await db.query({ [CRM_NS.config]: { $: { where: { key: CONFIG_KEY }, limit: 1 } } });
1289
+ const row = (result[CRM_NS.config] ?? [])[0];
1290
+ return row ? rowToConfig(row) : null;
1291
+ }
1292
+ async function saveConfig(deps, patch, opts = {}) {
1293
+ const { crm, db, now } = resolveDeps(deps);
1294
+ const declared = crm.config.templates ?? {};
1295
+ for (const [id, tpl] of Object.entries(patch.emailTemplates ?? {})) {
1296
+ if (!declared[id]) throw new CrmInputError(`unknown template "${id}"`);
1297
+ if (tpl.subject !== void 0 && typeof tpl.subject !== "string")
1298
+ throw new CrmInputError(`template "${id}": subject must be a string`);
1299
+ if (tpl.text !== void 0 && typeof tpl.text !== "string")
1300
+ throw new CrmInputError(`template "${id}": text must be a string`);
1301
+ if (tpl.enabled !== void 0 && typeof tpl.enabled !== "boolean")
1302
+ throw new CrmInputError(`template "${id}": enabled must be a boolean`);
1303
+ }
1304
+ const existing = await getConfig(deps);
1305
+ const base = existing ?? {
1306
+ id: "",
1307
+ key: CONFIG_KEY,
1308
+ emailTemplates: defaultTemplates(crm),
1309
+ settings: {},
1310
+ updatedAt: 0
1311
+ };
1312
+ const templates = { ...defaultTemplates(crm), ...base.emailTemplates };
1313
+ for (const [id, tpl] of Object.entries(patch.emailTemplates ?? {})) {
1314
+ const prev = templates[id] ?? { subject: "", text: "", enabled: false };
1315
+ templates[id] = { ...prev, ...tpl };
1316
+ }
1317
+ const merged = {
1318
+ ...base,
1319
+ notificationEmail: patch.notificationEmail !== void 0 ? patch.notificationEmail ?? void 0 : base.notificationEmail,
1320
+ replyTo: patch.replyTo !== void 0 ? patch.replyTo ?? void 0 : base.replyTo,
1321
+ debugEmail: patch.debugEmail !== void 0 ? patch.debugEmail ?? void 0 : base.debugEmail,
1322
+ emailTemplates: templates,
1323
+ settings: patch.settings !== void 0 ? patch.settings : base.settings,
1324
+ updatedAt: now()
1325
+ };
1326
+ const { duplicate } = await db.transact(
1327
+ [
1328
+ {
1329
+ t: "update",
1330
+ ns: CRM_NS.config,
1331
+ id: { ns: CRM_NS.config, attr: "key", value: CONFIG_KEY },
1332
+ attrs: {
1333
+ key: CONFIG_KEY,
1334
+ notificationEmail: merged.notificationEmail ?? null,
1335
+ replyTo: merged.replyTo ?? null,
1336
+ debugEmail: merged.debugEmail ?? null,
1337
+ emailTemplates: merged.emailTemplates,
1338
+ settings: merged.settings,
1339
+ updatedAt: merged.updatedAt
1340
+ }
1341
+ }
1342
+ ],
1343
+ { mutationId: opts.mutationId }
1344
+ );
1345
+ return { config: merged, duplicate };
1346
+ }
1347
+
1348
+ // src/email.ts
1349
+ async function sendTemplatedEmail(deps, opts) {
1350
+ const { crm, db, now, newId } = resolveDeps(deps);
1351
+ const spec = crm.config.templates?.[opts.templateId];
1352
+ if (!spec) return { sent: false, reason: "unknown_template" };
1353
+ const config = await getConfig(deps);
1354
+ const stored = config?.emailTemplates[opts.templateId] ?? null;
1355
+ if (!stored || !stored.subject && !stored.text) return { sent: false, reason: "no_template_copy" };
1356
+ if (!stored.enabled && !opts.force) return { sent: false, reason: "disabled" };
1357
+ const record = await mustGetRecord(deps, opts.recordId);
1358
+ const channels = await listChannels(deps, record.id);
1359
+ const channel = opts.channelId ? channels.find((c) => c.id === opts.channelId) : channels.find((c) => c.kind === "email" && c.isPrimary);
1360
+ if (!channel) return { sent: false, reason: "no_channel" };
1361
+ if (!canEmail(channel.consent, spec.class)) return { sent: false, reason: "blocked_by_consent" };
1362
+ const prior = await db.query({
1363
+ [CRM_NS.emailLog]: { $: { where: { dedupeKey: opts.dedupeKey }, limit: 10 } }
1364
+ });
1365
+ if ((prior[CRM_NS.emailLog] ?? []).some((row) => !row["error"] && row["transport"] === "sent"))
1366
+ return { sent: false, reason: "duplicate" };
1367
+ const vars = { ...opts.vars };
1368
+ const headers = {};
1369
+ if (spec.class === "marketing") {
1370
+ const unsubscribeUrl = `${opts.baseUrl}${opts.basePath ?? "/api/crm"}/unsubscribe?token=${channel.unsubscribeToken}`;
1371
+ vars["unsubscribeUrl"] = vars["unsubscribeUrl"] ?? unsubscribeUrl;
1372
+ headers["List-Unsubscribe"] = `<${unsubscribeUrl}>`;
1373
+ headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
1374
+ }
1375
+ let subject = renderTemplate(stored.subject, vars);
1376
+ const text = renderTemplate(stored.text, vars);
1377
+ let to = channel.value;
1378
+ let redirected = false;
1379
+ let logOnly = !deps.sender;
1380
+ if (opts.envName !== "production") {
1381
+ if (config?.debugEmail) {
1382
+ to = config.debugEmail;
1383
+ subject = `[dev] ${subject}`;
1384
+ redirected = true;
1385
+ } else {
1386
+ logOnly = true;
1387
+ }
1388
+ }
1389
+ const logRow = (extra, mutationId) => db.transact(
1390
+ [
1391
+ {
1392
+ t: "update",
1393
+ ns: CRM_NS.emailLog,
1394
+ id: newId(),
1395
+ attrs: {
1396
+ recordId: opts.recordId,
1397
+ channelId: channel.id,
1398
+ to,
1399
+ templateId: opts.templateId,
1400
+ subject,
1401
+ redirected,
1402
+ dedupeKey: opts.dedupeKey,
1403
+ sentAt: now(),
1404
+ ...extra
1405
+ }
1406
+ }
1407
+ ],
1408
+ { mutationId }
1409
+ );
1410
+ if (logOnly || !deps.sender) {
1411
+ await logRow({ transport: "log-only" }, `email-log:${opts.dedupeKey}`);
1412
+ return { sent: false, reason: "log_only", transport: "log-only" };
1413
+ }
1414
+ try {
1415
+ const receipt = await deps.sender.send({
1416
+ from: opts.from,
1417
+ to: [to],
1418
+ subject,
1419
+ text,
1420
+ ...config?.replyTo ? { replyTo: config.replyTo } : {},
1421
+ ...Object.keys(headers).length > 0 ? { headers } : {}
1422
+ });
1423
+ await logRow({ transport: "sent", messageId: receipt.messageId }, `email:${opts.dedupeKey}`);
1424
+ return { sent: true, transport: "sent" };
1425
+ } catch (error) {
1426
+ await logRow({ transport: "sent", error: error instanceof Error ? error.message : String(error) });
1427
+ return { sent: false, reason: "transport_error" };
1428
+ }
1429
+ }
1430
+ async function listEmailLog(deps, opts = {}) {
1431
+ const { db } = resolveDeps(deps);
1432
+ const result = await db.query({
1433
+ [CRM_NS.emailLog]: {
1434
+ $: {
1435
+ ...opts.recordId ? { where: { recordId: opts.recordId } } : {},
1436
+ order: { sentAt: "desc" },
1437
+ limit: Math.min(opts.limit ?? 50, 200),
1438
+ offset: opts.offset ?? 0
1439
+ }
1440
+ }
1441
+ });
1442
+ return result[CRM_NS.emailLog] ?? [];
1443
+ }
1444
+ async function recordCanEmail(deps, recordId, cls) {
1445
+ const channels = await listChannels(deps, recordId);
1446
+ const primary = channels.find((c) => c.kind === "email" && c.isPrimary);
1447
+ if (!primary) return false;
1448
+ return canEmail(primary.consent, cls);
1449
+ }
1450
+
1451
+ // src/facets/identity.ts
1452
+ async function linkIdentity(deps, opts) {
1453
+ const { db, now } = resolveDeps(deps);
1454
+ const record = await mustGetRecord(deps, opts.recordId);
1455
+ const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();
1456
+ if (!email) throw new CrmInputError("record has no email to match on");
1457
+ const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });
1458
+ const user = (result["$users"] ?? []).find((row) => !row["deleted"]);
1459
+ if (!user) return { linked: false };
1460
+ const { duplicate } = await db.transact(
1461
+ [
1462
+ {
1463
+ t: "update",
1464
+ ns: CRM_NS.record,
1465
+ id: record.id,
1466
+ attrs: { clerkUserId: user.id, updatedAt: now() }
1467
+ }
1468
+ ],
1469
+ { mutationId: opts.mutationId }
1470
+ );
1471
+ return { linked: true, clerkUserId: user.id, duplicate };
1472
+ }
1473
+
1474
+ // src/summary.ts
1475
+ async function typeSummary(deps, type) {
1476
+ const { crm, db } = resolveDeps(deps);
1477
+ const def = crm.type(type);
1478
+ const live = (extra) => ({
1479
+ where: { and: [{ type }, { archived: false }, ...extra] }
1480
+ });
1481
+ const stageIds = (def.pipeline?.stages ?? []).map((s) => s.id);
1482
+ const [total, openTasks, ...stageCounts] = await Promise.all([
1483
+ db.aggregate(CRM_NS.record, { count: true }, live([])),
1484
+ db.aggregate(CRM_NS.activity, { count: true }, {
1485
+ where: { and: [{ kind: "task" }, { status: { $in: ["open", "waiting"] } }] }
1486
+ }),
1487
+ ...stageIds.map((stage) => db.aggregate(CRM_NS.record, { count: true }, live([{ stage }])))
1488
+ ]);
1489
+ const stages = {};
1490
+ stageIds.forEach((stage, i) => {
1491
+ stages[stage] = stageCounts[i]?.count ?? 0;
1492
+ });
1493
+ return { type, total: total?.count ?? 0, stages, openTasks: openTasks?.count ?? 0 };
1494
+ }
1495
+
1496
+ // src/http.ts
1497
+ var json = (body, status = 200) => new Response(JSON.stringify(body), {
1498
+ status,
1499
+ headers: { "content-type": "application/json" }
1500
+ });
1501
+ var errorResponse = (error) => {
1502
+ if (error instanceof CrmInputError)
1503
+ return json({ error: error.message, ...error.fields ? { fields: error.fields } : {} }, 400);
1504
+ if (error instanceof CrmNotFoundError) return json({ error: error.message }, 404);
1505
+ return json({ error: "internal error" }, 500);
1506
+ };
1507
+ async function readJson(req) {
1508
+ let body;
1509
+ try {
1510
+ body = await req.json();
1511
+ } catch {
1512
+ throw new CrmInputError("invalid JSON body");
1513
+ }
1514
+ if (typeof body !== "object" || body === null || Array.isArray(body))
1515
+ throw new CrmInputError("body must be a JSON object");
1516
+ return body;
1517
+ }
1518
+ var csv = (value) => value ? value.split(",").map((v) => v.trim()).filter(Boolean) : void 0;
1519
+ var int = (value) => {
1520
+ if (value == null || value === "") return void 0;
1521
+ const n = Number(value);
1522
+ if (!Number.isInteger(n)) throw new CrmInputError(`not an integer: "${value}"`);
1523
+ return n;
1524
+ };
1525
+ function parseListParams(url) {
1526
+ const q = url.searchParams;
1527
+ const type = q.get("type");
1528
+ if (!type) throw new CrmInputError("type is required");
1529
+ const params = { type };
1530
+ const search = q.get("search");
1531
+ if (search) params.search = search;
1532
+ params.stage = csv(q.get("stage"));
1533
+ params.emailStatus = csv(q.get("emailStatus"));
1534
+ params.billingStatus = csv(q.get("billingStatus"));
1535
+ const ownerId = q.get("ownerId");
1536
+ if (ownerId) params.ownerId = ownerId;
1537
+ const tag = q.get("tag");
1538
+ if (tag) params.tag = tag;
1539
+ if (q.get("archived") === "true") params.archived = true;
1540
+ const sort = q.get("sort");
1541
+ if (sort) {
1542
+ const [field, dir] = sort.split(":");
1543
+ if (!field || dir !== "asc" && dir !== "desc")
1544
+ throw new CrmInputError('sort must be "field:asc" or "field:desc"');
1545
+ params.sort = { field, dir };
1546
+ }
1547
+ params.limit = int(q.get("limit"));
1548
+ params.offset = int(q.get("offset"));
1549
+ const fields = q.get("fields");
1550
+ if (fields) {
1551
+ try {
1552
+ params.fields = JSON.parse(fields);
1553
+ } catch {
1554
+ throw new CrmInputError("fields must be URL-encoded JSON");
1555
+ }
1556
+ }
1557
+ return params;
1558
+ }
1559
+ var escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
1560
+ function unsubscribePage(token, done) {
1561
+ const body = done ? "<p>You're unsubscribed. You can close this page.</p>" : `<form method="post"><input type="hidden" name="token" value="${escapeHtml(token)}"><p>Stop receiving these emails?</p><button type="submit">Unsubscribe</button></form>`;
1562
+ return new Response(
1563
+ `<!doctype html><meta charset="utf-8"><meta name="robots" content="noindex"><title>Unsubscribe</title><main style="font-family:system-ui;max-width:32rem;margin:4rem auto">${body}</main>`,
1564
+ { status: 200, headers: { "content-type": "text/html; charset=utf-8" } }
1565
+ );
1566
+ }
1567
+
1568
+ // src/routes/params.ts
1569
+ function str(body, key) {
1570
+ const value = body[key];
1571
+ if (typeof value !== "string" || value === "")
1572
+ throw new CrmInputError(`"${key}" must be a non-empty string`);
1573
+ return value;
1574
+ }
1575
+ function optStr(body, key) {
1576
+ const value = body[key];
1577
+ if (value === void 0 || value === null) return void 0;
1578
+ if (typeof value !== "string") throw new CrmInputError(`"${key}" must be a string`);
1579
+ return value;
1580
+ }
1581
+ function nullableStr(body, key) {
1582
+ const value = body[key];
1583
+ if (value === void 0) return void 0;
1584
+ if (value === null) return null;
1585
+ if (typeof value !== "string") throw new CrmInputError(`"${key}" must be a string or null`);
1586
+ return value;
1587
+ }
1588
+ function optNum(body, key) {
1589
+ const value = body[key];
1590
+ if (value === void 0 || value === null) return void 0;
1591
+ if (typeof value !== "number" || !Number.isFinite(value))
1592
+ throw new CrmInputError(`"${key}" must be a number`);
1593
+ return value;
1594
+ }
1595
+ function nullableNum(body, key) {
1596
+ const value = body[key];
1597
+ if (value === void 0) return void 0;
1598
+ if (value === null) return null;
1599
+ if (typeof value !== "number" || !Number.isFinite(value))
1600
+ throw new CrmInputError(`"${key}" must be a number or null`);
1601
+ return value;
1602
+ }
1603
+ function optBool(body, key) {
1604
+ const value = body[key];
1605
+ if (value === void 0 || value === null) return void 0;
1606
+ if (typeof value !== "boolean") throw new CrmInputError(`"${key}" must be a boolean`);
1607
+ return value;
1608
+ }
1609
+ function obj(body, key) {
1610
+ const value = body[key];
1611
+ if (typeof value !== "object" || value === null || Array.isArray(value))
1612
+ throw new CrmInputError(`"${key}" must be an object`);
1613
+ return value;
1614
+ }
1615
+ function optObj(body, key) {
1616
+ if (body[key] === void 0) return void 0;
1617
+ return obj(body, key);
1618
+ }
1619
+
1620
+ // src/routes/activities.ts
1621
+ async function handleRecordActivities(ctx, req, url, recordId) {
1622
+ if (req.method === "GET") {
1623
+ const activities = await listActivities(ctx.deps, {
1624
+ recordId,
1625
+ kind: url.searchParams.get("kind") ?? void 0,
1626
+ limit: numParam(url, "limit"),
1627
+ offset: numParam(url, "offset")
1628
+ });
1629
+ return json({ activities });
1630
+ }
1631
+ if (req.method === "POST") {
1632
+ const body = await readJson(req);
1633
+ const created = await addActivity(ctx.deps, {
1634
+ recordId,
1635
+ kind: str(body, "kind"),
1636
+ body: str(body, "body"),
1637
+ authorId: ctx.actor.userId,
1638
+ dueAt: optNum(body, "dueAt"),
1639
+ assigneeId: optStr(body, "assigneeId"),
1640
+ waitingOn: optStr(body, "waitingOn"),
1641
+ meta: optObj(body, "meta"),
1642
+ mutationId: optStr(body, "mutationId")
1643
+ });
1644
+ return json(created, 201);
1645
+ }
1646
+ return json({ error: "method not allowed" }, 405);
1647
+ }
1648
+ async function handleActivityItem(ctx, req, id) {
1649
+ if (req.method !== "PATCH") return json({ error: "method not allowed" }, 405);
1650
+ const body = await readJson(req);
1651
+ const status = optStr(body, "status");
1652
+ const result = await updateTask(ctx.deps, {
1653
+ id,
1654
+ status,
1655
+ dueAt: nullableNum(body, "dueAt"),
1656
+ assigneeId: nullableStr(body, "assigneeId"),
1657
+ waitingOn: nullableStr(body, "waitingOn"),
1658
+ body: optStr(body, "body"),
1659
+ mutationId: optStr(body, "mutationId")
1660
+ });
1661
+ return json(result);
1662
+ }
1663
+ async function handleTasks(ctx, req, url) {
1664
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
1665
+ const statusCsv = url.searchParams.get("status");
1666
+ const tasks = await listTasks(ctx.deps, {
1667
+ assigneeId: url.searchParams.get("assigneeId") ?? void 0,
1668
+ status: statusCsv ? statusCsv.split(",").filter(Boolean) : void 0,
1669
+ dueBefore: numParam(url, "dueBefore"),
1670
+ limit: numParam(url, "limit"),
1671
+ offset: numParam(url, "offset")
1672
+ });
1673
+ return json({ tasks });
1674
+ }
1675
+ function numParam(url, key) {
1676
+ const raw = url.searchParams.get(key);
1677
+ if (raw == null || raw === "") return void 0;
1678
+ const n = Number(raw);
1679
+ if (!Number.isFinite(n)) throw new CrmInputError(`"${key}" must be a number`);
1680
+ return n;
1681
+ }
1682
+
1683
+ // src/routes/actions.ts
1684
+ async function handleStage(ctx, req, id) {
1685
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1686
+ const body = await readJson(req);
1687
+ const moved = await setStage(ctx.deps, {
1688
+ id,
1689
+ to: str(body, "to"),
1690
+ authorId: ctx.actor.userId,
1691
+ mutationId: optStr(body, "mutationId")
1692
+ });
1693
+ let hookError;
1694
+ if (moved.hook && !moved.duplicate) {
1695
+ try {
1696
+ await moved.hook(moved.record);
1697
+ } catch (error) {
1698
+ hookError = error instanceof Error ? error.message : String(error);
1699
+ }
1700
+ }
1701
+ return json({
1702
+ record: moved.record,
1703
+ from: moved.from,
1704
+ duplicate: moved.duplicate,
1705
+ ...hookError ? { hookError } : {}
1706
+ });
1707
+ }
1708
+ async function handleRank(ctx, req, id) {
1709
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1710
+ const body = await readJson(req);
1711
+ const result = await setRank(ctx.deps, {
1712
+ id,
1713
+ beforeId: optStr(body, "beforeId"),
1714
+ afterId: optStr(body, "afterId"),
1715
+ mutationId: optStr(body, "mutationId")
1716
+ });
1717
+ return json(result);
1718
+ }
1719
+ async function handleTags(ctx, req, id, rest) {
1720
+ if (req.method === "POST" && rest.length === 0) {
1721
+ const body = await readJson(req);
1722
+ const result = await addTag(ctx.deps, {
1723
+ recordId: id,
1724
+ tag: str(body, "tag"),
1725
+ mutationId: optStr(body, "mutationId")
1726
+ });
1727
+ return json(result, 201);
1728
+ }
1729
+ if (req.method === "DELETE" && rest.length === 1) {
1730
+ const result = await removeTag(ctx.deps, { recordId: id, tag: decodeURIComponent(rest[0]) });
1731
+ return json(result);
1732
+ }
1733
+ return json({ error: "method not allowed" }, 405);
1734
+ }
1735
+ async function handleLinks(ctx, req, id) {
1736
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1737
+ const body = await readJson(req);
1738
+ const opts = {
1739
+ relation: str(body, "relation"),
1740
+ fromId: id,
1741
+ toId: str(body, "toId"),
1742
+ mutationId: optStr(body, "mutationId")
1743
+ };
1744
+ const result = optBool(body, "remove") ? await removeLink(ctx.deps, opts) : await addLink(ctx.deps, opts);
1745
+ return json(result);
1746
+ }
1747
+ async function handleLinkIdentity(ctx, req, id) {
1748
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1749
+ const body = await readJson(req);
1750
+ const result = await linkIdentity(ctx.deps, {
1751
+ recordId: id,
1752
+ email: optStr(body, "email"),
1753
+ mutationId: optStr(body, "mutationId")
1754
+ });
1755
+ return json(result);
1756
+ }
1757
+ async function handleSendEmail(ctx, req, id) {
1758
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1759
+ const body = await readJson(req);
1760
+ const from = ctx.opts.from;
1761
+ if (!from) throw new CrmInputError("email sending is not configured (missing from address)");
1762
+ const vars = {};
1763
+ for (const [key, value] of Object.entries(optObj(body, "vars") ?? {})) {
1764
+ if (typeof value !== "string") throw new CrmInputError(`var "${key}" must be a string`);
1765
+ vars[key] = value;
1766
+ }
1767
+ const result = await sendTemplatedEmail(ctx.deps, {
1768
+ recordId: id,
1769
+ channelId: optStr(body, "channelId"),
1770
+ templateId: str(body, "templateId"),
1771
+ vars,
1772
+ dedupeKey: optStr(body, "dedupeKey") ?? `manual:${resolveDeps(ctx.deps).newId()}`,
1773
+ force: optBool(body, "force"),
1774
+ from,
1775
+ envName: ctx.opts.envName,
1776
+ baseUrl: ctx.opts.baseUrl,
1777
+ basePath: ctx.opts.basePath
1778
+ });
1779
+ return json(result);
1780
+ }
1781
+
1782
+ // src/routes/records.ts
1783
+ async function handleRecordsRoot(ctx, req, url) {
1784
+ if (req.method === "GET") {
1785
+ const result = await listRecords(ctx.deps, parseListParams(url));
1786
+ return json(result);
1787
+ }
1788
+ if (req.method === "POST") {
1789
+ const body = await readJson(req);
1790
+ const created = await createRecord(ctx.deps, {
1791
+ type: str(body, "type"),
1792
+ input: obj(body, "input"),
1793
+ ownerId: optStr(body, "ownerId"),
1794
+ stage: optStr(body, "stage"),
1795
+ mutationId: optStr(body, "mutationId")
1796
+ });
1797
+ return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);
1798
+ }
1799
+ return json({ error: "method not allowed" }, 405);
1800
+ }
1801
+ async function handleRecordItem(ctx, req, id) {
1802
+ if (req.method === "GET") {
1803
+ const record = await getRecord(ctx.deps, id);
1804
+ if (!record) throw new CrmNotFoundError("record");
1805
+ const [tags, channels, links] = await Promise.all([
1806
+ listTags(ctx.deps, id),
1807
+ listChannels(ctx.deps, id),
1808
+ listLinks(ctx.deps, id)
1809
+ ]);
1810
+ return json({ record, tags, channels, links });
1811
+ }
1812
+ if (req.method === "PATCH") {
1813
+ const body = await readJson(req);
1814
+ const updated = await updateRecord(ctx.deps, {
1815
+ id,
1816
+ input: optObj(body, "input") ?? {},
1817
+ ownerId: nullableStr(body, "ownerId"),
1818
+ mutationId: optStr(body, "mutationId")
1819
+ });
1820
+ return json({ record: updated.record, duplicate: updated.duplicate });
1821
+ }
1822
+ return json({ error: "method not allowed" }, 405);
1823
+ }
1824
+ async function handleArchive(ctx, req, id) {
1825
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1826
+ const body = await readJson(req);
1827
+ const result = await setArchived(ctx.deps, {
1828
+ id,
1829
+ archived: optBool(body, "archived") ?? true,
1830
+ mutationId: optStr(body, "mutationId")
1831
+ });
1832
+ return json(result);
1833
+ }
1834
+
1835
+ // src/routes/misc.ts
1836
+ function specFrom(body) {
1837
+ const spec = obj(body, "spec");
1838
+ return {
1839
+ name: str(spec, "name"),
1840
+ type: str(spec, "type"),
1841
+ filters: optObj(spec, "filters") ?? {},
1842
+ sort: spec["sort"] ?? null,
1843
+ columns: Array.isArray(spec["columns"]) ? spec["columns"] : [],
1844
+ shared: optBool(spec, "shared") ?? false
1845
+ };
1846
+ }
1847
+ async function handleViews(ctx, req, url, rest) {
1848
+ if (rest.length === 0 && req.method === "GET") {
1849
+ const views = await listViews(ctx.deps, {
1850
+ viewerId: ctx.actor.userId,
1851
+ type: url.searchParams.get("type") ?? void 0
1852
+ });
1853
+ return json({ views });
1854
+ }
1855
+ if (rest.length === 0 && req.method === "POST") {
1856
+ const body = await readJson(req);
1857
+ const created = await saveView(ctx.deps, {
1858
+ spec: specFrom(body),
1859
+ ownerId: ctx.actor.userId,
1860
+ mutationId: optStr(body, "mutationId")
1861
+ });
1862
+ return json(created, 201);
1863
+ }
1864
+ const id = rest[0];
1865
+ if (id && req.method === "PATCH") {
1866
+ const body = await readJson(req);
1867
+ const spec = optObj(body, "spec") ?? {};
1868
+ const result = await updateView(ctx.deps, {
1869
+ id,
1870
+ spec,
1871
+ ownerId: ctx.actor.userId,
1872
+ mutationId: optStr(body, "mutationId")
1873
+ });
1874
+ return json(result);
1875
+ }
1876
+ if (id && req.method === "DELETE") {
1877
+ const result = await deleteView(ctx.deps, { id, ownerId: ctx.actor.userId });
1878
+ return json(result);
1879
+ }
1880
+ return json({ error: "method not allowed" }, 405);
1881
+ }
1882
+ async function handleSummary(ctx, req, url) {
1883
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
1884
+ const type = url.searchParams.get("type");
1885
+ if (!type) throw new CrmInputError("type is required");
1886
+ return json(await typeSummary(ctx.deps, type));
1887
+ }
1888
+ async function handleConfig(ctx, req) {
1889
+ if (req.method === "GET") {
1890
+ const config = await getConfig(ctx.deps);
1891
+ return json({ config });
1892
+ }
1893
+ if (req.method === "PUT") {
1894
+ const body = await readJson(req);
1895
+ const result = await saveConfig(ctx.deps, body, {
1896
+ mutationId: optStr(body, "mutationId")
1897
+ });
1898
+ return json(result);
1899
+ }
1900
+ return json({ error: "method not allowed" }, 405);
1901
+ }
1902
+ async function handleEmailLog(ctx, req, url) {
1903
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
1904
+ const limitRaw = url.searchParams.get("limit");
1905
+ const rows = await listEmailLog(ctx.deps, {
1906
+ recordId: url.searchParams.get("recordId") ?? void 0,
1907
+ limit: limitRaw ? Number(limitRaw) : void 0
1908
+ });
1909
+ return json({ log: rows });
1910
+ }
1911
+ async function handleRebalance(ctx, req) {
1912
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1913
+ const body = await readJson(req);
1914
+ const result = await rebalanceRanks(ctx.deps, {
1915
+ type: str(body, "type"),
1916
+ mutationId: optStr(body, "mutationId")
1917
+ });
1918
+ return json(result);
1919
+ }
1920
+ async function handleUnsubscribe(deps, req, url) {
1921
+ if (req.method === "GET") {
1922
+ const token2 = url.searchParams.get("token");
1923
+ if (!token2) return json({ error: "token is required" }, 400);
1924
+ return unsubscribePage(token2, false);
1925
+ }
1926
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
1927
+ let token = url.searchParams.get("token") ?? "";
1928
+ let oneClick = false;
1929
+ const contentType = req.headers.get("content-type") ?? "";
1930
+ if (contentType.includes("form")) {
1931
+ const form = await req.formData();
1932
+ token = String(form.get("token") ?? token);
1933
+ oneClick = String(form.get("List-Unsubscribe") ?? "") === "One-Click";
1934
+ } else if (contentType.includes("json")) {
1935
+ const body = await req.json().catch(() => ({}));
1936
+ if (typeof body["token"] === "string") token = body["token"];
1937
+ }
1938
+ if (!token) return json({ error: "token is required" }, 400);
1939
+ const event = oneClick ? "unsubscribe.oneclick" : "unsubscribe.token";
1940
+ await applyConsent(deps, { token, event, mutationId: `consent:${token}:unsubscribe` });
1941
+ return oneClick ? json({ ok: true }) : unsubscribePage(token, true);
1942
+ }
1943
+
1944
+ // src/routes/index.ts
1945
+ async function route(ctx, req, url, seg) {
1946
+ const [head, id, action, ...rest] = seg;
1947
+ if (head === "records") {
1948
+ if (id === void 0) return handleRecordsRoot(ctx, req, url);
1949
+ if (action === void 0) return handleRecordItem(ctx, req, id);
1950
+ if (action === "archive") return handleArchive(ctx, req, id);
1951
+ if (action === "stage") return handleStage(ctx, req, id);
1952
+ if (action === "rank") return handleRank(ctx, req, id);
1953
+ if (action === "tags") return handleTags(ctx, req, id, rest);
1954
+ if (action === "links") return handleLinks(ctx, req, id);
1955
+ if (action === "link-identity") return handleLinkIdentity(ctx, req, id);
1956
+ if (action === "email") return handleSendEmail(ctx, req, id);
1957
+ if (action === "activities") return handleRecordActivities(ctx, req, url, id);
1958
+ return null;
1959
+ }
1960
+ if (head === "activities" && id !== void 0 && action === void 0)
1961
+ return handleActivityItem(ctx, req, id);
1962
+ if (head === "tasks" && id === void 0) return handleTasks(ctx, req, url);
1963
+ if (head === "views") return handleViews(ctx, req, url, seg.slice(1));
1964
+ if (head === "summary" && id === void 0) return handleSummary(ctx, req, url);
1965
+ if (head === "config" && id === void 0) return handleConfig(ctx, req);
1966
+ if (head === "email-log" && id === void 0) return handleEmailLog(ctx, req, url);
1967
+ if (head === "rank" && id === "rebalance" && action === void 0)
1968
+ return handleRebalance(ctx, req);
1969
+ return null;
1970
+ }
1971
+ function createCrmRoutes(options) {
1972
+ const basePath = options.basePath ?? "/api/crm";
1973
+ const opts = {
1974
+ ...options,
1975
+ basePath,
1976
+ envName: options.envName ?? "development",
1977
+ baseUrl: options.baseUrl ?? ""
1978
+ };
1979
+ const deps = {
1980
+ crm: options.crm,
1981
+ db: options.db,
1982
+ now: options.now,
1983
+ newId: options.newId,
1984
+ sender: options.sender
1985
+ };
1986
+ return async (req) => {
1987
+ const url = new URL(req.url);
1988
+ if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) return null;
1989
+ const segments = url.pathname.slice(basePath.length).split("/").filter(Boolean);
1990
+ try {
1991
+ if (segments[0] === "unsubscribe" && segments.length === 1)
1992
+ return await handleUnsubscribe(deps, req, url);
1993
+ const actor = await options.authorize(req);
1994
+ if (!actor) return json({ error: "unauthorized" }, 401);
1995
+ const ctx = { deps, opts, actor };
1996
+ return await route(ctx, req, url, segments) ?? json({ error: "not found" }, 404);
1997
+ } catch (error) {
1998
+ return errorResponse(error);
1999
+ }
2000
+ };
2001
+ }
2002
+
2003
+ // src/client.ts
2004
+ var CrmClientError = class extends Error {
2005
+ status;
2006
+ fields;
2007
+ constructor(status, message, fields) {
2008
+ super(message);
2009
+ this.name = "CrmClientError";
2010
+ this.status = status;
2011
+ this.fields = fields;
2012
+ }
2013
+ };
2014
+ var CrmClient = class {
2015
+ base;
2016
+ doFetch;
2017
+ headers;
2018
+ constructor(options = {}) {
2019
+ this.base = `${options.baseUrl ?? ""}${options.basePath ?? "/api/crm"}`;
2020
+ this.doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
2021
+ this.headers = options.headers;
2022
+ }
2023
+ async request(method, path, body) {
2024
+ const headers = { ...await this.headers?.() };
2025
+ if (body !== void 0) headers["content-type"] = "application/json";
2026
+ const response = await this.doFetch(`${this.base}${path}`, {
2027
+ method,
2028
+ headers,
2029
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
2030
+ });
2031
+ const payload = await response.json().catch(() => ({}));
2032
+ if (!response.ok)
2033
+ throw new CrmClientError(
2034
+ response.status,
2035
+ typeof payload["error"] === "string" ? payload["error"] : `HTTP ${response.status}`,
2036
+ payload["fields"]
2037
+ );
2038
+ return payload;
2039
+ }
2040
+ listRecords(params) {
2041
+ const q = new URLSearchParams({ type: params.type });
2042
+ if (params.search) q.set("search", params.search);
2043
+ if (params.stage?.length) q.set("stage", params.stage.join(","));
2044
+ if (params.emailStatus?.length) q.set("emailStatus", params.emailStatus.join(","));
2045
+ if (params.billingStatus?.length) q.set("billingStatus", params.billingStatus.join(","));
2046
+ if (params.ownerId) q.set("ownerId", params.ownerId);
2047
+ if (params.tag) q.set("tag", params.tag);
2048
+ if (params.archived) q.set("archived", "true");
2049
+ if (params.sort) q.set("sort", `${params.sort.field}:${params.sort.dir}`);
2050
+ if (params.limit != null) q.set("limit", String(params.limit));
2051
+ if (params.offset != null) q.set("offset", String(params.offset));
2052
+ if (params.fields) q.set("fields", JSON.stringify(params.fields));
2053
+ return this.request("GET", `/records?${q}`);
2054
+ }
2055
+ getRecord(id) {
2056
+ return this.request("GET", `/records/${encodeURIComponent(id)}`);
2057
+ }
2058
+ createRecord(body) {
2059
+ return this.request("POST", "/records", body);
2060
+ }
2061
+ updateRecord(id, body) {
2062
+ return this.request("PATCH", `/records/${encodeURIComponent(id)}`, body);
2063
+ }
2064
+ setArchived(id, archived) {
2065
+ return this.request("POST", `/records/${encodeURIComponent(id)}/archive`, { archived });
2066
+ }
2067
+ setStage(id, to, mutationId) {
2068
+ return this.request("POST", `/records/${encodeURIComponent(id)}/stage`, { to, mutationId });
2069
+ }
2070
+ setRank(id, body) {
2071
+ return this.request("POST", `/records/${encodeURIComponent(id)}/rank`, body);
2072
+ }
2073
+ addTag(id, tag) {
2074
+ return this.request("POST", `/records/${encodeURIComponent(id)}/tags`, { tag });
2075
+ }
2076
+ removeTag(id, tag) {
2077
+ return this.request(
2078
+ "DELETE",
2079
+ `/records/${encodeURIComponent(id)}/tags/${encodeURIComponent(tag)}`
2080
+ );
2081
+ }
2082
+ setLink(id, body) {
2083
+ return this.request("POST", `/records/${encodeURIComponent(id)}/links`, body);
2084
+ }
2085
+ linkIdentity(id, email) {
2086
+ return this.request("POST", `/records/${encodeURIComponent(id)}/link-identity`, { email });
2087
+ }
2088
+ sendEmail(id, body) {
2089
+ return this.request("POST", `/records/${encodeURIComponent(id)}/email`, body);
2090
+ }
2091
+ listActivities(recordId, opts = {}) {
2092
+ const q = new URLSearchParams();
2093
+ if (opts.kind) q.set("kind", opts.kind);
2094
+ if (opts.limit != null) q.set("limit", String(opts.limit));
2095
+ return this.request("GET", `/records/${encodeURIComponent(recordId)}/activities?${q}`);
2096
+ }
2097
+ addActivity(recordId, body) {
2098
+ return this.request("POST", `/records/${encodeURIComponent(recordId)}/activities`, body);
2099
+ }
2100
+ updateTask(id, body) {
2101
+ return this.request("PATCH", `/activities/${encodeURIComponent(id)}`, body);
2102
+ }
2103
+ listTasks(opts = {}) {
2104
+ const q = new URLSearchParams();
2105
+ if (opts.assigneeId) q.set("assigneeId", opts.assigneeId);
2106
+ if (opts.status?.length) q.set("status", opts.status.join(","));
2107
+ if (opts.limit != null) q.set("limit", String(opts.limit));
2108
+ return this.request("GET", `/tasks?${q}`);
2109
+ }
2110
+ listViews(type) {
2111
+ return this.request("GET", `/views${type ? `?type=${encodeURIComponent(type)}` : ""}`);
2112
+ }
2113
+ saveView(spec) {
2114
+ return this.request("POST", "/views", { spec });
2115
+ }
2116
+ updateView(id, spec) {
2117
+ return this.request("PATCH", `/views/${encodeURIComponent(id)}`, { spec });
2118
+ }
2119
+ deleteView(id) {
2120
+ return this.request("DELETE", `/views/${encodeURIComponent(id)}`);
2121
+ }
2122
+ summary(type) {
2123
+ return this.request("GET", `/summary?type=${encodeURIComponent(type)}`);
2124
+ }
2125
+ getConfig() {
2126
+ return this.request("GET", "/config");
2127
+ }
2128
+ saveConfig(patch) {
2129
+ return this.request("PUT", "/config", patch);
2130
+ }
2131
+ emailLog(opts = {}) {
2132
+ const q = new URLSearchParams();
2133
+ if (opts.recordId) q.set("recordId", opts.recordId);
2134
+ if (opts.limit != null) q.set("limit", String(opts.limit));
2135
+ return this.request("GET", `/email-log?${q}`);
2136
+ }
2137
+ rebalance(type) {
2138
+ return this.request("POST", "/rank/rebalance", { type });
2139
+ }
2140
+ };
2141
+
2142
+ // src/descriptor.ts
2143
+ var crmIntegration = {
2144
+ id: "crm",
2145
+ title: "CRM records, pipelines & contactability",
2146
+ npm: "@odla-ai/crm",
2147
+ settings: [
2148
+ {
2149
+ key: "basePath",
2150
+ description: 'Route mount point the app worker serves the CRM under. Default "/api/crm".',
2151
+ public: true,
2152
+ perEnv: false,
2153
+ source: "createCrmRoutes({ basePath }) in the app worker"
2154
+ },
2155
+ {
2156
+ key: "notificationEmail / replyTo / debugEmail",
2157
+ description: "Destination addresses for owner notifications, reply routing, and the dev redirect \u2014 runtime-editable.",
2158
+ public: false,
2159
+ perEnv: false,
2160
+ source: "crm_config row (odla-db), edited in the app's CRM settings UI"
2161
+ }
2162
+ ],
2163
+ secrets: [],
2164
+ schema: CRM_SCHEMA,
2165
+ rules: CRM_RULES,
2166
+ provision: {
2167
+ human: [
2168
+ "None for the core install \u2014 records/pipelines/email-consent need no external accounts.",
2169
+ "When billing lands (@odla-ai/stripe): paste the printed webhook URL into the Stripe dashboard and vault the sk_/whsec_ secrets (Studio, write-only)."
2170
+ ],
2171
+ cli: [
2172
+ "POST the merged CRM_SCHEMA to /app/:id/schema.",
2173
+ "Install CRM_RULES (deny-all) at /app/:id/admin/rules.",
2174
+ "Seed the crm_config row from the app's defineCrm template defaults."
2175
+ ],
2176
+ doctor: [
2177
+ "Every crm_* namespace has rules installed (deny-all: no rule = exposed to nothing, but assert explicitly).",
2178
+ "The crm_config row exists and its emailTemplates parse against the code-declared registry.",
2179
+ "lintTemplate reports no unknown {{vars}} in stored template copy.",
2180
+ "A GET probe of <basePath>/records without credentials answers 401 (routes mounted, authorize enforced)."
2181
+ ]
2182
+ }
2183
+ };
2184
+ //# sourceMappingURL=index.cjs.map