@odla-ai/crm 0.6.0 → 0.7.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
@@ -370,6 +370,55 @@ type PreparedWrite = {
370
370
  errors: Record<string, string>;
371
371
  };
372
372
 
373
+ /** A CEL expression over `values`, e.g. `values.country == "US"`. */
374
+ type FieldCondition = string;
375
+ /** Conditions a field declaration may carry. */
376
+ interface FieldConditions {
377
+ /** Render the field only while this holds. Absent means always visible. */
378
+ visibleWhen?: FieldCondition;
379
+ /** Demand a value only while this holds. Absent means the static `required`. */
380
+ requiredWhen?: FieldCondition;
381
+ }
382
+ /** Whether a field should be shown, and whether it must be answered. */
383
+ interface FieldState {
384
+ visible: boolean;
385
+ required: boolean;
386
+ }
387
+ /**
388
+ * Reject an unparseable condition at config time.
389
+ *
390
+ * Called while a chapter or CRM config is being resolved, so a typo is a build
391
+ * error rather than a field that quietly misbehaves on a live join page.
392
+ *
393
+ * @throws Error naming the field and the parse failure.
394
+ */
395
+ declare function assertFieldCondition(expression: string, label: string): void;
396
+ /**
397
+ * Evaluate one condition against the current answers.
398
+ *
399
+ * An unanswered field reads as the empty string rather than raising. That
400
+ * matters more than it sounds: on first paint nothing is answered, so without
401
+ * it every condition would error at once and each conditional field would
402
+ * flash into view before vanishing. It also makes conditions read the way an
403
+ * author expects — `values.country == "US"` is false before anyone has picked
404
+ * a country, and `values.country != "US"` is true — with no `has()` ceremony.
405
+ *
406
+ * A genuinely unevaluable expression yields `fallback`. Those are rare by
407
+ * construction, because {@link assertFieldCondition} rejects unparseable
408
+ * conditions when the config is resolved.
409
+ */
410
+ declare function evaluateFieldCondition(expression: FieldCondition, values: Record<string, unknown>, fallback: boolean): boolean;
411
+ /**
412
+ * Resolve a field's live state from its conditions and the answers so far.
413
+ *
414
+ * `staticRequired` is the field's unconditional requiredness, used when it
415
+ * declares no `requiredWhen`. A field that is not visible is never required —
416
+ * demanding an answer to a question nobody was asked is unsatisfiable.
417
+ */
418
+ declare function resolveFieldState(conditions: FieldConditions | undefined, values: Record<string, unknown>, staticRequired?: boolean): FieldState;
419
+ /** Resolve every declared field at once, for a renderer or a validator. */
420
+ declare function resolveFieldStates(conditions: Readonly<Record<string, FieldConditions>>, values: Record<string, unknown>, staticRequired?: readonly string[]): Record<string, FieldState>;
421
+
373
422
  /** Value kinds a custom field can hold. `email`/`url`/`enum` are validated
374
423
  * strings; `date` accepts epoch ms or ISO strings and stores epoch ms. */
375
424
  type FieldType = "string" | "number" | "boolean" | "date" | "email" | "url" | "enum" | "json";
@@ -385,6 +434,12 @@ interface FieldDef {
385
434
  slot?: CrmSlot;
386
435
  /** Include in the FTS haystack. Defaults to true for string-ish fields. */
387
436
  search?: boolean;
437
+ /** Show this field only while the CEL condition holds, e.g.
438
+ * `values.country == "US"`. Absent means always visible. */
439
+ visibleWhen?: FieldCondition;
440
+ /** Demand a value only while the CEL condition holds. Absent falls back to
441
+ * `required`. A hidden field is never required. */
442
+ requiredWhen?: FieldCondition;
388
443
  }
389
444
  /** One pipeline stage; declaration order is the sort order (`stageIndex`). */
390
445
  interface StageDef {
@@ -1472,4 +1527,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1472
1527
  */
1473
1528
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1474
1529
 
1475
- 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 CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, 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, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, 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, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1530
+ 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 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 };
package/dist/index.d.ts CHANGED
@@ -370,6 +370,55 @@ type PreparedWrite = {
370
370
  errors: Record<string, string>;
371
371
  };
372
372
 
