@odla-ai/crm 0.4.0 → 0.6.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
@@ -8,6 +8,8 @@ declare const CRM_NS: {
8
8
  readonly emailLog: "crm_email_log";
9
9
  readonly view: "crm_view";
10
10
  readonly config: "crm_config";
11
+ readonly origin: "crm_record_origin";
12
+ readonly delivery: "crm_record_delivery";
11
13
  };
12
14
  /** Generic promoted columns a type's custom fields can claim for indexed
13
15
  * sort/filter: four strings, three numbers, two dates. Slots are per-type
@@ -75,7 +77,7 @@ interface SerializedSchema {
75
77
  links: Record<string, SerializedLink>;
76
78
  }
77
79
  /**
78
- * The pre-serialized (wire-shape) odla-db schema for the eight crm
80
+ * The pre-serialized (wire-shape) odla-db schema for the ten crm
79
81
  * namespaces; POST it to `/app/:id/schema` as `{ schema: CRM_SCHEMA }`.
80
82
  * One generic `crm_record` holds every record type (the type registry is
81
83
  * app config, not schema); natural-key uniqueness on tags, links, channels,
@@ -328,6 +330,32 @@ interface CrmConfigRow {
328
330
  settings: Record<string, unknown>;
329
331
  updatedAt: number;
330
332
  }
333
+ /** Structured upstream identity for a record received from another app. */
334
+ interface CrmRecordOrigin {
335
+ id: string;
336
+ key: string;
337
+ recordId: string;
338
+ sourceId: string;
339
+ sourceRecordId: string;
340
+ sourceUrl?: string;
341
+ payloadVersion: number;
342
+ firstReceivedAt: number;
343
+ lastReceivedAt: number;
344
+ }
345
+ /** Latest delivery state for one local record → remote target edge. */
346
+ interface CrmRecordDelivery {
347
+ id: string;
348
+ key: string;
349
+ recordId: string;
350
+ targetId: string;
351
+ remoteRecordId?: string;
352
+ status: "delivered" | "failed";
353
+ attempts: number;
354
+ payloadVersion: number;
355
+ lastAttemptAt: number;
356
+ deliveredAt?: number;
357
+ error?: string;
358
+ }
331
359
  /** Outcome of validating + coercing input for a type (see `prepare`). On
332
360
  * success, `attrs` are the columns to WRITE (never null — odla-db rejects null
333
361
  * on a typed scalar) and `retract` names the slots/promoted columns to CLEAR
@@ -386,6 +414,9 @@ interface TypeFacets {
386
414
  interface TypeDef {
387
415
  label: string;
388
416
  labelPlural?: string;
417
+ /** Optional admin collection group. Hosts can keep people and portfolio
418
+ * records in separate workspaces without moving either outside the CRM. */
419
+ workspace?: string;
389
420
  /** Field mapped to the promoted `name` column. Default `"name"`. */
390
421
  nameField?: string;
391
422
  /** `email`-typed field mapped to `primaryEmail` (lowercased) and backed by
@@ -443,6 +474,12 @@ interface Crm {
443
474
  * request runs.
444
475
  */
445
476
  declare function defineCrm(config: CrmConfig): Crm;
477
+ /**
478
+ * Compose independently-owned CRM config fragments. Duplicate type, relation,
479
+ * or template ids fail closed so adopting a feature preset cannot silently
480
+ * replace a host's operating pipeline or email classification.
481
+ */
482
+ declare function composeCrmConfigs(...configs: readonly CrmConfig[]): CrmConfig;
446
483
 
447
484
  /** The stage a new record of this type starts in (first declared stage). */
448
485
  declare function initialStage(def: TypeDef): string | undefined;
