@happyvertical/smrt-core 0.40.70 → 0.41.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.
Files changed (157) hide show
  1. package/AGENTS.md +2 -2
  2. package/agents/change-feed.md +1 -1
  3. package/agents/schema-paths.md +487 -29
  4. package/dist/browser.js +5 -4
  5. package/dist/cascade.d.ts +120 -0
  6. package/dist/cascade.d.ts.map +1 -0
  7. package/dist/cascade.js +430 -0
  8. package/dist/cascade.js.map +1 -0
  9. package/dist/change-feed.d.ts +34 -2
  10. package/dist/change-feed.d.ts.map +1 -1
  11. package/dist/change-feed.js +52 -11
  12. package/dist/change-feed.js.map +1 -1
  13. package/dist/class.d.ts +36 -3
  14. package/dist/class.d.ts.map +1 -1
  15. package/dist/class.js +59 -5
  16. package/dist/class.js.map +1 -1
  17. package/dist/collection-cache.js +0 -0
  18. package/dist/collection-cache.js.map +1 -1
  19. package/dist/collection.d.ts +29 -0
  20. package/dist/collection.d.ts.map +1 -1
  21. package/dist/collection.js +66 -14
  22. package/dist/collection.js.map +1 -1
  23. package/dist/config.d.ts +10 -0
  24. package/dist/config.d.ts.map +1 -1
  25. package/dist/config.js.map +1 -1
  26. package/dist/decorators/index.d.ts +63 -5
  27. package/dist/decorators/index.d.ts.map +1 -1
  28. package/dist/decorators/index.js +37 -5
  29. package/dist/decorators/index.js.map +1 -1
  30. package/dist/dispatch/collections/Dispatches.d.ts.map +1 -1
  31. package/dist/dispatch/collections/Dispatches.js +19 -4
  32. package/dist/dispatch/collections/Dispatches.js.map +1 -1
  33. package/dist/dispatch/types.d.ts +5 -0
  34. package/dist/dispatch/types.d.ts.map +1 -1
  35. package/dist/embedded-write-queue.d.ts +46 -0
  36. package/dist/embedded-write-queue.d.ts.map +1 -0
  37. package/dist/embedded-write-queue.js +66 -0
  38. package/dist/embedded-write-queue.js.map +1 -0
  39. package/dist/embeddings/storage.d.ts +7 -0
  40. package/dist/embeddings/storage.d.ts.map +1 -1
  41. package/dist/embeddings/storage.js +29 -12
  42. package/dist/embeddings/storage.js.map +1 -1
  43. package/dist/errors.d.ts +1 -1
  44. package/dist/hierarchical.js +1 -1
  45. package/dist/index.d.ts +2 -1
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +8 -6
  48. package/dist/interceptors.d.ts +21 -0
  49. package/dist/interceptors.d.ts.map +1 -1
  50. package/dist/interceptors.js +27 -1
  51. package/dist/interceptors.js.map +1 -1
  52. package/dist/manifest/generator.d.ts.map +1 -1
  53. package/dist/manifest/generator.js +4 -7
  54. package/dist/manifest/generator.js.map +1 -1
  55. package/dist/manifest/static-manifest.js +10 -10
  56. package/dist/manifest/static-manifest.js.map +1 -1
  57. package/dist/manifest/store.js +1 -1
  58. package/dist/manifest/store.js.map +1 -1
  59. package/dist/manifest.json +19 -19
  60. package/dist/migrations/differ.d.ts +9 -1
  61. package/dist/migrations/differ.d.ts.map +1 -1
  62. package/dist/migrations/differ.js +10 -5
  63. package/dist/migrations/differ.js.map +1 -1
  64. package/dist/migrations/index.d.ts +1 -0
  65. package/dist/migrations/index.d.ts.map +1 -1
  66. package/dist/migrations/index.js +2 -1
  67. package/dist/migrations/minor-units.d.ts +162 -0
  68. package/dist/migrations/minor-units.d.ts.map +1 -0
  69. package/dist/migrations/minor-units.js +381 -0
  70. package/dist/migrations/minor-units.js.map +1 -0
  71. package/dist/migrations.js +2 -1
  72. package/dist/object.d.ts +98 -5
  73. package/dist/object.d.ts.map +1 -1
  74. package/dist/object.js +138 -30
  75. package/dist/object.js.map +1 -1
  76. package/dist/query-bounds.d.ts +5 -1
  77. package/dist/query-bounds.d.ts.map +1 -1
  78. package/dist/query-bounds.js +5 -1
  79. package/dist/query-bounds.js.map +1 -1
  80. package/dist/registry/class-registration.d.ts.map +1 -1
  81. package/dist/registry/class-registration.js +3 -1
  82. package/dist/registry/class-registration.js.map +1 -1
  83. package/dist/registry/manifest-field-merge.d.ts +12 -0
  84. package/dist/registry/manifest-field-merge.d.ts.map +1 -1
  85. package/dist/registry/manifest-field-merge.js +14 -2
  86. package/dist/registry/manifest-field-merge.js.map +1 -1
  87. package/dist/registry/schema-builder.d.ts +22 -1
  88. package/dist/registry/schema-builder.d.ts.map +1 -1
  89. package/dist/registry/schema-builder.js +205 -165
  90. package/dist/registry/schema-builder.js.map +1 -1
  91. package/dist/registry/types.d.ts +3 -2
  92. package/dist/registry/types.d.ts.map +1 -1
  93. package/dist/registry.d.ts +41 -46
  94. package/dist/registry.d.ts.map +1 -1
  95. package/dist/registry.js +61 -83
  96. package/dist/registry.js.map +1 -1
  97. package/dist/scanner/manifest-generator.d.ts +45 -0
  98. package/dist/scanner/manifest-generator.d.ts.map +1 -1
  99. package/dist/scanner/manifest-generator.js +92 -28
  100. package/dist/scanner/manifest-generator.js.map +1 -1
  101. package/dist/schema/conflict-target.d.ts +104 -0
  102. package/dist/schema/conflict-target.d.ts.map +1 -0
  103. package/dist/schema/conflict-target.js +129 -0
  104. package/dist/schema/conflict-target.js.map +1 -0
  105. package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
  106. package/dist/schema/ddl/duckdb-strategy.js +2 -1
  107. package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
  108. package/dist/schema/ddl/postgres-strategy.d.ts.map +1 -1
  109. package/dist/schema/ddl/postgres-strategy.js +12 -1
  110. package/dist/schema/ddl/postgres-strategy.js.map +1 -1
  111. package/dist/schema/generator.d.ts +252 -16
  112. package/dist/schema/generator.d.ts.map +1 -1
  113. package/dist/schema/generator.js +411 -106
  114. package/dist/schema/generator.js.map +1 -1
  115. package/dist/schema/index-utils.d.ts +120 -0
  116. package/dist/schema/index-utils.d.ts.map +1 -1
  117. package/dist/schema/index-utils.js +242 -1
  118. package/dist/schema/index-utils.js.map +1 -1
  119. package/dist/schema/index.d.ts +1 -1
  120. package/dist/schema/index.d.ts.map +1 -1
  121. package/dist/schema/index.js +2 -2
  122. package/dist/schema/live-parity.d.ts.map +1 -1
  123. package/dist/schema/live-parity.js +4 -2
  124. package/dist/schema/live-parity.js.map +1 -1
  125. package/dist/schema/system-table-shapes.d.ts +13 -0
  126. package/dist/schema/system-table-shapes.d.ts.map +1 -1
  127. package/dist/schema/system-table-shapes.js +14 -1
  128. package/dist/schema/system-table-shapes.js.map +1 -1
  129. package/dist/schema/utils.d.ts +1 -1
  130. package/dist/schema/utils.d.ts.map +1 -1
  131. package/dist/schema/utils.js +3 -3
  132. package/dist/schema/utils.js.map +1 -1
  133. package/dist/schema.js +2 -2
  134. package/dist/smrt-knowledge.json +9 -9
  135. package/dist/system/compatibility.d.ts +42 -0
  136. package/dist/system/compatibility.d.ts.map +1 -1
  137. package/dist/system/compatibility.js +182 -9
  138. package/dist/system/compatibility.js.map +1 -1
  139. package/dist/system/index.d.ts +1 -0
  140. package/dist/system/index.d.ts.map +1 -1
  141. package/dist/system/index.js +3 -2
  142. package/dist/system/retention.d.ts +237 -0
  143. package/dist/system/retention.d.ts.map +1 -0
  144. package/dist/system/retention.js +497 -0
  145. package/dist/system/retention.js.map +1 -0
  146. package/dist/system/schema.d.ts +100 -15
  147. package/dist/system/schema.d.ts.map +1 -1
  148. package/dist/system/schema.js +81 -45
  149. package/dist/system/schema.js.map +1 -1
  150. package/dist/system/types.d.ts +0 -2
  151. package/dist/system/types.d.ts.map +1 -1
  152. package/dist/testing/database.d.ts.map +1 -1
  153. package/dist/testing/database.js.map +1 -1
  154. package/dist/vite-plugin/index.d.ts.map +1 -1
  155. package/dist/vite-plugin/index.js +4 -9
  156. package/dist/vite-plugin/index.js.map +1 -1
  157. package/package.json +4 -4
