@happyvertical/smrt-tenancy 0.60.13 → 0.60.15

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/AGENTS.md CHANGED
@@ -143,3 +143,12 @@ Modes: `'required'` (default — throws without context) or `'optional'` (passes
143
143
  ## Known exceptions to monorepo standards
144
144
 
145
145
  - **`serializeInstance()` in `src/interceptor.ts` calls `instance.toJSON()` directly** (standards.md §7 forbids this in favor of `transformJSON()`). The interceptor must serialize arbitrary instances handed to it — including workspace stubs and plain-object test doubles whose classes may not extend `SmrtObject` and therefore have no `transformJSON()` hook. The call is duck-typed and falls back to manual key iteration when `toJSON` is absent. See the inline comment at the call site for the full rationale.
146
+
147
+ ## Portable model annotations (#4765)
148
+
149
+ Model-only packages may import the original `TenantScoped`, `tenantId`, and
150
+ annotation option types from `@happyvertical/smrt-tenancy/decorators`. This public
151
+ entry reuses the same functions and registry as the root; it imports no context,
152
+ AsyncLocalStorage, query helpers or adapters. It only declares metadata. Existing
153
+ server interception, context, filtering and RLS/authorization remain required and
154
+ unchanged. Never replace these declarations with consumer-owned decorator stubs.
@@ -0,0 +1,239 @@
1
+ import { ObjectRegistry, toSnakeCase } from "@happyvertical/smrt-core";
2
+ import { createLogger } from "@happyvertical/logger";
3
+ //#region src/registry.ts
4
+ var logger = createLogger({ level: "info" });
5
+ var DEFAULT_CONFIG = {
6
+ mode: "required",
7
+ field: "tenantId",
8
+ autoFilter: true,
9
+ autoPopulate: true,
10
+ allowSuperAdminBypass: false
11
+ };
12
+ var tenantScopedClasses = /* @__PURE__ */ new Map();
13
+ var directSimpleRegistrations = /* @__PURE__ */ new Map();
14
+ var directQualifiedRegistrations = /* @__PURE__ */ new Map();
15
+ var directSimpleBindings = /* @__PURE__ */ new Map();
16
+ var unregisteredDecoratorRegistrations = /* @__PURE__ */ new Map();
17
+ var auditedSelectors = /* @__PURE__ */ new Set();
18
+ function isQualifiedClassName(className) {
19
+ return className.includes(":");
20
+ }
21
+ function isCurrentDirectSimpleBinding(binding) {
22
+ return ObjectRegistry.getClassByQualifiedName(binding.qualifiedName)?.constructor === binding.constructor;
23
+ }
24
+ function bindDirectSimpleRegistration(className) {
25
+ if (!directSimpleRegistrations.get(className) || directSimpleBindings.has(className)) return;
26
+ const matches = ObjectRegistry.findClassesByName(className);
27
+ if (matches.length !== 1 || !matches[0].qualifiedName) return;
28
+ directSimpleBindings.set(className, {
29
+ qualifiedName: matches[0].qualifiedName,
30
+ constructor: matches[0].constructor
31
+ });
32
+ warnOnRegistrationMismatch(className);
33
+ }
34
+ function getDirectSimpleRegistration(className) {
35
+ const config = directSimpleRegistrations.get(className);
36
+ if (!config) return void 0;
37
+ const binding = directSimpleBindings.get(className);
38
+ if (binding && !isCurrentDirectSimpleBinding(binding)) throw new Error(`Stale tenant-scoped class registration '${className}'; unregister and register it again for the current constructor.`);
39
+ if (ObjectRegistry.findClassesByName(className).length > 1) throw new Error(`Ambiguous tenant-scoped class registration '${className}'; register an explicit qualified class name instead.`);
40
+ return config;
41
+ }
42
+ function registerTenantScopedConstructor(target, config = {}) {
43
+ const resolved = {
44
+ ...DEFAULT_CONFIG,
45
+ ...config
46
+ };
47
+ unregisteredDecoratorRegistrations.set(target.name, resolved);
48
+ tenantScopedClasses.set(target.name, resolved);
49
+ }
50
+ function registerTenantScopedClass(className, config = {}) {
51
+ const resolved = {
52
+ ...DEFAULT_CONFIG,
53
+ ...config
54
+ };
55
+ tenantScopedClasses.set(className, resolved);
56
+ auditedSelectors.delete(className);
57
+ if (isQualifiedClassName(className)) {
58
+ directQualifiedRegistrations.set(className, resolved);
59
+ warnOnRegistrationMismatch(className);
60
+ return;
61
+ }
62
+ directSimpleRegistrations.set(className, resolved);
63
+ const existingBinding = directSimpleBindings.get(className);
64
+ if (existingBinding && !isCurrentDirectSimpleBinding(existingBinding)) directSimpleBindings.delete(className);
65
+ bindDirectSimpleRegistration(className);
66
+ warnOnRegistrationMismatch(className);
67
+ }
68
+ function unregisterTenantScopedClass(className) {
69
+ auditedSelectors.delete(className);
70
+ tenantScopedClasses.delete(className);
71
+ if (isQualifiedClassName(className)) {
72
+ directQualifiedRegistrations.delete(className);
73
+ return;
74
+ }
75
+ directSimpleRegistrations.delete(className);
76
+ directSimpleBindings.delete(className);
77
+ unregisteredDecoratorRegistrations.delete(className);
78
+ }
79
+ function cloneConfig(config) {
80
+ return { ...config };
81
+ }
82
+ function getDirectTenantScopedConfig(className) {
83
+ const direct = getDeclaredTenantScopedConfig(className);
84
+ const qualifiedName = ObjectRegistry.getClass(className)?.qualifiedName;
85
+ if (direct && qualifiedName && ObjectRegistry.getRuntimeOverride(qualifiedName)?.tenancy) return {
86
+ ...direct,
87
+ mode: "required"
88
+ };
89
+ return direct;
90
+ }
91
+ function getDeclaredTenantScopedConfig(className) {
92
+ ObjectRegistry.assertTenantScopedRegistrationValid(className);
93
+ const directQualified = directQualifiedRegistrations.get(className);
94
+ if (directQualified) {
95
+ if (!auditedSelectors.has(className)) warnOnRegistrationMismatch(className);
96
+ return cloneConfig(directQualified);
97
+ }
98
+ const registered = isQualifiedClassName(className) ? ObjectRegistry.getClassByQualifiedName(className) : ObjectRegistry.getClass(className);
99
+ if (registered) {
100
+ const simple = registered.name;
101
+ const bound = directSimpleBindings.get(simple);
102
+ if (bound) {
103
+ if (bound.qualifiedName === className && bound.constructor === registered.constructor) return cloneConfig(directSimpleRegistrations.get(simple));
104
+ if (!isCurrentDirectSimpleBinding(bound)) throw new Error(`Stale tenant-scoped class registration '${simple}'; unregister and register it again for the current constructor.`);
105
+ }
106
+ if (!bound && directSimpleRegistrations.has(simple)) {
107
+ if (ObjectRegistry.findClassesByName(simple).length > 1) throw new Error(`Ambiguous tenant-scoped class registration '${simple}'; register an explicit qualified class name instead.`);
108
+ bindDirectSimpleRegistration(simple);
109
+ const rebound = directSimpleBindings.get(simple);
110
+ if (rebound?.qualifiedName === className && rebound.constructor === registered.constructor) return cloneConfig(directSimpleRegistrations.get(simple));
111
+ }
112
+ }
113
+ if (!isQualifiedClassName(className)) {
114
+ const directSimple = getDirectSimpleRegistration(className);
115
+ if (directSimple) return cloneConfig(directSimple);
116
+ }
117
+ const coreConfig = ObjectRegistry.getTenantScopedConfig(className);
118
+ if (coreConfig) return {
119
+ mode: coreConfig.mode,
120
+ field: coreConfig.field,
121
+ autoFilter: coreConfig.autoFilter,
122
+ autoPopulate: coreConfig.autoPopulate,
123
+ allowSuperAdminBypass: coreConfig.allowSuperAdminBypass
124
+ };
125
+ if (!registered && !isQualifiedClassName(className)) {
126
+ const decoratorConfig = unregisteredDecoratorRegistrations.get(className);
127
+ if (decoratorConfig) return cloneConfig(decoratorConfig);
128
+ }
129
+ }
130
+ function getInheritedTenantScopedConfig(className) {
131
+ const chain = ObjectRegistry.getInheritanceChain(className);
132
+ for (let i = chain.length - 2; i >= 0; i--) {
133
+ const ancestor = chain[i];
134
+ const direct = getDirectTenantScopedConfig(ancestor);
135
+ if (direct) return direct;
136
+ }
137
+ }
138
+ function getTenantScopedConfig(className) {
139
+ const direct = getDirectTenantScopedConfig(className);
140
+ if (direct) return direct;
141
+ return getInheritedTenantScopedConfig(className);
142
+ }
143
+ ObjectRegistry.registerOwnershipColumnSource((qualifiedName) => {
144
+ const config = getTenantScopedConfig(qualifiedName);
145
+ return config ? [toSnakeCase(config.field)] : void 0;
146
+ });
147
+ function isTenantScopedClass(className) {
148
+ return getTenantScopedConfig(className) !== void 0;
149
+ }
150
+ function getAllTenantScopedClasses() {
151
+ return new Map(tenantScopedClasses);
152
+ }
153
+ function clearTenantScopedRegistry() {
154
+ auditedSelectors.clear();
155
+ tenantScopedClasses.clear();
156
+ directSimpleRegistrations.clear();
157
+ directQualifiedRegistrations.clear();
158
+ directSimpleBindings.clear();
159
+ unregisteredDecoratorRegistrations.clear();
160
+ }
161
+ function resolveSelectorClass(selector) {
162
+ if (isQualifiedClassName(selector)) return ObjectRegistry.getClassByQualifiedName(selector);
163
+ const bound = directSimpleBindings.get(selector);
164
+ if (bound) return ObjectRegistry.getClassByQualifiedName(bound.qualifiedName);
165
+ const matches = ObjectRegistry.findClassesByName(selector);
166
+ return matches.length === 1 ? matches[0] : void 0;
167
+ }
168
+ function declaresFieldInChain(registered, fieldName) {
169
+ if (registered.fields.has(fieldName)) return true;
170
+ if (registered.inheritedFields?.has(fieldName)) return true;
171
+ const visited = /* @__PURE__ */ new Set([registered.constructor]);
172
+ let ctor = Object.getPrototypeOf(registered.constructor);
173
+ while (typeof ctor === "function" && !visited.has(ctor)) {
174
+ visited.add(ctor);
175
+ if (ObjectRegistry.getClassByConstructor(ctor)?.fields.has(fieldName)) return true;
176
+ ctor = Object.getPrototypeOf(ctor);
177
+ }
178
+ return false;
179
+ }
180
+ function auditSelector(selector, config) {
181
+ const registered = resolveSelectorClass(selector);
182
+ if (!registered) return [];
183
+ const className = registered.qualifiedName || registered.name;
184
+ const findings = [];
185
+ if (!declaresFieldInChain(registered, config.field)) {
186
+ findings.push({
187
+ selector,
188
+ className,
189
+ kind: "missing_tenant_field",
190
+ severity: "error",
191
+ message: `${className} is registered tenant-scoped on field '${config.field}', but the model declares no such field. Tenant filtering and population target a column its manifest and schema do not have. Add the field (or declare \`@smrt({ tenantScoped })\`) and regenerate the manifest.`
192
+ });
193
+ return findings;
194
+ }
195
+ if (!ObjectRegistry.getTenantScopedConfig(className)) findings.push({
196
+ selector,
197
+ className,
198
+ kind: "undeclared_tenant_scope",
199
+ severity: "info",
200
+ message: `${className} is tenant-scoped only by runtime registration; its manifest declares no tenancy. Declare \`@smrt({ tenantScoped })\` so schema, generated surfaces and knowledge agree with the read policy.`
201
+ });
202
+ const tenantColumn = toSnakeCase(config.field);
203
+ const conflictColumns = ObjectRegistry.getConflictColumns(className);
204
+ if (!(conflictColumns.length === 1 && conflictColumns[0] === "id") && !conflictColumns.includes(tenantColumn)) findings.push({
205
+ selector,
206
+ className,
207
+ kind: "natural_key_not_tenant_scoped",
208
+ severity: "warning",
209
+ message: `${className} is registered tenant-scoped, but its natural key (${conflictColumns.join(", ")}) omits '${tenantColumn}', so it is unique across tenants: a second tenant cannot store a key another tenant already uses. A new object saved on such a key is refused (TENANT_ISOLATION_VIOLATION) when the row it collides with has a different '${tenantColumn}'; one whose slug was derived from its name moves to a free slug instead. Include '${tenantColumn}' in the conflict columns (or drop the explicit conflictColumns) and run \`smrt db:migrate\`.`
210
+ });
211
+ return findings;
212
+ }
213
+ function auditTenantScopedRegistrations() {
214
+ const findings = [];
215
+ for (const [selector, config] of directQualifiedRegistrations) findings.push(...auditSelector(selector, config));
216
+ for (const [selector, config] of directSimpleRegistrations) findings.push(...auditSelector(selector, config));
217
+ return findings;
218
+ }
219
+ function warnOnRegistrationMismatch(selector) {
220
+ if (auditedSelectors.has(selector)) return;
221
+ const config = directQualifiedRegistrations.get(selector) ?? directSimpleRegistrations.get(selector);
222
+ if (!config) return;
223
+ let findings;
224
+ try {
225
+ findings = auditSelector(selector, config);
226
+ } catch {
227
+ return;
228
+ }
229
+ if (!resolveSelectorClass(selector)) return;
230
+ auditedSelectors.add(selector);
231
+ for (const finding of findings) {
232
+ if (finding.severity === "info") continue;
233
+ logger.warn(`[smrt-tenancy] ${finding.message}`);
234
+ }
235
+ }
236
+ //#endregion
237
+ export { isTenantScopedClass as a, unregisterTenantScopedClass as c, getTenantScopedConfig as i, clearTenantScopedRegistry as n, registerTenantScopedClass as o, getAllTenantScopedClasses as r, registerTenantScopedConstructor as s, auditTenantScopedRegistrations as t };
238
+
239
+ //# sourceMappingURL=registry-DH0v5Efm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry-DH0v5Efm.js","names":[],"sources":["../../src/registry.ts"],"sourcesContent":["/**\n * Tenant-Scoped Class Registry\n *\n * Tracks which classes are tenant-scoped and their configuration.\n * Used by the interceptor to determine how to handle operations.\n *\n * This registry supports two patterns:\n * 1. @TenantScoped() decorator + tenantId field (original pattern)\n * 2. @smrt({ tenantScoped: true }) in smrt-core (Issue #688 pattern)\n *\n * Both patterns are automatically recognized by the interceptor.\n *\n * @see https://github.com/happyvertical/smrt/issues/675\n * @see https://github.com/happyvertical/smrt/issues/688\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport { ObjectRegistry, toSnakeCase } from '@happyvertical/smrt-core';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Resolved tenancy configuration for a single class, as stored in the registry.\n *\n * Every field has a concrete (non-optional) value — defaults are applied by\n * `registerTenantScopedClass()` when the class is registered via `@TenantScoped()`.\n *\n * @see TenantScopedOptions\n * @see registerTenantScopedClass\n */\nexport interface TenantScopedConfig {\n /**\n * Tenancy mode for this class\n * - 'required': Must have tenant context for all operations\n * - 'optional': Works with or without tenant context\n * @default 'required'\n */\n mode: 'required' | 'optional';\n\n /**\n * Field name containing tenant ID\n * @default 'tenantId'\n */\n field: string;\n\n /**\n * Auto-filter all queries by tenant\n * @default true\n */\n autoFilter: boolean;\n\n /**\n * Auto-populate tenant ID from context on create\n * @default true\n */\n autoPopulate: boolean;\n\n /**\n * Allow super admin bypass for this class\n * @default false\n */\n allowSuperAdminBypass: boolean;\n}\n\nconst DEFAULT_CONFIG: TenantScopedConfig = {\n mode: 'required',\n field: 'tenantId',\n autoFilter: true,\n autoPopulate: true,\n allowSuperAdminBypass: false,\n};\n\n// Registry snapshot exposed by getAllTenantScopedClasses().\nconst tenantScopedClasses = new Map<string, TenantScopedConfig>();\n\n// Direct callers select a class by string. Keep simple and qualified selectors\n// separate: a simple selector may be bound only after core proves that exactly\n// one constructor owns that name.\nconst directSimpleRegistrations = new Map<string, TenantScopedConfig>();\nconst directQualifiedRegistrations = new Map<string, TenantScopedConfig>();\nconst directSimpleBindings = new Map<\n string,\n { qualifiedName: string; constructor: Function }\n>();\n\n// Decorators retain a simple mirror only until core has registered their\n// authoritative qualified policy. Qualified runtime resolution always defers\n// to core, preserving manifest and explicit-@smrt precedence.\nconst unregisteredDecoratorRegistrations = new Map<\n string,\n TenantScopedConfig\n>();\n\n// Selectors already audited (and warned about) since their last registration.\nconst auditedSelectors = new Set<string>();\n\nfunction isQualifiedClassName(className: string): boolean {\n return className.includes(':');\n}\n\nfunction isCurrentDirectSimpleBinding(binding: {\n qualifiedName: string;\n constructor: Function;\n}): boolean {\n return (\n ObjectRegistry.getClassByQualifiedName(binding.qualifiedName)\n ?.constructor === binding.constructor\n );\n}\n\nfunction bindDirectSimpleRegistration(className: string): void {\n const config = directSimpleRegistrations.get(className);\n if (!config || directSimpleBindings.has(className)) return;\n\n const matches = ObjectRegistry.findClassesByName(className);\n if (matches.length !== 1 || !matches[0].qualifiedName) return;\n\n directSimpleBindings.set(className, {\n qualifiedName: matches[0].qualifiedName,\n constructor: matches[0].constructor,\n });\n warnOnRegistrationMismatch(className);\n}\n\nfunction getDirectSimpleRegistration(\n className: string,\n): TenantScopedConfig | undefined {\n const config = directSimpleRegistrations.get(className);\n if (!config) return undefined;\n\n const binding = directSimpleBindings.get(className);\n if (binding && !isCurrentDirectSimpleBinding(binding)) {\n throw new Error(\n `Stale tenant-scoped class registration '${className}'; ` +\n 'unregister and register it again for the current constructor.',\n );\n }\n\n const matches = ObjectRegistry.findClassesByName(className);\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous tenant-scoped class registration '${className}'; ` +\n 'register an explicit qualified class name instead.',\n );\n }\n\n return config;\n}\n\n/** @internal Used by TenantScoped; direct callers must use the string API. */\nexport function registerTenantScopedConstructor(\n target: Function,\n config: Partial<TenantScopedConfig> = {},\n): void {\n const resolved = { ...DEFAULT_CONFIG, ...config };\n unregisteredDecoratorRegistrations.set(target.name, resolved);\n tenantScopedClasses.set(target.name, resolved);\n}\n\n/**\n * Register a class as tenant-scoped with the given configuration.\n *\n * Call this directly when you cannot use decorators (e.g., third-party classes\n * or plain objects in tests). Defaults from `DEFAULT_CONFIG` are merged over\n * any omitted options. `@TenantScoped()` has its own constructor-aware mirror\n * and reconciles its authoritative policy in core.\n *\n * A simple selector binds to its exact core constructor when one owner is\n * uniquely resolvable, including when registration happens before core. Once\n * bound it remains attached to that constructor if a same-name peer appears.\n * If core clears that constructor and reuses its qualified name, the selector\n * fails closed until the caller explicitly unregisters and re-registers it.\n * If ownership is ambiguous before binding, interception fails closed until a\n * caller registers an explicit qualified selector. Calling this again for the\n * same selector overwrites that selector's previous entry.\n *\n * @param className - A simple class name (e.g., `'Document'`) or exact core\n * qualified name (e.g., `'@package/name:Document'`).\n * @param config - Partial tenancy configuration; omitted fields receive defaults.\n *\n * @example\n * ```typescript\n * // Manually register a class (e.g., for testing)\n * registerTenantScopedClass('Document', { mode: 'optional' });\n * ```\n *\n * @see TenantScoped\n * @see unregisterTenantScopedClass\n */\nexport function registerTenantScopedClass(\n className: string,\n config: Partial<TenantScopedConfig> = {},\n): void {\n const resolved = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n tenantScopedClasses.set(className, resolved);\n\n auditedSelectors.delete(className);\n if (isQualifiedClassName(className)) {\n directQualifiedRegistrations.set(className, resolved);\n warnOnRegistrationMismatch(className);\n return;\n }\n\n directSimpleRegistrations.set(className, resolved);\n const existingBinding = directSimpleBindings.get(className);\n if (existingBinding && !isCurrentDirectSimpleBinding(existingBinding)) {\n directSimpleBindings.delete(className);\n }\n bindDirectSimpleRegistration(className);\n warnOnRegistrationMismatch(className);\n}\n\n/**\n * Remove a class from the tenant-scoped registry.\n *\n * Primarily intended for test teardown — use `clearTenantScopedRegistry()` to\n * reset the entire registry at once.\n *\n * @param className - The class name to remove (e.g., `'Document'`).\n *\n * @see clearTenantScopedRegistry\n * @see registerTenantScopedClass\n */\nexport function unregisterTenantScopedClass(className: string): void {\n auditedSelectors.delete(className);\n tenantScopedClasses.delete(className);\n if (isQualifiedClassName(className)) {\n directQualifiedRegistrations.delete(className);\n return;\n }\n\n directSimpleRegistrations.delete(className);\n directSimpleBindings.delete(className);\n unregisteredDecoratorRegistrations.delete(className);\n}\n\n/**\n * Return a shallow copy of a config so callers can never mutate the stored\n * registration. The same backing object is shared by the base and every\n * inheriting descendant, so handing out the reference would let an accidental\n * caller mutation silently corrupt the base (and all children). (#1598 review)\n */\nfunction cloneConfig(config: TenantScopedConfig): TenantScopedConfig {\n return { ...config };\n}\n\n/**\n * Resolve a class's OWN tenancy configuration — no STI inheritance, EXACT name\n * match only.\n *\n * Checks the registration mechanisms in order: an explicit direct selector,\n * then core's declared policy. `@TenantScoped()` reconciles its policy in core;\n * its simple-name mirror is used only for unregistered test doubles.\n *\n * Lookups are by exact name only — no simple-name fallback — so a qualified\n * lookup (e.g. `@happyvertical/smrt-affiliates:Payout`, explicitly not scoped)\n * can never strip its namespace and match a same-simple-name scoped class in\n * another package (e.g. `@happyvertical/smrt-commerce:Payout`). (#1598 review)\n */\nfunction getDirectTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n const direct = getDeclaredTenantScopedConfig(className);\n const qualifiedName = ObjectRegistry.getClass(className)?.qualifiedName;\n if (\n direct &&\n qualifiedName &&\n ObjectRegistry.getRuntimeOverride(qualifiedName)?.tenancy\n ) {\n return { ...direct, mode: 'required' };\n }\n return direct;\n}\n\nfunction getDeclaredTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // Core marks caught silent-manifest/runtime-decorator conflicts invalid.\n // Check before the simple-name decorator mirror so every identity path\n // fails closed rather than falling through to an unscoped operation.\n ObjectRegistry.assertTenantScopedRegistrationValid(className);\n // 1. Explicit direct qualified selector.\n const directQualified = directQualifiedRegistrations.get(className);\n if (directQualified) {\n // A qualified selector registered before core learned the class is\n // audited on first use instead.\n if (!auditedSelectors.has(className)) warnOnRegistrationMismatch(className);\n return cloneConfig(directQualified);\n }\n\n const registered = isQualifiedClassName(className)\n ? ObjectRegistry.getClassByQualifiedName(className)\n : ObjectRegistry.getClass(className);\n\n // A direct simple selector can bind lazily after registration-before-core.\n // It is never inferred from a qualified name when more than one core class\n // owns that simple name.\n if (registered) {\n const simple = registered.name;\n const bound = directSimpleBindings.get(simple);\n if (bound) {\n if (\n bound.qualifiedName === className &&\n bound.constructor === registered.constructor\n ) {\n return cloneConfig(directSimpleRegistrations.get(simple)!);\n }\n // Core can clear and re-register a qualified name with a different\n // constructor. Never transfer the old selector binding to it: the caller\n // must explicitly unregister/re-register after that lifecycle reset.\n if (!isCurrentDirectSimpleBinding(bound)) {\n throw new Error(\n `Stale tenant-scoped class registration '${simple}'; ` +\n 'unregister and register it again for the current constructor.',\n );\n }\n }\n if (!bound && directSimpleRegistrations.has(simple)) {\n const matches = ObjectRegistry.findClassesByName(simple);\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous tenant-scoped class registration '${simple}'; ` +\n 'register an explicit qualified class name instead.',\n );\n }\n bindDirectSimpleRegistration(simple);\n const rebound = directSimpleBindings.get(simple);\n if (\n rebound?.qualifiedName === className &&\n rebound.constructor === registered.constructor\n ) {\n return cloneConfig(directSimpleRegistrations.get(simple)!);\n }\n }\n }\n\n if (!isQualifiedClassName(className)) {\n // Explicit direct selectors retain their established precedence. For\n // plain-object/test-double paths this is the historical simple-selector\n // fallback, subject to the existing ambiguity checks.\n const directSimple = getDirectSimpleRegistration(className);\n if (directSimple) return cloneConfig(directSimple);\n }\n\n // 2. Core registry (@smrt({ tenantScoped: true }) pattern - Issue #688).\n // findClass() resolves qualified names package-safely, so this branch is\n // already disambiguated.\n const coreConfig = ObjectRegistry.getTenantScopedConfig(className);\n if (coreConfig) {\n // Convert core config to TenantScopedConfig format\n return {\n mode: coreConfig.mode,\n field: coreConfig.field,\n autoFilter: coreConfig.autoFilter,\n autoPopulate: coreConfig.autoPopulate,\n allowSuperAdminBypass: coreConfig.allowSuperAdminBypass,\n };\n }\n\n // A decorator mirror is only authoritative when core has no registration.\n // A registered unqualified consumer still has a canonical simple identity.\n if (!registered && !isQualifiedClassName(className)) {\n const decoratorConfig = unregisteredDecoratorRegistrations.get(className);\n if (decoratorConfig) return cloneConfig(decoratorConfig);\n }\n\n return undefined;\n}\n\n/**\n * Resolve tenancy configuration inherited from an STI/ancestor class.\n *\n * `@TenantScoped` (and `@smrt({ tenantScoped })`) register ONLY the exact class\n * decorated — recognition does NOT propagate to subclasses. Before #1596 this\n * meant an STI child with its own collection (the child is the collection's\n * `_itemClass`) was treated as non-tenant-scoped at runtime: the interceptor\n * skipped tenant filtering on its `list()`/`get()` (cross-tenant reads), skipped\n * tenant population in `beforeSave`, and skipped the raw-SQL policy. Manual\n * re-declaration on every child was the fragile pattern that already bit images\n * (#1407) and messages.\n *\n * We now walk the STI inheritance chain so any descendant of a tenant-scoped\n * base is recognized automatically and inherits the base's config. A subclass\n * of a tenant-scoped class is always itself tenant-scoped — there is no safe\n * reason for it to opt out — so the walk intentionally covers any inheritance\n * (the motivating leak is STI child collections, but this is correct for CTI\n * hierarchies too).\n *\n * Ancestors are walked from nearest-to-self toward the root, returning the\n * first tenant-scoped ancestor's config so a closer ancestor wins. The class's\n * OWN declaration is resolved by the direct lookup in `getTenantScopedConfig`\n * and always takes precedence over anything inherited here.\n */\nfunction getInheritedTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // getInheritanceChain returns [root, ..., self] (qualified names where the\n // class has package context). It is cached by core and only reached here when\n // the direct lookup misses, so the per-call cost on non-tenant classes is a\n // cache hit plus this short loop. Returns [] for unregistered classes.\n const chain = ObjectRegistry.getInheritanceChain(className);\n // chain[length - 1] is the class itself (already covered by the direct\n // lookup); walk its ancestors from nearest to root.\n for (let i = chain.length - 2; i >= 0; i--) {\n const ancestor = chain[i];\n\n // Exact, package-safe match first — covers `@smrt({ tenantScoped })` bases\n // (resolved through the core registry by qualified name) and any class\n // whose @TenantScoped key matches the chain entry verbatim.\n const direct = getDirectTenantScopedConfig(ancestor);\n if (direct) {\n return direct;\n }\n\n // Do not bridge a qualified ancestor back to a simple registration here.\n // The exact lookup above reaches the core declaration reconciled by the\n // decorator. Stripping would let an unrelated same-name peer lend its\n // direct or decorator policy to this inheritance chain.\n }\n return undefined;\n}\n\n/**\n * Retrieve the resolved tenancy configuration for a class.\n *\n * Resolution order:\n * 1. The class's OWN declaration — local `@TenantScoped()` registry first, then\n * the core `@smrt({ tenantScoped: true })` registry.\n * 2. STI inheritance — the nearest tenant-scoped ancestor's config (#1596).\n *\n * A class that declares its own tenancy never reaches step 2, so an explicit\n * child `@TenantScoped` always overrides the inherited base config.\n *\n * @param className - The class name to look up.\n * @returns The `TenantScopedConfig` if the class is tenant-scoped directly or\n * by inheritance, or `undefined` if it is not.\n *\n * @see isTenantScopedClass\n * @see getAllTenantScopedClasses\n */\nexport function getTenantScopedConfig(\n className: string,\n): TenantScopedConfig | undefined {\n // A class's own @TenantScoped / @smrt({ tenantScoped }) declaration wins.\n const direct = getDirectTenantScopedConfig(className);\n if (direct) return direct;\n // Otherwise inherit recognition from a tenant-scoped STI ancestor (#1596).\n return getInheritedTenantScopedConfig(className);\n}\n\n/**\n * Tell core which column records a row's owner for every tenant-scoped class,\n * including runtime registrations on a custom field\n * (`registerTenantScopedClass('Team', { field: 'organizationId' })`) that the\n * manifest knows nothing about. Core's natural-key save guard compares these\n * columns, so a save whose key collides with another organization's row is\n * refused (`TENANT_ISOLATION_VIOLATION`) instead of adopting it. Resolved on\n * every lookup, so selectors that bind later or are unregistered are honoured.\n */\nObjectRegistry.registerOwnershipColumnSource((qualifiedName) => {\n const config = getTenantScopedConfig(qualifiedName);\n return config ? [toSnakeCase(config.field)] : undefined;\n});\n\n/**\n * Return `true` if the named class is tenant-scoped — directly (via\n * `@TenantScoped()` / `@smrt({ tenantScoped: true })`) or by inheriting from a\n * tenant-scoped STI ancestor (#1596).\n *\n * @param className - The class name to look up (e.g., `'Document'`).\n * @returns `true` if the class is tenant-scoped by any mechanism.\n *\n * @see getTenantScopedConfig\n * @see registerTenantScopedClass\n */\nexport function isTenantScopedClass(className: string): boolean {\n return getTenantScopedConfig(className) !== undefined;\n}\n\n/**\n * Return a snapshot of all classes registered via `@TenantScoped()`.\n *\n * Returns a new `Map` so mutations to the returned value do not affect the\n * internal registry. Note that classes registered only through the core\n * `ObjectRegistry` (`@smrt({ tenantScoped: true })`) are **not** included in\n * this map.\n *\n * @returns A copy of the local tenant-scoped class registry, keyed by class name.\n *\n * @see isTenantScopedClass\n * @see getTenantScopedConfig\n */\nexport function getAllTenantScopedClasses(): Map<string, TenantScopedConfig> {\n return new Map(tenantScopedClasses);\n}\n\n/**\n * Remove all entries from the local tenant-scoped class registry.\n *\n * Intended for test teardown via `resetTenancy()`. Does not affect\n * registrations held by the core `ObjectRegistry`.\n *\n * @see resetTenancy\n * @see unregisterTenantScopedClass\n */\nexport function clearTenantScopedRegistry(): void {\n auditedSelectors.clear();\n tenantScopedClasses.clear();\n directSimpleRegistrations.clear();\n directQualifiedRegistrations.clear();\n directSimpleBindings.clear();\n unregisteredDecoratorRegistrations.clear();\n}\n\n/**\n * One finding from {@link auditTenantScopedRegistrations}.\n *\n * - `missing_tenant_field` (`error`): the class has no field named by the\n * registration, so the interceptor filters and populates a column that does\n * not exist in the model's manifest/schema.\n * - `natural_key_not_tenant_scoped` (`warning`): the class's upsert conflict\n * target (and so its unique index) omits the tenant column — its natural key\n * is unique ACROSS tenants. The interceptor hides other tenants' rows from\n * lookups, so a second tenant's same-key save collides with a row it cannot\n * see; core refuses that save (`TENANT_ISOLATION_VIOLATION`) instead of\n * overwriting the other tenant's row, but the second tenant still cannot\n * store the key.\n * - `undeclared_tenant_scope` (`info`): tenant scope exists only as this\n * runtime registration; the model's manifest declares no tenancy. Its\n * default natural key is still tenant-led when it has a `tenantId` field,\n * but generated surfaces, knowledge, and schema contracts cannot see the\n * read policy. Declaring `@smrt({ tenantScoped })` makes it visible.\n */\nexport interface TenantRegistrationFinding {\n /** The selector passed to `registerTenantScopedClass()`. */\n selector: string;\n /** The core class it resolved to (qualified name when known). */\n className: string;\n kind:\n | 'missing_tenant_field'\n | 'natural_key_not_tenant_scoped'\n | 'undeclared_tenant_scope';\n severity: 'error' | 'warning' | 'info';\n message: string;\n}\n\nfunction resolveSelectorClass(selector: string) {\n if (isQualifiedClassName(selector)) {\n return ObjectRegistry.getClassByQualifiedName(selector);\n }\n const bound = directSimpleBindings.get(selector);\n if (bound) return ObjectRegistry.getClassByQualifiedName(bound.qualifiedName);\n const matches = ObjectRegistry.findClassesByName(selector);\n return matches.length === 1 ? matches[0] : undefined;\n}\n\ntype RegisteredSmrtClass = NonNullable<ReturnType<typeof resolveSelectorClass>>;\n\n/**\n * Whether the class or one of its registered ancestors declares `fieldName`.\n *\n * A class's own field map holds only its own decorator fields until its\n * manifest entry loads; an STI child registered first (a bundled server) has\n * its inherited tenant field on the registered parent only (#3623). Walk the\n * constructor's prototype chain through public registry lookups — read-only,\n * unlike `getInheritanceChain()`, which caches whatever partial chain exists\n * at registration time.\n */\nfunction declaresFieldInChain(\n registered: RegisteredSmrtClass,\n fieldName: string,\n): boolean {\n if (registered.fields.has(fieldName)) return true;\n if (registered.inheritedFields?.has(fieldName)) return true;\n const visited = new Set<unknown>([registered.constructor]);\n let ctor: unknown = Object.getPrototypeOf(registered.constructor);\n while (typeof ctor === 'function' && !visited.has(ctor)) {\n visited.add(ctor);\n const ancestor = ObjectRegistry.getClassByConstructor(\n ctor as RegisteredSmrtClass['constructor'],\n );\n if (ancestor?.fields.has(fieldName)) return true;\n ctor = Object.getPrototypeOf(ctor);\n }\n return false;\n}\n\nfunction auditSelector(\n selector: string,\n config: TenantScopedConfig,\n): TenantRegistrationFinding[] {\n const registered = resolveSelectorClass(selector);\n if (!registered) return [];\n const className = registered.qualifiedName || registered.name;\n const findings: TenantRegistrationFinding[] = [];\n\n if (!declaresFieldInChain(registered, config.field)) {\n findings.push({\n selector,\n className,\n kind: 'missing_tenant_field',\n severity: 'error',\n message:\n `${className} is registered tenant-scoped on field '${config.field}', ` +\n 'but the model declares no such field. Tenant filtering and population ' +\n 'target a column its manifest and schema do not have. Add the field ' +\n '(or declare `@smrt({ tenantScoped })`) and regenerate the manifest.',\n });\n return findings;\n }\n\n if (!ObjectRegistry.getTenantScopedConfig(className)) {\n findings.push({\n selector,\n className,\n kind: 'undeclared_tenant_scope',\n severity: 'info',\n message:\n `${className} is tenant-scoped only by runtime registration; its ` +\n 'manifest declares no tenancy. Declare `@smrt({ tenantScoped })` so ' +\n 'schema, generated surfaces and knowledge agree with the read policy.',\n });\n }\n\n const tenantColumn = toSnakeCase(config.field);\n const conflictColumns = ObjectRegistry.getConflictColumns(className);\n const keyedOnPrimaryKey =\n conflictColumns.length === 1 && conflictColumns[0] === 'id';\n if (!keyedOnPrimaryKey && !conflictColumns.includes(tenantColumn)) {\n findings.push({\n selector,\n className,\n kind: 'natural_key_not_tenant_scoped',\n severity: 'warning',\n message:\n `${className} is registered tenant-scoped, but its natural key ` +\n `(${conflictColumns.join(', ')}) omits '${tenantColumn}', so it is ` +\n 'unique across tenants: a second tenant cannot store a key another ' +\n 'tenant already uses. A new object saved on such a key is refused ' +\n '(TENANT_ISOLATION_VIOLATION) when the row it collides with has a ' +\n `different '${tenantColumn}'; one whose slug was derived from its ` +\n 'name moves to a free slug instead. ' +\n `Include '${tenantColumn}' in the conflict columns (or drop the ` +\n 'explicit conflictColumns) and run `smrt db:migrate`.',\n });\n }\n return findings;\n}\n\n/**\n * Audit every string-selector registration (`registerTenantScopedClass()`)\n * against the core model it resolves to. Selectors whose class core has not\n * registered yet are skipped (they are audited when they bind).\n *\n * Registration also runs this per selector and logs `error`/`warning`\n * findings once, so a mismatch surfaces at startup; call this directly for a\n * complete report (for example from a health check or a test).\n */\nexport function auditTenantScopedRegistrations(): TenantRegistrationFinding[] {\n const findings: TenantRegistrationFinding[] = [];\n for (const [selector, config] of directQualifiedRegistrations) {\n findings.push(...auditSelector(selector, config));\n }\n for (const [selector, config] of directSimpleRegistrations) {\n findings.push(...auditSelector(selector, config));\n }\n return findings;\n}\n\nfunction warnOnRegistrationMismatch(selector: string): void {\n if (auditedSelectors.has(selector)) return;\n const config =\n directQualifiedRegistrations.get(selector) ??\n directSimpleRegistrations.get(selector);\n if (!config) return;\n let findings: TenantRegistrationFinding[];\n try {\n findings = auditSelector(selector, config);\n } catch {\n // Ambiguous or stale identities fail closed on use; the audit stays quiet.\n return;\n }\n if (!resolveSelectorClass(selector)) return; // not in core yet; retry later\n auditedSelectors.add(selector);\n for (const finding of findings) {\n if (finding.severity === 'info') continue;\n logger.warn(`[smrt-tenancy] ${finding.message}`);\n }\n}\n"],"mappings":";;;AAmBA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;AA6C7C,IAAM,iBAAqC;CACzC,MAAM;CACN,OAAO;CACP,YAAY;CACZ,cAAc;CACd,uBAAuB;AACzB;AAGA,IAAM,sCAAsB,IAAI,IAAgC;AAKhE,IAAM,4CAA4B,IAAI,IAAgC;AACtE,IAAM,+CAA+B,IAAI,IAAgC;AACzE,IAAM,uCAAuB,IAAI,IAG/B;AAKF,IAAM,qDAAqC,IAAI,IAG7C;AAGF,IAAM,mCAAmB,IAAI,IAAY;AAEzC,SAAS,qBAAqB,WAA4B;CACxD,OAAO,UAAU,SAAS,GAAG;AAC/B;AAEA,SAAS,6BAA6B,SAG1B;CACV,OACE,eAAe,wBAAwB,QAAQ,aAAa,CAAA,EACxD,gBAAgB,QAAQ;AAEhC;AAEA,SAAS,6BAA6B,WAAyB;CAE7D,IAAI,CADW,0BAA0B,IAAI,SACxC,KAAU,qBAAqB,IAAI,SAAS,GAAG;CAEpD,MAAM,UAAU,eAAe,kBAAkB,SAAS;CAC1D,IAAI,QAAQ,WAAW,KAAK,CAAC,QAAQ,EAAC,CAAE,eAAe;CAEvD,qBAAqB,IAAI,WAAW;EAClC,eAAe,QAAQ,EAAC,CAAE;EAC1B,aAAa,QAAQ,EAAC,CAAE;CAC1B,CAAC;CACD,2BAA2B,SAAS;AACtC;AAEA,SAAS,4BACP,WACgC;CAChC,MAAM,SAAS,0BAA0B,IAAI,SAAS;CACtD,IAAI,CAAC,QAAQ,OAAO,KAAA;CAEpB,MAAM,UAAU,qBAAqB,IAAI,SAAS;CAClD,IAAI,WAAW,CAAC,6BAA6B,OAAO,GAClD,MAAM,IAAI,MACR,2CAA2C,UAAS,iEAEtD;CAIF,IADgB,eAAe,kBAAkB,SAC7C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AAG,cAAc,UAAU,MAAM,CAAC;CAElD,KAAA,MAAW,CAAC,UAAU,WAAW,2BAC/B,SAAS,KAAK,GAAG,cAAc,UAAU,MAAM,CAAC;CAElD,OAAO;AACT;AAEA,SAAS,2BAA2B,UAAwB;CAC1D,IAAI,iBAAiB,IAAI,QAAQ,GAAG;CACpC,MAAM,SACJ,6BAA6B,IAAI,QAAQ,KACzC,0BAA0B,IAAI,QAAQ;CACxC,IAAI,CAAC,QAAQ;CACb,IAAI;CACJ,IAAI;EACF,WAAW,cAAc,UAAU,MAAM;CAC3C,QAAQ;EAEN;CACF;CACA,IAAI,CAAC,qBAAqB,QAAQ,GAAG;CACrC,iBAAiB,IAAI,QAAQ;CAC7B,KAAA,MAAW,WAAW,UAAU;EAC9B,IAAI,QAAQ,aAAa,QAAQ;EACjC,OAAO,KAAK,kBAAkB,QAAQ,SAAS;CACjD;AACF"}
@@ -1,241 +1,8 @@
1
1
  import { a as getCurrentTenant, c as isSuperAdminBypass, l as isSystemContext, m as withTenant, n as TenantContextError, o as getTenantId, p as withSystemContext, r as TenantIsolationError, s as hasTenantContext } from "./context-CwbLwyIV.js";
2
- import { GlobalInterceptors, ObjectRegistry, resolveGetStringFilter, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, toSnakeCase } from "@happyvertical/smrt-core";
2
+ import { a as isTenantScopedClass, i as getTenantScopedConfig, n as clearTenantScopedRegistry } from "./registry-DH0v5Efm.js";
3
+ import { GlobalInterceptors, resolveGetStringFilter, setAiUsageTenantResolver, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver } from "@happyvertical/smrt-core";
3
4
  import { AsyncLocalStorage } from "node:async_hooks";
4
5
  import { createLogger } from "@happyvertical/logger";
5
- //#region src/registry.ts
6
- var logger$1 = createLogger({ level: "info" });
7
- var DEFAULT_CONFIG = {
8
- mode: "required",
9
- field: "tenantId",
10
- autoFilter: true,
11
- autoPopulate: true,
12
- allowSuperAdminBypass: false
13
- };
14
- var tenantScopedClasses = /* @__PURE__ */ new Map();
15
- var directSimpleRegistrations = /* @__PURE__ */ new Map();
16
- var directQualifiedRegistrations = /* @__PURE__ */ new Map();
17
- var directSimpleBindings = /* @__PURE__ */ new Map();
18
- var unregisteredDecoratorRegistrations = /* @__PURE__ */ new Map();
19
- var auditedSelectors = /* @__PURE__ */ new Set();
20
- function isQualifiedClassName(className) {
21
- return className.includes(":");
22
- }
23
- function isCurrentDirectSimpleBinding(binding) {
24
- return ObjectRegistry.getClassByQualifiedName(binding.qualifiedName)?.constructor === binding.constructor;
25
- }
26
- function bindDirectSimpleRegistration(className) {
27
- if (!directSimpleRegistrations.get(className) || directSimpleBindings.has(className)) return;
28
- const matches = ObjectRegistry.findClassesByName(className);
29
- if (matches.length !== 1 || !matches[0].qualifiedName) return;
30
- directSimpleBindings.set(className, {
31
- qualifiedName: matches[0].qualifiedName,
32
- constructor: matches[0].constructor
33
- });
34
- warnOnRegistrationMismatch(className);
35
- }
36
- function getDirectSimpleRegistration(className) {
37
- const config = directSimpleRegistrations.get(className);
38
- if (!config) return void 0;
39
- const binding = directSimpleBindings.get(className);
40
- if (binding && !isCurrentDirectSimpleBinding(binding)) throw new Error(`Stale tenant-scoped class registration '${className}'; unregister and register it again for the current constructor.`);
41
- if (ObjectRegistry.findClassesByName(className).length > 1) throw new Error(`Ambiguous tenant-scoped class registration '${className}'; register an explicit qualified class name instead.`);
42
- return config;
43
- }
44
- function registerTenantScopedConstructor(target, config = {}) {
45
- const resolved = {
46
- ...DEFAULT_CONFIG,
47
- ...config
48
- };
49
- unregisteredDecoratorRegistrations.set(target.name, resolved);
50
- tenantScopedClasses.set(target.name, resolved);
51
- }
52
- function registerTenantScopedClass(className, config = {}) {
53
- const resolved = {
54
- ...DEFAULT_CONFIG,
55
- ...config
56
- };
57
- tenantScopedClasses.set(className, resolved);
58
- auditedSelectors.delete(className);
59
- if (isQualifiedClassName(className)) {
60
- directQualifiedRegistrations.set(className, resolved);
61
- warnOnRegistrationMismatch(className);
62
- return;
63
- }
64
- directSimpleRegistrations.set(className, resolved);
65
- const existingBinding = directSimpleBindings.get(className);
66
- if (existingBinding && !isCurrentDirectSimpleBinding(existingBinding)) directSimpleBindings.delete(className);
67
- bindDirectSimpleRegistration(className);
68
- warnOnRegistrationMismatch(className);
69
- }
70
- function unregisterTenantScopedClass(className) {
71
- auditedSelectors.delete(className);
72
- tenantScopedClasses.delete(className);
73
- if (isQualifiedClassName(className)) {
74
- directQualifiedRegistrations.delete(className);
75
- return;
76
- }
77
- directSimpleRegistrations.delete(className);
78
- directSimpleBindings.delete(className);
79
- unregisteredDecoratorRegistrations.delete(className);
80
- }
81
- function cloneConfig(config) {
82
- return { ...config };
83
- }
84
- function getDirectTenantScopedConfig(className) {
85
- const direct = getDeclaredTenantScopedConfig(className);
86
- const qualifiedName = ObjectRegistry.getClass(className)?.qualifiedName;
87
- if (direct && qualifiedName && ObjectRegistry.getRuntimeOverride(qualifiedName)?.tenancy) return {
88
- ...direct,
89
- mode: "required"
90
- };
91
- return direct;
92
- }
93
- function getDeclaredTenantScopedConfig(className) {
94
- ObjectRegistry.assertTenantScopedRegistrationValid(className);
95
- const directQualified = directQualifiedRegistrations.get(className);
96
- if (directQualified) {
97
- if (!auditedSelectors.has(className)) warnOnRegistrationMismatch(className);
98
- return cloneConfig(directQualified);
99
- }
100
- const registered = isQualifiedClassName(className) ? ObjectRegistry.getClassByQualifiedName(className) : ObjectRegistry.getClass(className);
101
- if (registered) {
102
- const simple = registered.name;
103
- const bound = directSimpleBindings.get(simple);
104
- if (bound) {
105
- if (bound.qualifiedName === className && bound.constructor === registered.constructor) return cloneConfig(directSimpleRegistrations.get(simple));
106
- if (!isCurrentDirectSimpleBinding(bound)) throw new Error(`Stale tenant-scoped class registration '${simple}'; unregister and register it again for the current constructor.`);
107
- }
108
- if (!bound && directSimpleRegistrations.has(simple)) {
109
- if (ObjectRegistry.findClassesByName(simple).length > 1) throw new Error(`Ambiguous tenant-scoped class registration '${simple}'; register an explicit qualified class name instead.`);
110
- bindDirectSimpleRegistration(simple);
111
- const rebound = directSimpleBindings.get(simple);
112
- if (rebound?.qualifiedName === className && rebound.constructor === registered.constructor) return cloneConfig(directSimpleRegistrations.get(simple));
113
- }
114
- }
115
- if (!isQualifiedClassName(className)) {
116
- const directSimple = getDirectSimpleRegistration(className);
117
- if (directSimple) return cloneConfig(directSimple);
118
- }
119
- const coreConfig = ObjectRegistry.getTenantScopedConfig(className);
120
- if (coreConfig) return {
121
- mode: coreConfig.mode,
122
- field: coreConfig.field,
123
- autoFilter: coreConfig.autoFilter,
124
- autoPopulate: coreConfig.autoPopulate,
125
- allowSuperAdminBypass: coreConfig.allowSuperAdminBypass
126
- };
127
- if (!registered && !isQualifiedClassName(className)) {
128
- const decoratorConfig = unregisteredDecoratorRegistrations.get(className);
129
- if (decoratorConfig) return cloneConfig(decoratorConfig);
130
- }
131
- }
132
- function getInheritedTenantScopedConfig(className) {
133
- const chain = ObjectRegistry.getInheritanceChain(className);
134
- for (let i = chain.length - 2; i >= 0; i--) {
135
- const ancestor = chain[i];
136
- const direct = getDirectTenantScopedConfig(ancestor);
137
- if (direct) return direct;
138
- }
139
- }
140
- function getTenantScopedConfig(className) {
141
- const direct = getDirectTenantScopedConfig(className);
142
- if (direct) return direct;
143
- return getInheritedTenantScopedConfig(className);
144
- }
145
- ObjectRegistry.registerOwnershipColumnSource((qualifiedName) => {
146
- const config = getTenantScopedConfig(qualifiedName);
147
- return config ? [toSnakeCase(config.field)] : void 0;
148
- });
149
- function isTenantScopedClass(className) {
150
- return getTenantScopedConfig(className) !== void 0;
151
- }
152
- function getAllTenantScopedClasses() {
153
- return new Map(tenantScopedClasses);
154
- }
155
- function clearTenantScopedRegistry() {
156
- auditedSelectors.clear();
157
- tenantScopedClasses.clear();
158
- directSimpleRegistrations.clear();
159
- directQualifiedRegistrations.clear();
160
- directSimpleBindings.clear();
161
- unregisteredDecoratorRegistrations.clear();
162
- }
163
- function resolveSelectorClass(selector) {
164
- if (isQualifiedClassName(selector)) return ObjectRegistry.getClassByQualifiedName(selector);
165
- const bound = directSimpleBindings.get(selector);
166
- if (bound) return ObjectRegistry.getClassByQualifiedName(bound.qualifiedName);
167
- const matches = ObjectRegistry.findClassesByName(selector);
168
- return matches.length === 1 ? matches[0] : void 0;
169
- }
170
- function declaresFieldInChain(registered, fieldName) {
171
- if (registered.fields.has(fieldName)) return true;
172
- if (registered.inheritedFields?.has(fieldName)) return true;
173
- const visited = /* @__PURE__ */ new Set([registered.constructor]);
174
- let ctor = Object.getPrototypeOf(registered.constructor);
175
- while (typeof ctor === "function" && !visited.has(ctor)) {
176
- visited.add(ctor);
177
- if (ObjectRegistry.getClassByConstructor(ctor)?.fields.has(fieldName)) return true;
178
- ctor = Object.getPrototypeOf(ctor);
179
- }
180
- return false;
181
- }
182
- function auditSelector(selector, config) {
183
- const registered = resolveSelectorClass(selector);
184
- if (!registered) return [];
185
- const className = registered.qualifiedName || registered.name;
186
- const findings = [];
187
- if (!declaresFieldInChain(registered, config.field)) {
188
- findings.push({
189
- selector,
190
- className,
191
- kind: "missing_tenant_field",
192
- severity: "error",
193
- message: `${className} is registered tenant-scoped on field '${config.field}', but the model declares no such field. Tenant filtering and population target a column its manifest and schema do not have. Add the field (or declare \`@smrt({ tenantScoped })\`) and regenerate the manifest.`
194
- });
195
- return findings;
196
- }
197
- if (!ObjectRegistry.getTenantScopedConfig(className)) findings.push({
198
- selector,
199
- className,
200
- kind: "undeclared_tenant_scope",
201
- severity: "info",
202
- message: `${className} is tenant-scoped only by runtime registration; its manifest declares no tenancy. Declare \`@smrt({ tenantScoped })\` so schema, generated surfaces and knowledge agree with the read policy.`
203
- });
204
- const tenantColumn = toSnakeCase(config.field);
205
- const conflictColumns = ObjectRegistry.getConflictColumns(className);
206
- if (!(conflictColumns.length === 1 && conflictColumns[0] === "id") && !conflictColumns.includes(tenantColumn)) findings.push({
207
- selector,
208
- className,
209
- kind: "natural_key_not_tenant_scoped",
210
- severity: "warning",
211
- message: `${className} is registered tenant-scoped, but its natural key (${conflictColumns.join(", ")}) omits '${tenantColumn}', so it is unique across tenants: a second tenant cannot store a key another tenant already uses. A new object saved on such a key is refused (TENANT_ISOLATION_VIOLATION) when the row it collides with has a different '${tenantColumn}'; one whose slug was derived from its name moves to a free slug instead. Include '${tenantColumn}' in the conflict columns (or drop the explicit conflictColumns) and run \`smrt db:migrate\`.`
212
- });
213
- return findings;
214
- }
215
- function auditTenantScopedRegistrations() {
216
- const findings = [];
217
- for (const [selector, config] of directQualifiedRegistrations) findings.push(...auditSelector(selector, config));
218
- for (const [selector, config] of directSimpleRegistrations) findings.push(...auditSelector(selector, config));
219
- return findings;
220
- }
221
- function warnOnRegistrationMismatch(selector) {
222
- if (auditedSelectors.has(selector)) return;
223
- const config = directQualifiedRegistrations.get(selector) ?? directSimpleRegistrations.get(selector);
224
- if (!config) return;
225
- let findings;
226
- try {
227
- findings = auditSelector(selector, config);
228
- } catch {
229
- return;
230
- }
231
- if (!resolveSelectorClass(selector)) return;
232
- auditedSelectors.add(selector);
233
- for (const finding of findings) {
234
- if (finding.severity === "info") continue;
235
- logger$1.warn(`[smrt-tenancy] ${finding.message}`);
236
- }
237
- }
238
- //#endregion
239
6
  //#region src/enabled-state.ts
240
7
  var enabled = false;
241
8
  function setTenancyEnabled(value) {
@@ -629,6 +396,7 @@ function enableTenancy(options = {}) {
629
396
  setDispatchTenantResolver(() => getTenantId());
630
397
  setTenantEntryPointRunner(runTenantScopedEntryPoint);
631
398
  setTenantScopedClassResolver((className) => isTenantScopedClass(className));
399
+ setAiUsageTenantResolver(() => getTenantId());
632
400
  setTenancyEnabled(true);
633
401
  }
634
402
  function disableTenancy() {
@@ -637,6 +405,7 @@ function disableTenancy() {
637
405
  setDispatchTenantResolver(void 0);
638
406
  setTenantEntryPointRunner(void 0);
639
407
  setTenantScopedClassResolver(void 0);
408
+ setAiUsageTenantResolver(void 0);
640
409
  registeredInterceptor = null;
641
410
  setTenancyEnabled(false);
642
411
  }
@@ -682,6 +451,6 @@ async function assertTenantIsolationViolation(fn, messageContains) {
682
451
  }
683
452
  }
684
453
  //#endregion
685
- export { registerTenantScopedClass as C, isTenantScopedClass as S, unregisterTenantScopedClass as T, isTenancyEnabled as _, setupTestTenancy as a, getAllTenantScopedClasses as b, disableTenancy as c, runTenantHierarchyReadScope as d, assertTenantReadAllowed as f, runTenantScopedEntryPoint as g, withTenantGlobalRead as h, resetTenancy as i, enableTenancy as l, queryWithGlobals as m, assertTenantIsolationViolation as n, testTenantIsolation as o, queryGlobal as p, createTestTenantContext as r, createTenantInterceptor as s, assertTenantContextRequired as t, getTenantHierarchyReadScope as u, auditTenantScopedRegistrations as v, registerTenantScopedConstructor as w, getTenantScopedConfig as x, clearTenantScopedRegistry as y };
454
+ export { isTenancyEnabled as _, setupTestTenancy as a, disableTenancy as c, runTenantHierarchyReadScope as d, assertTenantReadAllowed as f, runTenantScopedEntryPoint as g, withTenantGlobalRead as h, resetTenancy as i, enableTenancy as l, queryWithGlobals as m, assertTenantIsolationViolation as n, testTenantIsolation as o, queryGlobal as p, createTestTenantContext as r, createTenantInterceptor as s, assertTenantContextRequired as t, getTenantHierarchyReadScope as u };
686
455
 
687
- //# sourceMappingURL=testing-Cx_KIEyw.js.map
456
+ //# sourceMappingURL=testing-B8cyKxLY.js.map