373
+ /** A CEL expression over `values`, e.g. `values.country == "US"`. */
374
+ type FieldCondition = string;
375
+ /** Conditions a field declaration may carry. */
376
+ interface FieldConditions {
377
+ /** Render the field only while this holds. Absent means always visible. */
378
+ visibleWhen?: FieldCondition;
379
+ /** Demand a value only while this holds. Absent means the static `required`. */
380
+ requiredWhen?: FieldCondition;
381
+ }
382
+ /** Whether a field should be shown, and whether it must be answered. */
383
+ interface FieldState {
384
+ visible: boolean;
385
+ required: boolean;
386
+ }
387
+ /**
388
+ * Reject an unparseable condition at config time.
389
+ *
390
+ * Called while a chapter or CRM config is being resolved, so a typo is a build
391
+ * error rather than a field that quietly misbehaves on a live join page.
392
+ *
393
+ * @throws Error naming the field and the parse failure.
394
+ */
395
+ declare function assertFieldCondition(expression: string, label: string): void;
396
+ /**
397
+ * Evaluate one condition against the current answers.
398
+ *
399
+ * An unanswered field reads as the empty string rather than raising. That
400
+ * matters more than it sounds: on first paint nothing is answered, so without
401
+ * it every condition would error at once and each conditional field would
402
+ * flash into view before vanishing. It also makes conditions read the way an
403
+ * author expects — `values.country == "US"` is false before anyone has picked
404
+ * a country, and `values.country != "US"` is true — with no `has()` ceremony.
405
+ *
406
+ * A genuinely unevaluable expression yields `fallback`. Those are rare by
407
+ * construction, because {@link assertFieldCondition} rejects unparseable
408
+ * conditions when the config is resolved.
409
+ */
410
+ declare function evaluateFieldCondition(expression: FieldCondition, values: Record<string, unknown>, fallback: boolean): boolean;
411
+ /**
412
+ * Resolve a field's live state from its conditions and the answers so far.
413
+ *
414
+ * `staticRequired` is the field's unconditional requiredness, used when it
415
+ * declares no `requiredWhen`. A field that is not visible is never required —
416
+ * demanding an answer to a question nobody was asked is unsatisfiable.
417
+ */
418
+ declare function resolveFieldState(conditions: FieldConditions | undefined, values: Record<string, unknown>, staticRequired?: boolean): FieldState;
419
+ /** Resolve every declared field at once, for a renderer or a validator. */
420
+ declare function resolveFieldStates(conditions: Readonly<Record<string, FieldConditions>>, values: Record<string, unknown>, staticRequired?: readonly string[]): Record<string, FieldState>;
421
+
373
422
  /** Value kinds a custom field can hold. `email`/`url`/`enum` are validated
374
423
  * strings; `date` accepts epoch ms or ISO strings and stores epoch ms. */
375
424
  type FieldType = "string" | "number" | "boolean" | "date" | "email" | "url" | "enum" | "json";
@@ -385,6 +434,12 @@ interface FieldDef {
385
434
  slot?: CrmSlot;
386
435
  /** Include in the FTS haystack. Defaults to true for string-ish fields. */
387
436
  search?: boolean;
437
+ /** Show this field only while the CEL condition holds, e.g.
438
+ * `values.country == "US"`. Absent means always visible. */
439
+ visibleWhen?: FieldCondition;
440
+ /** Demand a value only while the CEL condition holds. Absent falls back to
441
+ * `required`. A hidden field is never required. */
442
+ requiredWhen?: FieldCondition;
388
443
  }
389
444
  /** One pipeline stage; declaration order is the sort order (`stageIndex`). */
390
445
  interface StageDef {
@@ -1472,4 +1527,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1472
1527
  */
1473
1528
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1474
1529
 
1475
- 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 CrmView, DEFAULT_LIMIT, EMAIL_STATUSES, type EmailStatus, type FieldDef, type FieldFilter, 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, canEmail, canTransition, channelKey, compileList, composeCrmConfigs, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, 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, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView, upsertRecordOrigin };
1530
+ 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 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 };
package/dist/index.js CHANGED
@@ -320,6 +320,45 @@ function lintTemplate(template, knownVars) {
320
320
  };
321
321
  }
322
322
 
323
+ // src/field-conditions.ts
324
+ import { Environment, ParseError } from "@marcbachmann/cel-js";
325
+ var env = new Environment({ unlistedVariablesAreDyn: true });
326
+ function assertFieldCondition(expression, label) {
327
+ try {
328
+ env.evaluate(expression, { values: {} });
329
+ } catch (error) {
330
+ if (error instanceof ParseError) {
331
+ throw new Error(`${label}: not a valid CEL condition \u2014 ${error.message}`);
332
+ }
333
+ }
334
+ }
335
+ var REFERENCED = /\bvalues\.([A-Za-z_][A-Za-z0-9_]*)/g;
336
+ function evaluateFieldCondition(expression, values, fallback) {
337
+ const unanswered = {};
338
+ for (const [, name] of expression.matchAll(REFERENCED)) {
339
+ if (name !== void 0 && !(name in values)) unanswered[name] = "";
340
+ }
341
+ try {
342
+ return env.evaluate(expression, { values: { ...unanswered, ...values } }) === true;
343
+ } catch {
344
+ return fallback;
345
+ }
346
+ }
347
+ function resolveFieldState(conditions, values, staticRequired = false) {
348
+ const visible = conditions?.visibleWhen === void 0 ? true : evaluateFieldCondition(conditions.visibleWhen, values, true);
349
+ if (!visible) return { visible: false, required: false };
350
+ const required2 = conditions?.requiredWhen === void 0 ? staticRequired : evaluateFieldCondition(conditions.requiredWhen, values, false);
351
+ return { visible, required: required2 };
352
+ }
353
+ function resolveFieldStates(conditions, values, staticRequired = []) {
354
+ const required2 = new Set(staticRequired);
355
+ const out = {};
356
+ for (const field of /* @__PURE__ */ new Set([...Object.keys(conditions), ...required2])) {
357
+ out[field] = resolveFieldState(conditions[field], values, required2.has(field));
358
+ }
359
+ return out;
360
+ }
361
+
323
362
  // src/validate.ts
