graphddb 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,992 @@
1
+ // src/select/column.ts
2
+ var COLUMN_REF = /* @__PURE__ */ Symbol.for("graphddb.columnRef");
3
+ function isColumn(value) {
4
+ return typeof value === "object" && value !== null && value[COLUMN_REF] === true;
5
+ }
6
+ function createColumnMap() {
7
+ const cache = /* @__PURE__ */ new Map();
8
+ return new Proxy(
9
+ {},
10
+ {
11
+ get(_target, prop) {
12
+ if (typeof prop !== "string") return void 0;
13
+ let col = cache.get(prop);
14
+ if (!col) {
15
+ col = { [COLUMN_REF]: true, name: prop };
16
+ cache.set(prop, col);
17
+ }
18
+ return col;
19
+ }
20
+ }
21
+ );
22
+ }
23
+
24
+ // src/decorators/key.ts
25
+ var KEY_MARKER = /* @__PURE__ */ Symbol("graphddb:key");
26
+ var KEY_SEGMENT = /* @__PURE__ */ Symbol("graphddb:keySegment");
27
+ function isKeySegment(value) {
28
+ return typeof value === "object" && value !== null && value[KEY_SEGMENT] === true;
29
+ }
30
+ function k(literals, ...columns) {
31
+ for (let i = 0; i < columns.length; i++) {
32
+ if (!isColumn(columns[i])) {
33
+ throw new Error(
34
+ `k\`...\`: interpolation #${i} must be a typed column reference (e.g. \`c.userId\`), not ${typeof columns[i]}. Key segments name fields via column references so they stay type-safe.`
35
+ );
36
+ }
37
+ }
38
+ return {
39
+ [KEY_SEGMENT]: true,
40
+ literals: [...literals],
41
+ columns
42
+ };
43
+ }
44
+ function isKeyDefinition(value) {
45
+ return typeof value === "object" && value !== null && KEY_MARKER in value;
46
+ }
47
+ function normalizeSegments(spec) {
48
+ if (spec === void 0) return [];
49
+ const list = Array.isArray(spec) ? spec : [spec];
50
+ for (const seg of list) {
51
+ if (!isKeySegment(seg)) {
52
+ throw new Error(
53
+ "key()/gsi(): pk and sk must be built with the `k` tagged template (e.g. k`USER#${c.userId}`) or an array of them."
54
+ );
55
+ }
56
+ }
57
+ return list;
58
+ }
59
+ function segmentFieldNames(segments) {
60
+ const seen = /* @__PURE__ */ new Set();
61
+ const out = [];
62
+ for (const seg of segments) {
63
+ for (const col of seg.columns) {
64
+ if (!seen.has(col.name)) {
65
+ seen.add(col.name);
66
+ out.push(col.name);
67
+ }
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ function buildSegmentedKey(structure) {
73
+ const pkSegments = normalizeSegments(structure.pk);
74
+ const skSegments = normalizeSegments(structure.sk);
75
+ if (pkSegments.length === 0) {
76
+ throw new Error("key()/gsi(): pk must define at least one segment.");
77
+ }
78
+ const seen = /* @__PURE__ */ new Set();
79
+ const inputFieldNames = [];
80
+ for (const name of [
81
+ ...segmentFieldNames(pkSegments),
82
+ ...segmentFieldNames(skSegments)
83
+ ]) {
84
+ if (!seen.has(name)) {
85
+ seen.add(name);
86
+ inputFieldNames.push(name);
87
+ }
88
+ }
89
+ return { segmented: { pkSegments, skSegments }, inputFieldNames };
90
+ }
91
+ function key(builder) {
92
+ const accessor = createColumnMap();
93
+ const structure = builder(accessor);
94
+ const { segmented, inputFieldNames } = buildSegmentedKey(structure);
95
+ return {
96
+ [KEY_MARKER]: true,
97
+ segmented,
98
+ inputFieldNames
99
+ };
100
+ }
101
+
102
+ // src/linter/linter.ts
103
+ var Linter = class {
104
+ rules = [];
105
+ addRule(rule) {
106
+ this.rules.push(rule);
107
+ }
108
+ run(metadata, registry) {
109
+ const results = [];
110
+ for (const rule of this.rules) {
111
+ results.push(...rule.check(metadata, registry));
112
+ }
113
+ return results;
114
+ }
115
+ runAll(registry) {
116
+ const results = [];
117
+ const all = registry.getAll();
118
+ for (const [, metadata] of all) {
119
+ results.push(...this.run(metadata, registry));
120
+ }
121
+ return results;
122
+ }
123
+ };
124
+
125
+ // src/linter/rules/no-scan.ts
126
+ var noScanRule = {
127
+ id: "no-scan",
128
+ severity: "error",
129
+ check(metadata) {
130
+ if (metadata.primaryKey === null && metadata.gsiDefinitions.length === 0) {
131
+ return [
132
+ {
133
+ ruleId: "no-scan",
134
+ severity: "error",
135
+ message: `Entity '${metadata.prefix}' has no primaryKey or GSI defined. All reads would require a full table scan.`,
136
+ entity: metadata.prefix
137
+ }
138
+ ];
139
+ }
140
+ return [];
141
+ }
142
+ };
143
+
144
+ // src/linter/rules/require-limit.ts
145
+ var requireLimitRule = {
146
+ id: "require-limit",
147
+ severity: "warning",
148
+ check(metadata) {
149
+ const results = [];
150
+ for (const relation of metadata.relations) {
151
+ if (relation.type !== "hasMany") continue;
152
+ if (relation.options?.versioned) continue;
153
+ const limit = relation.options?.limit;
154
+ if (!limit || limit.default === void 0 || limit.max === void 0) {
155
+ const kb = Object.keys(relation.keyBinding).join(", ");
156
+ results.push({
157
+ ruleId: "require-limit",
158
+ severity: "warning",
159
+ message: `hasMany relation (keyBinding: [${kb}]) on entity '${metadata.prefix}' is missing limit.default or limit.max. Unbounded queries may consume excessive RCU.`,
160
+ entity: metadata.prefix
161
+ });
162
+ }
163
+ }
164
+ return results;
165
+ }
166
+ };
167
+
168
+ // src/linter/rules/gsi-ambiguity.ts
169
+ function isSubsetOf(a, b) {
170
+ const setB = new Set(b);
171
+ return a.length > 0 && a.every((f) => setB.has(f));
172
+ }
173
+ var gsiAmbiguityRule = {
174
+ id: "gsi-ambiguity",
175
+ severity: "error",
176
+ check(metadata) {
177
+ const results = [];
178
+ const patterns = [];
179
+ if (metadata.primaryKey) {
180
+ patterns.push({
181
+ label: "primaryKey",
182
+ fieldNames: metadata.primaryKey.inputFieldNames
183
+ });
184
+ }
185
+ for (const gsi of metadata.gsiDefinitions) {
186
+ patterns.push({ label: gsi.indexName, fieldNames: gsi.inputFieldNames });
187
+ }
188
+ for (let i = 0; i < patterns.length; i++) {
189
+ for (let j = i + 1; j < patterns.length; j++) {
190
+ const a = patterns[i];
191
+ const b = patterns[j];
192
+ if (isSubsetOf(a.fieldNames, b.fieldNames) || isSubsetOf(b.fieldNames, a.fieldNames)) {
193
+ const smaller = a.fieldNames.length <= b.fieldNames.length ? a : b;
194
+ results.push({
195
+ ruleId: "gsi-ambiguity",
196
+ severity: "error",
197
+ message: `Ambiguous GSI resolution: field set [${smaller.fieldNames.join(", ")}] matches both '${a.label}' and '${b.label}'. Each access pattern must have a unique field combination.`,
198
+ entity: metadata.prefix,
199
+ field: smaller.fieldNames.join(", ")
200
+ });
201
+ }
202
+ }
203
+ }
204
+ return results;
205
+ }
206
+ };
207
+
208
+ // src/planner/key-resolver.ts
209
+ function fieldSetsEqual(a, b) {
210
+ if (a.length !== b.length) return false;
211
+ const sorted = [...b].sort();
212
+ return [...a].sort().every((v, i) => v === sorted[i]);
213
+ }
214
+ function classifySegmentMatch(segmented, queryFields) {
215
+ const pkFields = segmentFieldNames(segmented.pkSegments);
216
+ const present = new Set(queryFields);
217
+ const allFields = /* @__PURE__ */ new Set([
218
+ ...pkFields,
219
+ ...segmentFieldNames(segmented.skSegments)
220
+ ]);
221
+ for (const f of queryFields) {
222
+ if (!allFields.has(f)) return null;
223
+ }
224
+ for (const f of pkFields) {
225
+ if (!present.has(f)) return null;
226
+ }
227
+ const sk = segmented.skSegments;
228
+ let consumed = 0;
229
+ let truncated = false;
230
+ for (let i = 0; i < sk.length; i++) {
231
+ const fields = sk[i].columns.map((c) => c.name);
232
+ const all = fields.every((f) => present.has(f));
233
+ const any = fields.some((f) => present.has(f));
234
+ if (all && fields.length > 0) {
235
+ if (truncated) return null;
236
+ consumed = i + 1;
237
+ continue;
238
+ }
239
+ if (fields.length === 0) {
240
+ if (!truncated) consumed = i + 1;
241
+ continue;
242
+ }
243
+ if (any) return null;
244
+ truncated = true;
245
+ }
246
+ const skFieldCount = segmentFieldNames(sk).length;
247
+ const allSkPresent = segmentFieldNames(sk).every((f) => present.has(f));
248
+ if (skFieldCount === 0 || allSkPresent && consumed === sk.length) {
249
+ return "full";
250
+ }
251
+ return "partial";
252
+ }
253
+ function resolveKey(queryFields, metadata) {
254
+ if (metadata.primaryKey && fieldSetsEqual(queryFields, metadata.primaryKey.inputFieldNames)) {
255
+ return {
256
+ type: "pk",
257
+ partial: false,
258
+ inputFieldNames: metadata.primaryKey.inputFieldNames
259
+ };
260
+ }
261
+ for (const gsi of metadata.gsiDefinitions) {
262
+ if (fieldSetsEqual(queryFields, gsi.inputFieldNames)) {
263
+ return {
264
+ type: "gsi",
265
+ indexName: gsi.indexName,
266
+ unique: gsi.unique,
267
+ partial: false,
268
+ inputFieldNames: gsi.inputFieldNames
269
+ };
270
+ }
271
+ }
272
+ if (metadata.primaryKey) {
273
+ const match = classifySegmentMatch(metadata.primaryKey.segmented, queryFields);
274
+ if (match === "partial") {
275
+ return { type: "pk", partial: true, inputFieldNames: queryFields };
276
+ }
277
+ if (match === "full") {
278
+ return { type: "pk", partial: false, inputFieldNames: queryFields };
279
+ }
280
+ }
281
+ for (const gsi of metadata.gsiDefinitions) {
282
+ const match = classifySegmentMatch(gsi.segmented, queryFields);
283
+ if (match === "partial") {
284
+ return {
285
+ type: "gsi",
286
+ indexName: gsi.indexName,
287
+ unique: false,
288
+ partial: true,
289
+ inputFieldNames: queryFields
290
+ };
291
+ }
292
+ if (match === "full") {
293
+ return {
294
+ type: "gsi",
295
+ indexName: gsi.indexName,
296
+ unique: gsi.unique,
297
+ partial: false,
298
+ inputFieldNames: queryFields
299
+ };
300
+ }
301
+ }
302
+ throw new Error(
303
+ `No access pattern found for fields [${queryFields.join(", ")}]. Available: primaryKey([${metadata.primaryKey?.inputFieldNames.join(", ") ?? ""}])` + metadata.gsiDefinitions.map((g) => `, ${g.indexName}([${g.inputFieldNames.join(", ")}])`).join("")
304
+ );
305
+ }
306
+
307
+ // src/linter/rules/missing-gsi.ts
308
+ var missingGsiRule = {
309
+ id: "missing-gsi",
310
+ severity: "error",
311
+ check(metadata, registry) {
312
+ const results = [];
313
+ for (const relation of metadata.relations) {
314
+ const targetFields = Object.keys(relation.keyBinding);
315
+ if (targetFields.length === 0) {
316
+ continue;
317
+ }
318
+ let targetMeta;
319
+ try {
320
+ const targetClass = relation.targetFactory();
321
+ targetMeta = registry.get(targetClass);
322
+ } catch {
323
+ results.push({
324
+ ruleId: "missing-gsi",
325
+ severity: "error",
326
+ message: `Relation '${relation.propertyName}' on entity '${metadata.prefix}' targets an entity that is not registered in MetadataRegistry.`,
327
+ entity: metadata.prefix,
328
+ field: relation.propertyName
329
+ });
330
+ continue;
331
+ }
332
+ try {
333
+ resolveKey(targetFields, targetMeta);
334
+ } catch {
335
+ results.push({
336
+ ruleId: "missing-gsi",
337
+ severity: "error",
338
+ message: `Relation '${relation.propertyName}' on entity '${metadata.prefix}' requires access pattern [${targetFields.join(", ")}] on target entity '${targetMeta.prefix}', but no matching primary key or GSI is defined.`,
339
+ entity: metadata.prefix,
340
+ field: relation.propertyName
341
+ });
342
+ }
343
+ }
344
+ return results;
345
+ }
346
+ };
347
+
348
+ // src/linter/rules/relation-depth.ts
349
+ var DEFAULT_MAX_DEPTH = 1;
350
+ function computeRelationDepth(metadata, registry, visited = /* @__PURE__ */ new Set()) {
351
+ if (metadata.relations.length === 0) {
352
+ return 0;
353
+ }
354
+ let maxDepth = 0;
355
+ for (const relation of metadata.relations) {
356
+ let targetClass;
357
+ try {
358
+ targetClass = relation.targetFactory();
359
+ } catch {
360
+ continue;
361
+ }
362
+ if (visited.has(targetClass)) {
363
+ continue;
364
+ }
365
+ let targetMeta;
366
+ try {
367
+ targetMeta = registry.get(targetClass);
368
+ } catch {
369
+ continue;
370
+ }
371
+ const nextVisited = new Set(visited);
372
+ nextVisited.add(targetClass);
373
+ const childDepth = 1 + computeRelationDepth(targetMeta, registry, nextVisited);
374
+ maxDepth = Math.max(maxDepth, childDepth);
375
+ }
376
+ return maxDepth;
377
+ }
378
+ var relationDepthRule = {
379
+ id: "relation-depth",
380
+ severity: "warning",
381
+ check(metadata, registry) {
382
+ const depth = computeRelationDepth(metadata, registry);
383
+ if (depth <= DEFAULT_MAX_DEPTH) {
384
+ return [];
385
+ }
386
+ return [
387
+ {
388
+ ruleId: "relation-depth",
389
+ severity: "warning",
390
+ message: `Entity '${metadata.prefix}' has relation paths exceeding default maxDepth ${DEFAULT_MAX_DEPTH} (detected depth: ${depth}). Deep traversal requires explicit maxDepth at runtime.`,
391
+ entity: metadata.prefix
392
+ }
393
+ ];
394
+ }
395
+ };
396
+
397
+ // src/linter/rules/same-partition-preset.ts
398
+ var samePartitionPresetRule = {
399
+ id: "same-partition-preset",
400
+ severity: "error",
401
+ check(metadata, registry) {
402
+ const results = [];
403
+ for (const relation of metadata.relations) {
404
+ if (relation.options?.pattern !== "samePartition") continue;
405
+ results.push(...checkRelation(metadata, relation, registry));
406
+ }
407
+ return results;
408
+ }
409
+ };
410
+ function err(metadata, relation, message) {
411
+ return {
412
+ ruleId: "same-partition-preset",
413
+ severity: "error",
414
+ message: `Relation '${relation.propertyName}' on entity '${metadata.prefix}' declares pattern 'samePartition' but ${message}`,
415
+ entity: metadata.prefix,
416
+ field: relation.propertyName
417
+ };
418
+ }
419
+ function checkRelation(metadata, relation, registry) {
420
+ if (relation.type !== "hasMany") {
421
+ return [
422
+ err(
423
+ metadata,
424
+ relation,
425
+ `is a '${relation.type}'. 'samePartition' lowers a parent\u2192children collection read (begins_with on a segmented sort key) and is only valid on @hasMany.`
426
+ )
427
+ ];
428
+ }
429
+ const results = [];
430
+ const maintenanceOptions = ["read", "write", "projection"].filter(
431
+ (k2) => relation.options?.[k2] !== void 0
432
+ );
433
+ if (maintenanceOptions.length > 0) {
434
+ results.push(
435
+ err(
436
+ metadata,
437
+ relation,
438
+ `also sets [${maintenanceOptions.join(", ")}]. 'samePartition' has no maintained materialisation \u2014 children are read live by begins_with, so it carries no read/write/projection effect. Drop these options (or use a maintained preset such as 'embeddedSnapshot').`
439
+ )
440
+ );
441
+ }
442
+ const targetFields = Object.keys(relation.keyBinding);
443
+ if (targetFields.length === 0) {
444
+ results.push(
445
+ err(metadata, relation, `has an empty keyBinding; nothing to lower.`)
446
+ );
447
+ return results;
448
+ }
449
+ let targetMeta;
450
+ try {
451
+ const targetClass = relation.targetFactory();
452
+ targetMeta = registry.get(targetClass);
453
+ } catch {
454
+ results.push(
455
+ err(
456
+ metadata,
457
+ relation,
458
+ `targets an entity that is not registered in MetadataRegistry.`
459
+ )
460
+ );
461
+ return results;
462
+ }
463
+ let resolved;
464
+ try {
465
+ resolved = resolveKey(targetFields, targetMeta);
466
+ } catch {
467
+ results.push(
468
+ err(
469
+ metadata,
470
+ relation,
471
+ `binds [${targetFields.join(", ")}] on target '${targetMeta.prefix}', which matches no access pattern. A same-partition relation must bind a contiguous prefix of the target's primary key.`
472
+ )
473
+ );
474
+ return results;
475
+ }
476
+ if (resolved.type !== "pk") {
477
+ results.push(
478
+ err(
479
+ metadata,
480
+ relation,
481
+ `binds [${targetFields.join(", ")}] to a ${resolved.type.toUpperCase()} on target '${targetMeta.prefix}'. A GSI is a different partition; 'samePartition' requires the binding to resolve on the target's primary key (same PK, segmented-SK begins_with).`
482
+ )
483
+ );
484
+ return results;
485
+ }
486
+ if (!resolved.partial) {
487
+ results.push(
488
+ err(
489
+ metadata,
490
+ relation,
491
+ `binds the target's full primary key on '${targetMeta.prefix}', which is a point read of a single item, not a child collection. 'samePartition' requires a partial key \u2014 the parent fields fully supply the PK and a proper prefix of the segmented SK, leaving a begins_with boundary for the children.`
492
+ )
493
+ );
494
+ }
495
+ return results;
496
+ }
497
+
498
+ // src/linter/rules/maintenance-shared.ts
499
+ function isMaintainedRelation(relation) {
500
+ const triggers = relation.options?.write?.maintainedOn;
501
+ return Array.isArray(triggers) && triggers.length > 0;
502
+ }
503
+ function maintainedRelations(metadata) {
504
+ return metadata.relations.filter(isMaintainedRelation);
505
+ }
506
+ function logicalName(metadata) {
507
+ return metadata.prefix.endsWith("#") ? metadata.prefix.slice(0, -1) : metadata.prefix;
508
+ }
509
+ function payloadAttributes(meta) {
510
+ const attrs = /* @__PURE__ */ new Set();
511
+ for (const f of meta.fields) attrs.add(f.propertyName);
512
+ if (meta.primaryKey) {
513
+ for (const f of segmentFieldNames(meta.primaryKey.segmented.pkSegments)) {
514
+ attrs.add(f);
515
+ }
516
+ for (const f of segmentFieldNames(meta.primaryKey.segmented.skSegments)) {
517
+ attrs.add(f);
518
+ }
519
+ }
520
+ for (const gsi of meta.gsiDefinitions) {
521
+ for (const f of segmentFieldNames(gsi.segmented.pkSegments)) attrs.add(f);
522
+ for (const f of segmentFieldNames(gsi.segmented.skSegments)) attrs.add(f);
523
+ }
524
+ return attrs;
525
+ }
526
+ function isPayloadRooted(value) {
527
+ return value.startsWith("$.input.") || value.startsWith("$.entity.");
528
+ }
529
+ function projectionSourceAttribute(value) {
530
+ const path = typeof value === "string" ? value : value.path;
531
+ if (typeof value === "string") {
532
+ if (!isPayloadRooted(path)) return path;
533
+ } else if (!isPayloadRooted(path)) {
534
+ return null;
535
+ }
536
+ const stripped = path.replace(/^\$\.(input|entity)\./, "");
537
+ return stripped.split(".")[0] ?? stripped;
538
+ }
539
+ function projectionEntries(projection) {
540
+ return projection ? Object.entries(projection) : [];
541
+ }
542
+
543
+ // src/linter/rules/missing-context.ts
544
+ var missingContextRule = {
545
+ id: "missing-context",
546
+ severity: "error",
547
+ check(metadata, registry) {
548
+ const results = [];
549
+ for (const relation of maintainedRelations(metadata)) {
550
+ results.push(...checkRelation2(metadata, relation, registry));
551
+ }
552
+ return results;
553
+ }
554
+ };
555
+ function err2(metadata, relation, message) {
556
+ return {
557
+ ruleId: "missing-context",
558
+ severity: "error",
559
+ message: `Maintained relation '${relation.propertyName}' on '${logicalName(metadata)}' ${message}`,
560
+ entity: metadata.prefix,
561
+ field: relation.propertyName
562
+ };
563
+ }
564
+ function checkRelation2(metadata, relation, registry) {
565
+ let sourceMeta;
566
+ try {
567
+ sourceMeta = registry.get(relation.targetFactory());
568
+ } catch {
569
+ return [];
570
+ }
571
+ const sourceName = logicalName(sourceMeta);
572
+ const payload = payloadAttributes(sourceMeta);
573
+ const available = `available: ${[...payload].sort().map((f) => `'${f}'`).join(", ")}`;
574
+ const results = [];
575
+ for (const sourceField of Object.keys(relation.keyBinding)) {
576
+ if (!payload.has(sourceField)) {
577
+ results.push(
578
+ err2(
579
+ metadata,
580
+ relation,
581
+ `resolves its destination row from source field '${sourceField}', but the source entity '${sourceName}' carries no such attribute on its write payload (${available}). Phase 1 maintenance is payload \u540C\u68B1 only (no write-time fetch) \u2014 include '${sourceField}' on '${sourceName}' or bind a key field it does carry.`
582
+ )
583
+ );
584
+ }
585
+ }
586
+ for (const [attr, value] of projectionEntries(relation.options?.projection)) {
587
+ const path = typeof value === "string" ? value : value.path;
588
+ const srcAttr = projectionSourceAttribute(value);
589
+ if (srcAttr === null || typeof value !== "string" && !isPayloadRooted(path)) {
590
+ results.push(
591
+ err2(
592
+ metadata,
593
+ relation,
594
+ `projects '${attr}' from '${path}', which is not a payload-rooted source path (\`$.input.*\` / \`$.entity.*\`). Phase 1 maintenance projects only from the source payload (payload \u540C\u68B1); there is no fetch / re-projection.`
595
+ )
596
+ );
597
+ continue;
598
+ }
599
+ if (!payload.has(srcAttr)) {
600
+ results.push(
601
+ err2(
602
+ metadata,
603
+ relation,
604
+ `projects '${attr}' from source attribute '${srcAttr}', but the source entity '${sourceName}' carries no such attribute on its write payload (${available}). Phase 1 maintenance is payload \u540C\u68B1 only (no write-time fetch / re-projection) \u2014 an attribute the source row does not carry cannot be projected.`
605
+ )
606
+ );
607
+ }
608
+ }
609
+ return results;
610
+ }
611
+
612
+ // src/linter/rules/embedded-snapshot-size.ts
613
+ var ITEM_LIMIT_BYTES = 400 * 1024;
614
+ var SOFT_BUDGET_BYTES = ITEM_LIMIT_BYTES / 2;
615
+ var DEFAULT_STRING_BYTES = 256;
616
+ var ATTR_NAME_OVERHEAD_BYTES = 16;
617
+ var embeddedSnapshotSizeRule = {
618
+ id: "400kb",
619
+ severity: "warning",
620
+ check(metadata, _registry) {
621
+ const results = [];
622
+ for (const relation of maintainedRelations(metadata)) {
623
+ const result = checkRelation3(metadata, relation);
624
+ if (result) results.push(result);
625
+ }
626
+ return results;
627
+ }
628
+ };
629
+ function estimateItemBytes(relation) {
630
+ let bytes = 0;
631
+ for (const [attr, value] of projectionEntries(relation.options?.projection)) {
632
+ bytes += ATTR_NAME_OVERHEAD_BYTES + attr.length;
633
+ bytes += attributeValueBytes(value);
634
+ }
635
+ return bytes;
636
+ }
637
+ function attributeValueBytes(value) {
638
+ if (typeof value !== "string" && value.op === "preview") {
639
+ const [n] = value.args;
640
+ if (typeof n === "number" && Number.isFinite(n)) return n;
641
+ }
642
+ return DEFAULT_STRING_BYTES;
643
+ }
644
+ function checkRelation3(metadata, relation) {
645
+ const itemBytes = estimateItemBytes(relation);
646
+ if (itemBytes === 0) return null;
647
+ const isCollection = relation.type === "hasMany";
648
+ const maxItems = relation.options?.read?.maxItems;
649
+ if (isCollection && maxItems === void 0) return null;
650
+ const count = isCollection ? maxItems : 1;
651
+ const estimate = itemBytes * count;
652
+ const shape = isCollection ? `${count} item(s) \xD7 ~${itemBytes} B` : `~${itemBytes} B snapshot`;
653
+ if (estimate >= ITEM_LIMIT_BYTES) {
654
+ return {
655
+ ruleId: "400kb",
656
+ severity: "error",
657
+ message: `Maintained relation '${relation.propertyName}' on '${logicalName(metadata)}' materializes ${shape} \u2248 ${estimate} B onto the owner row, which meets or exceeds DynamoDB's 400 KB item limit (${ITEM_LIMIT_BYTES} B). The maintenance write would fail once the collection fills \u2014 reduce \`read.maxItems\` or the projected attributes (e.g. tighter \`preview(n)\` bounds).`,
658
+ entity: metadata.prefix,
659
+ field: relation.propertyName
660
+ };
661
+ }
662
+ if (estimate >= SOFT_BUDGET_BYTES) {
663
+ return {
664
+ ruleId: "400kb",
665
+ severity: "warning",
666
+ message: `Maintained relation '${relation.propertyName}' on '${logicalName(metadata)}' materializes ${shape} \u2248 ${estimate} B onto the owner row, over half of DynamoDB's 400 KB item limit (${ITEM_LIMIT_BYTES} B). Little headroom remains for the rest of the item \u2014 consider a tighter \`read.maxItems\` / projection.`,
667
+ entity: metadata.prefix,
668
+ field: relation.propertyName
669
+ };
670
+ }
671
+ return null;
672
+ }
673
+
674
+ // src/linter/rules/hot-partition.ts
675
+ var HOT_TRIGGER_FANIN = 2;
676
+ var hotPartitionRule = {
677
+ id: "hot-partition",
678
+ severity: "warning",
679
+ check(metadata, _registry) {
680
+ const results = [];
681
+ const maintained = maintainedRelations(metadata);
682
+ for (const relation of maintained) {
683
+ if (relation.type !== "hasMany") continue;
684
+ if (relation.options?.read?.maxItems === void 0) {
685
+ results.push(unboundedWarning(metadata, relation));
686
+ }
687
+ }
688
+ const byTrigger = /* @__PURE__ */ new Map();
689
+ for (const relation of maintained) {
690
+ for (const trigger of relation.options?.write?.maintainedOn ?? []) {
691
+ const bucket = byTrigger.get(trigger);
692
+ if (bucket) bucket.push(relation.propertyName);
693
+ else byTrigger.set(trigger, [relation.propertyName]);
694
+ }
695
+ }
696
+ for (const [trigger, props] of byTrigger) {
697
+ if (props.length > HOT_TRIGGER_FANIN) {
698
+ results.push(fanInWarning(metadata, trigger, props));
699
+ }
700
+ }
701
+ return results;
702
+ }
703
+ };
704
+ function unboundedWarning(metadata, relation) {
705
+ return {
706
+ ruleId: "hot-partition",
707
+ severity: "warning",
708
+ message: `Maintained collection '${relation.propertyName}' on '${logicalName(metadata)}' has no \`read.maxItems\` bound: every maintained source row appends to the same owner ("root") item, so that single partition takes unbounded write traffic and the item trends toward the 400 KB limit. Declare a \`read.maxItems\` window (e.g. latest-N) or read the children from their own partition (\`samePartition\`) instead of inlining a snapshot.`,
709
+ entity: metadata.prefix,
710
+ field: relation.propertyName
711
+ };
712
+ }
713
+ function fanInWarning(metadata, trigger, props) {
714
+ return {
715
+ ruleId: "hot-partition",
716
+ severity: "warning",
717
+ message: `${props.length} maintained relations on '${logicalName(metadata)}' ([${props.map((p) => `'${p}'`).join(", ")}]) all fire on trigger '${trigger}', concentrating that many maintenance writes onto the single owner ("root") row in one mutation. This amplifies per-source-row write cost on one partition \u2014 consider splitting the maintained shapes across rows / partitions.`,
718
+ entity: metadata.prefix
719
+ };
720
+ }
721
+
722
+ // src/linter/rules/fan-out.ts
723
+ var MAX_MAINTENANCE_HOPS = 1;
724
+ var fanOutRule = {
725
+ id: "fan-out",
726
+ severity: "warning",
727
+ check(metadata, registry) {
728
+ const results = [];
729
+ for (const relation of maintainedRelations(metadata)) {
730
+ const point = checkDestinationFanOut(metadata, relation);
731
+ if (point) results.push(point);
732
+ }
733
+ const chain = maintenanceChain(metadata, registry, /* @__PURE__ */ new Set([modelKey(metadata)]));
734
+ if (chain.hops > MAX_MAINTENANCE_HOPS) {
735
+ results.push({
736
+ ruleId: "fan-out",
737
+ severity: "warning",
738
+ message: `Entity '${chain.root}' is the root of a maintenance chain ${chain.hops} hops deep, terminating at '${logicalName(metadata)}': a single '${chain.root}' lifecycle event cascades through ${chain.hops} maintenance writes \u2014 each maintained row is itself the trigger source of the next hop \u2014 until it reaches '${logicalName(metadata)}'. A multi-step maintenance fan-out amplifies one write into many; flatten the chain or move downstream hops to a stream (\`updateMode: 'stream'\`).`,
739
+ entity: metadata.prefix
740
+ });
741
+ }
742
+ return results;
743
+ }
744
+ };
745
+ function checkDestinationFanOut(metadata, relation) {
746
+ const ownerKeyFields = Object.values(relation.keyBinding);
747
+ if (ownerKeyFields.length === 0) return null;
748
+ let resolved;
749
+ try {
750
+ resolved = resolveKey(ownerKeyFields, metadata);
751
+ } catch {
752
+ return null;
753
+ }
754
+ const isPoint = !resolved.partial && (resolved.type === "pk" || resolved.type === "gsi" && resolved.unique);
755
+ if (isPoint) return null;
756
+ const shape = resolved.partial ? `a partial ${resolved.type.toUpperCase()} (a begins_with range of rows)` : `a non-unique ${resolved.type.toUpperCase()} (many matching rows)`;
757
+ return {
758
+ ruleId: "fan-out",
759
+ severity: "warning",
760
+ message: `Maintained relation '${relation.propertyName}' on '${logicalName(metadata)}' binds its destination row by [${ownerKeyFields.map((f) => `'${f}'`).join(", ")}], which resolves to ${shape} on '${logicalName(metadata)}'. A single source event then fans its maintenance write out across every matching destination row in one mutation (unbounded fan-out). Bind the destination's full primary key (or a unique GSI) so each source event maintains exactly one row.`,
761
+ entity: metadata.prefix,
762
+ field: relation.propertyName
763
+ };
764
+ }
765
+ function modelKey(metadata) {
766
+ return logicalName(metadata);
767
+ }
768
+ function maintenanceChain(metadata, registry, visited) {
769
+ const maintained = maintainedRelations(metadata);
770
+ if (maintained.length === 0) return { hops: 0, root: logicalName(metadata) };
771
+ let best = { hops: 0, root: logicalName(metadata) };
772
+ for (const relation of maintained) {
773
+ let targetMeta;
774
+ try {
775
+ targetMeta = registry.get(relation.targetFactory());
776
+ } catch {
777
+ continue;
778
+ }
779
+ const key2 = modelKey(targetMeta);
780
+ if (visited.has(key2)) continue;
781
+ const next = new Set(visited);
782
+ next.add(key2);
783
+ const upstream = maintenanceChain(targetMeta, registry, next);
784
+ if (1 + upstream.hops > best.hops) {
785
+ best = { hops: 1 + upstream.hops, root: upstream.root };
786
+ }
787
+ }
788
+ return best;
789
+ }
790
+
791
+ // src/linter/rules/multi-maintainer-same-row.ts
792
+ var multiMaintainerSameRowRule = {
793
+ id: "multi-maintainer-same-row",
794
+ severity: "error",
795
+ check(metadata, _registry) {
796
+ const maintained = maintainedRelations(metadata);
797
+ if (maintained.length < 2) return [];
798
+ const owner = logicalName(metadata);
799
+ const groups = /* @__PURE__ */ new Map();
800
+ for (const relation of maintained) {
801
+ const rowKey = destinationRowKey(owner, relation);
802
+ for (const trigger of relation.options?.write?.maintainedOn ?? []) {
803
+ const groupKey = `${trigger} ${rowKey}`;
804
+ const group = groups.get(groupKey);
805
+ if (group) group.props.push(relation.propertyName);
806
+ else groups.set(groupKey, { trigger, props: [relation.propertyName] });
807
+ }
808
+ }
809
+ const results = [];
810
+ for (const { trigger, props } of groups.values()) {
811
+ if (props.length < 2) continue;
812
+ results.push({
813
+ ruleId: "multi-maintainer-same-row",
814
+ severity: "error",
815
+ message: `Maintained relations [${props.map((p) => `'${p}'`).join(", ")}] on '${owner}' all fire on trigger '${trigger}' and write the SAME destination row. Phase 1 maintenance is "1 mutation \xD7 1 target row = 1 effect" (\u8AD6\u70B92 = b): a single mutation cannot touch one row with ${props.length} maintain effects \u2014 DynamoDB rejects two writes to the same key in one TransactWriteItems (cf. #96). Merge the projections into one maintained relation, or split them onto distinct destination rows / triggers.`,
816
+ entity: metadata.prefix,
817
+ field: props[0]
818
+ });
819
+ }
820
+ return results;
821
+ }
822
+ };
823
+ function destinationRowKey(owner, relation) {
824
+ const parts = Object.entries(relation.keyBinding).map(([sourceField, ownerField]) => `${ownerField}=$.entity.${sourceField}`).sort();
825
+ return `${owner}#${parts.join("&")}`;
826
+ }
827
+
828
+ // src/client/TableMapping.ts
829
+ var TableMapping = class {
830
+ static mapping = {};
831
+ static set(mapping) {
832
+ this.mapping = { ...mapping };
833
+ }
834
+ static resolve(declaredName) {
835
+ return this.mapping[declaredName] ?? declaredName;
836
+ }
837
+ /** @internal — for testing only */
838
+ static reset() {
839
+ this.mapping = {};
840
+ }
841
+ };
842
+
843
+ // src/linter/rules/cfn-schema-consistency.ts
844
+ var MAX_GSIS_PER_TABLE = 20;
845
+ function gsiShape(gsi) {
846
+ const hasSk = gsi.segmented.skSegments.length > 0;
847
+ return { indexName: gsi.indexName, hasSk };
848
+ }
849
+ function err3(entity, message) {
850
+ return {
851
+ ruleId: "cfn-schema-consistency",
852
+ severity: "error",
853
+ message,
854
+ entity
855
+ };
856
+ }
857
+ var cfnSchemaConsistencyRule = {
858
+ id: "cfn-schema-consistency",
859
+ severity: "error",
860
+ check(metadata, registry) {
861
+ return checkAllTables(metadata, registry);
862
+ }
863
+ };
864
+ function checkAllTables(current, registry) {
865
+ const seenMeta = /* @__PURE__ */ new Set();
866
+ const byPhysical = /* @__PURE__ */ new Map();
867
+ const add = (meta) => {
868
+ if (seenMeta.has(meta)) return;
869
+ seenMeta.add(meta);
870
+ const physical = TableMapping.resolve(meta.tableName);
871
+ const list = byPhysical.get(physical) ?? [];
872
+ list.push(meta);
873
+ byPhysical.set(physical, list);
874
+ };
875
+ add(current);
876
+ for (const [, meta] of registry.getFinalized()) add(meta);
877
+ const currentPhysical = TableMapping.resolve(current.tableName);
878
+ const entities = byPhysical.get(currentPhysical);
879
+ if (!entities) return [];
880
+ return checkTable(currentPhysical, entities);
881
+ }
882
+ function checkTable(physical, entities) {
883
+ const ordered = [...entities].sort((a, b) => a.prefix.localeCompare(b.prefix));
884
+ const results = [];
885
+ results.push(...checkBaseKeySchema(physical, ordered));
886
+ results.push(...checkGsiUnion(physical, ordered));
887
+ return results;
888
+ }
889
+ function checkBaseKeySchema(physical, entities) {
890
+ const withSk = [];
891
+ const withoutSk = [];
892
+ for (const meta of entities) {
893
+ if (!meta.primaryKey) continue;
894
+ const hasSk = meta.primaryKey.segmented.skSegments.length > 0;
895
+ (hasSk ? withSk : withoutSk).push(meta.prefix);
896
+ }
897
+ if (withSk.length > 0 && withoutSk.length > 0) {
898
+ const offender = [...withSk, ...withoutSk].sort()[0];
899
+ return [
900
+ err3(
901
+ offender,
902
+ `CloudFormation schema consistency: physical table '${physical}' has an ambiguous base KeySchema \u2014 some entities declare a sort key and some do not (with SK: [${withSk.join(", ")}]; without SK: [${withoutSk.join(", ")}]). A single DynamoDB table has exactly one KeySchema; every entity sharing a table must agree on whether the base key has an SK.`
903
+ )
904
+ ];
905
+ }
906
+ return [];
907
+ }
908
+ function checkGsiUnion(physical, entities) {
909
+ const results = [];
910
+ const seen = /* @__PURE__ */ new Map();
911
+ for (const meta of entities) {
912
+ for (const gsi of meta.gsiDefinitions) {
913
+ const shape = gsiShape(gsi);
914
+ const existing = seen.get(shape.indexName);
915
+ if (!existing) {
916
+ seen.set(shape.indexName, { shape, entity: meta.prefix });
917
+ continue;
918
+ }
919
+ const conflict = describeConflict(existing.shape, shape);
920
+ if (conflict) {
921
+ results.push(
922
+ err3(
923
+ meta.prefix,
924
+ `CloudFormation schema consistency: GSI '${shape.indexName}' on physical table '${physical}' is declared inconsistently across entities that share it \u2014 ${conflict} (first declared by '${existing.entity}', conflicting declaration on '${meta.prefix}'). A single DynamoDB table has exactly one GSI per index name; entities may share an index name (projecting different logical fields into the shared physical key), but only when its physical key structure (sort-key presence) is identical.`
925
+ )
926
+ );
927
+ }
928
+ }
929
+ }
930
+ if (seen.size > MAX_GSIS_PER_TABLE) {
931
+ const names = [...seen.keys()].sort();
932
+ const offender = [...entities].map((e) => e.prefix).sort()[0];
933
+ results.push(
934
+ err3(
935
+ offender,
936
+ `CloudFormation schema consistency: physical table '${physical}' would have ${seen.size} global secondary indexes after unioning across entities, exceeding the DynamoDB limit of ${MAX_GSIS_PER_TABLE}. Distinct index names: [${names.join(", ")}]. Reduce the number of distinct GSIs on this table.`
937
+ )
938
+ );
939
+ }
940
+ return results;
941
+ }
942
+ function describeConflict(a, b) {
943
+ if (a.hasSk !== b.hasSk) {
944
+ return `one declaration has a sort key and the other does not (${a.hasSk ? "with" : "without"} SK vs. ${b.hasSk ? "with" : "without"} SK)`;
945
+ }
946
+ return null;
947
+ }
948
+
949
+ // src/linter/default-linter.ts
950
+ function createDefaultLinter() {
951
+ const linter = new Linter();
952
+ linter.addRule(noScanRule);
953
+ linter.addRule(requireLimitRule);
954
+ linter.addRule(gsiAmbiguityRule);
955
+ linter.addRule(missingGsiRule);
956
+ linter.addRule(relationDepthRule);
957
+ linter.addRule(samePartitionPresetRule);
958
+ linter.addRule(missingContextRule);
959
+ linter.addRule(embeddedSnapshotSizeRule);
960
+ linter.addRule(hotPartitionRule);
961
+ linter.addRule(fanOutRule);
962
+ linter.addRule(multiMaintainerSameRowRule);
963
+ linter.addRule(cfnSchemaConsistencyRule);
964
+ return linter;
965
+ }
966
+
967
+ export {
968
+ isColumn,
969
+ createColumnMap,
970
+ isKeySegment,
971
+ k,
972
+ isKeyDefinition,
973
+ segmentFieldNames,
974
+ buildSegmentedKey,
975
+ key,
976
+ Linter,
977
+ noScanRule,
978
+ requireLimitRule,
979
+ gsiAmbiguityRule,
980
+ resolveKey,
981
+ missingGsiRule,
982
+ relationDepthRule,
983
+ samePartitionPresetRule,
984
+ missingContextRule,
985
+ embeddedSnapshotSizeRule,
986
+ hotPartitionRule,
987
+ fanOutRule,
988
+ multiMaintainerSameRowRule,
989
+ TableMapping,
990
+ cfnSchemaConsistencyRule,
991
+ createDefaultLinter
992
+ };