@auto-engineer/server-generator-apollo-emmett 1.110.4 → 1.110.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +5 -5
  3. package/.turbo/turbo-type-check.log +1 -1
  4. package/CHANGELOG.md +41 -0
  5. package/dist/src/codegen/templates/command/decide.specs.ts +12 -8
  6. package/dist/src/codegen/templates/command/decide.specs.ts.ejs +6 -1
  7. package/dist/src/codegen/templates/command/decide.ts.ejs +3 -2
  8. package/dist/src/codegen/templates/command/evolve.specs.ts +5 -0
  9. package/dist/src/codegen/templates/command/evolve.ts.ejs +5 -0
  10. package/dist/src/codegen/templates/query/projection.specs.specs.ts +228 -5
  11. package/dist/src/codegen/templates/query/projection.specs.ts +24 -3
  12. package/dist/src/codegen/templates/query/projection.specs.ts.ejs +15 -5
  13. package/dist/src/codegen/templates/query/projection.ts.ejs +9 -3
  14. package/dist/src/codegen/templates/query/query.resolver.specs.ts +4 -4
  15. package/dist/src/codegen/templates/query/query.resolver.ts.ejs +1 -1
  16. package/dist/src/codegen/templates/react/react.specs.ts +7 -0
  17. package/dist/src/codegen/templates/react/react.ts.ejs +7 -0
  18. package/dist/src/codegen/templates/react/register.specs.ts +6 -0
  19. package/dist/src/codegen/templates/react/register.ts.ejs +6 -0
  20. package/ketchup-plan.md +5 -0
  21. package/package.json +4 -4
  22. package/src/codegen/templates/command/decide.specs.ts +12 -8
  23. package/src/codegen/templates/command/decide.specs.ts.ejs +6 -1
  24. package/src/codegen/templates/command/decide.ts.ejs +3 -2
  25. package/src/codegen/templates/command/evolve.specs.ts +5 -0
  26. package/src/codegen/templates/command/evolve.ts.ejs +5 -0
  27. package/src/codegen/templates/query/projection.specs.specs.ts +228 -5
  28. package/src/codegen/templates/query/projection.specs.ts +24 -3
  29. package/src/codegen/templates/query/projection.specs.ts.ejs +15 -5
  30. package/src/codegen/templates/query/projection.ts.ejs +9 -3
  31. package/src/codegen/templates/query/query.resolver.specs.ts +4 -4
  32. package/src/codegen/templates/query/query.resolver.ts.ejs +1 -1
  33. package/src/codegen/templates/react/react.specs.ts +7 -0
  34. package/src/codegen/templates/react/react.ts.ejs +7 -0
  35. package/src/codegen/templates/react/register.specs.ts +6 -0
  36. package/src/codegen/templates/react/register.ts.ejs +6 -0