324
363
  var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
325
364
  var STRINGISH = /* @__PURE__ */ new Set(["string", "email", "url", "enum"]);
@@ -458,6 +497,18 @@ function checkType(typeName, def) {
458
497
  if (field.type === "enum" && !(field.options && field.options.length > 0))
459
498
  fail(fat, "enum fields need non-empty options");
460
499
  if (field.type !== "enum" && field.options) fail(fat, "options are for enum fields only");
500
+ for (const key of ["visibleWhen", "requiredWhen"]) {
501
+ const expression = field[key];
502
+ if (expression === void 0) continue;
503
+ if (typeof expression !== "string" || !expression.trim()) {
504
+ fail(`${fat}.${key}`, "must be a non-empty CEL condition");
505
+ }
506
+ try {
507
+ assertFieldCondition(expression, `${fat}.${key}`);
508
+ } catch (error) {
509
+ fail(`${fat}.${key}`, error instanceof Error ? error.message : "invalid condition");
510
+ }
511
+ }
461
512
  if (field.slot) {
462
513
  if (!CRM_SLOTS.includes(field.slot)) fail(fat, `unknown slot ${field.slot}`);
463
514
  if (!SLOT_KIND[field.slot].includes(field.type))
@@ -1138,6 +1189,14 @@ async function listLinks(deps, recordId) {
1138
1189
  return (result[CRM_NS.link] ?? []).map((row) => row);
1139
1190
  }
1140
1191
 
1192
+ // src/time.ts
1193
+ function epochOf(value) {
1194
+ if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
1195
+ if (typeof value !== "string") return void 0;
1196
+ const parsed = Date.parse(value);
1197
+ return Number.isNaN(parsed) ? void 0 : parsed;
1198
+ }
1199
+
1141
1200
  // src/provenance.ts
1142
1201
  var SOURCE_ID = /^[a-z0-9][a-z0-9-]{1,127}$/;
1143
1202
  var TARGET_ID = SOURCE_ID;
@@ -1152,11 +1211,20 @@ function recordOriginKey(sourceId, sourceRecordId) {
1152
1211
  if (!SOURCE_ID.test(source)) throw new CrmInputError("sourceId must be a lowercase app slug");
1153
1212
  return `${source}:${record}`;
1154
1213
  }
1214
+ function originRow(row) {
1215
+ const out = { ...row };
1216
+ for (const field of ["firstReceivedAt", "lastReceivedAt"]) {
1217
+ const parsed = epochOf(out[field]);
1218
+ if (parsed !== void 0) out[field] = parsed;
1219
+ }
1220
+ return out;
1221
+ }
1155
1222
  async function getRecordOrigin(deps, sourceId, sourceRecordId) {
1156
1223
  const { db } = resolveDeps(deps);
1157
1224
  const key = recordOriginKey(sourceId, sourceRecordId);
1158
1225
  const result = await db.query({ [CRM_NS.origin]: { $: { where: { key }, limit: 1 } } });
1159
- return (result[CRM_NS.origin] ?? [])[0] ?? null;
1226
+ const row = (result[CRM_NS.origin] ?? [])[0];
1227
+ return row ? originRow(row) : null;
1160
1228
  }
1161
1229
  async function getRecordByOrigin(deps, sourceId, sourceRecordId) {
1162
1230
  const origin = await getRecordOrigin(deps, sourceId, sourceRecordId);
@@ -1202,7 +1270,7 @@ async function listRecordOrigins(deps, recordId) {
1202
1270
  const result = await db.query({
1203
1271
  [CRM_NS.origin]: { $: { where: { recordId }, order: { firstReceivedAt: "asc" }, limit: 200 } }
1204
1272
  });
1205
- return result[CRM_NS.origin] ?? [];
1273
+ return (result[CRM_NS.origin] ?? []).map(originRow);
1206
1274
  }
1207
1275
  function recordDeliveryKey(recordId, targetId) {
1208
1276
  const record = required(recordId, "recordId");
@@ -2547,6 +2615,7 @@ export {
2547
2615
  addTag,
2548
2616
  applyConsent,
2549
2617
  applyConsentEvent,
2618
+ assertFieldCondition,
2550
2619
  canEmail,
2551
2620
  canTransition,
2552
2621
  channelKey,
@@ -2563,6 +2632,7 @@ export {
2563
2632
  defineCrm,
2564
2633
  deleteView,
2565
2634
  emailChannelOps,
2635
+ evaluateFieldCondition,
2566
2636
  foldEmailStatus,
2567
2637
  formatCrmDiscussionReference,
2568
2638
  getConfig,
@@ -2598,6 +2668,8 @@ export {
2598
2668
  removeTag,
2599
2669
  renderTemplate,
2600
2670
  resolveDeps,
2671
+ resolveFieldState,
2672
+ resolveFieldStates,
2601
2673
  resolveSortColumn,
2602
2674
  rowToRecord,
2603
2675
  saveConfig,