@odla-ai/crm 0.10.1 → 0.11.1

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
@@ -1317,6 +1336,11 @@ interface CrmRouteOpts {
1317
1336
  * admin actor (401 otherwise) EXCEPT the public unsubscribe pair, where the
1318
1337
  * per-channel token is the credential. Domain errors map to 400/404 JSON;
1319
1338
  * anything unexpected is a 500 without internals.
1339
+ *
1340
+ * An id in the path (a record, activity or view id, or a tag) is
1341
+ * percent-decoded once, so the id `CrmClient` encodes is the id looked up;
1342
+ * malformed encoding there is a 400. Build paths by hand the same way:
1343
+ * `encodeURIComponent(id)`.
1320
1344
  */
1321
1345
  declare function createCrmRoutes(options: CrmRouteOpts): (req: Request) => Promise<Response | null>;
1322
1346
 
@@ -1584,10 +1608,12 @@ interface EmailCopyValidation {
1584
1608
  }
1585
1609
  /** Validate saved copy and, when supplied, its actual event data. Does not render, store, or send mail.
1586
1610
  * Unknown tokens, missing required values, explicit internal draft notes and invalid tier names fail closed.
1587
- * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks. */
1611
+ * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks.
1612
+ * A `{{#name}} … {{/name}}` section is checked like a variable (the event must supply `name`); its blank
1613
+ * value is the ordinary "hide this part" case, and the variables inside a hidden section are not missing. */
1588
1614
  declare function validateEmailCopy(copy: {
1589
1615
  subject?: unknown;
1590
1616
  text?: unknown;
1591
1617
  }, options?: EmailCopyValidation): EmailCopyIssue[];
1592
1618
 
1593
- 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 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, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin, validateEmailCopy };
1619
+ 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
@@ -1317,6 +1336,11 @@ interface CrmRouteOpts {
1317
1336
  * admin actor (401 otherwise) EXCEPT the public unsubscribe pair, where the
1318
1337
  * per-channel token is the credential. Domain errors map to 400/404 JSON;
1319
1338
  * anything unexpected is a 500 without internals.
1339
+ *
1340
+ * An id in the path (a record, activity or view id, or a tag) is
1341
+ * percent-decoded once, so the id `CrmClient` encodes is the id looked up;
1342
+ * malformed encoding there is a 400. Build paths by hand the same way:
1343
+ * `encodeURIComponent(id)`.
1320
1344
  */
1321
1345
  declare function createCrmRoutes(options: CrmRouteOpts): (req: Request) => Promise<Response | null>;
1322
1346
 
@@ -1584,10 +1608,12 @@ interface EmailCopyValidation {
1584
1608
  }
1585
1609
  /** Validate saved copy and, when supplied, its actual event data. Does not render, store, or send mail.
1586
1610
  * Unknown tokens, missing required values, explicit internal draft notes and invalid tier names fail closed.
1587
- * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks. */
1611
+ * Optional values must be named by the event contract; arbitrary unknown placeholders never become blanks.
1612
+ * A `{{#name}} … {{/name}}` section is checked like a variable (the event must supply `name`); its blank
1613
+ * value is the ordinary "hide this part" case, and the variables inside a hidden section are not missing. */
1588
1614
  declare function validateEmailCopy(copy: {
1589
1615
  subject?: unknown;
1590
1616
  text?: unknown;
1591
1617
  }, options?: EmailCopyValidation): EmailCopyIssue[];
1592
1618
 
1593
- 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 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, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin, validateEmailCopy };
1619
+ 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);
@@ -1678,13 +1737,16 @@ ${text}`;
1678
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)) {
1679
1738
  issues.push({ code: "internal-copy", message: "Replace internal draft or retirement notes with recipient-facing copy." });
1680
1739
  }
1681
- const tokens = [...new Set([...combined.matchAll(/\{\{(\w+)\}\}/g)].map((match) => match[1]))];
1682
- if (/[{}]/.test(combined.replace(/\{\{\w+\}\}/g, ""))) issues.push({ code: "placeholder-invalid", message: "Fix malformed placeholders; use {{variableName}}." });
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 });
1683
1744
  for (const variable of tokens) {
1684
1745
  if (options.allowedVariables && !options.allowedVariables.includes(variable)) issues.push({ code: "variable-unknown", variable, message: `This event does not supply {{${variable}}}.` });
1685
1746
  }
1686
1747
  if (options.values) {
1687
- for (const variable of /* @__PURE__ */ new Set([...tokens, ...options.requiredVariables ?? []])) {
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 ?? []])) {
1688
1750
  const value = options.values[variable];
1689
1751
  if (typeof value !== "string" || !value.trim() && !options.optionalVariables?.includes(variable)) {
1690
1752
  issues.push({ code: "value-missing", variable, message: `Missing event value: ${variable}.` });
@@ -1957,6 +2019,13 @@ function unsubscribePage(token, done) {
1957
2019
  }
1958
2020
 
1959
2021
  // src/routes/params.ts
2022
+ function pathId(segment) {
2023
+ try {
2024
+ return decodeURIComponent(segment);
2025
+ } catch {
2026
+ throw new CrmInputError("malformed percent-encoding in the path");
2027
+ }
2028
+ }
1960
2029
  function str(body, key) {
1961
2030
  const value = body[key];
1962
2031
  if (typeof value !== "string" || value === "")
@@ -2118,7 +2187,7 @@ async function handleTags(ctx, req, id, rest) {
2118
2187
  return json(result, 201);
2119
2188
  }
2120
2189
  if (req.method === "DELETE" && rest.length === 1) {
2121
- const result = await removeTag(ctx.deps, { recordId: id, tag: decodeURIComponent(rest[0]) });
2190
+ const result = await removeTag(ctx.deps, { recordId: id, tag: rest[0] });
2122
2191
  return json(result);
2123
2192
  }
2124
2193
  return json({ error: "method not allowed" }, 405);
@@ -2466,30 +2535,31 @@ async function handleCrmDiscussionReferences(ctx, req, url) {
2466
2535
 
2467
2536
  // src/routes/index.ts
2468
2537
  async function route(ctx, req, url, seg) {
2469
- const [head, id, action, ...rest] = seg;
2470
- if (head === "discussion-references" && id === void 0)
2538
+ const [head, second, action, ...rest] = seg;
2539
+ if (head === "discussion-references" && second === void 0)
2471
2540
  return handleCrmDiscussionReferences(ctx, req, url);
2472
2541
  if (head === "records") {
2473
- if (id === void 0) return handleRecordsRoot(ctx, req, url);
2542
+ if (second === void 0) return handleRecordsRoot(ctx, req, url);
2543
+ const id = pathId(second);
2474
2544
  if (action === void 0) return handleRecordItem(ctx, req, id);
2475
2545
  if (action === "archive") return handleArchive(ctx, req, id);
2476
2546
  if (action === "stage") return handleStage(ctx, req, id);
2477
2547
  if (action === "rank") return handleRank(ctx, req, id);
2478
- if (action === "tags") return handleTags(ctx, req, id, rest);
2548
+ if (action === "tags") return handleTags(ctx, req, id, rest.map(pathId));
2479
2549
  if (action === "links") return handleLinks(ctx, req, id);
2480
2550
  if (action === "link-identity") return handleLinkIdentity(ctx, req, id);
2481
2551
  if (action === "email") return handleSendEmail(ctx, req, id);
2482
2552
  if (action === "activities") return handleRecordActivities(ctx, req, url, id);
2483
2553
  return null;
2484
2554
  }
2485
- if (head === "activities" && id !== void 0 && action === void 0)
2486
- return handleActivityItem(ctx, req, id);
2487
- if (head === "tasks" && id === void 0) return handleTasks(ctx, req, url);
2488
- if (head === "views") return handleViews(ctx, req, url, seg.slice(1));
2489
- if (head === "summary" && id === void 0) return handleSummary(ctx, req, url);
2490
- if (head === "config" && id === void 0) return handleConfig(ctx, req);
2491
- if (head === "email-log" && id === void 0) return handleEmailLog(ctx, req, url);
2492
- if (head === "rank" && id === "rebalance" && action === void 0)
2555
+ if (head === "activities" && second !== void 0 && action === void 0)
2556
+ return handleActivityItem(ctx, req, pathId(second));
2557
+ if (head === "tasks" && second === void 0) return handleTasks(ctx, req, url);
2558
+ if (head === "views") return handleViews(ctx, req, url, seg.slice(1).map(pathId));
2559
+ if (head === "summary" && second === void 0) return handleSummary(ctx, req, url);
2560
+ if (head === "config" && second === void 0) return handleConfig(ctx, req);
2561
+ if (head === "email-log" && second === void 0) return handleEmailLog(ctx, req, url);
2562
+ if (head === "rank" && second === "rebalance" && action === void 0)
2493
2563
  return handleRebalance(ctx, req);
2494
2564
  return null;
2495
2565
  }
@@ -2828,6 +2898,11 @@ export {
2828
2898
  setRank,
2829
2899
  setStage,
2830
2900
  stageIndexOf,
2901
+ stripTemplateTokens,
2902
+ templateLiveVars,
2903
+ templateSectionIssues,
2904
+ templateSectionNames,
2905
+ templateTokens,
2831
2906
  templateVars,
2832
2907
  typeSummary,
2833
2908
  updateRecord,