@odla-ai/crm 0.10.0 → 0.11.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 CHANGED
@@ -68,6 +68,7 @@ __export(index_exports, {
68
68
  getRecordByOrigin: () => getRecordByOrigin,
69
69
  getRecordOrigin: () => getRecordOrigin,
70
70
  initialStage: () => initialStage,
71
+ isEmailTierName: () => isEmailTierName,
71
72
  linkIdentity: () => linkIdentity,
72
73
  lintTemplate: () => lintTemplate,
73
74
  listActivities: () => listActivities,
@@ -108,12 +109,18 @@ __export(index_exports, {
108
109
  setRank: () => setRank,
109
110
  setStage: () => setStage,
110
111
  stageIndexOf: () => stageIndexOf,
112
+ stripTemplateTokens: () => stripTemplateTokens,
113
+ templateLiveVars: () => templateLiveVars,
114
+ templateSectionIssues: () => templateSectionIssues,
115
+ templateSectionNames: () => templateSectionNames,
116
+ templateTokens: () => templateTokens,
111
117
  templateVars: () => templateVars,
112
118
  typeSummary: () => typeSummary,
113
119
  updateRecord: () => updateRecord,
114
120
  updateTask: () => updateTask,
115
121
  updateView: () => updateView,
116
- upsertRecordOrigin: () => upsertRecordOrigin
122
+ upsertRecordOrigin: () => upsertRecordOrigin,
123
+ validateEmailCopy: () => validateEmailCopy
117
124
  });
118
125
  module.exports = __toCommonJS(index_exports);
119
126
 
@@ -421,15 +428,74 @@ function canTransition(def, record, to) {
421
428
  }
422
429
 
423
430
  // src/template.ts
424
- var TOKEN_RE = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
431
+ var NAME = "[a-zA-Z][a-zA-Z0-9_]*";
432
+ var TOKEN_RE = new RegExp(`\\{\\{\\s*([#/]?)\\s*(${NAME})\\s*\\}\\}`, "g");
433
+ var SECTION_RE = new RegExp(`\\{\\{\\s*#\\s*(${NAME})\\s*\\}\\}([\\s\\S]*?)\\{\\{\\s*\\/\\s*\\1\\s*\\}\\}(\\n{0,2})`, "g");
434
+ var MAX_SECTION_PASSES = 10;
435
+ function templateTokens(template) {
436
+ const out = [];
437
+ for (const match of template.matchAll(TOKEN_RE)) {
438
+ out.push({ name: match[2], kind: match[1] === "#" ? "open" : match[1] === "/" ? "close" : "var" });
439
+ }
440
+ return out;
441
+ }
442
+ function stripTemplateTokens(template) {
443
+ return template.replace(TOKEN_RE, "");
444
+ }
445
+ function templateSectionIssues(template) {
446
+ const open = [], issues = [];
447
+ for (const token of templateTokens(template)) {
448
+ if (token.kind === "open") open.push(token.name);
449
+ else if (token.kind === "close") {
450
+ const at = open.lastIndexOf(token.name);
451
+ if (at < 0) issues.push(`{{/${token.name}}} closes a section that was never opened.`);
452
+ else open.splice(at, 1);
453
+ }
454
+ }
455
+ for (const name of open) issues.push(`Close the {{#${name}}} section with {{/${name}}}.`);
456
+ return issues;
457
+ }
458
+ function resolveSections(template, vars) {
459
+ let out = template;
460
+ for (let pass = 0; pass < MAX_SECTION_PASSES; pass++) {
461
+ let changed = false;
462
+ out = out.replace(SECTION_RE, (match, name, inner, trailing, offset, whole) => {
463
+ changed = true;
464
+ if ((vars[name] ?? "").trim()) return inner + trailing;
465
+ const before = whole.slice(0, offset);
466
+ if (!(offset === 0 || before.endsWith("\n"))) return trailing;
467
+ let keep = trailing.slice(1);
468
+ if (before.endsWith("\n\n") && keep.startsWith("\n")) keep = keep.slice(1);
469
+ return keep;
470
+ });
471
+ if (!changed) break;
472
+ }
473
+ return out;
474
+ }
425
475
  function renderTemplate(template, vars) {
426
- return template.replace(TOKEN_RE, (_, name) => vars[name] ?? "");
476
+ return resolveSections(template, vars).replace(TOKEN_RE, (_, kind, name) => kind ? "" : vars[name] ?? "");
427
477
  }
428
478
  function templateVars(template) {
429
479
  const seen = /* @__PURE__ */ new Set();
430
- for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1]);
480
+ for (const token of templateTokens(template)) seen.add(token.name);
431
481
  return [...seen];
432
482
  }
