@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.d.cts CHANGED
@@ -750,10 +750,29 @@ declare function applyConsentEvent(current: ConsentState, event: ConsentEvent):
750
750
  * only (transactional lifecycle mail still delivers). */
751
751
  declare function canEmail(consent: ConsentState, cls: "transactional" | "marketing"): boolean;
752
752
 
753
- /** Substitute `{{var}}` tokens from `vars`; unknown tokens render as "". */
753
+ /** One `{{…}}` tag in a template: a variable, or the opening or closing tag of a section. */
754
+ interface TemplateToken {
755
+ name: string;
756
+ kind: "var" | "open" | "close";
757
+ }
758
+ /** Every tag in a template, in order. */
759
+ declare function templateTokens(template: string): TemplateToken[];
760
+ /** A template with every well-formed tag removed, so any brace left behind is a typo. */
761
+ declare function stripTemplateTokens(template: string): string;
762
+ /** Section tags that do not pair up: a `{{/name}}` with no open section, or a `{{#name}}` never closed. */
763
+ declare function templateSectionIssues(template: string): string[];
764
+ /** Substitute `{{var}}` tokens from `vars` after resolving sections; unknown tokens and stray section tags render as "". */
754
765
  declare function renderTemplate(template: string, vars: Record<string, string>): string;
755
- /** The distinct `{{var}}` names a template references, in first-seen order. */
766
+ /** The distinct names a template references, in first-seen order; section names count. */
756
767
  declare function templateVars(template: string): string[];
768
+ /**
769
+ * The plain variables that would actually render for `vars`: those outside any
770
+ * section, plus those inside sections whose values are present. A name inside a
771
+ * hidden section is not a missing value; it is copy the reader will never see.
772
+ */
773
+ declare function templateLiveVars(template: string, vars: Record<string, string>): string[];
774
+ /** The distinct names a template uses only as sections (never as a plain `{{var}}`). */
775
+ declare function templateSectionNames(template: string): string[];
757
776
  /**
758
777
  * Template health check for the settings UI: which referenced vars aren't
759
778
  * in the declared contract (typos — they'd silently render as ""), and which
@@ -1141,7 +1160,7 @@ interface SendEmailOpts {
1141
1160
  baseUrl: string;
1142
1161
  /** Route mount point for the unsubscribe link. Default "/api/crm". */
1143
1162
  basePath?: string;
1144
- /** Admin test-send: bypasses the enabled flag — NEVER the consent gate. */
1163
+ /** Admin test-send: permits an explicitly disabled template, but never bypasses copy validation or consent. */
1145
1164
  force?: boolean;
1146
1165
  }
1147
1166
  /** What happened to the send — delivered, gated, logged, or failed. */
@@ -1153,7 +1172,8 @@ interface SendEmailResult {
1153
1172
  }
1154
1173
  /**
1155
1174
  * Render and send one templated email to a record's contact channel, with
1156
- * consent gating, dedupe, dev redirection, and an unconditional audit row.
1175
+ * copy validation, explicit enablement, consent gating, dedupe, dev redirection,
1176
+ * and audit rows for transport attempts. Incomplete or internal copy never reaches transport.
1157
1177
  * Marketing-class sends get `{{unsubscribeUrl}}` plus RFC 8058 one-click
1158
1178
  * headers automatically.
1159
1179
  */
@@ -1565,4 +1585,30 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1565
1585
  */
1566
1586
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1567
1587
 
