@happyvertical/smrt-vitest 0.61.2 → 0.61.4

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.
@@ -0,0 +1,697 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /** Registry-driven minimum-data fixtures and persistence contracts. Vitest only. */
10
+ import { randomUUID } from 'node:crypto';
11
+ import { existsSync, readFileSync } from 'node:fs';
12
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
13
+ import { isDeepStrictEqual } from 'node:util';
14
+ import { isFrameworkBaseClass, ObjectRegistry, smrt, } from '@happyvertical/smrt-core';
15
+ import { getTestDatabase } from '@happyvertical/smrt-core/testing';
16
+ import { describe, it } from 'vitest';
17
+ import { setupSmrtManifests } from './index.js';
18
+ import { minimalRowExpectedFailures, } from './minimal-row-expected-failures.js';
19
+ import { getTestManifestPath } from './test-db.js';
20
+ /**
21
+ * A required parent lives in a package the package under test does not
22
+ * declare (directly or transitively). Whether that package has a built
23
+ * manifest depends on what else was built, so the harness refuses to resolve
24
+ * it in every shape instead of passing only where it happens to be built.
25
+ */
26
+ class UndeclaredParentError extends Error {
27
+ owner;
28
+ related;
29
+ packageName;
30
+ underTest;
31
+ constructor(owner, related, packageName, underTest) {
32
+ super(`Required parent ${related} of ${owner} belongs to ${packageName}, which ${underTest} does not declare as a dependency`);
33
+ this.owner = owner;
34
+ this.related = related;
35
+ this.packageName = packageName;
36
+ this.underTest = underTest;
37
+ }
38
+ }
39
+ class RequiredFieldError extends Error {
40
+ model;
41
+ field;
42
+ constructor(model, field, cause) {
43
+ super(`Model ${model}: required field ${field}: ${errorText(cause)}`, {
44
+ cause,
45
+ });
46
+ this.model = model;
47
+ this.field = field;
48
+ }
49
+ }
50
+ // These are framework-maintained values, not optional business data.
51
+ const systemFields = new Set([
52
+ 'id',
53
+ 'slug',
54
+ 'context',
55
+ 'created_at',
56
+ 'updated_at',
57
+ 'createdAt',
58
+ 'updatedAt',
59
+ '_meta_type',
60
+ '_meta_data',
61
+ ]);
62
+ // Inferred return: an option a subclass cleared is `null` in `_meta` (#4942).
63
+ function fieldOptions(field) {
64
+ return { ...field._meta, ...field.options, ...field };
65
+ }
66
+ /**
67
+ * A calculated field (`generated`, #4915): the database computes it and a
68
+ * caller's value is refused, so a minimal row never writes it and readback
69
+ * does not expect its default. Only an expression counts: `_meta.generated:
70
+ * true` is the older marker for a field the framework added (the tenant
71
+ * column of `tenantScoped`), which the caller does supply.
72
+ */
73
+ function isGenerated(field) {
74
+ const generated = fieldOptions(field).generated;
75
+ return typeof generated === 'object' && generated !== null;
76
+ }
77
+ function required(model, name, field) {
78
+ const options = fieldOptions(field);
79
+ const tenancy = options.__tenancy;
80
+ const scoped = ObjectRegistry.getClass(model)?.tenantScopedConfig;
81
+ return (options.required === true ||
82
+ (tenancy?.isTenantIdField === true && tenancy.mode === 'required') ||
83
+ (scoped?.mode === 'required' && scoped.field === name));
84
+ }
85
+ function isTenantField(model, name, field) {
86
+ return (fieldOptions(field).__tenancy?.isTenantIdField === true ||
87
+ ObjectRegistry.getClass(model)?.tenantScopedConfig?.field === name);
88
+ }
89
+ function sample(field, populated = false) {
90
+ const options = fieldOptions(field);
91
+ if (options.enum?.length) {
92
+ const value = options.enum[0];
93
+ if ((typeof value === 'number' &&
94
+ (value < (options.min ?? -Infinity) ||
95
+ value > (options.max ?? Infinity))) ||
96
+ (typeof value === 'string' &&
97
+ (value.length < (options.minLength ?? 0) ||
98
+ value.length > (options.maxLength ?? Infinity)))) {
99
+ throw new Error('The first enum value does not satisfy the declared bounds');
100
+ }
101
+ return value;
102
+ }
103
+ switch (field.type) {
104
+ case 'integer':
105
+ case 'decimal': {
106
+ const low = field.type === 'integer'
107
+ ? Math.max(Number.MIN_SAFE_INTEGER, Math.ceil(options.min ?? -Infinity))
108
+ : (options.min ?? -Infinity);
109
+ const high = field.type === 'integer'
110
+ ? Math.min(Number.MAX_SAFE_INTEGER, Math.floor(options.max ?? Infinity))
111
+ : (options.max ?? Infinity);
112
+ const value = Math.min(high, Math.max(low, 1));
113
+ if (!Number.isFinite(value) || low > high) {
114
+ throw new Error('No value satisfies the numeric bounds');
115
+ }
116
+ return value;
117
+ }
118
+ case 'boolean':
119
+ return populated;
120
+ case 'datetime':
121
+ return new Date('2030-01-01T00:00:00.000Z');
122
+ case 'json':
123
+ return populated ? { minimal: true } : {};
124
+ case 'oneToMany':
125
+ case 'manyToMany':
126
+ return [];
127
+ default: {
128
+ if (options.sqlType?.toUpperCase() === 'UUID')
129
+ return randomUUID();
130
+ const min = Math.max(1, Math.ceil(options.minLength ?? 1));
131
+ const max = Math.floor(options.maxLength ?? Math.max(min, 7));
132
+ if (min > max)
133
+ throw new Error('No value satisfies the length bounds');
134
+ return 'minimal'.repeat(Math.ceil(min / 7)).slice(0, max);
135
+ }
136
+ }
137
+ }
138
+ /** Package under test; set by registerMinimalRowTests, else the cwd package. */
139
+ let declaredRoot = process.cwd();
140
+ const declaredClosures = new Map();
141
+ /** Nearest node_modules/<name>/package.json above `from`, as Node resolves it. */
142
+ function findInstalledPackageJson(from, name) {
143
+ for (let dir = resolve(from);; dir = dirname(dir)) {
144
+ const file = join(dir, 'node_modules', name, 'package.json');
145
+ if (existsSync(file))
146
+ return file;
147
+ if (dirname(dir) === dir)
148
+ return null;
149
+ }
150
+ }
151
+ /**
152
+ * The package and every `@happyvertical/smrt-*` package it declares, directly
153
+ * or transitively, in dependencies, peerDependencies or devDependencies. Built
154
+ * dependencies are exactly this set in a Turbo `^build` shard; nothing outside
155
+ * it can be assumed to have a manifest.
156
+ */
157
+ function declaredPackages(root) {
158
+ const cached = declaredClosures.get(root);
159
+ if (cached)
160
+ return cached;
161
+ const found = new Set();
162
+ const visit = (directory, file) => {
163
+ const json = JSON.parse(readFileSync(file, 'utf8'));
164
+ if (json.name)
165
+ found.add(json.name);
166
+ for (const name of Object.keys({
167
+ ...json.dependencies,
168
+ ...json.peerDependencies,
169
+ ...json.devDependencies,
170
+ })) {
171
+ if (!name.startsWith('@happyvertical/smrt-') || found.has(name))
172
+ continue;
173
+ const installed = findInstalledPackageJson(directory, name);
174
+ if (installed)
175
+ visit(dirname(installed), installed);
176
+ else
177
+ found.add(name);
178
+ }
179
+ };
180
+ visit(root, join(root, 'package.json'));
181
+ declaredClosures.set(root, found);
182
+ return found;
183
+ }
184
+ /** Refuse a parent whose package is outside the declared closure. */
185
+ function assertDeclared(owner, related, packageName) {
186
+ if (!packageName ||
187
+ packageName === owner.packageName ||
188
+ declaredPackages(declaredRoot).has(packageName))
189
+ return;
190
+ throw new UndeclaredParentError(owner.qualifiedName ?? owner.name, related, packageName, JSON.parse(readFileSync(join(declaredRoot, 'package.json'), 'utf8'))
191
+ .name);
192
+ }
193
+ function registration(model) {
194
+ const found = ObjectRegistry.getClass(model);
195
+ if (!found)
196
+ throw new Error(`Model ${model}: not registered`);
197
+ return found;
198
+ }
199
+ async function relatedModel(owner, field) {
200
+ const related = field.related;
201
+ if (!related)
202
+ throw new Error(`Unresolved required relationship on ${owner.name}`);
203
+ // Judge the package before looking at the registry: an undeclared package may
204
+ // already be registered here, which must not change the verdict.
205
+ if (related.includes(':'))
206
+ assertDeclared(owner, related, related.slice(0, related.lastIndexOf(':')));
207
+ if (related.includes(':') && !ObjectRegistry.hasClass(related)) {
208
+ await ObjectRegistry.ensureManifestLoaded(related);
209
+ }
210
+ const found = related.includes(':')
211
+ ? ObjectRegistry.getClass(related)
212
+ : (owner.packageName &&
213
+ ObjectRegistry.getClassInPackage(owner.packageName, related)) ||
214
+ ObjectRegistry.getClass(related);
215
+ if (!found)
216
+ throw new Error(`Required parent ${related} is not registered`);
217
+ assertDeclared(owner, related, found.packageName);
218
+ return found.qualifiedName ?? found.name;
219
+ }
220
+ /** Build required input only. Required parents are saved on the supplied database. */
221
+ export async function buildMinimalRow(model, options = {}) {
222
+ const fields = await ObjectRegistry.getAllFields(model);
223
+ const tenant = [...fields].find(([name, field]) => isTenantField(model, name, field));
224
+ return buildRow(model, {
225
+ ...options,
226
+ tenantId: options.tenantId ??
227
+ (tenant && !required(model, tenant[0], tenant[1])
228
+ ? undefined
229
+ : randomUUID()),
230
+ ancestors: [],
231
+ parents: new Map(),
232
+ });
233
+ }
234
+ async function buildRow(model, context) {
235
+ const owner = registration(model);
236
+ const identity = owner.qualifiedName ?? owner.name;
237
+ if (context.ancestors.includes(identity)) {
238
+ throw new Error(`Model ${identity}: required foreign-key cycle: ${[...context.ancestors, identity].join(' -> ')}`);
239
+ }
240
+ const fields = await ObjectRegistry.getAllFields(identity);
241
+ if (context.tenantId === undefined &&
242
+ [...fields].some(([name, field]) => isTenantField(identity, name, field) && required(identity, name, field))) {
243
+ context = { ...context, tenantId: randomUUID() };
244
+ }
245
+ const row = {};
246
+ for (const [name, field] of fields) {
247
+ const tenant = isTenantField(identity, name, field);
248
+ // A required child may reference an optionally scoped parent. Its parent
249
+ // must belong to the same tenant, rather than defaulting to global scope.
250
+ const parentTenant = tenant && context.ancestors.length > 0 && context.tenantId !== undefined;
251
+ if (systemFields.has(name) ||
252
+ isGenerated(field) ||
253
+ (!required(identity, name, field) && !parentTenant))
254
+ continue;
255
+ try {
256
+ if (isTenantField(identity, name, field)) {
257
+ row[name] = context.tenantId;
258
+ }
259
+ else if (field.type === 'foreignKey' ||
260
+ field.type === 'crossPackageRef') {
261
+ row[name] = await parentId(owner, name, field, context);
262
+ }
263
+ else {
264
+ row[name] = sample(field);
265
+ }
266
+ }
267
+ catch (cause) {
268
+ if (cause instanceof UndeclaredParentError)
269
+ throw cause;
270
+ throw new RequiredFieldError(identity, name, cause);
271
+ }
272
+ }
273
+ return row;
274
+ }
275
+ async function parentId(owner, name, field, context) {
276
+ if (!context.db)
277
+ throw new Error('A database is needed to create the required parent');
278
+ const target = await relatedModel(owner, field);
279
+ // Preserve semantic roles: sellerTenantId and payerTenantId must be distinct,
280
+ // while courseId on a child and on its revision names the same ancestor.
281
+ const key = `${target}:${name}`;
282
+ const existing = context.parents.get(key);
283
+ if (existing)
284
+ return existing;
285
+ await loadConstructor(target);
286
+ const parentRow = await buildRow(target, {
287
+ ...context,
288
+ ancestors: [...context.ancestors, owner.qualifiedName ?? owner.name],
289
+ });
290
+ const parents = await ObjectRegistry.getCollection(target, {
291
+ db: context.db,
292
+ });
293
+ let parent;
294
+ try {
295
+ parent = await parents.create(parentRow);
296
+ }
297
+ catch (cause) {
298
+ throw new Error(`Model ${target}: required parent could not be saved: ${errorText(cause)}`, { cause });
299
+ }
300
+ if (!parent.id)
301
+ throw new Error(`Model ${target}: parent creation did not return an id`);
302
+ context.parents.set(key, parent.id);
303
+ return parent.id;
304
+ }
305
+ function sourcePath(file, root) {
306
+ if (isAbsolute(file) && existsSync(file))
307
+ return file;
308
+ const src = file.replaceAll('\\', '/').lastIndexOf('/src/');
309
+ if (src >= 0)
310
+ return join(root, file.slice(src + 1));
311
+ if (file.startsWith('src/'))
312
+ return join(root, file);
313
+ return resolve(root, file);
314
+ }
315
+ async function loadConstructor(model) {
316
+ const found = registration(model);
317
+ if (ObjectRegistry.hasRuntimeConstructor(model))
318
+ return;
319
+ if (!found.sourceFilePath)
320
+ throw new Error(`Model ${model}: manifest has no source path`);
321
+ let root = process.cwd();
322
+ if (found.packageName) {
323
+ const workspace = join(root, '..', found.packageName.replace('@happyvertical/smrt-', ''));
324
+ if (existsSync(join(workspace, 'package.json')))
325
+ root = workspace;
326
+ }
327
+ const module = await import(__rewriteRelativeImportExtension(
328
+ /* @vite-ignore */ sourcePath(found.sourceFilePath, root)));
329
+ if (!ObjectRegistry.hasRuntimeConstructor(model) &&
330
+ typeof module[found.name] === 'function') {
331
+ // Undecorated subclasses and collections are legitimate manifest entries.
332
+ smrt({ ...found.config, packageName: found.packageName })(module[found.name]);
333
+ }
334
+ // Collection registration belongs to the item model. Private helper
335
+ // collections need no exported constructor; no row is instantiated for them.
336
+ if (ObjectRegistry.isCollectionClass(model))
337
+ return;
338
+ if (!ObjectRegistry.hasRuntimeConstructor(model)) {
339
+ throw new Error(`Model ${model}: real constructor was not registered`);
340
+ }
341
+ }
342
+ function errorText(error) {
343
+ if (!(error instanceof Error))
344
+ return String(error);
345
+ return `${error.message}${error.cause ? `: ${errorText(error.cause)}` : ''}`;
346
+ }
347
+ function errorField(error) {
348
+ if (!(error instanceof Error))
349
+ return undefined;
350
+ const details = error.details;
351
+ return typeof details?.field === 'string'
352
+ ? details.field
353
+ : errorField(error.cause);
354
+ }
355
+ function empty(value) {
356
+ return (value == null ||
357
+ value === '' ||
358
+ value === 0 ||
359
+ value === false ||
360
+ (Array.isArray(value) && value.length === 0) ||
361
+ (typeof value === 'object' &&
362
+ !(value instanceof Date) &&
363
+ Object.keys(value).length === 0));
364
+ }
365
+ class OptionalFieldError extends Error {
366
+ model;
367
+ field;
368
+ constructor(model, field, detail, cause) {
369
+ super(`Model ${model}: optional field ${field} ${detail}`, { cause });
370
+ this.model = model;
371
+ this.field = field;
372
+ }
373
+ }
374
+ async function exercise(model, populatedField) {
375
+ const classes = new Set();
376
+ const visited = new Set();
377
+ function includePackageTables(packageName) {
378
+ if (!packageName)
379
+ return;
380
+ for (const [name, entry] of ObjectRegistry.getAllClasses()) {
381
+ if (entry.packageName === packageName &&
382
+ !ObjectRegistry.isCollectionClass(name) &&
383
+ !isFrameworkBaseClass(entry.name, entry.packageName) &&
384
+ !/(?:\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)(?:__tests__|test-support|fixtures|tests)\/)/.test(entry.sourceFilePath ?? '')) {
385
+ classes.add(name);
386
+ }
387
+ }
388
+ }
389
+ async function includeRequiredParents(name) {
390
+ if (visited.has(name))
391
+ return;
392
+ visited.add(name);
393
+ classes.add(name);
394
+ await loadConstructor(name);
395
+ const owner = registration(name);
396
+ // Hooks may query sibling tables even when those tables contain no rows.
397
+ // Prepare the package schema, while keeping seed data minimal.
398
+ includePackageTables(owner.packageName);
399
+ for (const [key, field] of await ObjectRegistry.getAllFields(name)) {
400
+ if (!isTenantField(name, key, field) &&
401
+ (field.type === 'foreignKey' || field.type === 'crossPackageRef')) {
402
+ if (required(name, key, field)) {
403
+ await includeRequiredParents(await relatedModel(owner, field));
404
+ }
405
+ else {
406
+ // Hooks may inspect an empty optional reference. Prepare known
407
+ // dependency tables, without loading unused optional dependencies.
408
+ const target = field.related &&
409
+ (field.related.includes(':')
410
+ ? ObjectRegistry.getClass(field.related)
411
+ : (owner.packageName &&
412
+ ObjectRegistry.getClassInPackage(owner.packageName, field.related)) ||
413
+ ObjectRegistry.getClass(field.related));
414
+ if (target &&
415
+ (!target.packageName ||
416
+ target.packageName === owner.packageName ||
417
+ declaredPackages(declaredRoot).has(target.packageName))) {
418
+ classes.add(target.qualifiedName ?? target.name);
419
+ includePackageTables(target.packageName);
420
+ }
421
+ }
422
+ }
423
+ }
424
+ }
425
+ await includeRequiredParents(model);
426
+ const populated = populatedField &&
427
+ (await ObjectRegistry.getAllFields(model)).get(populatedField);
428
+ if (populated &&
429
+ !isTenantField(model, populatedField, populated) &&
430
+ (populated.type === 'foreignKey' || populated.type === 'crossPackageRef')) {
431
+ await includeRequiredParents(await relatedModel(registration(model), populated));
432
+ }
433
+ const db = await getTestDatabase({ type: 'sqlite', classes: [] });
434
+ try {
435
+ await getTestDatabase({
436
+ db,
437
+ classes: [...classes],
438
+ includeSystemTables: false,
439
+ });
440
+ const fields = await ObjectRegistry.getAllFields(model);
441
+ const row = await buildMinimalRow(model, { db });
442
+ if (populatedField) {
443
+ const field = fields.get(populatedField);
444
+ if (!field)
445
+ throw new Error(`Model ${model}: unknown field ${populatedField}`);
446
+ row[populatedField] = isTenantField(model, populatedField, field)
447
+ ? randomUUID()
448
+ : field.type === 'foreignKey' || field.type === 'crossPackageRef'
449
+ ? await parentId(registration(model), populatedField, field, {
450
+ db,
451
+ ancestors: [],
452
+ tenantId: row[ObjectRegistry.getClass(model)?.tenantScopedConfig?.field ??
453
+ 'tenantId'],
454
+ parents: new Map(),
455
+ })
456
+ : sample(field, true);
457
+ }
458
+ const defaultsAt = Date.now();
459
+ const defaultObject = new (registration(model).constructor)({ ...row, db });
460
+ await defaultObject.initialize();
461
+ const defaults = defaultObject;
462
+ const serializedDefaults = defaultObject.toJSON();
463
+ const collection = await ObjectRegistry.getCollection(model, { db });
464
+ // Collection.create() invokes the model's save(). A second save would test
465
+ // updates and incorrectly reject append-only models.
466
+ const created = await collection.create(row);
467
+ const read = await collection.get({ id: created.id });
468
+ if (!read)
469
+ throw new Error(`Model ${model}: get did not return the saved row`);
470
+ const listed = await collection.list({ where: { id: created.id } });
471
+ if (!listed.some((item) => item.id === created.id)) {
472
+ throw new Error(`Model ${model}: list did not return the saved row`);
473
+ }
474
+ for (const item of [read, ...listed]) {
475
+ for (const [name, field] of fields) {
476
+ if (name === populatedField ||
477
+ systemFields.has(name) ||
478
+ isGenerated(field) ||
479
+ required(model, name, field) ||
480
+ field.type === 'oneToMany' ||
481
+ field.type === 'manyToMany' ||
482
+ fieldOptions(field).transient)
483
+ continue;
484
+ const actual = item[name];
485
+ const serializedDefault = serializedDefaults[name] ??
486
+ serializedDefaults[name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)];
487
+ let serializedEmptyDefault = false;
488
+ // JSON helpers can store an empty object/array as text. Compare to the
489
+ // unsaved serializer's default, preserving nonempty text assertions.
490
+ if (typeof actual === 'string' &&
491
+ typeof serializedDefault === 'object' &&
492
+ empty(serializedDefault)) {
493
+ try {
494
+ serializedEmptyDefault = isDeepStrictEqual(JSON.parse(actual), serializedDefault);
495
+ }
496
+ catch {
497
+ /* Ordinary text stays text. */
498
+ }
499
+ }
500
+ // A constructor's `new Date()` default is a clock value, not a literal.
501
+ const dynamicDateDefault = defaults[name] instanceof Date &&
502
+ actual instanceof Date &&
503
+ actual.getTime() >= defaults[name].getTime() &&
504
+ actual.getTime() - defaults[name].getTime() <=
505
+ Date.now() - defaultsAt;
506
+ if (!empty(actual) &&
507
+ !isDeepStrictEqual(actual, defaults[name]) &&
508
+ !isDeepStrictEqual(actual, fieldOptions(field).default) &&
509
+ !dynamicDateDefault &&
510
+ !serializedEmptyDefault) {
511
+ throw new OptionalFieldError(model, name, `read back populated: ${JSON.stringify(actual)}`);
512
+ }
513
+ }
514
+ }
515
+ }
516
+ finally {
517
+ await db.close?.();
518
+ }
519
+ }
520
+ /** Run the full contract, probing one optional input at a time on fresh databases. */
521
+ export async function assertMinimalRow(model) {
522
+ try {
523
+ await loadConstructor(model);
524
+ await exercise(model);
525
+ }
526
+ catch (cause) {
527
+ if (cause instanceof OptionalFieldError)
528
+ throw cause;
529
+ if (cause instanceof UndeclaredParentError)
530
+ throw cause;
531
+ // A required parent or required value failed before optional inputs on
532
+ // this model were used. Do not misattribute its field to this child.
533
+ if (cause instanceof RequiredFieldError)
534
+ throw cause;
535
+ const message = errorText(cause);
536
+ const fields = await ObjectRegistry.getAllFields(model);
537
+ const optional = [...fields].filter(([name, field]) => (!systemFields.has(name) ||
538
+ name === 'createdAt' ||
539
+ name === 'updatedAt') &&
540
+ !isGenerated(field) &&
541
+ !required(model, name, field));
542
+ const structuredField = errorField(cause);
543
+ if (structuredField &&
544
+ optional.some(([name]) => name === structuredField)) {
545
+ throw new OptionalFieldError(model, structuredField, `failed: ${message}`, cause);
546
+ }
547
+ const named = optional.find(([name]) => {
548
+ const snake = name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
549
+ return new RegExp(`\\b(?:field ['"]?(?:${name}|${snake})['"]?\\b|(?:${name}|${snake}) (?:is required|must|cannot|is invalid))`, 'i').test(message);
550
+ });
551
+ if (named)
552
+ throw new OptionalFieldError(model, named[0], `failed: ${message}`, cause);
553
+ for (const [name] of optional) {
554
+ try {
555
+ await exercise(model, name);
556
+ }
557
+ catch (probeError) {
558
+ // Reaching the readback assertions proves that this input repaired
559
+ // the original create/save/read/list failure, even if another field
560
+ // now violates the empty/default contract.
561
+ if (!(probeError instanceof OptionalFieldError))
562
+ continue;
563
+ }
564
+ throw new OptionalFieldError(model, name, `is needed by model code: ${message}`, cause);
565
+ }
566
+ throw new Error(`Model ${model}: minimal row failed (optional field not determined): ${message}`, { cause });
567
+ }
568
+ }
569
+ /** Resolve a ledger field through required-parent metadata, never model code. */
570
+ async function ledgerField(model, path) {
571
+ const [name, ...rest] = path.split('.');
572
+ const field = (await ObjectRegistry.getAllFields(model)).get(name);
573
+ if (!field || !rest.length)
574
+ return field;
575
+ if (field.type !== 'foreignKey' && field.type !== 'crossPackageRef')
576
+ return undefined;
577
+ return ledgerField(await relatedModel(registration(model), field), rest.join('.'));
578
+ }
579
+ /** Enforce a known finding without hiding changed failures or newly passing models. */
580
+ export async function checkMinimalRowExpectedFailure(model, expected, run = () => assertMinimalRow(model)) {
581
+ try {
582
+ await run();
583
+ }
584
+ catch (error) {
585
+ if (!expected ||
586
+ expected.model !== model ||
587
+ !errorText(error).includes(expected.error))
588
+ throw error;
589
+ const kind = expected.kind ?? 'optional-field';
590
+ if (kind === 'service-only') {
591
+ if (expected.field !== '(service-only write)')
592
+ throw error;
593
+ }
594
+ else {
595
+ const paths = expected.field.split(',').map((path) => path.trim());
596
+ if (error instanceof RequiredFieldError &&
597
+ (error.model !== model ||
598
+ !paths.every((path) => path.startsWith(`${error.field}.`))))
599
+ throw error;
600
+ for (const path of paths) {
601
+ const field = await ledgerField(model, path);
602
+ // Nested JSON properties cannot be resolved by relationship metadata;
603
+ // record their owning field (e.g. promotion) in the ledger instead.
604
+ if (!field ||
605
+ (kind === 'optional-field' && fieldOptions(field).required === true))
606
+ throw error;
607
+ }
608
+ if (error instanceof OptionalFieldError &&
609
+ (error.model !== model || !paths.includes(error.field)))
610
+ throw error;
611
+ }
612
+ return;
613
+ }
614
+ if (expected)
615
+ throw new Error(`Model ${model}: ${expected.kind ?? 'optional-field'} ${expected.field} now passes; remove this entry from minimal-row-expected-failures.ts`);
616
+ }
617
+ /** Register one test per local model. Call with top-level await in a test file. */
618
+ export async function registerMinimalRowTests(options = {}) {
619
+ const root = resolve(options.root ?? process.cwd());
620
+ declaredRoot = root;
621
+ const packageName = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).name;
622
+ await setupSmrtManifests({ root });
623
+ const manifest = JSON.parse(readFileSync(getTestManifestPath(root), 'utf8'));
624
+ // Import models AND collections; metadata stubs do not exercise model code.
625
+ const files = new Set(Object.values(manifest.objects)
626
+ .filter((entry) => (!entry.packageName || entry.packageName === packageName) &&
627
+ entry.filePath &&
628
+ !/\.(test|spec)\.[cm]?[jt]sx?$/.test(entry.filePath) &&
629
+ !/(?:^|\/)(?:__tests__|test-support|fixtures|tests)\//.test(entry.filePath))
630
+ .flatMap((entry) => entry.filePath ? [sourcePath(entry.filePath, root)] : []));
631
+ for (const file of [...files].sort())
632
+ await import(__rewriteRelativeImportExtension(/* @vite-ignore */ file));
633
+ const models = [...ObjectRegistry.getAllClasses()].filter(([, entry]) => entry.packageName === packageName);
634
+ if (models.length === 0)
635
+ throw new Error(`No registered models found for ${packageName}`);
636
+ // Collections without their own decorator still carry custom create/list hooks.
637
+ for (const [model, entry] of models) {
638
+ if (ObjectRegistry.isCollectionClass(model) &&
639
+ !isFrameworkBaseClass(entry.name, entry.packageName) &&
640
+ entry.sourceFilePath &&
641
+ !/(?:^|\/)(?:__tests__|test-support|fixtures|tests)\//.test(entry.sourceFilePath)) {
642
+ await loadConstructor(model);
643
+ }
644
+ }
645
+ const candidates = models.map(([model, entry]) => ({
646
+ model,
647
+ reason: entry.sourceFilePath &&
648
+ /(?:\.(?:test|spec)\.[cm]?[jt]sx?$|(?:^|\/)(?:__tests__|test-support|fixtures|tests)\/)/.test(entry.sourceFilePath)
649
+ ? 'test fixture'
650
+ : isFrameworkBaseClass(entry.name, entry.packageName)
651
+ ? 'framework base'
652
+ : ObjectRegistry.isCollectionClass(model)
653
+ ? 'collection-only class'
654
+ : entry.config.abstract
655
+ ? 'abstract model'
656
+ : undefined,
657
+ }));
658
+ const skipped = candidates
659
+ .filter((entry) => entry.reason)
660
+ .map((entry) => `${entry.model}: ${entry.reason}`);
661
+ const localFailures = minimalRowExpectedFailures.filter((entry) => entry.model.startsWith(`${packageName}:`));
662
+ for (const entry of localFailures) {
663
+ if (!entry.reason.trim() ||
664
+ !entry.error.trim() ||
665
+ !candidates.some((candidate) => candidate.model === entry.model && !candidate.reason)) {
666
+ throw new Error(`Model ${entry.model}: remove this entry or provide its failure evidence; it is not a tested model`);
667
+ }
668
+ }
669
+ describe(`minimal rows: ${packageName}`, () => {
670
+ for (const { model, reason } of candidates) {
671
+ if (reason) {
672
+ it.skip(`${model} (${reason})`, () => { });
673
+ continue;
674
+ }
675
+ const expected = localFailures.find((entry) => entry.model === model);
676
+ const contract = expected?.kind === 'service-only'
677
+ ? 'service-only: refuses direct writes'
678
+ : expected?.kind === 'needs-domain-value'
679
+ ? 'needs-domain-value: preserves the specific domain refusal'
680
+ : expected?.kind === 'undeclared-parent'
681
+ ? 'undeclared-parent: refuses a required parent outside its declared packages'
682
+ : 'create, save, get, list with optional fields empty/default';
683
+ it(`${model}: ${contract}`, async () => {
684
+ await checkMinimalRowExpectedFailure(model, expected);
685
+ });
686
+ }
687
+ });
688
+ const counts = [
689
+ 'optional-field',
690
+ 'service-only',
691
+ 'needs-domain-value',
692
+ 'undeclared-parent',
693
+ ].map((kind) => `${kind}=${localFailures.filter((entry) => (entry.kind ?? 'optional-field') === kind).length}`);
694
+ console.info(`[minimal-row] findings: ${counts.join('; ')}\n` +
695
+ `[minimal-row] ${packageName}: ${candidates.length - skipped.length} tested; ${skipped.length} skipped${skipped.length ? `\n${skipped.join('\n')}` : ''}`);
696
+ }
697
+ //# sourceMappingURL=minimal-row.js.map