483
+ function templateLiveVars(template, vars) {
484
+ const live = /* @__PURE__ */ new Set(), open = [];
485
+ for (const token of templateTokens(template)) {
486
+ if (token.kind === "open") open.push(token.name);
487
+ else if (token.kind === "close") {
488
+ const at = open.lastIndexOf(token.name);
489
+ if (at >= 0) open.splice(at, 1);
490
+ } else if (open.every((name) => (vars[name] ?? "").trim())) live.add(token.name);
491
+ }
492
+ return [...live];
493
+ }
494
+ function templateSectionNames(template) {
495
+ const tokens = templateTokens(template);
496
+ const plain = new Set(tokens.filter((token) => token.kind === "var").map((token) => token.name));
497
+ return [...new Set(tokens.filter((token) => token.kind !== "var" && !plain.has(token.name)).map((token) => token.name))];
498
+ }
433
499
  function lintTemplate(template, knownVars) {
434
500
  const used = templateVars(template);
435
501
  const known = new Set(knownVars);
@@ -1780,6 +1846,46 @@ async function saveConfig(deps, patch, opts = {}) {
1780
1846
  return { config: merged, duplicate };
1781
1847
  }
1782
1848
 
1849
+ // src/email-validation.ts
1850
+ function isEmailTierName(value, id) {
1851
+ return typeof value === "string" && !!value.trim() && value.trim() !== id && !/^(?:unknown|undefined|null|n\/a|(?:sku|price|tier|prod)_[\w-]+|[0-9a-f]{8}-[0-9a-f-]{27,})$/i.test(value.trim()) && !/[{}\r\n]/.test(value);
1852
+ }
1853
+ function validateEmailCopy(copy, options = {}) {
1854
+ const issues = [];
1855
+ const subject = typeof copy.subject === "string" ? copy.subject : "";
1856
+ const text = typeof copy.text === "string" ? copy.text : "";
1857
+ if (!subject.trim()) issues.push({ code: "subject-missing", message: "Add an email subject." });
1858
+ if (!text.trim()) issues.push({ code: "body-missing", message: "Add an email body." });
1859
+ if (/[\r\n]/.test(subject) || subject.length > 200) issues.push({ code: "subject-invalid", message: "Use a single-line subject of at most 200 characters." });
1860
+ if (text.length > 1e4) issues.push({ code: "body-invalid", message: "Keep the email body within 10,000 characters." });
1861
+ const combined = `${subject}
1862
+ ${text}`;
1863
+ if (/^\s*(?:\(\s*unused\s*:|Unused\.\s*Switched off\b|(?:TODO|TBD|PLACEHOLDER)\s*:|DRAFT\s*[-:]|\[\s*(?:draft|placeholder)\s*\]|do not (?:send|use) this (?:email|template))/im.test(combined)) {
1864
+ issues.push({ code: "internal-copy", message: "Replace internal draft or retirement notes with recipient-facing copy." });
1865
+ }
1866
+ const tokens = templateVars(combined);
1867
+ const sections = new Set(templateSectionNames(combined));
1868
+ if (/[{}]/.test(stripTemplateTokens(combined))) issues.push({ code: "placeholder-invalid", message: "Fix malformed placeholders; use {{variableName}}, or {{#name}} \u2026 {{/name}} for a section." });
1869
+ for (const message of templateSectionIssues(combined)) issues.push({ code: "section-invalid", message });
1870
+ for (const variable of tokens) {
1871
+ if (options.allowedVariables && !options.allowedVariables.includes(variable)) issues.push({ code: "variable-unknown", variable, message: `This event does not supply {{${variable}}}.` });
1872
+ }
1873
+ if (options.values) {
1874
+ for (const name of sections) if (typeof options.values[name] !== "string") issues.push({ code: "value-missing", variable: name, message: `Missing event value: ${name}.` });
1875
+ for (const variable of /* @__PURE__ */ new Set([...templateLiveVars(combined, options.values), ...options.requiredVariables ?? []])) {
1876
+ const value = options.values[variable];
1877
+ if (typeof value !== "string" || !value.trim() && !options.optionalVariables?.includes(variable)) {
1878
+ issues.push({ code: "value-missing", variable, message: `Missing event value: ${variable}.` });
1879
+ } else if ((variable === "tierName" || variable === "tier") && !isEmailTierName(value, options.tierId)) {
1880
+ issues.push({ code: "tier-name-invalid", variable, message: "Resolve the membership tier's display name before sending." });
1881
+ } else if (/\{\{|\}\}/.test(value)) {
1882
+ issues.push({ code: "value-invalid", variable, message: `Unresolved placeholder in ${variable}.` });
1883
+ }
1884
+ }
1885
+ }
1886
+ return issues;
1887
+ }
1888
+
1783
1889
  // src/email.ts
1784
1890
  async function sendTemplatedEmail(deps, opts) {
1785
1891
  const { crm, db, now, newId } = resolveDeps(deps);
@@ -1788,7 +1894,8 @@ async function sendTemplatedEmail(deps, opts) {
1788
1894
  const config = await getConfig(deps);
1789
1895
  const stored = config?.emailTemplates[opts.templateId] ?? null;
1790
1896
  if (!stored || !stored.subject && !stored.text) return { sent: false, reason: "no_template_copy" };
1791
- if (!stored.enabled && !opts.force) return { sent: false, reason: "disabled" };
1897
+ if (typeof stored.enabled !== "boolean") return { sent: false, reason: "template-invalid" };
1898
+ if (stored.enabled !== true && !opts.force) return { sent: false, reason: "disabled" };
1792
1899
  const record = await mustGetRecord(deps, opts.recordId);
1793
1900
  const channels = await listChannels(deps, record.id);
1794
1901
  const channel = opts.channelId ? channels.find((c) => c.id === opts.channelId) : channels.find((c) => c.kind === "email" && c.isPrimary);
@@ -1807,8 +1914,10 @@ async function sendTemplatedEmail(deps, opts) {
1807
1914
  headers["List-Unsubscribe"] = `<${unsubscribeUrl}>`;
1808
1915
  headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
1809
1916
  }
1917
+ if (validateEmailCopy(stored, { allowedVariables: spec.vars, values: vars }).length) return { sent: false, reason: "template-invalid" };
1810
1918
  let subject = renderTemplate(stored.subject, vars);
1811
1919
  const text = renderTemplate(stored.text, vars);
1920
+ if (validateEmailCopy({ subject, text }, { allowedVariables: [] }).length) return { sent: false, reason: "template-invalid" };
1812
1921
  let to = channel.value;
1813
1922
  let redirected = false;
1814
1923
  let logOnly = !deps.sender;