1568
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1588
+ /** One actionable problem with email copy or the data needed to render it. */
1589
+ interface EmailCopyIssue {
1590
+ code: string;
1591
+ message: string;
1592
+ variable?: string;
1593
+ }
1594
+ /** A display name suitable for membership mail, never a missing name or a provider identifier. */
1595
+ declare function isEmailTierName(value: unknown, id?: string): value is string;
1596
+ /** Variables and concrete data to check. Omit values when auditing saved copy before an event occurs. */
1597
+ interface EmailCopyValidation {
1598
+ allowedVariables?: readonly string[];
1599
+ optionalVariables?: readonly string[];
1600
+ requiredVariables?: readonly string[];
1601
+ values?: Record<string, string>;
1602
+ tierId?: string;
1603
+ }
1604
+ /** Validate saved copy and, when supplied, its actual event data. Does not render, store, or send mail.
1605
+ * Unknown tokens, missing required values, explicit internal draft notes and invalid tier names fail closed.
1606
+ * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks.
1607
+ * A `{{#name}} … {{/name}}` section is checked like a variable (the event must supply `name`); its blank
1608
+ * value is the ordinary "hide this part" case, and the variables inside a hidden section are not missing. */
1609
+ declare function validateEmailCopy(copy: {
1610
+ subject?: unknown;
1611
+ text?: unknown;
1612
+ }, options?: EmailCopyValidation): EmailCopyIssue[];
1613
+
1614
+ export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailCopyIssue, type EmailCopyValidation, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TemplateToken, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, isEmailTierName, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, stripTemplateTokens, templateLiveVars, templateSectionIssues, templateSectionNames, templateTokens, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin, validateEmailCopy };
package/dist/index.d.ts CHANGED
@@ -750,10 +750,29 @@ declare function applyConsentEvent(current: ConsentState, event: ConsentEvent):
750
750
  * only (transactional lifecycle mail still delivers). */
751
751
  declare function canEmail(consent: ConsentState, cls: "transactional" | "marketing"): boolean;
752
752
 
753
- /** Substitute `{{var}}` tokens from `vars`; unknown tokens render as "". */
753
+ /** One `{{…}}` tag in a template: a variable, or the opening or closing tag of a section. */
754
+ interface TemplateToken {
755
+ name: string;
756
+ kind: "var" | "open" | "close";
757
+ }
758
+ /** Every tag in a template, in order. */
759
+ declare function templateTokens(template: string): TemplateToken[];
760
+ /** A template with every well-formed tag removed, so any brace left behind is a typo. */
761
+ declare function stripTemplateTokens(template: string): string;
762
+ /** Section tags that do not pair up: a `{{/name}}` with no open section, or a `{{#name}}` never closed. */
763
+ declare function templateSectionIssues(template: string): string[];
764
+ /** Substitute `{{var}}` tokens from `vars` after resolving sections; unknown tokens and stray section tags render as "". */
754
765
  declare function renderTemplate(template: string, vars: Record<string, string>): string;
755
- /** The distinct `{{var}}` names a template references, in first-seen order. */
766
+ /** The distinct names a template references, in first-seen order; section names count. */
756
767
  declare function templateVars(template: string): string[];
768
+ /**
769
+ * The plain variables that would actually render for `vars`: those outside any
770
+ * section, plus those inside sections whose values are present. A name inside a
771
+ * hidden section is not a missing value; it is copy the reader will never see.
772
+ */
773
+ declare function templateLiveVars(template: string, vars: Record<string, string>): string[];
774
+ /** The distinct names a template uses only as sections (never as a plain `{{var}}`). */
775
+ declare function templateSectionNames(template: string): string[];
757
776
  /**
758
777
  * Template health check for the settings UI: which referenced vars aren't
759
778
  * in the declared contract (typos — they'd silently render as ""), and which
@@ -1141,7 +1160,7 @@ interface SendEmailOpts {
1141
1160
  baseUrl: string;
1142
1161
  /** Route mount point for the unsubscribe link. Default "/api/crm". */
1143
1162
  basePath?: string;
1144
- /** Admin test-send: bypasses the enabled flag — NEVER the consent gate. */
1163
+ /** Admin test-send: permits an explicitly disabled template, but never bypasses copy validation or consent. */
1145
1164
  force?: boolean;
1146
1165
  }