@@ -801,6 +838,47 @@ declare function removeLink(deps: CrmDeps, opts: {
801
838
  /** Every link touching a record, either direction. */
802
839
  declare function listLinks(deps: CrmDeps, recordId: string): Promise<CrmLink[]>;
803
840
 
841
+ /** Stable natural key for an upstream record identity. */
842
+ declare function recordOriginKey(sourceId: string, sourceRecordId: string): string;
843
+ /** Look up a structured origin row by upstream site + record id. */
844
+ declare function getRecordOrigin(deps: CrmDeps, sourceId: string, sourceRecordId: string): Promise<CrmRecordOrigin | null>;
845
+ /** Resolve the local CRM record identified by an upstream origin. */
846
+ declare function getRecordByOrigin(deps: CrmDeps, sourceId: string, sourceRecordId: string): Promise<CrmRecord | null>;
847
+ /** Idempotently bind one upstream record identity to a local CRM record. */
848
+ declare function upsertRecordOrigin(deps: CrmDeps, opts: {
849
+ recordId: string;
850
+ sourceId: string;
851
+ sourceRecordId: string;
852
+ sourceUrl?: string;
853
+ payloadVersion: number;
854
+ mutationId?: string;
855
+ }): Promise<{
856
+ origin: CrmRecordOrigin;
857
+ duplicate: boolean;
858
+ }>;
859
+ /** List every upstream identity attached to a local record. */
860
+ declare function listRecordOrigins(deps: CrmDeps, recordId: string): Promise<CrmRecordOrigin[]>;
861
+ /** Stable natural key for one local record → target delivery edge. */
862
+ declare function recordDeliveryKey(recordId: string, targetId: string): string;
863
+ /** Record one success or failure while retaining the latest edge state. */
864
+ declare function recordDeliveryAttempt(deps: CrmDeps, opts: {
865
+ recordId: string;
866
+ targetId: string;
867
+ status: "delivered" | "failed";
868
+ payloadVersion: number;
869
+ remoteRecordId?: string;
870
+ error?: string;
871
+ mutationId?: string;
872
+ }): Promise<{
873
+ delivery: CrmRecordDelivery;
874
+ duplicate: boolean;
875
+ }>;
876
+ /** List delivery state for one record, or every edge to one target. */
877
+ declare function listRecordDeliveries(deps: CrmDeps, filter: {
878
+ recordId?: string;
879
+ targetId?: string;
880
+ }): Promise<CrmRecordDelivery[]>;
881
+
804
882
  /** Append a note/call/meeting or open a follow-up task on a record. */
805
883
  declare function addActivity(deps: CrmDeps, opts: {
806
884
  recordId: string;
@@ -1164,6 +1242,10 @@ interface RecordDetail {
1164
1242
  tags: CrmTag[];
1165
1243
  channels: CrmContactChannel[];
1166
1244
  links: CrmLink[];
1245
+ /** Structured upstream identities; absent only from pre-upgrade custom APIs. */
1246
+ origins?: CrmRecordOrigin[];
1247
+ /** Latest outbound state per target; absent only from pre-upgrade custom APIs. */
1248
+ deliveries?: CrmRecordDelivery[];
1167
1249
  }
1168
1250
  /** One list window plus the total matching count. */
1169
1251
  interface RecordPage {
@@ -1390,4 +1472,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1390
1472
  */
1391
1473
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1392
1474
 
1393
- 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 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, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
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 };
package/dist/index.d.ts CHANGED
@@ -8,6 +8,8 @@ declare const CRM_NS: {
8
8
  readonly emailLog: "crm_email_log";
9
9
  readonly view: "crm_view";
10
10
  readonly config: "crm_config";
11
+ readonly origin: "crm_record_origin";
12
+ readonly delivery: "crm_record_delivery";
11
13
  };
12
14
  /** Generic promoted columns a type's custom fields can claim for indexed
13
15
  * sort/filter: four strings, three numbers, two dates. Slots are per-type
@@ -75,7 +77,7 @@ interface SerializedSchema {
75
77
  links: Record<string, SerializedLink>;
76
78
  }
77
79
  /**
78
- * The pre-serialized (wire-shape) odla-db schema for the eight crm
80
+ * The pre-serialized (wire-shape) odla-db schema for the ten crm
79
81
  * namespaces; POST it to `/app/:id/schema` as `{ schema: CRM_SCHEMA }`.
80
82
  * One generic `crm_record` holds every record type (the type registry is
81
83
  * app config, not schema); natural-key uniqueness on tags, links, channels,
@@ -328,6 +330,32 @@ interface CrmConfigRow {
328
330
  settings: Record<string, unknown>;
329
331
  updatedAt: number;
330
332
  }
333
+ /** Structured upstream identity for a record received from another app. */
334
+ interface CrmRecordOrigin {
335
+ id: string;
336
+ key: string;
337
+ recordId: string;
338
+ sourceId: string;
339
+ sourceRecordId: string;
340
+ sourceUrl?: string;
341
+ payloadVersion: number;
342
+ firstReceivedAt: number;
343
+ lastReceivedAt: number;
344
+ }
345
+ /** Latest delivery state for one local record → remote target edge. */
346
+ interface CrmRecordDelivery {
347
+ id: string;
348
+ key: string;
349
+ recordId: string;
350
+ targetId: string;
351
+ remoteRecordId?: string;
352
+ status: "delivered" | "failed";
353
+ attempts: number;
354
+ payloadVersion: number;
355
+ lastAttemptAt: number;
356
+ deliveredAt?: number;
357
+ error?: string;
358
+ }
331
359
  /** Outcome of validating + coercing input for a type (see `prepare`). On
332
360
  * success, `attrs` are the columns to WRITE (never null — odla-db rejects null
333
361
  * on a typed scalar) and `retract` names the slots/promoted columns to CLEAR
@@ -386,6 +414,9 @@ interface TypeFacets {
386
414
  interface TypeDef {
387
415
  label: string;
388
416
  labelPlural?: string;
417
+ /** Optional admin collection group. Hosts can keep people and portfolio
418
+ * records in separate workspaces without moving either outside the CRM. */
419
+ workspace?: string;
389
420
  /** Field mapped to the promoted `name` column. Default `"name"`. */
390
421
  nameField?: string;
391
422
  /** `email`-typed field mapped to `primaryEmail` (lowercased) and backed by
@@ -443,6 +474,12 @@ interface Crm {
443
474
  * request runs.
444
475
  */
445
476
  declare function defineCrm(config: CrmConfig): Crm;
477
+ /**
478
+ * Compose independently-owned CRM config fragments. Duplicate type, relation,
479
+ * or template ids fail closed so adopting a feature preset cannot silently
480
+ * replace a host's operating pipeline or email classification.
481
+ */
482
+ declare function composeCrmConfigs(...configs: readonly CrmConfig[]): CrmConfig;
446
483
 
447
484
  /** The stage a new record of this type starts in (first declared stage). */
448
485
  declare function initialStage(def: TypeDef): string | undefined;
@@ -801,6 +838,47 @@ declare function removeLink(deps: CrmDeps, opts: {
801
838
  /** Every link touching a record, either direction. */
802
839
  declare function listLinks(deps: CrmDeps, recordId: string): Promise<CrmLink[]>;
803
840
 
841
+ /** Stable natural key for an upstream record identity. */
842
+ declare function recordOriginKey(sourceId: string, sourceRecordId: string): string;
843
+ /** Look up a structured origin row by upstream site + record id. */
844
+ declare function getRecordOrigin(deps: CrmDeps, sourceId: string, sourceRecordId: string): Promise<CrmRecordOrigin | null>;
845
+ /** Resolve the local CRM record identified by an upstream origin. */
846
+ declare function getRecordByOrigin(deps: CrmDeps, sourceId: string, sourceRecordId: string): Promise<CrmRecord | null>;
847
+ /** Idempotently bind one upstream record identity to a local CRM record. */
848
+ declare function upsertRecordOrigin(deps: CrmDeps, opts: {
849
+ recordId: string;
850
+ sourceId: string;
851
+ sourceRecordId: string;
852
+ sourceUrl?: string;
853
+ payloadVersion: number;
854
+ mutationId?: string;
855
+ }): Promise<{
856
+ origin: CrmRecordOrigin;
857
+ duplicate: boolean;
858
+ }>;
859
+ /** List every upstream identity attached to a local record. */
860
+ declare function listRecordOrigins(deps: CrmDeps, recordId: string): Promise<CrmRecordOrigin[]>;
861
+ /** Stable natural key for one local record → target delivery edge. */
862
+ declare function recordDeliveryKey(recordId: string, targetId: string): string;
863
+ /** Record one success or failure while retaining the latest edge state. */
864
+ declare function recordDeliveryAttempt(deps: CrmDeps, opts: {
865
+ recordId: string;
866
+ targetId: string;
867
+ status: "delivered" | "failed";
868
+ payloadVersion: number;
869
+ remoteRecordId?: string;
870
+ error?: string;
871
+ mutationId?: string;
872
+ }): Promise<{
873
+ delivery: CrmRecordDelivery;
874
+ duplicate: boolean;
875
+ }>;
876
+ /** List delivery state for one record, or every edge to one target. */
877
+ declare function listRecordDeliveries(deps: CrmDeps, filter: {
878
+ recordId?: string;
879
+ targetId?: string;
880
+ }): Promise<CrmRecordDelivery[]>;
881
+
804
882
  /** Append a note/call/meeting or open a follow-up task on a record. */
805
883
  declare function addActivity(deps: CrmDeps, opts: {
806
884
  recordId: string;
@@ -1164,6 +1242,10 @@ interface RecordDetail {
1164
1242
  tags: CrmTag[];
1165
1243
  channels: CrmContactChannel[];
1166
1244
  links: CrmLink[];
1245
+ /** Structured upstream identities; absent only from pre-upgrade custom APIs. */
1246
+ origins?: CrmRecordOrigin[];
1247
+ /** Latest outbound state per target; absent only from pre-upgrade custom APIs. */
1248
+ deliveries?: CrmRecordDelivery[];
1167
1249
  }
1168
1250
  /** One list window plus the total matching count. */
1169
1251
  interface RecordPage {
@@ -1390,4 +1472,4 @@ declare const crmIntegration: CrmIntegrationDescriptor;
1390
1472
  */
1391
1473
  declare function createCrmIntegration(crm: Crm, options?: CrmIntegrationOptions): CrmIntegrationDescriptor;
1392
1474
 
1393
- 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 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, createCrmIntegration, createCrmRoutes, createRecord, crmDiscussionReferenceHref, crmDiscussionReferenceId, crmIntegration, crmRules, defaultTemplates, defineCrm, deleteView, emailChannelOps, foldEmailStatus, formatCrmDiscussionReference, getConfig, getRecord, initialStage, linkIdentity, lintTemplate, listActivities, listChannels, listEmailLog, listLinks, listRecords, listTags, listTasks, listViews, mustGetRecord, needsRebalance, normalizeTag, parseCrmDiscussionReference, prepare, rankBetween, rebalancePlan, rebalanceRanks, recordCanEmail, removeLink, removeTag, renderTemplate, resolveDeps, resolveSortColumn, rowToRecord, saveConfig, saveView, searchTextFor, sendTemplatedEmail, setArchived, setRank, setStage, stageIndexOf, templateVars, typeSummary, updateRecord, updateTask, updateView };
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 };
package/dist/index.js CHANGED
@@ -7,7 +7,9 @@ var CRM_NS = {
7
7
  channel: "crm_contact_channel",
8
8
  emailLog: "crm_email_log",
9
9
  view: "crm_view",
10
- config: "crm_config"
10
+ config: "crm_config",
11
+ origin: "crm_record_origin",
12
+ delivery: "crm_record_delivery"
11
13
  };
12
14
  var CRM_SLOTS = ["s1", "s2", "s3", "s4", "n1", "n2", "n3", "d1", "d2"];
13
15
  var CONSENT_STATES = ["subscribed", "unsubscribed", "bounced", "suppressed"];
@@ -205,6 +207,37 @@ var CRM_SCHEMA = {
205
207
  settings: a("json"),
206
208
  updatedAt: idx("date")
207
209
  }
210
+ },
211
+ [CRM_NS.origin]: {
212
+ attrs: {
213
+ // One upstream record maps to one local record. The structured source
214
+ // survives tag edits and supports more than one upstream site.
215
+ key: uniq("string"),
216
+ // `${sourceId}:${sourceRecordId}`
217
+ recordId: idx("string"),
218
+ sourceId: idx("string"),
219
+ sourceRecordId: idx("string"),
220
+ sourceUrl: opt("string"),
221
+ payloadVersion: idx("number"),
222
+ firstReceivedAt: idx("date"),
223
+ lastReceivedAt: idx("date")
224
+ }
225
+ },
226
+ [CRM_NS.delivery]: {
227
+ attrs: {
228
+ // The latest delivery state for one local record → target edge.
229
+ key: uniq("string"),
230
+ // `${recordId}:${targetId}`
231
+ recordId: idx("string"),
232
+ targetId: idx("string"),
233
+ remoteRecordId: idx("string", true),
234
+ status: idx("string"),
235
+ attempts: idx("number"),
236
+ payloadVersion: idx("number"),
237
+ lastAttemptAt: idx("date"),
238
+ deliveredAt: idx("date", true),
239
+ error: opt("string")
240
+ }
208
241
  }
209
242
  },
210
243
  links: {}
@@ -414,6 +447,9 @@ function fail(path, message) {
414
447
  function checkType(typeName, def) {
415
448
  const at = `types.${typeName}`;
416
449
  if (!NAME_RE.test(typeName)) fail(at, "must match /^[a-z][a-z0-9_-]*$/");
450
+ if (def.workspace != null && !NAME_RE.test(def.workspace)) {
451
+ fail(`${at}.workspace`, "must match /^[a-z][a-z0-9_-]*$/");
452
+ }
417
453
  const claimed = /* @__PURE__ */ new Map();
418
454
  for (const [fieldName, field] of Object.entries(def.fields)) {
419
455
  const fat = `${at}.fields.${fieldName}`;
@@ -494,6 +530,28 @@ ${tpl.defaults.text}`, tpl.vars);
494
530
  stageIndex: (name, stage) => stageIndexOf(type(name), stage)
495
531
  };
496
532
  }
533
+ function composeCrmConfigs(...configs) {
534
+ if (configs.length === 0) throw new Error("composeCrmConfigs: at least one config is required");
535
+ const result = { types: {} };
536
+ const merge = (kind, target, source) => {
537
+ for (const [id, value] of Object.entries(source ?? {})) {
538
+ if (Object.hasOwn(target, id)) throw new Error(`composeCrmConfigs: duplicate ${kind} "${id}"`);
539
+ target[id] = value;
540
+ }
541
+ };
542
+ for (const config of configs) {
543
+ merge("type", result.types, config.types);
544
+ if (config.relations) {
545
+ result.relations ??= {};
546
+ merge("relation", result.relations, config.relations);
547
+ }
548
+ if (config.templates) {
549
+ result.templates ??= {};
550
+ merge("template", result.templates, config.templates);
551
+ }
552
+ }
553
+ return result;
554
+ }
497
555
 
498
556
  // src/discussion-reference.ts
499
557
  var CRM_DISCUSSION_REFERENCE_KINDS = [
@@ -1080,6 +1138,129 @@ async function listLinks(deps, recordId) {
1080
1138
  return (result[CRM_NS.link] ?? []).map((row) => row);
1081
1139
  }
1082
1140
 
1141
+ // src/provenance.ts
1142
+ var SOURCE_ID = /^[a-z0-9][a-z0-9-]{1,127}$/;
1143
+ var TARGET_ID = SOURCE_ID;
1144
+ function required(value, label, max = 512) {
1145
+ const normalized = value.trim();
1146
+ if (!normalized || normalized.length > max) throw new CrmInputError(`${label} must be 1\u2013${max} characters`);
1147
+ return normalized;
1148
+ }
1149
+ function recordOriginKey(sourceId, sourceRecordId) {
1150
+ const source = required(sourceId, "sourceId", 128);
1151
+ const record = required(sourceRecordId, "sourceRecordId");
1152
+ if (!SOURCE_ID.test(source)) throw new CrmInputError("sourceId must be a lowercase app slug");
1153
+ return `${source}:${record}`;
1154
+ }
1155
+ async function getRecordOrigin(deps, sourceId, sourceRecordId) {
1156
+ const { db } = resolveDeps(deps);
1157
+ const key = recordOriginKey(sourceId, sourceRecordId);
1158
+ const result = await db.query({ [CRM_NS.origin]: { $: { where: { key }, limit: 1 } } });
1159
+ return (result[CRM_NS.origin] ?? [])[0] ?? null;
1160
+ }
1161
+ async function getRecordByOrigin(deps, sourceId, sourceRecordId) {
1162
+ const origin = await getRecordOrigin(deps, sourceId, sourceRecordId);
1163
+ return origin ? getRecord(deps, origin.recordId) : null;
1164
+ }
1165
+ async function upsertRecordOrigin(deps, opts) {
1166
+ const { db, now } = resolveDeps(deps);
1167
+ await mustGetRecord(deps, opts.recordId);
1168
+ const key = recordOriginKey(opts.sourceId, opts.sourceRecordId);
1169
+ if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {
1170
+ throw new CrmInputError("payloadVersion must be a positive integer");
1171
+ }
1172
+ const sourceUrl = opts.sourceUrl == null ? void 0 : required(opts.sourceUrl, "sourceUrl", 2048);
1173
+ const existing = await getRecordOrigin(deps, opts.sourceId, opts.sourceRecordId);
1174
+ if (existing && existing.recordId !== opts.recordId) {
1175
+ throw new CrmInputError("upstream record is already bound to another local record");
1176
+ }
1177
+ const at = now();
1178
+ const attrs = {
1179
+ key,
1180
+ recordId: opts.recordId,
1181
+ sourceId: opts.sourceId,
1182
+ sourceRecordId: opts.sourceRecordId,
1183
+ payloadVersion: opts.payloadVersion,
1184
+ firstReceivedAt: existing?.firstReceivedAt ?? at,
1185
+ lastReceivedAt: at,
1186
+ ...sourceUrl ? { sourceUrl } : {}
1187
+ };
1188
+ const { duplicate } = await db.transact(
1189
+ [{ t: "update", ns: CRM_NS.origin, id: { ns: CRM_NS.origin, attr: "key", value: key }, attrs }],
1190
+ { mutationId: opts.mutationId }
1191
+ );
1192
+ return {
1193
+ duplicate,
1194
+ origin: {
1195
+ id: existing?.id ?? key,
1196
+ ...attrs
1197
+ }
1198
+ };
1199
+ }
1200
+ async function listRecordOrigins(deps, recordId) {
1201
+ const { db } = resolveDeps(deps);
1202
+ const result = await db.query({
1203
+ [CRM_NS.origin]: { $: { where: { recordId }, order: { firstReceivedAt: "asc" }, limit: 200 } }
1204
+ });
1205
+ return result[CRM_NS.origin] ?? [];
1206
+ }
1207
+ function recordDeliveryKey(recordId, targetId) {
1208
+ const record = required(recordId, "recordId");
1209
+ const target = required(targetId, "targetId", 128);
1210
+ if (!TARGET_ID.test(target)) throw new CrmInputError("targetId must be a lowercase app slug");
1211
+ return `${record}:${target}`;
1212
+ }
1213
+ async function recordDeliveryAttempt(deps, opts) {
1214
+ const { db, now } = resolveDeps(deps);
1215
+ await mustGetRecord(deps, opts.recordId);
1216
+ const key = recordDeliveryKey(opts.recordId, opts.targetId);
1217
+ if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {
1218
+ throw new CrmInputError("payloadVersion must be a positive integer");
1219
+ }
1220
+ const found = await db.query({ [CRM_NS.delivery]: { $: { where: { key }, limit: 1 } } });
1221
+ const existing = (found[CRM_NS.delivery] ?? [])[0];
1222
+ const at = now();
1223
+ const remoteRecordId = opts.remoteRecordId == null ? existing?.remoteRecordId : required(opts.remoteRecordId, "remoteRecordId");
1224
+ const error = opts.error == null ? void 0 : required(opts.error, "error", 1e3);
1225
+ const attrs = {
1226
+ key,
1227
+ recordId: opts.recordId,
1228
+ targetId: opts.targetId,
1229
+ status: opts.status,
1230
+ attempts: (existing?.attempts ?? 0) + 1,
1231
+ payloadVersion: opts.payloadVersion,
1232
+ lastAttemptAt: at,
1233
+ ...remoteRecordId ? { remoteRecordId } : {},
1234
+ ...opts.status === "delivered" ? { deliveredAt: at } : existing?.deliveredAt ? { deliveredAt: existing.deliveredAt } : {},
1235
+ ...error ? { error } : {}
1236
+ };
1237
+ const ref = { ns: CRM_NS.delivery, attr: "key", value: key };
1238
+ const ops = [{ t: "update", ns: CRM_NS.delivery, id: ref, attrs }];
1239
+ if (opts.status === "delivered" && existing?.error) {
1240
+ ops.push({ t: "retract", ns: CRM_NS.delivery, id: ref, attrs: ["error"] });
1241
+ }
1242
+ const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });
1243
+ return {
1244
+ duplicate,
1245
+ delivery: {
1246
+ id: existing?.id ?? key,
1247
+ ...attrs
1248
+ }
1249
+ };
1250
+ }
1251
+ async function listRecordDeliveries(deps, filter) {
1252
+ if (!filter.recordId && !filter.targetId) throw new CrmInputError("recordId or targetId is required");
1253
+ const { db } = resolveDeps(deps);
1254
+ const where = {
1255
+ ...filter.recordId ? { recordId: required(filter.recordId, "recordId") } : {},
1256
+ ...filter.targetId ? { targetId: required(filter.targetId, "targetId", 128) } : {}
1257
+ };
1258
+ const result = await db.query({
1259
+ [CRM_NS.delivery]: { $: { where, order: { lastAttemptAt: "desc" }, limit: 500 } }
1260
+ });
1261
+ return result[CRM_NS.delivery] ?? [];
1262
+ }
1263
+
1083
1264
  // src/activities.ts
1084
1265
  var rowToActivity = (row) => row;
1085
1266
  async function addActivity(deps, opts) {
@@ -1797,12 +1978,14 @@ async function handleRecordItem(ctx, req, id) {
1797
1978
  if (req.method === "GET") {
1798
1979
  const record = await getRecord(ctx.deps, id);
1799
1980
  if (!record) throw new CrmNotFoundError("record");
1800
- const [tags, channels, links] = await Promise.all([
1981
+ const [tags, channels, links, origins, deliveries] = await Promise.all([
1801
1982
  listTags(ctx.deps, id),
1802
1983
  listChannels(ctx.deps, id),
1803
- listLinks(ctx.deps, id)
1984
+ listLinks(ctx.deps, id),
1985
+ listRecordOrigins(ctx.deps, id),
1986
+ listRecordDeliveries(ctx.deps, { recordId: id })
1804
1987
  ]);
1805
- return json({ record, tags, channels, links });
1988
+ return json({ record, tags, channels, links, origins, deliveries });
1806
1989
  }
1807
1990
  if (req.method === "PATCH") {
1808
1991
  const body = await readJson(req);
@@ -2368,6 +2551,7 @@ export {
2368
2551
  canTransition,
2369
2552
  channelKey,
2370
2553
  compileList,
2554
+ composeCrmConfigs,
2371
2555
  createCrmIntegration,
2372
2556
  createCrmRoutes,
2373
2557
  createRecord,
@@ -2383,6 +2567,8 @@ export {
2383
2567
  formatCrmDiscussionReference,
2384
2568
  getConfig,
2385
2569
  getRecord,
2570
+ getRecordByOrigin,
2571
+ getRecordOrigin,
2386
2572
  initialStage,
2387
2573
  linkIdentity,
2388
2574
  lintTemplate,
@@ -2390,6 +2576,8 @@ export {
2390
2576
  listChannels,
2391
2577
  listEmailLog,
2392
2578
  listLinks,
2579
+ listRecordDeliveries,
2580
+ listRecordOrigins,
2393
2581
  listRecords,
2394
2582
  listTags,
2395
2583
  listTasks,
@@ -2403,6 +2591,9 @@ export {
2403
2591
  rebalancePlan,
2404
2592
  rebalanceRanks,
2405
2593
  recordCanEmail,
2594
+ recordDeliveryAttempt,
2595
+ recordDeliveryKey,
2596
+ recordOriginKey,
2406
2597
  removeLink,
2407
2598
  removeTag,
2408
2599
  renderTemplate,
@@ -2421,6 +2612,7 @@ export {
2421
2612
  typeSummary,
2422
2613
  updateRecord,
2423
2614
  updateTask,
2424
- updateView
2615
+ updateView,
2616
+ upsertRecordOrigin
2425
2617
  };
2426
2618
  //# sourceMappingURL=index.js.map