@@ -0,0 +1,120 @@
1
+ import { DatabaseInterface } from '@happyvertical/sql';
2
+ import { ObjectRegistry } from './registry.js';
3
+ /**
4
+ * Referential action applied to rows pointing at a deleted object.
5
+ *
6
+ * Same vocabulary as SQL's `ON DELETE`, enforced by the framework instead of
7
+ * the engine. `NO ACTION` means "leave the rows alone" — SMRT emits no
8
+ * constraint, so nothing raises.
9
+ */
10
+ export type OnDeleteAction = 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';
11
+ /** One reference that must be resolved before the target row can be removed. */
12
+ export interface CascadeReference {
13
+ /** Registered name of the class holding the referencing column. */
14
+ className: string;
15
+ /** Table holding the referencing rows. */
16
+ tableName: string;
17
+ /** Field name (camelCase) on the referencing class. */
18
+ fieldName: string;
19
+ /** Column (snake_case) holding the reference. */
20
+ column: string;
21
+ /** Resolved action, never `NO ACTION` (those are dropped from the plan). */
22
+ action: Exclude<OnDeleteAction, 'NO ACTION'>;
23
+ /** `true` when the action was declared rather than derived from the key. */
24
+ declared: boolean;
25
+ }
26
+ /** A polymorphic association table that can point at any class. */
27
+ export interface CascadePolymorphicReference {
28
+ /** Registered name of the association class. */
29
+ className: string;
30
+ /** Table holding the association rows. */
31
+ tableName: string;
32
+ }
33
+ /** Everything that must happen before rows of one class can be deleted. */
34
+ export interface CascadePlan {
35
+ /** Typed `@foreignKey` / `@crossPackageRef` references, action-resolved. */
36
+ references: CascadeReference[];
37
+ /** Polymorphic association tables that may point at this class. */
38
+ polymorphic: CascadePolymorphicReference[];
39
+ /** `meta_type` values that identify this class in an association row. */
40
+ metaTypes: string[];
41
+ /** `true` when nothing references this class and nothing has to be visited. */
42
+ isEmpty: boolean;
43
+ }
44
+ /**
45
+ * Read-only slice of `ObjectRegistry` this module needs.
46
+ *
47
+ * Taking it as a parameter — rather than importing the registry as a value —
48
+ * keeps `cascade.ts` out of the `registry → object → cascade` import cycle,
49
+ * and lets tests drive the planner from a hand-built registry.
50
+ */
51
+ export type CascadeRegistryView = Pick<typeof ObjectRegistry, 'getRelationshipMap' | 'getFields' | 'getConflictColumns' | 'getTableName' | 'getSelfReferableNames' | 'getClass' | 'getSTIBase' | 'getDescendants'>;
52
+ /**
53
+ * Normalize a declared `onDelete` value.
54
+ *
55
+ * Accepts any casing and both `SET NULL` and `SET_NULL`, matching what the
56
+ * schema generator has always carried in the manifest. Returns `undefined` for
57
+ * an unset or unrecognized value so the caller can fall back to the default.
58
+ */
59
+ export declare function normalizeOnDelete(value: unknown): OnDeleteAction | undefined;
60
+ /**
61
+ * Build the cascade plan for one class.
62
+ *
63
+ * The plan is derived entirely from registry metadata, so it is valid for any
64
+ * database the class is used against. It is rebuilt per delete rather than
65
+ * cached: registration is incremental (manifests load lazily, tests register
66
+ * classes between cases) and a stale plan would silently skip a table.
67
+ *
68
+ * @param registry - Registry view (`ObjectRegistry` satisfies it)
69
+ * @param className - Class whose incoming references should be resolved
70
+ */
71
+ export declare function buildCascadePlan(registry: CascadeRegistryView, className: string): CascadePlan;
72
+ /** Outcome of a cascade run, returned so the caller can invalidate caches. */
73
+ export interface CascadeResult {
74
+ /** Tables whose rows were removed or nulled, excluding the target's own. */
75
+ affectedTables: Set<string>;
76
+ /**
77
+ * Qualified class name that owns each entry in {@link affectedTables},
78
+ * where resolvable — lets the caller check *that* class's own
79
+ * cross-process cache config rather than only its own.
80
+ */
81
+ affectedTableClasses: Map<string, string>;
82
+ }
83
+ /**
84
+ * Resolve every reference to `ids` of `className` and clean their framework
85
+ * side rows, then hand control back so the caller can delete the rows.
86
+ *
87
+ * Callers are expected to run this on a transaction-bound `db` — see
88
+ * {@link runCascadeDelete}, which owns that decision.
89
+ */
90
+ export declare function cascadeReferencesTo(db: DatabaseInterface, registry: CascadeRegistryView, target: {
91
+ className: string;
92
+ tableName: string;
93
+ ids: string[];
94
+ }): Promise<CascadeResult>;
95
+ /**
96
+ * Run the cascade and the target row's own deletion atomically.
97
+ *
98
+ * When anything references the class and the adapter exposes `transaction()`,
99
+ * the whole sequence runs inside one — including the caller's `deleteSelf`
100
+ * statement, so a failure part-way through cannot leave the object deleted with
101
+ * its junction rows intact (or vice versa). Adapters without transaction
102
+ * support run the same statements sequentially; this is the documented
103
+ * degradation, not a silent one.
104
+ *
105
+ * When nothing references the class there is nothing to keep consistent, and
106
+ * the transaction is skipped — see the comment on that branch.
107
+ *
108
+ * @param db - Database the object is bound to
109
+ * @param registry - Registry view used to build cascade plans
110
+ * @param target - Class, table and id of the object being deleted
111
+ * @param deleteSelf - Issues the target row's own `DELETE`, on the tx-bound db
112
+ * @returns Tables affected by the cascade, for read-cache invalidation
113
+ */
114
+ export declare function runCascadeDelete(db: DatabaseInterface, registry: CascadeRegistryView, target: {
115
+ className: string;
116
+ tableName: string;
117
+ /** An unsaved object has none; the cascade is then a no-op. */
118
+ id: string | null | undefined;
119
+ }, deleteSelf: (db: DatabaseInterface) => Promise<void>): Promise<CascadeResult>;
120
+ //# sourceMappingURL=cascade.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cascade.d.ts","sourceRoot":"","sources":["../src/cascade.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AAK5D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAMpD;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,WAAW,CAAC;AAsB/E,gFAAgF;AAChF,MAAM,WAAW,gBAAgB;IAC/B,mEAAmE;IACnE,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,SAAS,EAAE,MAAM,CAAC;IAClB,iDAAiD;IACjD,MAAM,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,MAAM,EAAE,OAAO,CAAC,cAAc,EAAE,WAAW,CAAC,CAAC;IAC7C,4EAA4E;IAC5E,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED,mEAAmE;AACnE,MAAM,WAAW,2BAA2B;IAC1C,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,2EAA2E;AAC3E,MA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,SAAS,EAAE,MAAM,CAAC;IAClB,+DAA+D;IAC/D,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;CAC/B,EACD,UAAU,EAAE,CAAC,EAAE,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,GACnD,OAAO,CAAC,aAAa,CAAC,CAgDxB"}
@@ -0,0 +1,430 @@
1
+ import { classifyDatabaseError } from "./db-errors.js";
2
+ import { ConfigurationError, DatabaseError } from "./errors.js";
3
+ import { chunkArray } from "./utils/chunk.js";
4
+ import { toSnakeCase } from "./utils/naming.js";
5
+ import { createLogger } from "@happyvertical/logger";
6
+ //#region src/cascade.ts
7
+ /**
8
+ * App-side referential integrity for `SmrtObject.delete()` (#2371).
9
+ *
10
+ * SMRT emits **no** DB-level `FOREIGN KEY` constraints on any engine, so the
11
+ * database will never clean up after a deleted row. Before this module,
12
+ * `delete()` removed the object's own row and nothing else: junction rows,
13
+ * polymorphic association rows, `_smrt_embeddings` and `_smrt_contexts` entries
14
+ * were all left pointing at an id that no longer resolved, and
15
+ * `@foreignKey(..., { onDelete })` was metadata nobody read.
16
+ *
17
+ * This module implements those semantics in the application layer. It mirrors
18
+ * what a DB-level constraint would do, deliberately including the parts that
19
+ * make it *unlike* a model-layer delete:
20
+ *
21
+ * - Cascaded rows are removed with set-based statements. Their `beforeDelete` /
22
+ * `afterDelete` hooks and interceptors do **not** run, and no change-feed
23
+ * tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.
24
+ * Only the object `delete()` was called on runs the full lifecycle.
25
+ * - When anything needs cascading, everything runs inside a single
26
+ * transaction when the adapter exposes one, so a partial cascade cannot
27
+ * survive a failure. A class with no typed references AND no registered
28
+ * polymorphic association class anywhere in the process skips the
29
+ * transaction — see {@link runCascadeDelete}. A `metaType` column can point
30
+ * at any class at runtime, so a polymorphic association class is always
31
+ * plausibly relevant; in an app with even one registered, this fast path is
32
+ * rare, not the common case.
33
+ *
34
+ * ## Which references are followed
35
+ *
36
+ * A reference is any `@foreignKey` / `@crossPackageRef` field on a registered
37
+ * class whose target resolves to the deleted object's class (or one of its
38
+ * registered STI ancestors), plus the polymorphic `(metaType, metaId)` pair on
39
+ * {@link SmrtPolymorphicAssociation} subclasses.
40
+ *
41
+ * The action comes from the field's declared `onDelete`. When it is not
42
+ * declared, the default is derived from the referencing class's natural key:
43
+ *
44
+ * | Reference | Default when `onDelete` is absent |
45
+ * |---|---|
46
+ * | Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |
47
+ * | Polymorphic `(metaType, metaId)` association row | `CASCADE` |
48
+ * | Anything else, including every `@tenantId()` field | `NO ACTION` (legacy behaviour — the row is left alone) |
49
+ *
50
+ * The natural-key rule is what makes junction rows work without any
51
+ * per-package annotation: a junction declares
52
+ * `@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so
53
+ * `content_id` identifies the row and the row cannot outlive the content it
54
+ * links. An ordinary child (`Order.customerId`) is keyed by `(slug, context)`,
55
+ * so it keeps today's behaviour unless it opts in with
56
+ * `@foreignKey(Customer, { onDelete: 'CASCADE' })`.
57
+ *
58
+ * `@tenantId()` fields are excluded from the natural-key rule even though
59
+ * `@happyvertical/smrt-tenancy` leads a tenant-scoped class's *default*
60
+ * `conflictColumns` with the tenant column (#2360): the tenant column scopes
61
+ * ownership, it does not identify the row the way a junction's foreign key
62
+ * does, and it targets a class (`Tenant`) that is virtually always
63
+ * referenced. Without this exclusion, deleting one `Tenant` row would
64
+ * recursively CASCADE through every tenant-scoped table that has not
65
+ * declared its own `conflictColumns` — the overwhelming majority. The field
66
+ * is detected via the `__tenancy.isTenantIdField` marker `@tenantId()`
67
+ * attaches to its own registration (`FieldMeta.__tenancy`, read structurally
68
+ * so `smrt-core` never depends on `smrt-tenancy`). `@tenantId()` exposes no
69
+ * `onDelete` option today, so this cannot currently be overridden per field.
70
+ *
71
+ * @see https://github.com/happyvertical/smrt/issues/2371
72
+ * @module
73
+ */
74
+ var logger = createLogger({ level: "info" });
75
+ /** Table holding framework-managed per-object memory entries. */
76
+ var CONTEXTS_TABLE = "_smrt_contexts";
77
+ /** Table holding framework-managed per-object embedding vectors. */
78
+ var EMBEDDINGS_TABLE = "_smrt_embeddings";
79
+ /**
80
+ * Reserved `_smrt_contexts.owner_id` used by `SmrtCollection.remember()` for
81
+ * collection-scoped memory. A real object id is a UUID and can never equal it,
82
+ * but the guard keeps a malformed id from wiping every sibling's defaults.
83
+ */
84
+ var COLLECTION_OWNER_SENTINEL = "__collection__";
85
+ /**
86
+ * Maximum number of cascade levels followed from the object `delete()` was
87
+ * called on. A cycle between two classes that both declare `onDelete: 'CASCADE'`
88
+ * is broken by the visited set; this bound catches unbounded *chains*.
89
+ */
90
+ var MAX_CASCADE_DEPTH = 10;
91
+ var CASCADE_ACTIONS = /* @__PURE__ */ new Set([
92
+ "CASCADE",
93
+ "SET NULL",
94
+ "RESTRICT",
95
+ "NO ACTION"
96
+ ]);
97
+ /**
98
+ * Normalize a declared `onDelete` value.
99
+ *
100
+ * Accepts any casing and both `SET NULL` and `SET_NULL`, matching what the
101
+ * schema generator has always carried in the manifest. Returns `undefined` for
102
+ * an unset or unrecognized value so the caller can fall back to the default.
103
+ */
104
+ function normalizeOnDelete(value) {
105
+ if (typeof value !== "string") return void 0;
106
+ const normalized = value.trim().toUpperCase().replace(/_/g, " ");
107
+ return CASCADE_ACTIONS.has(normalized) ? normalized : void 0;
108
+ }
109
+ function isPolymorphicAssociationClass(fields) {
110
+ return fields.has("metaType") && fields.has("metaId") && fields.has("role");
111
+ }
112
+ /**
113
+ * Build the cascade plan for one class.
114
+ *
115
+ * The plan is derived entirely from registry metadata, so it is valid for any
116
+ * database the class is used against. It is rebuilt per delete rather than
117
+ * cached: registration is incremental (manifests load lazily, tests register
118
+ * classes between cases) and a stale plan would silently skip a table.
119
+ *
120
+ * @param registry - Registry view (`ObjectRegistry` satisfies it)
121
+ * @param className - Class whose incoming references should be resolved
122
+ */
123
+ function buildCascadePlan(registry, className) {
124
+ const targetNames = new Set(registry.getSelfReferableNames(className));
125
+ for (const name of [...targetNames]) {
126
+ const qualified = registry.getClass(name)?.qualifiedName;
127
+ if (qualified) targetNames.add(qualified);
128
+ }
129
+ const references = [];
130
+ const polymorphic = [];
131
+ for (const [sourceClass, relationships] of registry.getRelationshipMap()) {
132
+ const fields = registry.getFields(sourceClass);
133
+ if (isPolymorphicAssociationClass(fields)) {
134
+ const tableName = registry.getTableName(sourceClass);
135
+ if (tableName) polymorphic.push({
136
+ className: sourceClass,
137
+ tableName
138
+ });
139
+ }
140
+ if (relationships.length === 0) continue;
141
+ let conflictColumns;
142
+ for (const relationship of relationships) {
143
+ if (relationship.type !== "foreignKey" && relationship.type !== "crossPackageRef") continue;
144
+ if (!targetNames.has(relationship.targetClass)) continue;
145
+ const tableName = registry.getTableName(sourceClass);
146
+ if (!tableName) continue;
147
+ const column = toSnakeCase(relationship.fieldName);
148
+ const declaredAction = normalizeOnDelete(relationship.options?.onDelete);
149
+ if (!conflictColumns) conflictColumns = new Set(registry.getConflictColumns(sourceClass));
150
+ const isTenantIdField = relationship.options?.__tenancy?.isTenantIdField === true;
151
+ const action = declaredAction ?? (!isTenantIdField && conflictColumns.has(column) ? "CASCADE" : "NO ACTION");
152
+ if (action === "NO ACTION") continue;
153
+ if (action === "SET NULL" && fields.get(relationship.fieldName)?.required) throw ConfigurationError.invalidConfiguration(`${sourceClass}.${relationship.fieldName} onDelete: 'SET NULL'`, relationship.fieldName, "a nullable field (mark it `nullable: true`, or use 'CASCADE' / 'RESTRICT')");
154
+ references.push({
155
+ className: sourceClass,
156
+ tableName,
157
+ fieldName: relationship.fieldName,
158
+ column,
159
+ action,
160
+ declared: declaredAction !== void 0
161
+ });
162
+ }
163
+ }
164
+ const metaTypes = [];
165
+ const qualified = registry.getClass(className)?.qualifiedName;
166
+ if (qualified) metaTypes.push(qualified);
167
+ const simple = registry.getClass(className)?.name ?? className;
168
+ if (!metaTypes.includes(simple)) metaTypes.push(simple);
169
+ return {
170
+ references,
171
+ polymorphic,
172
+ metaTypes,
173
+ isEmpty: references.length === 0 && polymorphic.length === 0
174
+ };
175
+ }
176
+ /** Resolve a registry-recorded class name to its qualified form, when known. */
177
+ function toQualifiedClassName(registry, className) {
178
+ return registry.getClass(className)?.qualifiedName ?? className;
179
+ }
180
+ /**
181
+ * Every value `_smrt_contexts.owner_class` / `_smrt_embeddings.object_class`
182
+ * could plausibly hold for a row belonging to an id of `className` (review
183
+ * fix): both name forms (qualified + simple — older rows predate package
184
+ * qualification) of `className` itself, plus every other member of its STI
185
+ * hierarchy sharing its table. A CASCADE-collected id can belong to any
186
+ * concrete STI subclass of the declaring reference, which stamps its own
187
+ * (more specific) runtime class name at write time, not the reference's.
188
+ *
189
+ * Narrowing by this set — instead of matching by id alone — closes a
190
+ * cross-class collision: two unrelated classes using `idType: 'text'`
191
+ * (non-UUID, not guaranteed globally unique) could otherwise share an id
192
+ * value and have one's `remember()`/embeddings rows deleted by the other's
193
+ * cascade.
194
+ */
195
+ function ownerClassCandidates(registry, className) {
196
+ const stiBase = registry.getSTIBase(className) ?? className;
197
+ const members = /* @__PURE__ */ new Set([
198
+ className,
199
+ stiBase,
200
+ ...registry.getDescendants(stiBase)
201
+ ]);
202
+ const names = /* @__PURE__ */ new Set();
203
+ for (const member of members) {
204
+ names.add(member);
205
+ const registered = registry.getClass(member);
206
+ if (registered?.qualifiedName) names.add(registered.qualifiedName);
207
+ if (registered?.name) names.add(registered.name);
208
+ }
209
+ return [...names];
210
+ }
211
+ /**
212
+ * Build the `where` clause matching `column` against one or more ids.
213
+ *
214
+ * A single id uses equality so the planner can use a plain index; multiple ids
215
+ * use the adapter's `in` operator.
216
+ */
217
+ function idPredicate(column, ids) {
218
+ return ids.length === 1 ? { [column]: ids[0] } : { [`${column} in`]: ids };
219
+ }
220
+ /**
221
+ * Run a cascade statement against a *referencing* table, tolerating the
222
+ * table (or an expected column) not existing in this database.
223
+ *
224
+ * The cascade plan is built from the in-process registry, which can carry a
225
+ * class from any imported package — including one whose table this specific
226
+ * database was never migrated to include (a partially adopted feature, a
227
+ * package pulled in for its types, or, in a test process, a fixture some
228
+ * other test file registered). A missing referencing table trivially has no
229
+ * rows to act on, so the correct behaviour is identical to the table
230
+ * existing and being empty — this must never abort an otherwise valid
231
+ * delete. Any other failure (a real constraint violation, a lock timeout, a
232
+ * genuine SQL error unrelated to the table's existence) still propagates.
233
+ */
234
+ async function tolerateMissingTable(operation, fallback, context) {
235
+ try {
236
+ return await operation();
237
+ } catch (error) {
238
+ if (classifyDatabaseError(error).kind === "undefined_object") {
239
+ logger.warn(`Cascade delete skipped ${context.action} on '${context.table}': table or column not found in this database.`, { error: error instanceof Error ? error.message : String(error) });
240
+ return fallback;
241
+ }
242
+ throw error;
243
+ }
244
+ }
245
+ async function selectIds(db, tableName, column, ids) {
246
+ const found = [];
247
+ for (const batch of chunkArray(ids, 900)) {
248
+ const rows = await tolerateMissingTable(() => db.list(tableName, idPredicate(column, batch)), [], {
249
+ table: tableName,
250
+ action: "CASCADE select"
251
+ });
252
+ for (const row of rows) {
253
+ const id = row?.id;
254
+ if (typeof id === "string" && id.length > 0) found.push(id);
255
+ }
256
+ }
257
+ return found;
258
+ }
259
+ async function deleteByIds(db, tableName, ids) {
260
+ for (const batch of chunkArray(ids, 900)) await tolerateMissingTable(() => db.delete(tableName, idPredicate("id", batch)), void 0, {
261
+ table: tableName,
262
+ action: "CASCADE delete"
263
+ });
264
+ }
265
+ /**
266
+ * Remove the framework-managed side rows owned by the given object ids.
267
+ *
268
+ * `_smrt_contexts` and `_smrt_embeddings` are keyed by `(owner_class, owner_id)`
269
+ * and `(object_class, object_id)` respectively. Matched by id *and* class
270
+ * (review fix): id alone would let two unrelated classes using
271
+ * `idType: 'text'` (non-UUID, not guaranteed globally unique) collide on a
272
+ * shared id value and delete each other's memory/embeddings rows. `classNames`
273
+ * is the STI-hierarchy-expanded candidate set from
274
+ * {@link ownerClassCandidates} — the class column stores the *runtime*
275
+ * constructor name, which for an STI hierarchy is a concrete subclass rather
276
+ * than the class the cascade was planned from, so a single exact name is not
277
+ * enough.
278
+ *
279
+ * A missing system table is not an error — an application database may predate
280
+ * the table, and losing derived rows must never fail an otherwise valid delete.
281
+ */
282
+ async function deleteSystemRows(db, ids, classNames) {
283
+ const ownerIds = ids.filter((id) => typeof id === "string" && id.length > 0 && id !== COLLECTION_OWNER_SENTINEL);
284
+ if (ownerIds.length === 0 || classNames.length === 0) return;
285
+ for (const [table, idColumn, classColumn] of [[
286
+ CONTEXTS_TABLE,
287
+ "owner_id",
288
+ "owner_class"
289
+ ], [
290
+ EMBEDDINGS_TABLE,
291
+ "object_id",
292
+ "object_class"
293
+ ]]) for (const batch of chunkArray(ownerIds, 900)) try {
294
+ await db.delete(table, {
295
+ ...idPredicate(idColumn, batch),
296
+ ...idPredicate(classColumn, classNames)
297
+ });
298
+ } catch (error) {
299
+ logger.warn(`Failed to clean ${table} rows during cascade delete: ${error instanceof Error ? error.message : String(error)}`);
300
+ }
301
+ }
302
+ /**
303
+ * Resolve every reference pointing at `ids` of `className`, recursively.
304
+ *
305
+ * Does **not** delete the rows identified by `ids` — the caller owns that, so
306
+ * `SmrtObject.delete()` keeps issuing its own final statement and its own
307
+ * lifecycle hooks.
308
+ */
309
+ async function resolveReferences(ctx, className, tableName, ids, depth) {
310
+ const pending = ids.filter((id) => {
311
+ const key = `${tableName}:${id}`;
312
+ if (ctx.visited.has(key)) return false;
313
+ ctx.visited.add(key);
314
+ return true;
315
+ });
316
+ if (pending.length === 0) return;
317
+ if (depth > MAX_CASCADE_DEPTH) throw DatabaseError.constraintViolation(`cascade delete from ${className} exceeded the maximum depth of ${MAX_CASCADE_DEPTH}; check for a chain of onDelete: 'CASCADE' references that never terminates`, className);
318
+ const plan = buildCascadePlan(ctx.registry, className);
319
+ for (const reference of plan.references) {
320
+ if (reference.action !== "RESTRICT") continue;
321
+ let remaining = 0;
322
+ for (const batch of chunkArray(pending, 900)) {
323
+ remaining += await tolerateMissingTable(() => ctx.db.count(reference.tableName, idPredicate(reference.column, batch)), 0, {
324
+ table: reference.tableName,
325
+ action: "RESTRICT check"
326
+ });
327
+ if (remaining > 0) break;
328
+ }
329
+ if (remaining > 0) throw DatabaseError.constraintViolation(`${reference.className}.${reference.fieldName} declares onDelete: 'RESTRICT' and ${remaining} row(s) still reference this ${className}`, reference.column);
330
+ }
331
+ for (const reference of plan.references) {
332
+ if (reference.action === "SET NULL") {
333
+ for (const batch of chunkArray(pending, 900)) await tolerateMissingTable(() => ctx.db.update(reference.tableName, idPredicate(reference.column, batch), { [reference.column]: null }), void 0, {
334
+ table: reference.tableName,
335
+ action: "SET NULL"
336
+ });
337
+ ctx.affectedTables.add(reference.tableName);
338
+ ctx.affectedTableClasses.set(reference.tableName, toQualifiedClassName(ctx.registry, reference.className));
339
+ continue;
340
+ }
341
+ if (reference.action !== "CASCADE") continue;
342
+ const childIds = await selectIds(ctx.db, reference.tableName, reference.column, pending);
343
+ if (childIds.length === 0) continue;
344
+ await resolveReferences(ctx, reference.className, reference.tableName, childIds, depth + 1);
345
+ await deleteSystemRows(ctx.db, childIds, ownerClassCandidates(ctx.registry, reference.className));
346
+ await deleteByIds(ctx.db, reference.tableName, childIds);
347
+ ctx.affectedTables.add(reference.tableName);
348
+ ctx.affectedTableClasses.set(reference.tableName, toQualifiedClassName(ctx.registry, reference.className));
349
+ }
350
+ for (const association of plan.polymorphic) for (const batch of chunkArray(pending, 900)) {
351
+ const where = { ...idPredicate("meta_id", batch) };
352
+ if (plan.metaTypes.length === 1) where.meta_type = plan.metaTypes[0];
353
+ else where["meta_type in"] = plan.metaTypes;
354
+ if (((await tolerateMissingTable(() => ctx.db.delete(association.tableName, where), void 0, {
355
+ table: association.tableName,
356
+ action: "polymorphic association cleanup"
357
+ }))?.affected ?? 0) > 0) {
358
+ ctx.affectedTables.add(association.tableName);
359
+ ctx.affectedTableClasses.set(association.tableName, toQualifiedClassName(ctx.registry, association.className));
360
+ }
361
+ }
362
+ }
363
+ /**
364
+ * Resolve every reference to `ids` of `className` and clean their framework
365
+ * side rows, then hand control back so the caller can delete the rows.
366
+ *
367
+ * Callers are expected to run this on a transaction-bound `db` — see
368
+ * {@link runCascadeDelete}, which owns that decision.
369
+ */
370
+ async function cascadeReferencesTo(db, registry, target) {
371
+ const ctx = {
372
+ db,
373
+ registry,
374
+ visited: /* @__PURE__ */ new Set(),
375
+ affectedTables: /* @__PURE__ */ new Set(),
376
+ affectedTableClasses: /* @__PURE__ */ new Map()
377
+ };
378
+ await resolveReferences(ctx, target.className, target.tableName, target.ids, 0);
379
+ await deleteSystemRows(db, target.ids, ownerClassCandidates(registry, target.className));
380
+ return {
381
+ affectedTables: ctx.affectedTables,
382
+ affectedTableClasses: ctx.affectedTableClasses
383
+ };
384
+ }
385
+ /**
386
+ * Run the cascade and the target row's own deletion atomically.
387
+ *
388
+ * When anything references the class and the adapter exposes `transaction()`,
389
+ * the whole sequence runs inside one — including the caller's `deleteSelf`
390
+ * statement, so a failure part-way through cannot leave the object deleted with
391
+ * its junction rows intact (or vice versa). Adapters without transaction
392
+ * support run the same statements sequentially; this is the documented
393
+ * degradation, not a silent one.
394
+ *
395
+ * When nothing references the class there is nothing to keep consistent, and
396
+ * the transaction is skipped — see the comment on that branch.
397
+ *
398
+ * @param db - Database the object is bound to
399
+ * @param registry - Registry view used to build cascade plans
400
+ * @param target - Class, table and id of the object being deleted
401
+ * @param deleteSelf - Issues the target row's own `DELETE`, on the tx-bound db
402
+ * @returns Tables affected by the cascade, for read-cache invalidation
403
+ */
404
+ async function runCascadeDelete(db, registry, target, deleteSelf) {
405
+ const ids = target.id ? [target.id] : [];
406
+ if (buildCascadePlan(registry, target.className).isEmpty) {
407
+ await deleteSelf(db);
408
+ await deleteSystemRows(db, ids, ownerClassCandidates(registry, target.className));
409
+ return {
410
+ affectedTables: /* @__PURE__ */ new Set(),
411
+ affectedTableClasses: /* @__PURE__ */ new Map()
412
+ };
413
+ }
414
+ const run = async (bound) => {
415
+ const result = await cascadeReferencesTo(bound, registry, {
416
+ className: target.className,
417
+ tableName: target.tableName,
418
+ ids
419
+ });
420
+ await deleteSelf(bound);
421
+ return result;
422
+ };
423
+ const transaction = db.transaction;
424
+ if (typeof transaction !== "function") return run(db);
425
+ return transaction.call(db, run);
426
+ }
427
+ //#endregion
428
+ export { buildCascadePlan, cascadeReferencesTo, normalizeOnDelete, runCascadeDelete };
429
+
430
+ //# sourceMappingURL=cascade.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cascade.js","names":[],"sources":["../src/cascade.ts"],"sourcesContent":["/**\n * App-side referential integrity for `SmrtObject.delete()` (#2371).\n *\n * SMRT emits **no** DB-level `FOREIGN KEY` constraints on any engine, so the\n * database will never clean up after a deleted row. Before this module,\n * `delete()` removed the object's own row and nothing else: junction rows,\n * polymorphic association rows, `_smrt_embeddings` and `_smrt_contexts` entries\n * were all left pointing at an id that no longer resolved, and\n * `@foreignKey(..., { onDelete })` was metadata nobody read.\n *\n * This module implements those semantics in the application layer. It mirrors\n * what a DB-level constraint would do, deliberately including the parts that\n * make it *unlike* a model-layer delete:\n *\n * - Cascaded rows are removed with set-based statements. Their `beforeDelete` /\n * `afterDelete` hooks and interceptors do **not** run, and no change-feed\n * tombstone is written for them — exactly as `ON DELETE CASCADE` behaves.\n * Only the object `delete()` was called on runs the full lifecycle.\n * - When anything needs cascading, everything runs inside a single\n * transaction when the adapter exposes one, so a partial cascade cannot\n * survive a failure. A class with no typed references AND no registered\n * polymorphic association class anywhere in the process skips the\n * transaction — see {@link runCascadeDelete}. A `metaType` column can point\n * at any class at runtime, so a polymorphic association class is always\n * plausibly relevant; in an app with even one registered, this fast path is\n * rare, not the common case.\n *\n * ## Which references are followed\n *\n * A reference is any `@foreignKey` / `@crossPackageRef` field on a registered\n * class whose target resolves to the deleted object's class (or one of its\n * registered STI ancestors), plus the polymorphic `(metaType, metaId)` pair on\n * {@link SmrtPolymorphicAssociation} subclasses.\n *\n * The action comes from the field's declared `onDelete`. When it is not\n * declared, the default is derived from the referencing class's natural key:\n *\n * | Reference | Default when `onDelete` is absent |\n * |---|---|\n * | Column is part of the referencing class's `conflictColumns`, and is not a `@tenantId()` field | `CASCADE` |\n * | Polymorphic `(metaType, metaId)` association row | `CASCADE` |\n * | Anything else, including every `@tenantId()` field | `NO ACTION` (legacy behaviour — the row is left alone) |\n *\n * The natural-key rule is what makes junction rows work without any\n * per-package annotation: a junction declares\n * `@smrt({ conflictColumns: ['content_id', 'asset_id', 'relationship'] })`, so\n * `content_id` identifies the row and the row cannot outlive the content it\n * links. An ordinary child (`Order.customerId`) is keyed by `(slug, context)`,\n * so it keeps today's behaviour unless it opts in with\n * `@foreignKey(Customer, { onDelete: 'CASCADE' })`.\n *\n * `@tenantId()` fields are excluded from the natural-key rule even though\n * `@happyvertical/smrt-tenancy` leads a tenant-scoped class's *default*\n * `conflictColumns` with the tenant column (#2360): the tenant column scopes\n * ownership, it does not identify the row the way a junction's foreign key\n * does, and it targets a class (`Tenant`) that is virtually always\n * referenced. Without this exclusion, deleting one `Tenant` row would\n * recursively CASCADE through every tenant-scoped table that has not\n * declared its own `conflictColumns` — the overwhelming majority. The field\n * is detected via the `__tenancy.isTenantIdField` marker `@tenantId()`\n * attaches to its own registration (`FieldMeta.__tenancy`, read structurally\n * so `smrt-core` never depends on `smrt-tenancy`). `@tenantId()` exposes no\n * `onDelete` option today, so this cannot currently be overridden per field.\n *\n * @see https://github.com/happyvertical/smrt/issues/2371\n * @module\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport { classifyDatabaseError } from './db-errors.js';\nimport { ConfigurationError, DatabaseError } from './errors.js';\n// Type-only: erased at runtime, so it cannot re-enter the\n// `registry → object → cascade` import cycle.\nimport type { ObjectRegistry } from './registry.js';\nimport { chunkArray, IN_LIST_CHUNK_SIZE } from './utils/chunk.js';\nimport { toSnakeCase } from './utils/naming.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Referential action applied to rows pointing at a deleted object.\n *\n * Same vocabulary as SQL's `ON DELETE`, enforced by the framework instead of\n * the engine. `NO ACTION` means \"leave the rows alone\" — SMRT emits no\n * constraint, so nothing raises.\n */\nexport type OnDeleteAction = 'CASCADE' | 'SET NULL' | 'RESTRICT' | 'NO ACTION';\n\n/** Table holding framework-managed per-object memory entries. */\nconst CONTEXTS_TABLE = '_smrt_contexts';\n\n/** Table holding framework-managed per-object embedding vectors. */\nconst EMBEDDINGS_TABLE = '_smrt_embeddings';\n\n/**\n * Reserved `_smrt_contexts.owner_id` used by `SmrtCollection.remember()` for\n * collection-scoped memory. A real object id is a UUID and can never equal it,\n * but the guard keeps a malformed id from wiping every sibling's defaults.\n */\nconst COLLECTION_OWNER_SENTINEL = '__collection__';\n\n/**\n * Maximum number of cascade levels followed from the object `delete()` was\n * called on. A cycle between two classes that both declare `onDelete: 'CASCADE'`\n * is broken by the visited set; this bound catches unbounded *chains*.\n */\nconst MAX_CASCADE_DEPTH = 10;\n\n/** One reference that must be resolved before the target row can be removed. */\nexport interface CascadeReference {\n /** Registered name of the class holding the referencing column. */\n className: string;\n /** Table holding the referencing rows. */\n tableName: string;\n /** Field name (camelCase) on the referencing class. */\n fieldName: string;\n /** Column (snake_case) holding the reference. */\n column: string;\n /** Resolved action, never `NO ACTION` (those are dropped from the plan). */\n action: Exclude<OnDeleteAction, 'NO ACTION'>;\n /** `true` when the action was declared rather than derived from the key. */\n declared: boolean;\n}\n\n/** A polymorphic association table that can point at any class. */\nexport interface CascadePolymorphicReference {\n /** Registered name of the association class. */\n className: string;\n /** Table holding the association rows. */\n tableName: string;\n}\n\n/** Everything that must happen before rows of one class can be deleted. */\nexport interface CascadePlan {\n /** Typed `@foreignKey` / `@crossPackageRef` references, action-resolved. */\n references: CascadeReference[];\n /** Polymorphic association tables that may point at this class. */\n polymorphic: CascadePolymorphicReference[];\n /** `meta_type` values that identify this class in an association row. */\n metaTypes: string[];\n /** `true` when nothing references this class and nothing has to be visited. */\n isEmpty: boolean;\n}\n\n/**\n * Read-only slice of `ObjectRegistry` this module needs.\n *\n * Taking it as a parameter — rather than importing the registry as a value —\n * keeps `cascade.ts` out of the `registry → object → cascade` import cycle,\n * and lets tests drive the planner from a hand-built registry.\n */\nexport type CascadeRegistryView = Pick<\n typeof ObjectRegistry,\n | 'getRelationshipMap'\n | 'getFields'\n | 'getConflictColumns'\n | 'getTableName'\n | 'getSelfReferableNames'\n | 'getClass'\n | 'getSTIBase'\n | 'getDescendants'\n>;\n\nconst CASCADE_ACTIONS = new Set<OnDeleteAction>([\n 'CASCADE',\n 'SET NULL',\n 'RESTRICT',\n 'NO ACTION',\n]);\n\n/**\n * Normalize a declared `onDelete` value.\n *\n * Accepts any casing and both `SET NULL` and `SET_NULL`, matching what the\n * schema generator has always carried in the manifest. Returns `undefined` for\n * an unset or unrecognized value so the caller can fall back to the default.\n */\nexport function normalizeOnDelete(value: unknown): OnDeleteAction | undefined {\n if (typeof value !== 'string') return undefined;\n const normalized = value.trim().toUpperCase().replace(/_/g, ' ');\n return CASCADE_ACTIONS.has(normalized as OnDeleteAction)\n ? (normalized as OnDeleteAction)\n : undefined;\n}\n\nfunction isPolymorphicAssociationClass(fields: Map<string, unknown>): boolean {\n // The three columns `SmrtPolymorphicAssociation` contributes. Requiring all\n // of them keeps an unrelated class that happens to carry a `metaType` from\n // being treated as an association table.\n return fields.has('metaType') && fields.has('metaId') && fields.has('role');\n}\n\n/**\n * Build the cascade plan for one class.\n *\n * The plan is derived entirely from registry metadata, so it is valid for any\n * database the class is used against. It is rebuilt per delete rather than\n * cached: registration is incremental (manifests load lazily, tests register\n * classes between cases) and a stale plan would silently skip a table.\n *\n * @param registry - Registry view (`ObjectRegistry` satisfies it)\n * @param className - Class whose incoming references should be resolved\n */\nexport function buildCascadePlan(\n registry: CascadeRegistryView,\n className: string,\n): CascadePlan {\n // `className` is normally already qualified (delete() passes\n // getResolvedQualifiedName()), but a common same-package `@foreignKey('X')`\n // still stores its target as the bare simple name `X`. That still matches:\n // getSelfReferableNames() walks the full ancestor chain (self included) and\n // adds each ancestor's *simple* name via `getClass(ancestor)?.name`, so the\n // simple form is already in the seed set below, not just the loop's\n // qualified-variant augmentation.\n const targetNames = new Set(registry.getSelfReferableNames(className));\n for (const name of [...targetNames]) {\n const qualified = registry.getClass(name)?.qualifiedName;\n if (qualified) targetNames.add(qualified);\n }\n\n const references: CascadeReference[] = [];\n const polymorphic: CascadePolymorphicReference[] = [];\n\n for (const [sourceClass, relationships] of registry.getRelationshipMap()) {\n const fields = registry.getFields(sourceClass);\n\n if (isPolymorphicAssociationClass(fields)) {\n const tableName = registry.getTableName(sourceClass);\n if (tableName) {\n polymorphic.push({ className: sourceClass, tableName });\n }\n }\n\n if (relationships.length === 0) continue;\n\n let conflictColumns: Set<string> | undefined;\n\n for (const relationship of relationships) {\n if (\n relationship.type !== 'foreignKey' &&\n relationship.type !== 'crossPackageRef'\n ) {\n continue;\n }\n if (!targetNames.has(relationship.targetClass)) continue;\n\n const tableName = registry.getTableName(sourceClass);\n if (!tableName) continue;\n\n const column = toSnakeCase(relationship.fieldName);\n const declaredAction = normalizeOnDelete(relationship.options?.onDelete);\n\n if (!conflictColumns) {\n conflictColumns = new Set(registry.getConflictColumns(sourceClass));\n }\n\n // A `@tenantId()` field is a structural scoping marker, not a\n // junction/ownership key — it lands in `conflictColumns` only because\n // #2360 leads every tenant-scoped class's *default* natural key with\n // the tenant column, not because the referencing row is *identified*\n // by its tenant the way a junction row is identified by its parent.\n // Without this guard, deleting a `Tenant` would silently CASCADE\n // through the tenant column of every tenant-scoped class in the\n // schema that has not declared its own `conflictColumns` — the\n // overwhelming majority. `@tenantId()` exposes no `onDelete` today, so\n // an explicit declaration can never widen this back to CASCADE; that\n // is deliberate until tenant-delete cascade is an explicit decision.\n const isTenantIdField =\n relationship.options?.__tenancy?.isTenantIdField === true;\n\n const action =\n declaredAction ??\n (!isTenantIdField && conflictColumns.has(column)\n ? 'CASCADE'\n : 'NO ACTION');\n\n if (action === 'NO ACTION') continue;\n\n if (\n action === 'SET NULL' &&\n fields.get(relationship.fieldName)?.required\n ) {\n // Fail on the declaration, not later on a NOT NULL violation from the\n // engine — the message there names a column, not the decorator.\n throw ConfigurationError.invalidConfiguration(\n `${sourceClass}.${relationship.fieldName} onDelete: 'SET NULL'`,\n relationship.fieldName,\n \"a nullable field (mark it `nullable: true`, or use 'CASCADE' / 'RESTRICT')\",\n );\n }\n\n references.push({\n className: sourceClass,\n tableName,\n fieldName: relationship.fieldName,\n column,\n action,\n declared: declaredAction !== undefined,\n });\n }\n }\n\n // Both forms are matched deliberately: an association row written before a\n // class was package-qualified still carries the simple `meta_type`. The\n // qualified form alone is unambiguous; the simple-name fallback can still\n // match a same-simple-name sibling class's row if it also shares a\n // `meta_id` — a real, not just theoretical, risk for a class declaring\n // `idType: 'text'` (non-UUID, not guaranteed globally unique), the same gap\n // `deleteSystemRows()` closed for `_smrt_contexts` / `_smrt_embeddings`\n // (review fix) by adding a class-name filter. Closing it here needs the\n // same STI-and-legacy-name-aware filter this module already builds for\n // `deleteSystemRows()` narrowed further to registry-unambiguous simple\n // names; tracked under #2419 alongside the other same-simple-name\n // collision gaps rather than reworked here.\n const metaTypes: string[] = [];\n const qualified = registry.getClass(className)?.qualifiedName;\n if (qualified) metaTypes.push(qualified);\n const simple = registry.getClass(className)?.name ?? className;\n if (!metaTypes.includes(simple)) metaTypes.push(simple);\n\n return {\n references,\n polymorphic,\n metaTypes,\n isEmpty: references.length === 0 && polymorphic.length === 0,\n };\n}\n\n/** Per-delete state shared by every level of the cascade. */\ninterface CascadeContext {\n db: DatabaseInterface;\n registry: CascadeRegistryView;\n /** `table:id` pairs already expanded, so a reference cycle terminates. */\n visited: Set<string>;\n /** Tables touched by the cascade, for read-cache invalidation. */\n affectedTables: Set<string>;\n /**\n * Qualified name of the class that owns each affected table, so the\n * caller can resolve *that* class's own `@smrt({ cache })` config —\n * cross-process cache invalidation is a per-class opt-in, and a table\n * cascaded into belongs to a different class than the one `delete()` was\n * called on.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/** Resolve a registry-recorded class name to its qualified form, when known. */\nfunction toQualifiedClassName(\n registry: CascadeRegistryView,\n className: string,\n): string {\n return registry.getClass(className)?.qualifiedName ?? className;\n}\n\n/**\n * Every value `_smrt_contexts.owner_class` / `_smrt_embeddings.object_class`\n * could plausibly hold for a row belonging to an id of `className` (review\n * fix): both name forms (qualified + simple — older rows predate package\n * qualification) of `className` itself, plus every other member of its STI\n * hierarchy sharing its table. A CASCADE-collected id can belong to any\n * concrete STI subclass of the declaring reference, which stamps its own\n * (more specific) runtime class name at write time, not the reference's.\n *\n * Narrowing by this set — instead of matching by id alone — closes a\n * cross-class collision: two unrelated classes using `idType: 'text'`\n * (non-UUID, not guaranteed globally unique) could otherwise share an id\n * value and have one's `remember()`/embeddings rows deleted by the other's\n * cascade.\n */\nfunction ownerClassCandidates(\n registry: CascadeRegistryView,\n className: string,\n): string[] {\n const stiBase = registry.getSTIBase(className) ?? className;\n const members = new Set<string>([\n className,\n stiBase,\n ...registry.getDescendants(stiBase),\n ]);\n\n const names = new Set<string>();\n for (const member of members) {\n names.add(member);\n const registered = registry.getClass(member);\n if (registered?.qualifiedName) names.add(registered.qualifiedName);\n if (registered?.name) names.add(registered.name);\n }\n return [...names];\n}\n\n/**\n * Build the `where` clause matching `column` against one or more ids.\n *\n * A single id uses equality so the planner can use a plain index; multiple ids\n * use the adapter's `in` operator.\n */\nfunction idPredicate(column: string, ids: string[]): Record<string, unknown> {\n return ids.length === 1 ? { [column]: ids[0] } : { [`${column} in`]: ids };\n}\n\n/**\n * Run a cascade statement against a *referencing* table, tolerating the\n * table (or an expected column) not existing in this database.\n *\n * The cascade plan is built from the in-process registry, which can carry a\n * class from any imported package — including one whose table this specific\n * database was never migrated to include (a partially adopted feature, a\n * package pulled in for its types, or, in a test process, a fixture some\n * other test file registered). A missing referencing table trivially has no\n * rows to act on, so the correct behaviour is identical to the table\n * existing and being empty — this must never abort an otherwise valid\n * delete. Any other failure (a real constraint violation, a lock timeout, a\n * genuine SQL error unrelated to the table's existence) still propagates.\n */\nasync function tolerateMissingTable<T>(\n operation: () => Promise<T>,\n fallback: T,\n context: { table: string; action: string },\n): Promise<T> {\n try {\n return await operation();\n } catch (error) {\n if (classifyDatabaseError(error).kind === 'undefined_object') {\n logger.warn(\n `Cascade delete skipped ${context.action} on '${context.table}': ` +\n 'table or column not found in this database.',\n { error: error instanceof Error ? error.message : String(error) },\n );\n return fallback;\n }\n throw error;\n }\n}\n\nasync function selectIds(\n db: DatabaseInterface,\n tableName: string,\n column: string,\n ids: string[],\n): Promise<string[]> {\n const found: string[] = [];\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n const rows = await tolerateMissingTable(\n () => db.list(tableName, idPredicate(column, batch)),\n [] as Record<string, unknown>[],\n { table: tableName, action: 'CASCADE select' },\n );\n for (const row of rows) {\n const id = row?.id;\n if (typeof id === 'string' && id.length > 0) found.push(id);\n }\n }\n return found;\n}\n\nasync function deleteByIds(\n db: DatabaseInterface,\n tableName: string,\n ids: string[],\n): Promise<void> {\n for (const batch of chunkArray(ids, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () => db.delete(tableName, idPredicate('id', batch)),\n undefined,\n { table: tableName, action: 'CASCADE delete' },\n );\n }\n}\n\n/**\n * Remove the framework-managed side rows owned by the given object ids.\n *\n * `_smrt_contexts` and `_smrt_embeddings` are keyed by `(owner_class, owner_id)`\n * and `(object_class, object_id)` respectively. Matched by id *and* class\n * (review fix): id alone would let two unrelated classes using\n * `idType: 'text'` (non-UUID, not guaranteed globally unique) collide on a\n * shared id value and delete each other's memory/embeddings rows. `classNames`\n * is the STI-hierarchy-expanded candidate set from\n * {@link ownerClassCandidates} — the class column stores the *runtime*\n * constructor name, which for an STI hierarchy is a concrete subclass rather\n * than the class the cascade was planned from, so a single exact name is not\n * enough.\n *\n * A missing system table is not an error — an application database may predate\n * the table, and losing derived rows must never fail an otherwise valid delete.\n */\nasync function deleteSystemRows(\n db: DatabaseInterface,\n ids: string[],\n classNames: string[],\n): Promise<void> {\n const ownerIds = ids.filter(\n (id) =>\n typeof id === 'string' &&\n id.length > 0 &&\n id !== COLLECTION_OWNER_SENTINEL,\n );\n if (ownerIds.length === 0 || classNames.length === 0) return;\n\n for (const [table, idColumn, classColumn] of [\n [CONTEXTS_TABLE, 'owner_id', 'owner_class'],\n [EMBEDDINGS_TABLE, 'object_id', 'object_class'],\n ] as const) {\n for (const batch of chunkArray(ownerIds, IN_LIST_CHUNK_SIZE)) {\n try {\n await db.delete(table, {\n ...idPredicate(idColumn, batch),\n ...idPredicate(classColumn, classNames),\n });\n } catch (error) {\n logger.warn(\n `Failed to clean ${table} rows during cascade delete: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n }\n }\n}\n\n/**\n * Resolve every reference pointing at `ids` of `className`, recursively.\n *\n * Does **not** delete the rows identified by `ids` — the caller owns that, so\n * `SmrtObject.delete()` keeps issuing its own final statement and its own\n * lifecycle hooks.\n */\nasync function resolveReferences(\n ctx: CascadeContext,\n className: string,\n tableName: string,\n ids: string[],\n depth: number,\n): Promise<void> {\n const pending = ids.filter((id) => {\n const key = `${tableName}:${id}`;\n if (ctx.visited.has(key)) return false;\n ctx.visited.add(key);\n return true;\n });\n if (pending.length === 0) return;\n\n if (depth > MAX_CASCADE_DEPTH) {\n throw DatabaseError.constraintViolation(\n `cascade delete from ${className} exceeded the maximum depth of ` +\n `${MAX_CASCADE_DEPTH}; check for a chain of onDelete: 'CASCADE' ` +\n 'references that never terminates',\n className,\n );\n }\n\n const plan = buildCascadePlan(ctx.registry, className);\n\n // RESTRICT first: refuse before anything has been mutated.\n for (const reference of plan.references) {\n if (reference.action !== 'RESTRICT') continue;\n let remaining = 0;\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n remaining += await tolerateMissingTable(\n () =>\n ctx.db.count(\n reference.tableName,\n idPredicate(reference.column, batch),\n ),\n 0,\n { table: reference.tableName, action: 'RESTRICT check' },\n );\n if (remaining > 0) break;\n }\n if (remaining > 0) {\n throw DatabaseError.constraintViolation(\n `${reference.className}.${reference.fieldName} declares ` +\n `onDelete: 'RESTRICT' and ${remaining} row(s) still reference this ` +\n `${className}`,\n reference.column,\n );\n }\n }\n\n for (const reference of plan.references) {\n if (reference.action === 'SET NULL') {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n await tolerateMissingTable(\n () =>\n ctx.db.update(\n reference.tableName,\n idPredicate(reference.column, batch),\n { [reference.column]: null },\n ),\n undefined,\n { table: reference.tableName, action: 'SET NULL' },\n );\n }\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n continue;\n }\n\n if (reference.action !== 'CASCADE') continue;\n\n const childIds = await selectIds(\n ctx.db,\n reference.tableName,\n reference.column,\n pending,\n );\n if (childIds.length === 0) continue;\n\n await resolveReferences(\n ctx,\n reference.className,\n reference.tableName,\n childIds,\n depth + 1,\n );\n await deleteSystemRows(\n ctx.db,\n childIds,\n ownerClassCandidates(ctx.registry, reference.className),\n );\n await deleteByIds(ctx.db, reference.tableName, childIds);\n ctx.affectedTables.add(reference.tableName);\n ctx.affectedTableClasses.set(\n reference.tableName,\n toQualifiedClassName(ctx.registry, reference.className),\n );\n }\n\n for (const association of plan.polymorphic) {\n for (const batch of chunkArray(pending, IN_LIST_CHUNK_SIZE)) {\n const where: Record<string, unknown> = {\n ...idPredicate('meta_id', batch),\n };\n if (plan.metaTypes.length === 1) {\n where.meta_type = plan.metaTypes[0];\n } else {\n where['meta_type in'] = plan.metaTypes;\n }\n const result = await tolerateMissingTable(\n () => ctx.db.delete(association.tableName, where),\n undefined,\n {\n table: association.tableName,\n action: 'polymorphic association cleanup',\n },\n );\n if ((result?.affected ?? 0) > 0) {\n ctx.affectedTables.add(association.tableName);\n ctx.affectedTableClasses.set(\n association.tableName,\n toQualifiedClassName(ctx.registry, association.className),\n );\n }\n }\n }\n}\n\n/** Outcome of a cascade run, returned so the caller can invalidate caches. */\nexport interface CascadeResult {\n /** Tables whose rows were removed or nulled, excluding the target's own. */\n affectedTables: Set<string>;\n /**\n * Qualified class name that owns each entry in {@link affectedTables},\n * where resolvable — lets the caller check *that* class's own\n * cross-process cache config rather than only its own.\n */\n affectedTableClasses: Map<string, string>;\n}\n\n/**\n * Resolve every reference to `ids` of `className` and clean their framework\n * side rows, then hand control back so the caller can delete the rows.\n *\n * Callers are expected to run this on a transaction-bound `db` — see\n * {@link runCascadeDelete}, which owns that decision.\n */\nexport async function cascadeReferencesTo(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: { className: string; tableName: string; ids: string[] },\n): Promise<CascadeResult> {\n const ctx: CascadeContext = {\n db,\n registry,\n visited: new Set(),\n affectedTables: new Set(),\n affectedTableClasses: new Map(),\n };\n await resolveReferences(\n ctx,\n target.className,\n target.tableName,\n target.ids,\n 0,\n );\n await deleteSystemRows(\n db,\n target.ids,\n ownerClassCandidates(registry, target.className),\n );\n return {\n affectedTables: ctx.affectedTables,\n affectedTableClasses: ctx.affectedTableClasses,\n };\n}\n\ntype TransactionCapable = DatabaseInterface & {\n transaction?: <T>(\n this: DatabaseInterface,\n callback: (tx: DatabaseInterface) => Promise<T>,\n ) => Promise<T>;\n};\n\n/**\n * Run the cascade and the target row's own deletion atomically.\n *\n * When anything references the class and the adapter exposes `transaction()`,\n * the whole sequence runs inside one — including the caller's `deleteSelf`\n * statement, so a failure part-way through cannot leave the object deleted with\n * its junction rows intact (or vice versa). Adapters without transaction\n * support run the same statements sequentially; this is the documented\n * degradation, not a silent one.\n *\n * When nothing references the class there is nothing to keep consistent, and\n * the transaction is skipped — see the comment on that branch.\n *\n * @param db - Database the object is bound to\n * @param registry - Registry view used to build cascade plans\n * @param target - Class, table and id of the object being deleted\n * @param deleteSelf - Issues the target row's own `DELETE`, on the tx-bound db\n * @returns Tables affected by the cascade, for read-cache invalidation\n */\nexport async function runCascadeDelete(\n db: DatabaseInterface,\n registry: CascadeRegistryView,\n target: {\n className: string;\n tableName: string;\n /** An unsaved object has none; the cascade is then a no-op. */\n id: string | null | undefined;\n },\n deleteSelf: (db: DatabaseInterface) => Promise<void>,\n): Promise<CascadeResult> {\n const ids = target.id ? [target.id] : [];\n\n // Nothing references this class AND no polymorphic association class is\n // registered anywhere in the process. `plan.polymorphic` is unconditionally\n // every registered `SmrtPolymorphicAssociation` subclass — a `metaType`\n // column can point at any class at runtime, so there is no static metadata\n // to scope it by, unlike a typed `@foreignKey`/`@crossPackageRef`. This\n // branch is therefore common for a class with no incoming references in an\n // app with no polymorphic associations at all, but rare — not \"the\n // overwhelmingly common case\" — once even one polymorphic class exists\n // anywhere in the process, since every delete's plan then carries it.\n // Opening a transaction to wrap statements that cannot disagree with each\n // other would cost two extra round trips, and on single-connection adapters\n // it would serialize concurrent deletes behind the transaction queue. Order\n // the two statements instead: the row goes first, so a failure leaves\n // everything as it was, and the derived side rows follow under the\n // best-effort contract they already carry.\n if (buildCascadePlan(registry, target.className).isEmpty) {\n await deleteSelf(db);\n await deleteSystemRows(\n db,\n ids,\n ownerClassCandidates(registry, target.className),\n );\n return { affectedTables: new Set(), affectedTableClasses: new Map() };\n }\n\n const run = async (bound: DatabaseInterface): Promise<CascadeResult> => {\n const result = await cascadeReferencesTo(bound, registry, {\n className: target.className,\n tableName: target.tableName,\n ids,\n });\n await deleteSelf(bound);\n return result;\n };\n\n const transaction = (db as TransactionCapable).transaction;\n if (typeof transaction !== 'function') {\n return run(db);\n }\n\n return transaction.call<\n DatabaseInterface,\n [(tx: DatabaseInterface) => Promise<CascadeResult>],\n Promise<CascadeResult>\n >(db, run);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;AAY7C,IAAM,iBAAiB;;AAGvB,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