1147
1166
  /** What happened to the send — delivered, gated, logged, or failed. */
@@ -1153,7 +1172,8 @@ interface SendEmailResult {
1153
1172
  }
1154
1173
  /**
1155
1174
  * Render and send one templated email to a record's contact channel, with
1156
- * consent gating, dedupe, dev redirection, and an unconditional audit row.
1175
+ * copy validation, explicit enablement, consent gating, dedupe, dev redirection,
1176
+ * and audit rows for transport attempts. Incomplete or internal copy never reaches transport.
1157
1177
  * Marketing-class sends get `{{unsubscribeUrl}}` plus RFC 8058 one-click
1158
1178
  * headers automatically.
1159
1179
  */
@@ -1565,4 +1585,30 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1565
1585
  */
1566
1586
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1567
1587
 
1568
- export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1588
+ /** One actionable problem with email copy or the data needed to render it. */
1589
+ interface EmailCopyIssue {
1590
+ code: string;
1591
+ message: string;
1592
+ variable?: string;
1593
+ }
1594
+ /** A display name suitable for membership mail, never a missing name or a provider identifier. */
1595
+ declare function isEmailTierName(value: unknown, id?: string): value is string;
1596
+ /** Variables and concrete data to check. Omit values when auditing saved copy before an event occurs. */
1597
+ interface EmailCopyValidation {
1598
+ allowedVariables?: readonly string[];
1599
+ optionalVariables?: readonly string[];
1600
+ requiredVariables?: readonly string[];
1601
+ values?: Record<string, string>;
1602
+ tierId?: string;
1603
+ }
1604
+ /** Validate saved copy and, when supplied, its actual event data. Does not render, store, or send mail.
1605
+ * Unknown tokens, missing required values, explicit internal draft notes and invalid tier names fail closed.
1606
+ * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks.
1607
+ * A `{{#name}} … {{/name}}` section is checked like a variable (the event must supply `name`); its blank
1608
+ * value is the ordinary "hide this part" case, and the variables inside a hidden section are not missing. */
1609
+ declare function validateEmailCopy(copy: {
1610
+ subject?: unknown;
1611
+ text?: unknown;
1612
+ }, options?: EmailCopyValidation): EmailCopyIssue[];
1613
+
1614
+ export { ACTIVITY_KINDS, type ActivityKind, type AttrType, type BillingEvent, type BillingProvider, CONFIG_KEY, CONSENT_STATES, CRM_DISCUSSION_REFERENCE_KINDS, CRM_NS, CRM_RULES, CRM_SCHEMA, CRM_SLOTS, type CompiledList, type ConfigPatch, type ConsentEvent, type ConsentOutcome, type ConsentState, type Crm, type CrmActivity, type CrmActor, type CrmAggregateResult, type CrmAggregateSpec, type CrmAttrs, CrmClient, type CrmClientOptions, type CrmConfig, type CrmConfigRow, type CrmContactChannel, type CrmDb, type CrmDeps, type CrmDiscussionReference, type CrmDiscussionReferenceActor, type CrmDiscussionReferenceKind, type CrmDiscussionReferenceTarget, type CrmEmailLogRow, type CrmEmailSender, type CrmEntityRef, CrmInputError, type CrmIntegrationDescriptor, type CrmIntegrationOptions, type CrmIntegrationProbe, type CrmIntegrationSeed, type CrmLink, type CrmListParams, type CrmLookup, CrmNotFoundError, type CrmOp, type CrmQuery, type CrmRecord, type CrmRecordDelivery, type CrmRecordOrigin, type CrmResult, type CrmRouteOpts, type CrmRow, type CrmRule, type CrmRules, type CrmScalar, type CrmSlot, type CrmSort, type CrmTag, type CrmTransactGuard, type CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailCopyIssue, type EmailCopyValidation, type EmailStatus, type FieldCondition, type FieldConditions, type FieldDef, type FieldFilter, type FieldState, type FieldType, MAX_LIMIT, type PipelineDef, type PreparedWrite, RANK_EPSILON, RANK_STEP, type RelationDef, SORTABLE_COLUMNS, type SendEmailOpts, type SendEmailResult, type SerializedAttr, type SerializedEntity, type SerializedLink, type SerializedLinkEnd, type SerializedSchema, type StageDef, type StoredTemplate, type SubscriptionSnapshot, TASK_STATUSES, type TaskStatus, type TemplateSpec, type TemplateToken, type TypeDef, type TypeFacets, type TypeSummary, type ViewFilters, type ViewSpec, addActivity, addLink, addTag, applyConsent, applyConsentEvent, assertFieldCondition, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, evaluateFieldCondition, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, getRecordByOrigin, getRecordOrigin, initialStage, isEmailTierName, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecordDeliveries, listRecordOrigins, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, recordDeliveryAttempt, recordDeliveryKey, recordOriginKey, removeLink, removeTag, renderTemplate, resolveDeps, resolveFieldState, resolveFieldStates, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, stripTemplateTokens, templateLiveVars, templateSectionIssues, templateSectionNames, templateTokens, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin, validateEmailCopy };
package/dist/index.js CHANGED
@@ -302,15 +302,74 @@ function canTransition(def, record, to) {
302
302
  }