@@ -114,9 +114,9 @@ describe('query.resolver.ts.ejs', () => {
114
114
  return model.find((item) => {
115
115
  if (location !== undefined && item.location !== location) return false;
116
116
 
117
- // TODO: 'maxPrice' has no matching field on the state type — implement custom filter logic.
117
+ // NOTE: 'maxPrice' has no matching field on the state type — add custom filter logic if needed.
118
118
 
119
- // TODO: 'minGuests' has no matching field on the state type — implement custom filter logic.
119
+ // NOTE: 'minGuests' has no matching field on the state type — add custom filter logic if needed.
120
120
 
121
121
  return true;
122
122
  });
@@ -935,7 +935,7 @@ describe('query.resolver.ts.ejs', () => {
935
935
  // If this query should return a single item, switch to findOne().
936
936
 
937
937
  return model.find((item) => {
938
- // TODO: 'pantryId' has no matching field on the state type — implement custom filter logic.
938
+ // NOTE: 'pantryId' has no matching field on the state type — add custom filter logic if needed.
939
939
 
940
940
  return true;
941
941
  });
@@ -1177,7 +1177,7 @@ describe('query.resolver.ts.ejs', () => {
1177
1177
  // If this query should return a single item, switch to findOne().
1178
1178
 
1179
1179
  return model.find((item) => {
1180
- // TODO: 'pantryId' has no matching field on the state type — implement custom filter logic.
1180
+ // NOTE: 'pantryId' has no matching field on the state type — add custom filter logic if needed.
1181
1181
 
1182
1182
  return true;
1183
1183
  });
@@ -170,7 +170,7 @@ return model.find((<%= hasArgs ? 'item' : '_item' %>) => {
170
170
  if (stateFieldNames.has(arg.name)) { %>
171
171
  if (<%= arg.name %> !== undefined && item.<%= arg.name %> !== <%= arg.name %>) return false;
172
172
  <% } else { %>
173
- // TODO: '<%= arg.name %>' has no matching field on the state type — implement custom filter logic.
173
+ // NOTE: '<%= arg.name %>' has no matching field on the state type — add custom filter logic if needed.
174
174
  <% }
175
175
  }
176
176
  } %>
@@ -256,6 +256,13 @@ describe('handle.ts.ejs (react slice)', () => {
256
256
  * NEVER hardcode values copied from test assertions.
257
257
  *
258
258
  * Preserve all import paths above — they are generated from the model.
259
+ *
260
+ * CONSTRAINTS:
261
+ * - NEVER use \`as SomeType\` type assertions. Use typed variable declarations.
262
+ * - Only reference event.data fields listed in the "Event fields:" comment below. Check the type before accessing any field.
263
+ * - Do NOT modify the inMemoryReactor configuration, connectionOptions, import statements, or commandSender.send() call structure. Only fill in data fields marked TODO.
264
+ * - When event.data contains nested arrays/objects (e.g., exercises[].sets[]), iterate them to compute values. Do NOT cast arrays/objects to primitive types.
265
+ *
259
266
  * Add business logic (validation, conditional sends) as needed.
260
267
  */
261
268
 
@@ -60,6 +60,13 @@ const willHaveAggregateStream = states.some(state =>
60
60
  <% if (willHaveAggregateStream) { -%>
61
61
  * Do NOT modify or remove aggregateStream calls — they load required state.
62
62
  <% } -%>
63
+ *
64
+ * CONSTRAINTS:
65
+ * - NEVER use `as SomeType` type assertions. Use typed variable declarations.
66
+ * - Only reference event.data fields listed in the "Event fields:" comment below. Check the type before accessing any field.
67
+ * - Do NOT modify the inMemoryReactor configuration, connectionOptions, import statements, or commandSender.send() call structure. Only fill in data fields marked TODO.
68
+ * - When event.data contains nested arrays/objects (e.g., exercises[].sets[]), iterate them to compute values. Do NOT cast arrays/objects to primitive types.
69
+ *
63
70
  * Add business logic (validation, conditional sends) as needed.
64
71
  */
65
72
  <%
@@ -246,6 +246,12 @@ describe('register.ts.ejs (react slice)', () => {
246
246
  * evolve: (s: Record<string, unknown>, e: { type: string; data: Record<string, unknown> }) => ...
247
247
  * - NEVER hardcode values copied from test assertions.
248
248
  * - Preserve all import paths above — they are generated from the model.
249
+ *
250
+ * CONSTRAINTS:
251
+ * - NEVER use \`as SomeType\` type assertions. Use typed variable declarations.
252
+ * - Only reference fields that exist on the event type (BookingRequested). Check the import above.
253
+ * - Do NOT modify the messageBus.subscribe() call, function signature, or import statements.
254
+ * - When event.data contains nested arrays/objects, iterate them. Do NOT cast to primitive types.
249
255
  */
250
256
 
251
257
  // await messageBus.send({
@@ -38,6 +38,12 @@ async (event: <%= pascalCase(eventType) %>) => {
38
38
  * evolve: (s: Record<string, unknown>, e: { type: string; data: Record<string, unknown> }) => ...
39
39
  * - NEVER hardcode values copied from test assertions.
40
40
  * - Preserve all import paths above — they are generated from the model.
41
+ *
42
+ * CONSTRAINTS:
43
+ * - NEVER use `as SomeType` type assertions. Use typed variable declarations.
44
+ * - Only reference fields that exist on the event type (<%= pascalCase(eventType) %>). Check the import above.
45
+ * - Do NOT modify the messageBus.subscribe() call, function signature, or import statements.
46
+ * - When event.data contains nested arrays/objects, iterate them. Do NOT cast to primitive types.
41
47
  */
42
48
 
43
49
  // await messageBus.send({
package/ketchup-plan.md CHANGED
@@ -4,6 +4,11 @@
4
4
 
5
5
  (none)
6
6
 
7
+ ## DONE (Round 3)
8
+
9
+ - [x] Burst 26: Add fart-model test for query-arg-differs-from-projection case
10
+ - [x] Burst 25: Exclude query arg fields from projection spec expected state (6da49a58)
11
+
7
12
  ## DONE
8
13
 
9
14
  - [x] Burst 24: Fix handle.ts multi-command stream pattern
package/package.json CHANGED
@@ -32,8 +32,8 @@
32
32
  "uuid": "^13.0.0",
33
33
  "web-streams-polyfill": "^4.1.0",
34
34
  "zod": "^3.22.4",
35
- "@auto-engineer/narrative": "1.110.4",
36
- "@auto-engineer/message-bus": "1.110.4"
35
+ "@auto-engineer/narrative": "1.110.5",
36
+ "@auto-engineer/message-bus": "1.110.5"
37
37
  },
38
38
  "publishConfig": {
39
39
  "access": "public"
@@ -44,9 +44,9 @@
44
44
  "typescript": "^5.8.3",
45
45
  "vitest": "^3.2.4",
46
46
  "tsx": "^4.19.2",
47
- "@auto-engineer/cli": "1.110.4"
47
+ "@auto-engineer/cli": "1.110.5"
48
48
  },
49
- "version": "1.110.4",
49
+ "version": "1.110.5",
50
50
  "scripts": {
51
51
  "generate:server": "tsx src/cli/index.ts",
52
52
  "build": "tsc && tsx ../../scripts/fix-esm-imports.ts && rm -rf dist/src/codegen/templates && mkdir -p dist/src/codegen && cp -r src/codegen/templates dist/src/codegen/templates && cp src/server.ts dist/src && cp -r src/utils dist/src && cp -r src/domain dist/src",
@@ -97,13 +97,14 @@ describe('decide.ts.ejs', () => {
97
97
  * You should:
98
98
  * - Validate the command input fields
99
99
  * - Inspect the current domain \`_state\` to determine if the command is allowed
100
- * - If State is a discriminated union, NEVER use \`as any\` to bypass type checking.
101
- * Narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
100
+ * - NEVER use \`as SomeType\` type assertions not \`as any\`, not \`as EventType\`, no casts at all. Use typed variable declarations.
101
+ * - If State is a discriminated union, narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
102
102
  * After narrowing, access variant fields directly — TypeScript infers the correct type.
103
103
  * - If invalid, throw one of the following domain errors: \`IllegalStateError\`
104
104
  * ⚠️ Error constructors: IllegalStateError takes a string message
105
105
  * - If valid, return one or more events with the correct structure
106
106
  *
107
+ * - Only destructure/reference command.data fields that exist in the command type (imported from ./commands). Do NOT access fields not declared in the type, even if example data includes them.
107
108
  * ⚠️ Only read from inputs — never mutate them. \`evolve.ts\` handles state updates.
108
109
 
109
110
  * Business rules:
@@ -235,13 +236,14 @@ describe('decide.ts.ejs', () => {
235
236
  * You should:
236
237
  * - Validate the command input fields
237
238
  * - Inspect the current domain \`_state\` to determine if the command is allowed
238
- * - If State is a discriminated union, NEVER use \`as any\` to bypass type checking.
239
- * Narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
239
+ * - NEVER use \`as SomeType\` type assertions not \`as any\`, not \`as EventType\`, no casts at all. Use typed variable declarations.
240
+ * - If State is a discriminated union, narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
240
241
  * After narrowing, access variant fields directly — TypeScript infers the correct type.
241
242
  * - If invalid, throw one of the following domain errors: \`IllegalStateError\`
242
243
  * ⚠️ Error constructors: IllegalStateError takes a string message
243
244
  * - If valid, return one or more events with the correct structure
244
245
  *
246
+ * - Only destructure/reference command.data fields that exist in the command type (imported from ./commands). Do NOT access fields not declared in the type, even if example data includes them.
245
247
  * ⚠️ Only read from inputs — never mutate them. \`evolve.ts\` handles state updates.
246
248
 
247
249
  * Business rules:
@@ -399,13 +401,14 @@ describe('decide.ts.ejs', () => {
399
401
  * You should:
400
402
  * - Validate the command input fields
401
403
  * - Inspect the current domain \`_state\` to determine if the command is allowed
402
- * - If State is a discriminated union, NEVER use \`as any\` to bypass type checking.
403
- * Narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
404
+ * - NEVER use \`as SomeType\` type assertions not \`as any\`, not \`as EventType\`, no casts at all. Use typed variable declarations.
405
+ * - If State is a discriminated union, narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
404
406
  * After narrowing, access variant fields directly — TypeScript infers the correct type.
405
407
  * - If invalid, throw one of the following domain errors: \`IllegalStateError\`, \`ValidationError\`
406
408
  * ⚠️ Error constructors: IllegalStateError takes a string message, ValidationError takes a string message
407
409
  * - If valid, return one or more events with the correct structure
408
410
  *
411
+ * - Only destructure/reference command.data fields that exist in the command type (imported from ./commands). Do NOT access fields not declared in the type, even if example data includes them.
409
412
  * ⚠️ Only read from inputs — never mutate them. \`evolve.ts\` handles state updates.
410
413
 
411
414
  * Business rules:
@@ -601,14 +604,15 @@ describe('decide.ts.ejs', () => {
601
604
  * You should:
602
605
  * - Validate the command input fields
603
606
  * - Inspect the current domain \`_state\` to determine if the command is allowed
604
- * - If State is a discriminated union, NEVER use \`as any\` to bypass type checking.
605
- * Narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
607
+ * - NEVER use \`as SomeType\` type assertions not \`as any\`, not \`as EventType\`, no casts at all. Use typed variable declarations.
608
+ * - If State is a discriminated union, narrow with the discriminant: \`if (_state.status !== 'active') throw new IllegalStateError('...');\`
606
609
  * After narrowing, access variant fields directly — TypeScript infers the correct type.
607
610
  * - Use \`products\` (integration result) to enrich or filter the output
608
611
  * - If invalid, throw one of the following domain errors: \`IllegalStateError\`
609
612
  * ⚠️ Error constructors: IllegalStateError takes a string message
610
613
  * - If valid, return one or more events with the correct structure
611
614
  *
615
+ * - Only destructure/reference command.data fields that exist in the command type (imported from ./commands). Do NOT access fields not declared in the type, even if example data includes them.
612
616
  * ⚠️ Only read from inputs — never mutate them. \`evolve.ts\` handles state updates.
613
617
  *
614
618
  * Integration result shape (Products):
@@ -145,8 +145,13 @@ describe('<%= ruleDescription %>', () => {
145
145
  ])
146
146
  .when({
147
147
  type: '<%= example.commandRef %>',
148
- data: <%- formatDataObject(example.exampleData, schema) %>,
149
148
  <% const commandFieldNames = new Set(schema?.fields?.map(f => f.name) || []);
149
+ const filteredCmdData = Object.fromEntries(
150
+ Object.entries(example.exampleData || {}).filter(([key]) => commandFieldNames.has(key))
151
+ );
152
+ -%>
153
+ data: <%- formatDataObject(filteredCmdData, schema) %>,
154
+ <%
150
155
  const { date: derivedDate, fields: derivedDateFieldNames } = findDerivedDateInfo(eventResults, commandFieldNames, gwt.given);
151
156
  const keepFieldNames = buildKeepFieldNames(eventResults, commandFieldNames, derivedDateFieldNames, gwt.given);
152
157
  -%>
@@ -61,8 +61,8 @@ case '<%= command %>': {
61
61
  * You should:
62
62
  * - Validate the command input fields
63
63
  * - Inspect the current domain `_state` to determine if the command is allowed
64
- * - If State is a discriminated union, NEVER use `as any` to bypass type checking.
65
- * Narrow with the discriminant: `if (_state.status !== 'active') throw new IllegalStateError('...');`
64
+ * - NEVER use `as SomeType` type assertions not `as any`, not `as EventType`, no casts at all. Use typed variable declarations.
65
+ * - If State is a discriminated union, narrow with the discriminant: `if (_state.status !== 'active') throw new IllegalStateError('...');`
66
66
  * After narrowing, access variant fields directly — TypeScript infers the correct type.
67
67
  <% if (integrationReturnType) { -%>
68
68
  * - Use `<%= camelCase(integrationReturnType) %>` (integration result) to enrich or filter the output
@@ -71,6 +71,7 @@ case '<%= command %>': {
71
71
  * ⚠️ Error constructors: IllegalStateError takes a string message<% if (usedErrors.includes('ValidationError')) { %>, ValidationError takes a string message<% } %><% if (usedErrors.includes('NotFoundError')) { %>, NotFoundError takes { id, type, message? }<% } %>
72
72
  * - If valid, return one or more events with the correct structure
73
73
  *
74
+ * - Only destructure/reference command.data fields that exist in the command type (imported from ./commands). Do NOT access fields not declared in the type, even if example data includes them.
74
75
  * ⚠️ Only read from inputs — never mutate them. `evolve.ts` handles state updates.
75
76
  <% if (integrationReturnFields.length > 0) { -%>
76
77
  *
@@ -102,6 +102,11 @@ describe('evolve.ts.ejs', () => {
102
102
  * [ ] Every return (except \`return state;\`) matches a variant from state.ts
103
103
  * [ ] Every return includes the discriminant field
104
104
  * [ ] No spread operators in return statements
105
+ *
106
+ * CONSTRAINTS:
107
+ * - NEVER use \`as SomeType\` type assertions. Return properly typed object literals.
108
+ * - Only reference event.data fields that exist on the event type (check imports above).
109
+ * - Only return fields that exist in the State type (check state.ts). Do NOT invent new fields.
105
110
  */
106
111
 
107
112
  export const evolve = (state: State, event: ListingCreated): State => {
@@ -22,6 +22,11 @@
22
22
  * [ ] Every return (except `return state;`) matches a variant from state.ts
23
23
  * [ ] Every return includes the discriminant field
24
24
  * [ ] No spread operators in return statements
25
+ *
26
+ * CONSTRAINTS:
27
+ * - NEVER use `as SomeType` type assertions. Return properly typed object literals.
28
+ * - Only reference event.data fields that exist on the event type (check imports above).
29
+ * - Only return fields that exist in the State type (check state.ts). Do NOT invent new fields.
25
30
  */
26
31
 
27
32
  export const evolve = (
@@ -1202,8 +1202,7 @@ describe('projection.specs.ts.ejs', () => {
1202
1202
  .collection<WorkoutHistory>('WorkoutHistoryProjection')
1203
1203
  .findOne((doc) => doc.memberId === 'mem_001');
1204
1204
 
1205
- const expected: WorkoutHistory = {
1206
- memberId: 'mem_001',
1205
+ const expected = {
1207
1206
  totalCalories: 250,
1208
1207
  };
1209
1208
 
@@ -1214,6 +1213,224 @@ describe('projection.specs.ts.ejs', () => {
1214
1213
  `);
1215
1214
  });
1216
1215
 
1216
+ it('should exclude query arg fields that differ from projection-computed values', async () => {
1217
+ const spec: SpecsSchema = {
1218
+ variant: 'specs',
1219
+ narratives: [
1220
+ {
1221
+ name: 'fart-flow',
1222
+ slices: [
1223
+ {
1224
+ type: 'command',
1225
+ name: 'log-fart',
1226
+ stream: 'farts-${userId}',
1227
+ client: { specs: [] },
1228
+ server: {
1229
+ description: '',
1230
+ specs: [
1231
+ {
1232
+ type: 'gherkin',
1233
+ feature: 'Log fart command',
1234
+ rules: [
1235
+ {
1236
+ name: 'Should record farts',
1237
+ examples: [
1238
+ {
1239
+ name: 'User logs fart',
1240
+ steps: [
1241
+ {
1242
+ keyword: 'When',
1243
+ text: 'LogFart',
1244
+ docString: { userId: 'usr_123', intensity: 7 },
1245
+ },
1246
+ {
1247
+ keyword: 'Then',
1248
+ text: 'FartLogged',
1249
+ docString: { userId: 'usr_123', fartId: 'fart_456', intensity: 7 },
1250
+ },
1251
+ ],
1252
+ },
1253
+ ],
1254
+ },
1255
+ ],
1256
+ },
1257
+ ],
1258
+ },
1259
+ },
1260
+ {
1261
+ type: 'query',
1262
+ name: 'view-fart-history',
1263
+ stream: 'farts',
1264
+ request:
1265
+ 'query GetFartHistory($userId: ID!, $minIntensity: Int) { fartHistory(userId: $userId, minIntensity: $minIntensity) { farts { fartId intensity } } }',
1266
+ client: { specs: [] },
1267
+ server: {
1268
+ description: '',
1269
+ data: {
1270
+ items: [
1271
+ {
1272
+ target: { type: 'State', name: 'FartHistory' },
1273
+ origin: { type: 'projection', name: 'FartHistoryProjection', idField: 'userId' },
1274
+ },
1275
+ ],
1276
+ },
1277
+ specs: [
1278
+ {
1279
+ type: 'gherkin',
1280
+ feature: 'View fart history query',
1281
+ rules: [
1282
+ {
1283
+ name: 'Fart history projection',
1284
+ examples: [
1285
+ {
1286
+ name: 'Shows farts after logging',
1287
+ steps: [
1288
+ {
1289
+ keyword: 'Given',
1290
+ text: 'FartLogged',
1291
+ docString: { userId: 'usr_123', fartId: 'fart_456', intensity: 7 },
1292
+ },
1293
+ {
1294
+ keyword: 'Given',
1295
+ text: 'FartLogged',
1296
+ docString: { userId: 'usr_123', fartId: 'fart_789', intensity: 9 },
1297
+ },
1298
+ {
1299
+ keyword: 'When',
1300
+ text: 'GetFartHistory',
1301
+ docString: { userId: 'usr_123', minIntensity: 6 },
1302
+ },
1303
+ {
1304
+ keyword: 'Then',
1305
+ text: 'FartHistory',
1306
+ docString: {
1307
+ userId: 'usr_123',
1308
+ farts: [
1309
+ { fartId: 'fart_456', intensity: 7 },
1310
+ { fartId: 'fart_789', intensity: 9 },
1311
+ ],
1312
+ minIntensity: 6,
1313
+ },
1314
+ },
1315
+ ],
1316
+ },
1317
+ ],
1318
+ },
1319
+ ],
1320
+ },
1321
+ ],
1322
+ },
1323
+ },
1324
+ ],
1325
+ },
1326
+ ],
1327
+ messages: [
1328
+ {
1329
+ type: 'command',
1330
+ name: 'LogFart',
1331
+ fields: [
1332
+ { name: 'userId', type: 'string', required: true },
1333
+ { name: 'intensity', type: 'number', required: true },
1334
+ ],
1335
+ },
1336
+ {
1337
+ type: 'event',
1338
+ name: 'FartLogged',
1339
+ source: 'internal',
1340
+ fields: [
1341
+ { name: 'userId', type: 'string', required: true },
1342
+ { name: 'fartId', type: 'string', required: true },
1343
+ { name: 'intensity', type: 'number', required: true },
1344
+ ],
1345
+ },
1346
+ {
1347
+ type: 'query',
1348
+ name: 'GetFartHistory',
1349
+ fields: [
1350
+ { name: 'userId', type: 'string', required: true },
1351
+ { name: 'minIntensity', type: 'number', required: true },
1352
+ ],
1353
+ },
1354
+ {
1355
+ type: 'state',
1356
+ name: 'FartHistory',
1357
+ fields: [
1358
+ { name: 'userId', type: 'string', required: true },
1359
+ { name: 'farts', type: 'Array<{ fartId: string; intensity: number }>', required: true },
1360
+ { name: 'minIntensity', type: 'number', required: true },
1361
+ ],
1362
+ },
1363
+ ],
1364
+ } as SpecsSchema;
1365
+
1366
+ const { plans } = await generateScaffoldFilePlans(spec.narratives, spec.messages, undefined, 'src/domain/flows');
1367
+ const specFile = plans.find((p) => p.outputPath.endsWith('view-fart-history/projection.specs.ts'));
1368
+
1369
+ expect(specFile?.contents).toMatchInlineSnapshot(`
1370
+ "import { describe, it, beforeEach, expect } from 'vitest';
1371
+ import { InMemoryProjectionSpec } from '@event-driven-io/emmett';
1372
+ import { projection } from './projection';
1373
+ import type { FartLogged } from '../log-fart/events';
1374
+ import { FartHistory } from './state';
1375
+
1376
+ type ProjectionEvent = FartLogged;
1377
+
1378
+ describe('Fart history projection', () => {
1379
+ let given: InMemoryProjectionSpec<ProjectionEvent>;
1380
+
1381
+ beforeEach(() => {
1382
+ given = InMemoryProjectionSpec.for({ projection });
1383
+ });
1384
+
1385
+ it('Shows farts after logging', () =>
1386
+ given([
1387
+ {
1388
+ type: 'FartLogged',
1389
+ data: {
1390
+ userId: 'usr_123',
1391
+ fartId: 'fart_456',
1392
+ intensity: 7,
1393
+ },
1394
+ metadata: {
1395
+ streamName: 'farts',
1396
+ streamPosition: 1n,
1397
+ globalPosition: 1n,
1398
+ },
1399
+ },
1400
+ {
1401
+ type: 'FartLogged',
1402
+ data: {
1403
+ userId: 'usr_123',
1404
+ fartId: 'fart_789',
1405
+ intensity: 9,
1406
+ },
1407
+ metadata: {
1408
+ streamName: 'farts',
1409
+ streamPosition: 1n,
1410
+ globalPosition: 1n,
1411
+ },
1412
+ },
1413
+ ])
1414
+ .when([])
1415
+ .then(async (state) => {
1416
+ const document = await state.database
1417
+ .collection<FartHistory>('FartHistoryProjection')
1418
+ .findOne((doc) => doc.userId === 'usr_123');
1419
+
1420
+ const expected = {
1421
+ farts: [
1422
+ { fartId: 'fart_456', intensity: 7 },
1423
+ { fartId: 'fart_789', intensity: 9 },
1424
+ ],
1425
+ };
1426
+
1427
+ expect(document).toMatchObject(expected);
1428
+ }));
1429
+ });
1430
+ "
1431
+ `);
1432
+ });
1433
+
1217
1434
  it('should serialize inline objects and arrays with Date sub-fields correctly', async () => {
1218
1435
  const spec: SpecsSchema = {
1219
1436
  variant: 'specs',
@@ -1572,6 +1789,11 @@ describe('projection.specs.ts.ejs', () => {
1572
1789
  * NEVER hardcode constant values — every output field must trace to an input.
1573
1790
  * Preserve all import paths above — they are generated from the model.
1574
1791
  * ⚠️ \`document\` may be null (first event for this entity). Guard before accessing properties.
1792
+ *
1793
+ * CONSTRAINTS:
1794
+ * - NEVER use \`as SomeType\` type assertions. Declare typed variables instead: \`const x: Type = value;\`
1795
+ * - Only reference event.data fields listed in the "Event fields:" line below.
1796
+ * - Do NOT modify anything outside this case block: imports, type parameters, canHandle, collectionName, and getDocumentId are auto-generated.
1575
1797
  *
1576
1798
  * Implement how this event updates the projection.
1577
1799
  *
@@ -1584,11 +1806,12 @@ describe('projection.specs.ts.ejs', () => {
1584
1806
  * internalField: SomeType;
1585
1807
  * }
1586
1808
  *
1587
- * 2. Cast document parameter to extended type:
1809
+ * 2. Assign document to extended type:
1588
1810
  * const current: InternalWorkoutHistory = document ?? { ...defaults };
1589
1811
  *
1590
- * 3. Cast return values to extended type:
1591
- * return { ...allFields, internalField } as InternalWorkoutHistory;
1812
+ * 3. Return via typed variable (preserves internal state for next event):
1813
+ * const result: InternalWorkoutHistory = { ...allFields, internalField };
1814
+ * return result;
1592
1815
  *
1593
1816
  * This keeps internal state separate from the public GraphQL schema.
1594
1817
 
@@ -244,6 +244,11 @@ describe('projection.ts.ejs', () => {
244
244
  * NEVER hardcode constant values — every output field must trace to an input.
245
245
  * Preserve all import paths above — they are generated from the model.
246
246
  * ⚠️ \`document\` may be null (first event for this entity). Guard before accessing properties.
247
+ *
248
+ * CONSTRAINTS:
249
+ * - NEVER use \`as SomeType\` type assertions. Declare typed variables instead: \`const x: Type = value;\`
250
+ * - Only reference event.data fields listed in the "Event fields:" line below.
251
+ * - Do NOT modify anything outside this case block: imports, type parameters, canHandle, collectionName, and getDocumentId are auto-generated.
247
252
  *
248
253
  * Implement how this event updates the projection.
249
254
  *
@@ -256,11 +261,12 @@ describe('projection.ts.ejs', () => {
256
261
  * internalField: SomeType;
257
262
  * }
258
263
  *
259
- * 2. Cast document parameter to extended type:
264
+ * 2. Assign document to extended type:
260
265
  * const current: InternalAvailableListings = document ?? { ...defaults };
261
266
  *
262
- * 3. Cast return values to extended type:
263
- * return { ...allFields, internalField } as InternalAvailableListings;
267
+ * 3. Return via typed variable (preserves internal state for next event):
268
+ * const result: InternalAvailableListings = { ...allFields, internalField };
269
+ * return result;
264
270
  *
265
271
  * This keeps internal state separate from the public GraphQL schema.
266
272
 
@@ -284,6 +290,11 @@ describe('projection.ts.ejs', () => {
284
290
  * NEVER hardcode constant values — every output field must trace to an input.
285
291
  * Preserve all import paths above — they are generated from the model.
286
292
  * ⚠️ \`document\` may be null (first event for this entity). Guard before accessing properties.
293
+ *
294
+ * CONSTRAINTS:
295
+ * - NEVER use \`as SomeType\` type assertions. Declare typed variables instead: \`const x: Type = value;\`
296
+ * - Only reference event.data fields listed in the "Event fields:" line below.
297
+ * - Do NOT modify anything outside this case block: imports, type parameters, canHandle, collectionName, and getDocumentId are auto-generated.
287
298
  *
288
299
  * This event might indicate removal of a AvailableListings.
289
300
  *
@@ -588,6 +599,11 @@ describe('projection.ts.ejs', () => {
588
599
  * NEVER hardcode constant values — every output field must trace to an input.
589
600
  * Preserve all import paths above — they are generated from the model.
590
601
  * ⚠️ \`document\` may be null (first event for this entity). Guard before accessing properties.
602
+ *
603
+ * CONSTRAINTS:
604
+ * - NEVER use \`as SomeType\` type assertions. Declare typed variables instead: \`const x: Type = value;\`
605
+ * - Only reference event.data fields listed in the "Event fields:" line below.
606
+ * - Do NOT modify anything outside this case block: imports, type parameters, canHandle, collectionName, and getDocumentId are auto-generated.
591
607
  *
592
608
  * **SINGLETON AGGREGATION PATTERN**
593
609
  *
@@ -810,6 +826,11 @@ describe('projection.ts.ejs', () => {
810
826
  * NEVER hardcode constant values — every output field must trace to an input.
811
827
  * Preserve all import paths above — they are generated from the model.
812
828
  * ⚠️ \`document\` may be null (first event for this entity). Guard before accessing properties.
829
+ *
830
+ * CONSTRAINTS:
831
+ * - NEVER use \`as SomeType\` type assertions. Declare typed variables instead: \`const x: Type = value;\`
832
+ * - Only reference event.data fields listed in the "Event fields:" line below.
833
+ * - Do NOT modify anything outside this case block: imports, type parameters, canHandle, collectionName, and getDocumentId are auto-generated.
813
834
  *
814
835
  * **COMPOSITE KEY PROJECTION**
815
836
  *
@@ -277,13 +277,23 @@ if (isCompositeKey) {
277
277
  }
278
278
  %>
279
279
 
280
- const expected: <%= TargetType %> = {
281
- <% const stateKeys = Object.keys(expectedState.exampleData || {});
280
+ <%
281
+ const stateKeys = Object.keys(expectedState.exampleData || {});
282
+ const queryArgs = isQueryActionTest
283
+ ? (testCase.when?.args
284
+ || (Array.isArray(testCase.when) && testCase.when[0]?.exampleData)
285
+ || {})
286
+ : {};
287
+ const queryArgKeys = new Set(Object.keys(queryArgs));
288
+ const assertionKeys = stateKeys.filter(k => !queryArgKeys.has(k));
282
289
  const stateMessage = messages.find(m => m.name === targetName);
283
- for (let i = 0; i < stateKeys.length; i++) {
284
- const key = stateKeys[i];
290
+ const isPartial = assertionKeys.length < stateKeys.length;
291
+ -%>
292
+ const expected<%= isPartial ? '' : `: ${TargetType}` %> = {
293
+ <% for (let i = 0; i < assertionKeys.length; i++) {
294
+ const key = assertionKeys[i];
285
295
  const value = expectedState.exampleData[key];
286
- const isLast = i === stateKeys.length - 1;
296
+ const isLast = i === assertionKeys.length - 1;
287
297
  const field = stateMessage?.fields?.find(f => f.name === key);
288
298
  const tsType = field?.tsType || field?.type || 'string';
289
299
  const formattedValue = formatSpecValue(value, tsType);