303
303
 
304
304
  // src/template.ts
305
- var TOKEN_RE = /\{\{\s*([a-zA-Z][a-zA-Z0-9_]*)\s*\}\}/g;
305
+ var NAME = "[a-zA-Z][a-zA-Z0-9_]*";
306
+ var TOKEN_RE = new RegExp(`\\{\\{\\s*([#/]?)\\s*(${NAME})\\s*\\}\\}`, "g");
307
+ var SECTION_RE = new RegExp(`\\{\\{\\s*#\\s*(${NAME})\\s*\\}\\}([\\s\\S]*?)\\{\\{\\s*\\/\\s*\\1\\s*\\}\\}(\\n{0,2})`, "g");
308
+ var MAX_SECTION_PASSES = 10;
309
+ function templateTokens(template) {
310
+ const out = [];
311
+ for (const match of template.matchAll(TOKEN_RE)) {
312
+ out.push({ name: match[2], kind: match[1] === "#" ? "open" : match[1] === "/" ? "close" : "var" });
313
+ }
314
+ return out;
315
+ }
316
+ function stripTemplateTokens(template) {
317
+ return template.replace(TOKEN_RE, "");
318
+ }
319
+ function templateSectionIssues(template) {
320
+ const open = [], issues = [];
321
+ for (const token of templateTokens(template)) {
322
+ if (token.kind === "open") open.push(token.name);
323
+ else if (token.kind === "close") {
324
+ const at = open.lastIndexOf(token.name);
325
+ if (at < 0) issues.push(`{{/${token.name}}} closes a section that was never opened.`);
326
+ else open.splice(at, 1);
327
+ }
328
+ }
329
+ for (const name of open) issues.push(`Close the {{#${name}}} section with {{/${name}}}.`);
330
+ return issues;
331
+ }
332
+ function resolveSections(template, vars) {
333
+ let out = template;
334
+ for (let pass = 0; pass < MAX_SECTION_PASSES; pass++) {
335
+ let changed = false;
336
+ out = out.replace(SECTION_RE, (match, name, inner, trailing, offset, whole) => {
337
+ changed = true;
338
+ if ((vars[name] ?? "").trim()) return inner + trailing;
339
+ const before = whole.slice(0, offset);
340
+ if (!(offset === 0 || before.endsWith("\n"))) return trailing;
341
+ let keep = trailing.slice(1);
342
+ if (before.endsWith("\n\n") && keep.startsWith("\n")) keep = keep.slice(1);
343
+ return keep;
344
+ });
345
+ if (!changed) break;
346
+ }
347
+ return out;
348
+ }
306
349
  function renderTemplate(template, vars) {
307
- return template.replace(TOKEN_RE, (_, name) => vars[name] ?? "");
350
+ return resolveSections(template, vars).replace(TOKEN_RE, (_, kind, name) => kind ? "" : vars[name] ?? "");
308
351
  }
309
352
  function templateVars(template) {
310
353
  const seen = /* @__PURE__ */ new Set();
311
- for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1]);
354
+ for (const token of templateTokens(template)) seen.add(token.name);
312
355
  return [...seen];
313
356
  }
357
+ function templateLiveVars(template, vars) {
358
+ const live = /* @__PURE__ */ new Set(), open = [];
359
+ for (const token of templateTokens(template)) {
360
+ if (token.kind === "open") open.push(token.name);
361
+ else if (token.kind === "close") {
362
+ const at = open.lastIndexOf(token.name);
363
+ if (at >= 0) open.splice(at, 1);
364
+ } else if (open.every((name) => (vars[name] ?? "").trim())) live.add(token.name);
365
+ }
366
+ return [...live];
367
+ }
368
+ function templateSectionNames(template) {
369
+ const tokens = templateTokens(template);
370
+ const plain = new Set(tokens.filter((token) => token.kind === "var").map((token) => token.name));
371
+ return [...new Set(tokens.filter((token) => token.kind !== "var" && !plain.has(token.name)).map((token) => token.name))];
372
+ }
314
373
  function lintTemplate(template, knownVars) {
315
374
  const used = templateVars(template);
316
375
  const known = new Set(knownVars);
@@ -1661,6 +1720,46 @@ async function saveConfig(deps, patch, opts = {}) {
1661
1720
  return { config: merged, duplicate };
1662
1721
  }
1663
1722
 
1723
+ // src/email-validation.ts
1724
+ function isEmailTierName(value, id) {
1725
+ 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);
1726
+ }
1727
+ function validateEmailCopy(copy, options = {}) {
1728
+ const issues = [];
1729
+ const subject = typeof copy.subject === "string" ? copy.subject : "";
1730
+ const text = typeof copy.text === "string" ? copy.text : "";
1731
+ if (!subject.trim()) issues.push({ code: "subject-missing", message: "Add an email subject." });
1732
+ if (!text.trim()) issues.push({ code: "body-missing", message: "Add an email body." });
1733
+ if (/[\r\n]/.test(subject) || subject.length > 200) issues.push({ code: "subject-invalid", message: "Use a single-line subject of at most 200 characters." });
1734
+ if (text.length > 1e4) issues.push({ code: "body-invalid", message: "Keep the email body within 10,000 characters." });
1735
+ const combined = `${subject}
1736
+ ${text}`;
1737
+ 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)) {
1738
+ issues.push({ code: "internal-copy", message: "Replace internal draft or retirement notes with recipient-facing copy." });
1739
+ }
1740
+ const tokens = templateVars(combined);
1741
+ const sections = new Set(templateSectionNames(combined));
1742
+ if (/[{}]/.test(stripTemplateTokens(combined))) issues.push({ code: "placeholder-invalid", message: "Fix malformed placeholders; use {{variableName}}, or {{#name}} \u2026 {{/name}} for a section." });
1743
+ for (const message of templateSectionIssues(combined)) issues.push({ code: "section-invalid", message });
1744
+ for (const variable of tokens) {
1745
+ if (options.allowedVariables && !options.allowedVariables.includes(variable)) issues.push({ code: "variable-unknown", variable, message: `This event does not supply {{${variable}}}.` });
1746
+ }
1747
+ if (options.values) {
1748
+ for (const name of sections) if (typeof options.values[name] !== "string") issues.push({ code: "value-missing", variable: name, message: `Missing event value: ${name}.` });
1749
+ for (const variable of /* @__PURE__ */ new Set([...templateLiveVars(combined, options.values), ...options.requiredVariables ?? []])) {
1750
+ const value = options.values[variable];
1751
+ if (typeof value !== "string" || !value.trim() && !options.optionalVariables?.includes(variable)) {
1752
+ issues.push({ code: "value-missing", variable, message: `Missing event value: ${variable}.` });
1753
+ } else if ((variable === "tierName" || variable === "tier") && !isEmailTierName(value, options.tierId)) {
1754
+ issues.push({ code: "tier-name-invalid", variable, message: "Resolve the membership tier's display name before sending." });
1755
+ } else if (/\{\{|\}\}/.test(value)) {
1756
+ issues.push({ code: "value-invalid", variable, message: `Unresolved placeholder in ${variable}.` });
1757
+ }
1758
+ }
1759
+ }
1760
+ return issues;
1761
+ }
1762
+
1664
1763
  // src/email.ts
1665
1764
  async function sendTemplatedEmail(deps, opts) {
1666
1765
  const { crm, db, now, newId } = resolveDeps(deps);
@@ -1669,7 +1768,8 @@ async function sendTemplatedEmail(deps, opts) {
1669
1768
  const config = await getConfig(deps);
1670
1769
  const stored = config?.emailTemplates[opts.templateId] ?? null;
1671
1770
  if (!stored || !stored.subject && !stored.text) return { sent: false, reason: "no_template_copy" };
1672
- if (!stored.enabled && !opts.force) return { sent: false, reason: "disabled" };
1771
+ if (typeof stored.enabled !== "boolean") return { sent: false, reason: "template-invalid" };
1772
+ if (stored.enabled !== true && !opts.force) return { sent: false, reason: "disabled" };
1673
1773
  const record = await mustGetRecord(deps, opts.recordId);
1674
1774
  const channels = await listChannels(deps, record.id);
1675
1775
  const channel = opts.channelId ? channels.find((c) => c.id === opts.channelId) : channels.find((c) => c.kind === "email" && c.isPrimary);
@@ -1688,8 +1788,10 @@ async function sendTemplatedEmail(deps, opts) {
1688
1788
  headers["List-Unsubscribe"] = `<${unsubscribeUrl}>`;
1689
1789
  headers["List-Unsubscribe-Post"] = "List-Unsubscribe=One-Click";
1690
1790
  }
1791
+ if (validateEmailCopy(stored, { allowedVariables: spec.vars, values: vars }).length) return { sent: false, reason: "template-invalid" };
1691
1792
  let subject = renderTemplate(stored.subject, vars);
1692
1793
  const text = renderTemplate(stored.text, vars);
1794
+ if (validateEmailCopy({ subject, text }, { allowedVariables: [] }).length) return { sent: false, reason: "template-invalid" };
1693
1795
  let to = channel.value;
1694
1796
  let redirected = false;
1695
1797
  let logOnly = !deps.sender;
@@ -2747,6 +2849,7 @@ export {
2747
2849
  getRecordByOrigin,
2748
2850
  getRecordOrigin,
2749
2851
  initialStage,
2852
+ isEmailTierName,
2750
2853
  linkIdentity,
2751
2854
  lintTemplate,
2752
2855
  listActivities,
@@ -2787,11 +2890,17 @@ export {
2787
2890
  setRank,
2788
2891
  setStage,
2789
2892
  stageIndexOf,
2893
+ stripTemplateTokens,
2894
+ templateLiveVars,
2895
+ templateSectionIssues,
2896
+ templateSectionNames,
2897
+ templateTokens,
2790
2898
  templateVars,
2791
2899
  typeSummary,
2792
2900
  updateRecord,
2793
2901
  updateTask,
2794
2902
  updateView,
2795
- upsertRecordOrigin
2903
+ upsertRecordOrigin,
2904
+ validateEmailCopy
2796
2905
  };
2797
2906
  //# sourceMappingURL=index.js.map