ddd-express 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/LICENSE +21 -0
  3. package/README.ar.md +117 -0
  4. package/README.md +314 -2
  5. package/dist/analyze/check.d.ts +74 -0
  6. package/dist/analyze/check.js +503 -0
  7. package/dist/analyze/document.d.ts +26 -0
  8. package/dist/analyze/document.js +126 -0
  9. package/dist/analyze/map.d.ts +19 -0
  10. package/dist/analyze/map.js +283 -0
  11. package/dist/analyze/openapi.d.ts +7 -0
  12. package/dist/analyze/openapi.js +236 -0
  13. package/dist/cli.d.ts +2 -0
  14. package/dist/cli.js +12 -0
  15. package/dist/core/errors.d.ts +5 -0
  16. package/dist/core/errors.js +13 -0
  17. package/dist/core/fields.d.ts +38 -0
  18. package/dist/core/fields.js +233 -0
  19. package/dist/core/markers.d.ts +25 -0
  20. package/dist/core/markers.js +60 -0
  21. package/dist/core/names.d.ts +30 -0
  22. package/dist/core/names.js +168 -0
  23. package/dist/core/output.d.ts +21 -0
  24. package/dist/core/output.js +29 -0
  25. package/dist/core/project.d.ts +135 -0
  26. package/dist/core/project.js +287 -0
  27. package/dist/core/writer.d.ts +39 -0
  28. package/dist/core/writer.js +138 -0
  29. package/dist/generators/analyze.d.ts +16 -0
  30. package/dist/generators/analyze.js +174 -0
  31. package/dist/generators/apply.d.ts +28 -0
  32. package/dist/generators/apply.js +234 -0
  33. package/dist/generators/common.d.ts +49 -0
  34. package/dist/generators/common.js +173 -0
  35. package/dist/generators/domain.d.ts +30 -0
  36. package/dist/generators/domain.js +198 -0
  37. package/dist/generators/engine.d.ts +71 -0
  38. package/dist/generators/engine.js +552 -0
  39. package/dist/generators/project.d.ts +10 -0
  40. package/dist/generators/project.js +214 -0
  41. package/dist/index.d.ts +10 -0
  42. package/dist/index.js +14 -0
  43. package/dist/model/commands.d.ts +28 -0
  44. package/dist/model/commands.js +228 -0
  45. package/dist/model/examples.d.ts +6 -0
  46. package/dist/model/examples.js +152 -0
  47. package/dist/model/parser.d.ts +28 -0
  48. package/dist/model/parser.js +222 -0
  49. package/dist/model/types.d.ts +98 -0
  50. package/dist/model/types.js +2 -0
  51. package/dist/model/validate.d.ts +30 -0
  52. package/dist/model/validate.js +215 -0
  53. package/dist/run.d.ts +4 -0
  54. package/dist/run.js +506 -0
  55. package/dist/scan/project-scan.d.ts +77 -0
  56. package/dist/scan/project-scan.js +226 -0
  57. package/dist/scan/source.d.ts +60 -0
  58. package/dist/scan/source.js +274 -0
  59. package/dist/templates/aggregate.d.ts +51 -0
  60. package/dist/templates/aggregate.js +407 -0
  61. package/dist/templates/building-blocks.d.ts +30 -0
  62. package/dist/templates/building-blocks.js +155 -0
  63. package/dist/templates/code.d.ts +14 -0
  64. package/dist/templates/code.js +51 -0
  65. package/dist/templates/command.d.ts +47 -0
  66. package/dist/templates/command.js +376 -0
  67. package/dist/templates/context.d.ts +16 -0
  68. package/dist/templates/context.js +43 -0
  69. package/dist/templates/field-code.d.ts +47 -0
  70. package/dist/templates/field-code.js +227 -0
  71. package/dist/templates/postgres.d.ts +25 -0
  72. package/dist/templates/postgres.js +113 -0
  73. package/dist/templates/project.d.ts +20 -0
  74. package/dist/templates/project.js +153 -0
  75. package/dist/templates/shared-kernel.d.ts +6 -0
  76. package/dist/templates/shared-kernel.js +44 -0
  77. package/package.json +58 -4
@@ -0,0 +1,407 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.eventClass = exports.AGGREGATE_RESERVED_FIELDS = void 0;
4
+ exports.commandModels = commandModels;
5
+ exports.stateTypeName = stateTypeName;
6
+ exports.aggregateFile = aggregateFile;
7
+ exports.articleFor = articleFor;
8
+ exports.aggregateIndex = aggregateIndex;
9
+ exports.aggregateSpec = aggregateSpec;
10
+ exports.eventFile = eventFile;
11
+ exports.aggregateEvents = aggregateEvents;
12
+ exports.portFile = portFile;
13
+ exports.dtoFile = dtoFile;
14
+ exports.useCaseFiles = useCaseFiles;
15
+ exports.facadeFile = facadeFile;
16
+ exports.useCasesSpec = useCasesSpec;
17
+ exports.mapperFile = mapperFile;
18
+ exports.repositoryFile = repositoryFile;
19
+ exports.requestFile = requestFile;
20
+ exports.routerFile = routerFile;
21
+ exports.routerSpec = routerSpec;
22
+ exports.wiringFor = wiringFor;
23
+ const fields_1 = require("../core/fields");
24
+ const markers_1 = require("../core/markers");
25
+ const project_1 = require("../core/project");
26
+ const code_1 = require("./code");
27
+ const command_1 = require("./command");
28
+ const field_code_1 = require("./field-code");
29
+ /** Field names the aggregate manages itself (they cannot be declared). */
30
+ exports.AGGREGATE_RESERVED_FIELDS = [
31
+ 'id',
32
+ 'createdAt',
33
+ 'updatedAt',
34
+ 'props',
35
+ 'record',
36
+ 'update',
37
+ 'delete',
38
+ 'equals',
39
+ 'pullEvents',
40
+ 'peekEvents',
41
+ 'validate',
42
+ 'toInput',
43
+ 'ensureState',
44
+ 'constructor',
45
+ ];
46
+ const eventClass = (m, suffix) => `${m.paths.names.pascal}${suffix}`;
47
+ exports.eventClass = eventClass;
48
+ const enumFields = (fields) => fields.filter((field) => field.type === 'enum');
49
+ /** First input field whose value can change to something else (used by the update tests). */
50
+ const updatableField = (fields) => (0, fields_1.inputFields)(fields).find((field) => (0, field_code_1.otherSample)(field) !== null);
51
+ const firstStringField = (fields) => (0, fields_1.inputFields)(fields).find((field) => field.type === 'string');
52
+ const usesNowDefault = (fields) => (0, fields_1.inputFields)(fields).some((field) => typeof field.defaultValue === 'object');
53
+ function commandModels(m) {
54
+ return m.commands.map((command) => ({
55
+ project: m.project,
56
+ context: m.context,
57
+ aggregate: m.paths,
58
+ fields: m.fields,
59
+ command,
60
+ paths: (0, project_1.commandPaths)(m.context, m.paths, command.names),
61
+ }));
62
+ }
63
+ function stateTypeName(m, state) {
64
+ return (0, field_code_1.enumNames)(m.paths.names, state).typeName;
65
+ }
66
+ // =============================================================================================
67
+ // domain/<aggregate>/<aggregate>.ts
68
+ // =============================================================================================
69
+ function aggregateFile(m) {
70
+ const n = m.paths.names;
71
+ const file = (0, project_1.ts)(m.paths.file);
72
+ const imp = (0, code_1.importer)(m.project, file);
73
+ const s = (0, project_1.sharedPaths)(m.project);
74
+ const ctx = m.context.names;
75
+ const inputs = (0, fields_1.inputFields)(m.fields);
76
+ const state = (0, command_1.stateFieldOf)(m.fields);
77
+ const managed = m.fields.filter((field) => field.managed);
78
+ const now = usesNowDefault(m.fields);
79
+ const validateCall = (arg) => `${n.pascal}.validate(${arg}${now ? ', now' : ''})`;
80
+ const ownEvents = new Set([(0, exports.eventClass)(m, 'Created'), (0, exports.eventClass)(m, 'Updated'), (0, exports.eventClass)(m, 'Deleted')]);
81
+ const commandEvents = [...new Set(m.commands.flatMap((command) => (command.emits ? [command.emits.names] : [])).map((names) => names.pascal))]
82
+ .filter((name) => !ownEvents.has(name));
83
+ const commandEventImports = commandEvents.map((name) => {
84
+ const names = m.commands.find((command) => command.emits?.names.pascal === name)?.emits?.names;
85
+ return `import { ${name} } from ${imp(`${m.context.events}/${names?.kebab}.event`)};`;
86
+ });
87
+ const enums = enumFields(m.fields).flatMap((field) => {
88
+ const { constName, typeName } = (0, field_code_1.enumNames)(n, field);
89
+ return [
90
+ `export const ${constName} = [${field.values.map((value) => `'${value}'`).join(', ')}] as const;`,
91
+ `export type ${typeName} = (typeof ${constName})[number];`,
92
+ '',
93
+ ];
94
+ });
95
+ const omitted = ["'createdAt'", "'updatedAt'", ...managed.map((field) => `'${field.names.camel}'`)].join(' | ');
96
+ return (0, code_1.lines)(`import { AggregateRoot } from ${imp(s.aggregateRoot)};`, state ? `import { DomainError } from ${imp(s.domainError)};` : null, `import { Guard } from ${imp(s.guard)};`, `import { sameValue, withoutUndefined } from ${imp(s.object)};`, `import { ${(0, exports.eventClass)(m, 'Created')} } from ${imp(m.paths.createdEvent)};`, `import { ${(0, exports.eventClass)(m, 'Updated')} } from ${imp(m.paths.updatedEvent)};`, `import { ${(0, exports.eventClass)(m, 'Deleted')} } from ${imp(m.paths.deletedEvent)};`, commandEventImports, `// ${markers_1.MARKERS.imports} — generated imports are added above this line`, '', enums, `/** The state of ${articleFor(n.human)} ${n.pascal}. */`, `export interface ${n.pascal}Props {`, (0, code_1.indent)(m.fields.map((field) => (0, field_code_1.stateMember)(n, field))), ' createdAt: Date;', ' updatedAt: Date;', '}', '', `/** What it takes to create ${articleFor(n.human)} ${n.pascal}.${inputs.some((field) => field.defaultValue !== undefined) ? ' Fields with a default may be left out.' : ''} */`, `export interface Create${n.pascal}Props {`, (0, code_1.indent)(inputs.map((field) => (0, field_code_1.inputMember)(n, field))), '}', '', `/** A change to ${articleFor(n.human)} ${n.pascal}: only the given fields change. */`, `export type Update${n.pascal}Props = Partial<Create${n.pascal}Props>;`, '', managed.length > 0
97
+ ? `/** The props set from input${managed.length > 0 ? ` (${managed.map((field) => field.names.camel).join(', ')} only changes through behaviour)` : ''}. */`
98
+ : '/** The props set from input. */', `type ${n.pascal}Data = Omit<${n.pascal}Props, ${omitted}>;`, '', '/**', ` * ${n.pascal} — Aggregate Root of the ${ctx.pascal} context.`, ' *', ' * - Every change goes through a method of this class: it is the single entry point.', ` * - The business rules (invariants) are checked here, so ${articleFor(n.human)} ${n.pascal} is never invalid.`, ' * - Other aggregates are referenced by their id only.', ' */', `export class ${n.pascal} extends AggregateRoot<string> {`, ` private props: ${n.pascal}Props;`, '', ` private constructor(id: string, props: ${n.pascal}Props) {`, ' super(id);', ' this.props = props;', ' }', '', ' // ---------- factories ----------', '', ` /** Creates a new ${n.pascal} and records ${(0, exports.eventClass)(m, 'Created')}. */`, ` static create(id: string, input: Create${n.pascal}Props, now: Date = new Date()): ${n.pascal} {`, ` const ${n.camel} = new ${n.pascal}(id, {`, ` ...${validateCall('input')},`, (0, code_1.indent)(managed.map((field) => `${field.names.camel}: '${(0, field_code_1.initialState)(field)}',`), 6), ' createdAt: now,', ' updatedAt: now,', ' });', ` ${n.camel}.record(new ${(0, exports.eventClass)(m, 'Created')}(id));`, ` return ${n.camel};`, ' }', '', ` /** Rebuilds ${articleFor(n.human)} ${n.pascal} from storage: no rule is re-checked and no event is recorded. */`, ` static rehydrate(id: string, props: ${n.pascal}Props): ${n.pascal} {`, ` return new ${n.pascal}(id, { ...props });`, ' }', '', ` // ---------- behaviour: the only way to change ${articleFor(n.human)} ${n.pascal} ----------`, '', ' /**', ' * Generic change of the editable fields. As your Ubiquitous Language grows, prefer behaviour', ' * that says what happens in business terms (`ddd-express command ...`).', ' */', ` update(changes: Update${n.pascal}Props, now: Date = new Date()): void {`, ` const next = ${validateCall('{ ...this.toInput(), ...withoutUndefined(changes) }')};`, ` const changed = (Object.keys(next) as (keyof ${n.pascal}Data)[]).filter(`, ' (key) => !sameValue(this.props[key], next[key]),', ' );', ' if (changed.length === 0) return;', ' this.props = { ...this.props, ...next, updatedAt: now };', ` this.record(new ${(0, exports.eventClass)(m, 'Updated')}(this.id, changed));`, ' }', '', ` /** Records ${(0, exports.eventClass)(m, 'Deleted')}; the use case then removes it from the repository. */`, ' delete(): void {', ` this.record(new ${(0, exports.eventClass)(m, 'Deleted')}(this.id));`, ' }', '', m.commands.flatMap((command) => [...(0, command_1.commandMethod)(n, m.fields, command), '']), ` // ${markers_1.MARKERS.behaviour} — generated behaviour is added above this line`, '', ' // ---------- read-only views ----------', '', m.fields.flatMap((field) => [...(0, code_1.indent)((0, field_code_1.getter)(n, field)), '']), ' get createdAt(): Date {', ' return new Date(this.props.createdAt.getTime());', ' }', '', ' get updatedAt(): Date {', ' return new Date(this.props.updatedAt.getTime());', ' }', '', ' // ---------- rules ----------', '', ` /** Every invariant of the editable fields, in one place. Add your business rules here. */`, ` private static validate(input: Create${n.pascal}Props${now ? ', now: Date' : ''}): ${n.pascal}Data {`, ' return {', (0, code_1.indent)(inputs.map((field) => `${field.names.camel}: ${(0, field_code_1.inputGuardCall)(n, field, 'input')},`), 6), ' };', ' }', '', ` private toInput(): Create${n.pascal}Props {`, ' return {', (0, code_1.indent)(inputs.map((field) => `${field.names.camel}: this.props.${field.names.camel},`), 6), ' };', ' }', state ? ['', ...(0, command_1.ensureStateMethod)(n, state, stateTypeName(m, state))] : null, '}');
99
+ }
100
+ function articleFor(word) {
101
+ return /^[aeiou]/i.test(word) ? 'an' : 'a';
102
+ }
103
+ function aggregateIndex(m) {
104
+ const n = m.paths.names;
105
+ const imp = (0, code_1.importer)(m.project, (0, project_1.ts)(m.paths.index));
106
+ const values = [n.pascal, ...enumFields(m.fields).map((field) => (0, field_code_1.enumNames)(n, field).constName)];
107
+ const types = [
108
+ `${n.pascal}Props`,
109
+ `Create${n.pascal}Props`,
110
+ `Update${n.pascal}Props`,
111
+ ...enumFields(m.fields).map((field) => (0, field_code_1.enumNames)(n, field).typeName),
112
+ ];
113
+ return (0, code_1.lines)(`export { ${values.join(', ')} } from ${imp(m.paths.file)};`, `export type { ${types.join(', ')} } from ${imp(m.paths.file)};`);
114
+ }
115
+ function validInputBlock(fields, typeName, plain = false) {
116
+ return [
117
+ `const validInput = (): ${typeName} => ({`,
118
+ ...(0, code_1.indent)((0, fields_1.inputFields)(fields).map((field) => `${field.names.camel}: ${plain ? (0, field_code_1.sample)(field).plain : (0, field_code_1.sample)(field).domain},`)),
119
+ '});',
120
+ ];
121
+ }
122
+ function aggregateSpec(m) {
123
+ const n = m.paths.names;
124
+ const file = (0, project_1.ts)(m.paths.spec);
125
+ const imp = (0, code_1.importer)(m.project, file);
126
+ const s = (0, project_1.sharedPaths)(m.project);
127
+ const inputs = (0, fields_1.inputFields)(m.fields);
128
+ const first = inputs[0];
129
+ const upd = updatableField(m.fields);
130
+ const updOther = upd ? (0, field_code_1.otherSample)(upd) : null;
131
+ const managed = m.fields.filter((field) => field.managed);
132
+ const defaulted = inputs.filter((field) => field.defaultValue !== undefined);
133
+ const withoutDefaults = inputs.filter((field) => field.defaultValue === undefined && !field.optional);
134
+ const createAsserts = [
135
+ ...inputs.map((field) => (0, field_code_1.sameAsSample)(field, `${n.camel}.${field.names.camel}`, (0, field_code_1.sample)(field))),
136
+ ...managed.map((field) => `assert.equal(${n.camel}.${field.names.camel}, '${(0, field_code_1.initialState)(field)}');`),
137
+ ];
138
+ const defaultAsserts = defaulted.map((field) => {
139
+ const value = field.defaultValue;
140
+ if (typeof value === 'object')
141
+ return `assert.equal(${n.camel}.${field.names.camel}.getTime(), now.getTime());`;
142
+ return `assert.equal(${n.camel}.${field.names.camel}, ${(0, field_code_1.defaultExpr)(field)});`;
143
+ });
144
+ const nowDefault = defaulted.some((field) => typeof field.defaultValue === 'object');
145
+ return (0, code_1.lines)((0, code_1.testImports)(m.project.config.testRunner), `import { DomainError } from ${imp(s.domainError)};`, upd ? `import { ${(0, exports.eventClass)(m, 'Updated')} } from ${imp(m.paths.updatedEvent)};` : null, `import { ${n.pascal}, type Create${n.pascal}Props } from ${imp(m.paths.file)};`, '', validInputBlock(m.fields, `Create${n.pascal}Props`), '', `describe('${n.pascal} aggregate', () => {`, ` it('is created from valid input and records ${(0, exports.eventClass)(m, 'Created')}', () => {`, ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', validInput());`, '', ` assert.equal(${n.camel}.id, '${n.kebab}-1');`, (0, code_1.indent)(createAsserts, 4), ` assert.deepEqual(${n.camel}.pullEvents().map((event) => event.eventName), ['${(0, exports.eventClass)(m, 'Created')}']);`, ' });', defaulted.length > 0 && [
146
+ '',
147
+ " it('uses the defaults for the fields that are left out', () => {",
148
+ nowDefault ? " const now = new Date('2026-03-01T10:00:00.000Z');" : null,
149
+ ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', {`,
150
+ ...(0, code_1.indent)(withoutDefaults.map((field) => `${field.names.camel}: ${(0, field_code_1.sample)(field).domain},`), 6),
151
+ nowDefault ? ' }, now);' : ' });',
152
+ '',
153
+ ...(0, code_1.indent)(defaultAsserts, 4),
154
+ ' });',
155
+ ].filter((line) => line !== null), '', ` it('rejects an invalid ${first.names.human}', () => {`, ' assert.throws(', ` () => ${n.pascal}.create('${n.kebab}-1', { ...validInput(), ${first.names.camel}: ${(0, field_code_1.invalidDomainValue)(first)} }),`, ' DomainError,', ' );', ' });', upd &&
156
+ updOther && [
157
+ '',
158
+ ` it('changes through update() and records ${(0, exports.eventClass)(m, 'Updated')} with the changed fields', () => {`,
159
+ ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', validInput());`,
160
+ ` ${n.camel}.pullEvents();`,
161
+ '',
162
+ ` ${n.camel}.update({ ${upd.names.camel}: ${updOther.domain} });`,
163
+ '',
164
+ ` ${(0, field_code_1.sameAsSample)(upd, `${n.camel}.${upd.names.camel}`, updOther)}`,
165
+ ` const [event] = ${n.camel}.pullEvents();`,
166
+ ` assert.ok(event instanceof ${(0, exports.eventClass)(m, 'Updated')});`,
167
+ ` assert.deepEqual(event.changes, ['${upd.names.camel}']);`,
168
+ ' });',
169
+ '',
170
+ " it('records nothing when an update changes nothing', () => {",
171
+ ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', validInput());`,
172
+ ` ${n.camel}.pullEvents();`,
173
+ '',
174
+ ` ${n.camel}.update({ ${upd.names.camel}: ${(0, field_code_1.sample)(upd).domain} });`,
175
+ '',
176
+ ` assert.deepEqual(${n.camel}.pullEvents(), []);`,
177
+ ' });',
178
+ ], '', " it('keeps its state when an update breaks a rule', () => {", ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', validInput());`, ` ${n.camel}.pullEvents();`, '', ` assert.throws(() => ${n.camel}.update({ ${first.names.camel}: ${(0, field_code_1.invalidDomainValue)(first)} }), DomainError);`, '', ` ${(0, field_code_1.sameAsSample)(first, `${n.camel}.${first.names.camel}`, (0, field_code_1.sample)(first))}`, ` assert.deepEqual(${n.camel}.pullEvents(), []);`, ' });', '', ` it('records ${(0, exports.eventClass)(m, 'Deleted')} when deleted', () => {`, ` const ${n.camel} = ${n.pascal}.create('${n.kebab}-1', validInput());`, ` ${n.camel}.pullEvents();`, '', ` ${n.camel}.delete();`, '', ` assert.deepEqual(${n.camel}.pullEvents().map((event) => event.eventName), ['${(0, exports.eventClass)(m, 'Deleted')}']);`, ' });', '', " it('is rebuilt from storage without recording events', () => {", ` const created = ${n.pascal}.create('${n.kebab}-1', validInput());`, '', ` const rebuilt = ${n.pascal}.rehydrate('${n.kebab}-1', {`, (0, code_1.indent)(m.fields.map((field) => `${field.names.camel}: created.${field.names.camel},`), 6), ' createdAt: created.createdAt,', ' updatedAt: created.updatedAt,', ' });', '', ' assert.ok(rebuilt.equals(created));', ' assert.deepEqual(rebuilt.peekEvents(), []);', ' });', '', " it('is identified by its id, not by its data', () => {", ` const a = ${n.pascal}.create('same-id', validInput());`, upd && updOther
179
+ ? ` const b = ${n.pascal}.create('same-id', { ...validInput(), ${upd.names.camel}: ${updOther.domain} });`
180
+ : ` const b = ${n.pascal}.create('same-id', validInput());`, ` const c = ${n.pascal}.create('other-id', validInput());`, '', ' assert.ok(a.equals(b));', ' assert.ok(!a.equals(c));', ' });', '});');
181
+ }
182
+ function constructorSignature(members) {
183
+ const params = members.map((member) => `${member.name}: ${member.type}`);
184
+ const oneLine = ` constructor(${params.join(', ')}) {`;
185
+ if (oneLine.length <= 100)
186
+ return [oneLine];
187
+ return [' constructor(', ...params.map((param) => ` ${param},`), ' ) {'];
188
+ }
189
+ /** A Domain Event class. Used for the aggregate's own events, command events and `ddd-express event`. */
190
+ function eventFile(project, file, className, contextPascal, description, members) {
191
+ const imp = (0, code_1.importer)(project, file);
192
+ const all = [{ name: 'aggregateId', type: 'string' }, ...members];
193
+ return (0, code_1.lines)(`import { DomainEvent } from ${imp((0, project_1.sharedPaths)(project).domainEvent)};`, '', '/**', ` * ${className} — Domain Event of the ${contextPascal} context.`, ...description.map((line) => ` * ${line}`), ' * Past tense: it already happened. It carries what listeners need — and nothing more.', ' */', `export class ${className} extends DomainEvent {`, (0, code_1.indent)(all.map((member) => `readonly ${member.name}: ${member.type};`)), '', constructorSignature(all), ' super();', (0, code_1.indent)(all.map((member) => `this.${member.name} = ${member.name};`), 4), ' }', '}');
194
+ }
195
+ function aggregateEvents(m) {
196
+ const n = m.paths.names;
197
+ const ctx = m.context.names.pascal;
198
+ const files = new Map();
199
+ files.set((0, project_1.ts)(m.paths.createdEvent), eventFile(m.project, (0, project_1.ts)(m.paths.createdEvent), (0, exports.eventClass)(m, 'Created'), ctx, [`A new ${n.pascal} was created.`], []));
200
+ files.set((0, project_1.ts)(m.paths.updatedEvent), eventFile(m.project, (0, project_1.ts)(m.paths.updatedEvent), (0, exports.eventClass)(m, 'Updated'), ctx, [`${articleFor(n.human) === 'an' ? 'An' : 'A'} ${n.pascal} changed; \`changes\` lists the fields that changed.`], [{ name: 'changes', type: 'readonly string[]' }]));
201
+ files.set((0, project_1.ts)(m.paths.deletedEvent), eventFile(m.project, (0, project_1.ts)(m.paths.deletedEvent), (0, exports.eventClass)(m, 'Deleted'), ctx, [`${articleFor(n.human) === 'an' ? 'An' : 'A'} ${n.pascal} was deleted.`], []));
202
+ return files;
203
+ }
204
+ function portFile(m) {
205
+ const n = m.paths.names;
206
+ const file = (0, project_1.ts)(m.paths.port);
207
+ const imp = (0, code_1.importer)(m.project, file);
208
+ return (0, code_1.lines)(`import type { ${n.pascal} } from ${imp(m.paths.index)};`, `import type { Page, PageQuery } from ${imp((0, project_1.sharedPaths)(m.project).pagination)};`, '', '/**', ` * Port: what the ${m.context.names.pascal} domain needs from storage, in its own words.`, ' * Adapters in infrastructure/persistence implement it (in-memory, Postgres, MongoDB, ...).', ' */', `export interface ${n.pascal}Repository {`, ` findById(id: string): Promise<${n.pascal} | null>;`, ` findAll(query: PageQuery): Promise<Page<${n.pascal}>>;`, ` save(${n.camel}: ${n.pascal}): Promise<void>;`, ` delete(${n.camel}: ${n.pascal}): Promise<void>;`, '}');
209
+ }
210
+ // =============================================================================================
211
+ // application/
212
+ // =============================================================================================
213
+ function dtoFile(m) {
214
+ const n = m.paths.names;
215
+ const file = (0, project_1.ts)(m.paths.dto);
216
+ const imp = (0, code_1.importer)(m.project, file);
217
+ const enumTypes = enumFields(m.fields).map((field) => (0, field_code_1.enumNames)(n, field).typeName);
218
+ return (0, code_1.lines)(`import type { ${[n.pascal, ...enumTypes].join(', ')} } from ${imp(m.paths.index)};`, '', `/** How ${articleFor(n.human)} ${n.pascal} looks to the outside world (HTTP responses, ...). Dates are ISO 8601 strings. */`, `export interface ${n.pascal}Dto {`, ' id: string;', (0, code_1.indent)(m.fields.map((field) => `${field.names.camel}: ${(0, field_code_1.plainType)(n, field)};`)), ' createdAt: string;', ' updatedAt: string;', '}', '', `export function to${n.pascal}Dto(${n.camel}: ${n.pascal}): ${n.pascal}Dto {`, ' return {', ` id: ${n.camel}.id,`, (0, code_1.indent)(m.fields.map((field) => `${field.names.camel}: ${(0, field_code_1.toPlain)(field, n.camel)},`), 4), ` createdAt: ${n.camel}.createdAt.toISOString(),`, ` updatedAt: ${n.camel}.updatedAt.toISOString(),`, ' };', '}');
219
+ }
220
+ function useCaseFields(m, withEvents) {
221
+ const n = m.paths.names;
222
+ const repo = m.paths.plural.camel;
223
+ return [
224
+ ` private readonly ${repo}: ${n.pascal}Repository;`,
225
+ ...(withEvents ? [' private readonly events: EventBus;'] : []),
226
+ '',
227
+ withEvents
228
+ ? ` constructor(${repo}: ${n.pascal}Repository, events: EventBus) {`
229
+ : ` constructor(${repo}: ${n.pascal}Repository) {`,
230
+ ` this.${repo} = ${repo};`,
231
+ ...(withEvents ? [' this.events = events;'] : []),
232
+ ' }',
233
+ ];
234
+ }
235
+ function useCaseFiles(m) {
236
+ const n = m.paths.names;
237
+ const pl = m.paths.plural;
238
+ const s = (0, project_1.sharedPaths)(m.project);
239
+ const repo = pl.camel;
240
+ const files = new Map();
241
+ const add = (target, render) => {
242
+ files.set((0, project_1.ts)(target), render((0, code_1.importer)(m.project, (0, project_1.ts)(target))));
243
+ };
244
+ add(m.paths.createUseCase, (imp) => (0, code_1.lines)(`import { ${n.pascal}, type Create${n.pascal}Props } from ${imp(m.paths.index)};`, `import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { EventBus } from ${imp(s.eventBus)};`, `import { newId } from ${imp(s.id)};`, `import { to${n.pascal}Dto, type ${n.pascal}Dto } from ${imp(m.paths.dto)};`, '', `export type Create${n.pascal}Input = Create${n.pascal}Props;`, '', '/**', ` * Use case: create ${articleFor(n.human)} ${n.pascal}.`, ' * It only orchestrates — the business rules live in the aggregate.', ' */', `export class Create${n.pascal}UseCase {`, useCaseFields(m, true), '', ` async execute(input: Create${n.pascal}Input): Promise<${n.pascal}Dto> {`, ` const ${n.camel} = ${n.pascal}.create(newId(), input);`, ` await this.${repo}.save(${n.camel});`, ` await this.events.publish(${n.camel}.pullEvents()); // only after a successful save`, ` return to${n.pascal}Dto(${n.camel});`, ' }', '}'));
245
+ add(m.paths.getUseCase, (imp) => (0, code_1.lines)(`import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import { NotFoundError } from ${imp(s.domainError)};`, `import { to${n.pascal}Dto, type ${n.pascal}Dto } from ${imp(m.paths.dto)};`, '', `/** Use case: read one ${n.pascal} by its id. */`, `export class Get${n.pascal}UseCase {`, useCaseFields(m, false), '', ` async execute(id: string): Promise<${n.pascal}Dto> {`, ` const ${n.camel} = await this.${repo}.findById(id);`, ` if (!${n.camel}) throw new NotFoundError('${n.pascal}', id);`, ` return to${n.pascal}Dto(${n.camel});`, ' }', '}'));
246
+ add(m.paths.listUseCase, (imp) => (0, code_1.lines)(`import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { Page, PageQuery } from ${imp(s.pagination)};`, `import { to${n.pascal}Dto, type ${n.pascal}Dto } from ${imp(m.paths.dto)};`, '', `/** Use case: read ${pl.pascal} page by page. */`, `export class List${pl.pascal}UseCase {`, useCaseFields(m, false), '', ` async execute(query: PageQuery): Promise<Page<${n.pascal}Dto>> {`, ` const page = await this.${repo}.findAll(query);`, ` return { ...page, items: page.items.map((${n.camel}) => to${n.pascal}Dto(${n.camel})) };`, ' }', '}'));
247
+ add(m.paths.updateUseCase, (imp) => (0, code_1.lines)(`import type { Update${n.pascal}Props } from ${imp(m.paths.index)};`, `import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { EventBus } from ${imp(s.eventBus)};`, `import { NotFoundError } from ${imp(s.domainError)};`, `import { to${n.pascal}Dto, type ${n.pascal}Dto } from ${imp(m.paths.dto)};`, '', `export type Update${n.pascal}Input = Update${n.pascal}Props;`, '', `/** Use case: change ${articleFor(n.human)} ${n.pascal}. Load → call behaviour → save → publish. */`, `export class Update${n.pascal}UseCase {`, useCaseFields(m, true), '', ` async execute(id: string, changes: Update${n.pascal}Input): Promise<${n.pascal}Dto> {`, ` const ${n.camel} = await this.${repo}.findById(id);`, ` if (!${n.camel}) throw new NotFoundError('${n.pascal}', id);`, ` ${n.camel}.update(changes);`, ` await this.${repo}.save(${n.camel});`, ` await this.events.publish(${n.camel}.pullEvents());`, ` return to${n.pascal}Dto(${n.camel});`, ' }', '}'));
248
+ add(m.paths.deleteUseCase, (imp) => (0, code_1.lines)(`import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { EventBus } from ${imp(s.eventBus)};`, `import { NotFoundError } from ${imp(s.domainError)};`, '', `/** Use case: delete ${articleFor(n.human)} ${n.pascal} and announce it with ${(0, exports.eventClass)(m, 'Deleted')}. */`, `export class Delete${n.pascal}UseCase {`, useCaseFields(m, true), '', ' async execute(id: string): Promise<void> {', ` const ${n.camel} = await this.${repo}.findById(id);`, ` if (!${n.camel}) throw new NotFoundError('${n.pascal}', id);`, ` ${n.camel}.delete();`, ` await this.${repo}.delete(${n.camel});`, ` await this.events.publish(${n.camel}.pullEvents());`, ' }', '}'));
249
+ return files;
250
+ }
251
+ /** application/<aggregate>.use-cases.ts — every use case of the aggregate, built in one place. */
252
+ function facadeFile(m) {
253
+ const n = m.paths.names;
254
+ const pl = m.paths.plural;
255
+ const file = (0, project_1.ts)(m.paths.useCases);
256
+ const imp = (0, code_1.importer)(m.project, file);
257
+ const s = (0, project_1.sharedPaths)(m.project);
258
+ const repo = pl.camel;
259
+ const commands = commandModels(m).map(command_1.commandFacadeEntry);
260
+ return (0, code_1.lines)(`import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { EventBus } from ${imp(s.eventBus)};`, `import { Create${n.pascal}UseCase } from ${imp(m.paths.createUseCase)};`, `import { Get${n.pascal}UseCase } from ${imp(m.paths.getUseCase)};`, `import { List${pl.pascal}UseCase } from ${imp(m.paths.listUseCase)};`, `import { Update${n.pascal}UseCase } from ${imp(m.paths.updateUseCase)};`, `import { Delete${n.pascal}UseCase } from ${imp(m.paths.deleteUseCase)};`, commands.flatMap((command) => command.imports), `// ${markers_1.MARKERS.imports} — generated imports are added above this line`, '', '/**', ` * Every use case of the ${n.pascal} aggregate, on the same repository and event bus.`, ' * The HTTP router, the tests and any other adapter (queue, CLI, GraphQL) get them from here.', ' */', `export function create${n.pascal}UseCases(${repo}: ${n.pascal}Repository, events: EventBus) {`, ' return {', ` create: new Create${n.pascal}UseCase(${repo}, events),`, ` get: new Get${n.pascal}UseCase(${repo}),`, ` list: new List${pl.pascal}UseCase(${repo}),`, ` update: new Update${n.pascal}UseCase(${repo}, events),`, ` delete: new Delete${n.pascal}UseCase(${repo}, events),`, commands.map((command) => command.entry), ` // ${markers_1.MARKERS.useCases} — generated use cases are added above this line`, ' };', '}', '', `export type ${n.pascal}UseCases = ReturnType<typeof create${n.pascal}UseCases>;`);
261
+ }
262
+ function useCasesSpec(m) {
263
+ const n = m.paths.names;
264
+ const pl = m.paths.plural;
265
+ const file = (0, project_1.ts)(m.paths.useCasesSpec);
266
+ const imp = (0, code_1.importer)(m.project, file);
267
+ const s = (0, project_1.sharedPaths)(m.project);
268
+ const first = (0, fields_1.inputFields)(m.fields)[0];
269
+ const upd = updatableField(m.fields);
270
+ const updOther = upd ? (0, field_code_1.otherSample)(upd) : null;
271
+ return (0, code_1.lines)((0, code_1.testImports)(m.project.config.testRunner), `import { DomainError, NotFoundError } from ${imp(s.domainError)};`, `import { RecordingEventBus } from ${imp(s.recordingEventBus)};`, `import { InMemory${n.pascal}Repository } from ${imp(m.paths.repository)};`, `import type { Create${n.pascal}Input } from ${imp(m.paths.createUseCase)};`, `import { create${n.pascal}UseCases } from ${imp(m.paths.useCases)};`, '', '/** The use cases on in-memory adapters, plus a bus that records what was published. */', 'function setup() {', ' const events = new RecordingEventBus();', ` return { events, ...create${n.pascal}UseCases(new InMemory${n.pascal}Repository(), events) };`, '}', '', validInputBlock(m.fields, `Create${n.pascal}Input`), '', `describe('${n.pascal} use cases', () => {`, ` it('creates ${articleFor(n.human)} ${n.human}, saves it, then publishes ${(0, exports.eventClass)(m, 'Created')}', async () => {`, ' const app = setup();', '', ' const created = await app.create.execute(validInput());', '', ' assert.deepEqual(await app.get.execute(created.id), created);', ` assert.deepEqual(app.events.names, ['${(0, exports.eventClass)(m, 'Created')}']);`, ' });', '', " it('saves and publishes nothing when a business rule is broken', async () => {", ' const app = setup();', '', ` await assert.rejects(app.create.execute({ ...validInput(), ${first.names.camel}: ${(0, field_code_1.invalidDomainValue)(first)} }), DomainError);`, '', ' assert.deepEqual(app.events.names, []);', ' assert.equal((await app.list.execute({ limit: 20, offset: 0 })).total, 0);', ' });', '', " it('fails with NotFoundError for an unknown id', async () => {", ' const app = setup();', '', " await assert.rejects(app.get.execute('missing-id'), NotFoundError);", " await assert.rejects(app.delete.execute('missing-id'), NotFoundError);", ' });', '', ` it('lists ${pl.human} page by page', async () => {`, ' const app = setup();', ' for (let i = 0; i < 3; i += 1) await app.create.execute(validInput());', '', ' const first = await app.list.execute({ limit: 2, offset: 0 });', ' const second = await app.list.execute({ limit: 2, offset: 2 });', '', ' assert.equal(first.total, 3);', ' assert.equal(first.items.length, 2);', ' assert.equal(second.items.length, 1);', ` assert.equal(new Set([...first.items, ...second.items].map((${n.camel}) => ${n.camel}.id)).size, 3);`, ' });', upd &&
272
+ updOther && [
273
+ '',
274
+ ` it('updates ${articleFor(n.human)} ${n.human} and publishes ${(0, exports.eventClass)(m, 'Updated')}', async () => {`,
275
+ ' const app = setup();',
276
+ ' const created = await app.create.execute(validInput());',
277
+ '',
278
+ ` const updated = await app.update.execute(created.id, { ${upd.names.camel}: ${updOther.domain} });`,
279
+ '',
280
+ ` assert.deepEqual(updated.${upd.names.camel}, ${updOther.plain});`,
281
+ ` assert.deepEqual((await app.get.execute(created.id)).${upd.names.camel}, ${updOther.plain});`,
282
+ ` assert.deepEqual(app.events.names, ['${(0, exports.eventClass)(m, 'Created')}', '${(0, exports.eventClass)(m, 'Updated')}']);`,
283
+ ' });',
284
+ ], '', ` it('deletes ${articleFor(n.human)} ${n.human} and publishes ${(0, exports.eventClass)(m, 'Deleted')}', async () => {`, ' const app = setup();', ' const created = await app.create.execute(validInput());', '', ' await app.delete.execute(created.id);', '', ' await assert.rejects(app.get.execute(created.id), NotFoundError);', ` assert.deepEqual(app.events.names, ['${(0, exports.eventClass)(m, 'Created')}', '${(0, exports.eventClass)(m, 'Deleted')}']);`, ' });', '});');
285
+ }
286
+ // =============================================================================================
287
+ // infrastructure/persistence
288
+ // =============================================================================================
289
+ function mapperFile(m) {
290
+ const n = m.paths.names;
291
+ const file = (0, project_1.ts)(m.paths.mapper);
292
+ const imp = (0, code_1.importer)(m.project, file);
293
+ const enumTypes = enumFields(m.fields).map((field) => (0, field_code_1.enumNames)(n, field).typeName);
294
+ return (0, code_1.lines)(`import { ${n.pascal} } from ${imp(m.paths.index)};`, enumTypes.length > 0 ? `import type { ${enumTypes.join(', ')} } from ${imp(m.paths.index)};` : null, '', `/** How ${articleFor(n.human)} ${n.pascal} is stored: plain, JSON-friendly data, no behaviour. */`, `export interface ${n.pascal}Record {`, ' id: string;', (0, code_1.indent)(m.fields.map((field) => `${field.names.camel}: ${(0, field_code_1.plainType)(n, field)};`)), ' createdAt: string;', ' updatedAt: string;', '}', '', '/** Translates between the aggregate (behaviour) and the record (storage). */', `export class ${n.pascal}Mapper {`, ` static toRecord(${n.camel}: ${n.pascal}): ${n.pascal}Record {`, ' return {', ` id: ${n.camel}.id,`, (0, code_1.indent)(m.fields.map((field) => `${field.names.camel}: ${(0, field_code_1.toPlain)(field, n.camel)},`), 6), ` createdAt: ${n.camel}.createdAt.toISOString(),`, ` updatedAt: ${n.camel}.updatedAt.toISOString(),`, ' };', ' }', '', ` static toDomain(record: ${n.pascal}Record): ${n.pascal} {`, ` return ${n.pascal}.rehydrate(record.id, {`, (0, code_1.indent)(m.fields.map((field) => `${field.names.camel}: ${(0, field_code_1.fromPlain)(field, 'record')},`), 6), ' createdAt: new Date(record.createdAt),', ' updatedAt: new Date(record.updatedAt),', ' });', ' }', '}');
295
+ }
296
+ function repositoryFile(m) {
297
+ const n = m.paths.names;
298
+ const file = (0, project_1.ts)(m.paths.repository);
299
+ const imp = (0, code_1.importer)(m.project, file);
300
+ const s = (0, project_1.sharedPaths)(m.project);
301
+ return (0, code_1.lines)(`import type { ${n.pascal} } from ${imp(m.paths.index)};`, `import type { ${n.pascal}Repository } from ${imp(m.context.portsIndex)};`, `import type { Page, PageQuery } from ${imp(s.pagination)};`, `import { ${n.pascal}Mapper, type ${n.pascal}Record } from ${imp(m.paths.mapper)};`, '', '/**', ` * Adapter: keeps ${m.paths.plural.human} in memory — for tests, demos and early development.`, ' * It stores copies (records), like a real database, so code behaves the same in production.', ` * Replace it with a real adapter (Postgres, MongoDB, ...) in ${m.context.names.kebab}.module.ts.`, ' */', `export class InMemory${n.pascal}Repository implements ${n.pascal}Repository {`, ` private readonly records = new Map<string, ${n.pascal}Record>();`, '', ` async findById(id: string): Promise<${n.pascal} | null> {`, ' const record = this.records.get(id);', ` return record ? ${n.pascal}Mapper.toDomain(record) : null;`, ' }', '', ` async findAll({ limit, offset }: PageQuery): Promise<Page<${n.pascal}>> {`, ' const all = [...this.records.values()].sort(', ' (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id),', ' );', ' return {', ` items: all.slice(offset, offset + limit).map((record) => ${n.pascal}Mapper.toDomain(record)),`, ' total: all.length,', ' limit,', ' offset,', ' };', ' }', '', ` async save(${n.camel}: ${n.pascal}): Promise<void> {`, ` this.records.set(${n.camel}.id, ${n.pascal}Mapper.toRecord(${n.camel}));`, ' }', '', ` async delete(${n.camel}: ${n.pascal}): Promise<void> {`, ` this.records.delete(${n.camel}.id);`, ' }', '}');
302
+ }
303
+ // =============================================================================================
304
+ // infrastructure/http
305
+ // =============================================================================================
306
+ function requestFile(m) {
307
+ const n = m.paths.names;
308
+ const file = (0, project_1.ts)(m.paths.request);
309
+ const imp = (0, code_1.importer)(m.project, file);
310
+ const inputs = (0, fields_1.inputFields)(m.fields);
311
+ const parsers = [...new Set(inputs.map(field_code_1.parserName))].sort();
312
+ const enumConsts = enumFields(inputs).map((field) => (0, field_code_1.enumNames)(n, field).constName);
313
+ const createMode = (field) => (field.optional ? 'optional' : field.defaultValue !== undefined ? 'ifPresent' : 'required');
314
+ return (0, code_1.lines)(`import { RequestBody, ${parsers.join(', ')} } from ${imp((0, project_1.sharedPaths)(m.project).requestBody)};`, enumConsts.length > 0 ? `import { ${enumConsts.join(', ')} } from ${imp(m.paths.index)};` : null, `import type { Create${n.pascal}Input } from ${imp(m.paths.createUseCase)};`, `import type { Update${n.pascal}Input } from ${imp(m.paths.updateUseCase)};`, '', '/**', ` * POST body → Create${n.pascal}Input.`, ` * Checks the SHAPE only (types, required fields); the ${n.pascal} aggregate checks the business rules.`, ' */', `export function parseCreate${n.pascal}Body(raw: unknown): Create${n.pascal}Input {`, ' const body = new RequestBody(raw);', ` const input: Create${n.pascal}Input = {`, (0, code_1.indent)(inputs.map((field) => `${field.names.camel}: body.${createMode(field)}('${field.names.camel}', ${(0, field_code_1.parserExpr)(n, field)}),`), 4), ' };', ' body.assertValid();', ' return input;', '}', '', `/** PATCH body → Update${n.pascal}Input. Only the fields sent are changed; optional fields accept null. */`, `export function parseUpdate${n.pascal}Body(raw: unknown): Update${n.pascal}Input {`, ' const body = new RequestBody(raw);', ` const changes: Update${n.pascal}Input = {`, (0, code_1.indent)(inputs.map((field) => `${field.names.camel}: body.${field.optional ? 'optional' : 'ifPresent'}('${field.names.camel}', ${(0, field_code_1.parserExpr)(n, field)}),`), 4), ' };', ' body.assertValid();', ' return changes;', '}');
315
+ }
316
+ function routerFile(m) {
317
+ const n = m.paths.names;
318
+ const pl = m.paths.plural;
319
+ const file = (0, project_1.ts)(m.paths.router);
320
+ const imp = (0, code_1.importer)(m.project, file);
321
+ const s = (0, project_1.sharedPaths)(m.project);
322
+ const commands = commandModels(m);
323
+ return (0, code_1.lines)("import { Router } from 'express';", `import { asyncHandler } from ${imp(s.asyncHandler)};`, `import { parsePageQuery } from ${imp(s.httpPagination)};`, `import { routeParam } from ${imp(s.routeParam)};`, `import type { ${n.pascal}UseCases } from ${imp(m.paths.useCases)};`, `import { parseCreate${n.pascal}Body, parseUpdate${n.pascal}Body } from ${imp(m.paths.request)};`, commands.flatMap((command) => (0, command_1.commandRouterImports)(command, file)), `// ${markers_1.MARKERS.imports} — generated imports are added above this line`, '', '/**', ' * Inbound adapter: translates HTTP into use-case calls — and nothing more.', ' * A queue consumer or a GraphQL resolver would call the very same use cases.', ' *', ' * POST / create → 201 + Location header', ' * GET / list → 200 { items, total, limit, offset } (?limit=&offset=)', ' * GET /:id get → 200 | 404', ' * PATCH /:id update → 200 | 404', ' * DELETE /:id delete → 204 | 404', ' * POST /:id/<action> behaviour → 200 | 404 | 422', ' *', ' * Errors: 400 malformed request, 404 not found, 422 business rule broken (see error-handler.ts).', ' */', `export function create${pl.pascal}Router(useCases: ${n.pascal}UseCases): Router {`, ' const router = Router();', '', ' router.post(', " '/',", ' asyncHandler(async (req, res) => {', ` const created = await useCases.create.execute(parseCreate${n.pascal}Body(req.body));`, ' res.status(201).location(`${req.baseUrl}/${created.id}`).json(created);', ' }),', ' );', '', ' router.get(', " '/',", ' asyncHandler(async (req, res) => {', ' res.json(await useCases.list.execute(parsePageQuery(req.query)));', ' }),', ' );', '', ' router.get(', " '/:id',", ' asyncHandler(async (req, res) => {', " res.json(await useCases.get.execute(routeParam(req, 'id')));", ' }),', ' );', '', ' router.patch(', " '/:id',", ' asyncHandler(async (req, res) => {', ` const changes = parseUpdate${n.pascal}Body(req.body);`, " res.json(await useCases.update.execute(routeParam(req, 'id'), changes));", ' }),', ' );', '', ' router.delete(', " '/:id',", ' asyncHandler(async (req, res) => {', " await useCases.delete.execute(routeParam(req, 'id'));", ' res.status(204).end();', ' }),', ' );', '', commands.flatMap((command) => [...(0, command_1.commandRoute)(command), '']), ` // ${markers_1.MARKERS.routes} — generated routes are added above this line`, '', ' return router;', '}');
324
+ }
325
+ function routerSpec(m) {
326
+ const n = m.paths.names;
327
+ const pl = m.paths.plural;
328
+ const file = (0, project_1.ts)(m.paths.routerSpec);
329
+ const imp = (0, code_1.importer)(m.project, file);
330
+ const s = (0, project_1.sharedPaths)(m.project);
331
+ const route = m.route;
332
+ const inputs = (0, fields_1.inputFields)(m.fields);
333
+ const required = inputs.find((field) => !field.optional && field.defaultValue === undefined);
334
+ const text = firstStringField(m.fields);
335
+ const upd = updatableField(m.fields);
336
+ const updOther = upd ? (0, field_code_1.otherSample)(upd) : null;
337
+ const managed = m.fields.filter((field) => field.managed);
338
+ const imports = (0, code_1.sortImports)([
339
+ ...(0, code_1.testImports)(m.project.config.testRunner),
340
+ `import { InMemoryEventBus } from ${imp(s.inMemoryEventBus)};`,
341
+ `import { call, createTestApp, withTestServer } from ${imp(s.testServer)};`,
342
+ `import { InMemory${n.pascal}Repository } from ${imp(m.paths.repository)};`,
343
+ `import { create${n.pascal}UseCases } from ${imp(m.paths.useCases)};`,
344
+ `import { create${pl.pascal}Router } from ${imp(m.paths.router)};`,
345
+ ]);
346
+ return (0, code_1.lines)(imports, '', `/** Starts a test server with the ${pl.human} routes on fresh in-memory adapters. */`, `async function with${pl.pascal}Api(test: (url: string) => Promise<void>): Promise<void> {`, ` const useCases = create${n.pascal}UseCases(new InMemory${n.pascal}Repository(), new InMemoryEventBus());`, ` const app = createTestApp((express) => express.use('${route}', create${pl.pascal}Router(useCases)));`, ` await withTestServer(app, (url) => test(\`\${url}${route}\`));`, '}', '', validInputBlock(m.fields, 'Record<string, unknown>', true), '', `describe('${pl.pascal} HTTP API (${route})', () => {`, ` it('POST creates ${articleFor(n.human)} ${n.human} → 201 with a Location header', async () => {`, ` await with${pl.pascal}Api(async (url) => {`, " const res = await call(url, { method: 'POST', body: validInput() });", '', ' assert.equal(res.status, 201);', ` assert.equal(res.headers.get('location'), \`${route}/\${res.body.id}\`);`, (0, code_1.indent)([
347
+ ...inputs.map((field) => `assert.deepEqual(res.body.${field.names.camel}, ${(0, field_code_1.sample)(field).plain});`),
348
+ ...managed.map((field) => `assert.equal(res.body.${field.names.camel}, ${(0, field_code_1.enumSample)((0, field_code_1.initialState)(field)).plain});`),
349
+ ], 6), ' });', ' });', '', " it('POST with a malformed body → 400 listing every problem', async () => {", ` await with${pl.pascal}Api(async (url) => {`, " const res = await call(url, { method: 'POST', body: { unexpected: true } });", '', ' assert.equal(res.status, 400);', required ? ` assert.ok(res.body.details.includes('${required.names.camel} is required'));` : null, " assert.ok(res.body.details.includes('unexpected is not an allowed field'));", ' });', ' });', text && [
350
+ '',
351
+ " it('POST that breaks a business rule → 422', async () => {",
352
+ ` await with${pl.pascal}Api(async (url) => {`,
353
+ ` const res = await call(url, { method: 'POST', body: { ...validInput(), ${text.names.camel}: ' ' } });`,
354
+ '',
355
+ ' assert.equal(res.status, 422);',
356
+ ' });',
357
+ ' });',
358
+ ], '', ` it('GET /:id returns the ${n.human}, or 404 when it does not exist', async () => {`, ` await with${pl.pascal}Api(async (url) => {`, " const created = await call(url, { method: 'POST', body: validInput() });", '', ' const found = await call(`${url}/${created.body.id}`);', ' const missing = await call(`${url}/missing-id`);', '', ' assert.equal(found.status, 200);', ' assert.deepEqual(found.body, created.body);', ' assert.equal(missing.status, 404);', ' });', ' });', '', ` it('GET / returns a page of ${pl.human}', async () => {`, ` await with${pl.pascal}Api(async (url) => {`, " await call(url, { method: 'POST', body: validInput() });", " await call(url, { method: 'POST', body: validInput() });", '', ' const page = await call(`${url}?limit=1`);', ' const invalid = await call(`${url}?limit=0`);', '', ' assert.equal(page.status, 200);', ' assert.equal(page.body.total, 2);', ' assert.equal(page.body.items.length, 1);', ' assert.equal(invalid.status, 400);', ' });', ' });', upd &&
359
+ updOther && [
360
+ '',
361
+ ` it('PATCH /:id changes only the given fields', async () => {`,
362
+ ` await with${pl.pascal}Api(async (url) => {`,
363
+ " const created = await call(url, { method: 'POST', body: validInput() });",
364
+ '',
365
+ ' const res = await call(`${url}/${created.body.id}`, {',
366
+ " method: 'PATCH',",
367
+ ` body: { ${upd.names.camel}: ${updOther.plain} },`,
368
+ ' });',
369
+ '',
370
+ ' assert.equal(res.status, 200);',
371
+ ` assert.deepEqual(res.body.${upd.names.camel}, ${updOther.plain});`,
372
+ ' });',
373
+ ' });',
374
+ ], managed.length > 0 && [
375
+ '',
376
+ ` it('PATCH /:id cannot change ${managed.map((field) => field.names.camel).join(', ')} (only behaviour can)', async () => {`,
377
+ ` await with${pl.pascal}Api(async (url) => {`,
378
+ " const created = await call(url, { method: 'POST', body: validInput() });",
379
+ '',
380
+ ' const res = await call(`${url}/${created.body.id}`, {',
381
+ " method: 'PATCH',",
382
+ ` body: { ${managed[0].names.camel}: '${managed[0].values[managed[0].values.length - 1]}' },`,
383
+ ' });',
384
+ '',
385
+ ' assert.equal(res.status, 400);',
386
+ ' });',
387
+ ' });',
388
+ ], '', " it('DELETE /:id → 204, then the resource is gone', async () => {", ` await with${pl.pascal}Api(async (url) => {`, " const created = await call(url, { method: 'POST', body: validInput() });", '', " const deleted = await call(`${url}/${created.body.id}`, { method: 'DELETE' });", ' const after = await call(`${url}/${created.body.id}`);', '', ' assert.equal(deleted.status, 204);', ' assert.equal(after.status, 404);', ' });', ' });', '});');
389
+ }
390
+ // =============================================================================================
391
+ // Wiring into <context>.module.ts
392
+ // =============================================================================================
393
+ function wiringFor(m) {
394
+ const n = m.paths.names;
395
+ const pl = m.paths.plural;
396
+ const imp = (0, code_1.importer)(m.project, (0, project_1.ts)(m.context.module));
397
+ const repository = `${n.camel}Repository`;
398
+ return {
399
+ key: `const ${repository} = `,
400
+ imports: [
401
+ `import { InMemory${n.pascal}Repository } from ${imp(m.paths.repository)};`,
402
+ `import { create${n.pascal}UseCases } from ${imp(m.paths.useCases)};`,
403
+ `import { create${pl.pascal}Router } from ${imp(m.paths.router)};`,
404
+ ],
405
+ block: (0, code_1.lines)(` // ${n.pascal}: repository adapter → use cases → HTTP routes (${m.route})`, ` const ${repository} = new InMemory${n.pascal}Repository();`, ` router.use('${m.route}', create${pl.pascal}Router(create${n.pascal}UseCases(${repository}, deps.eventBus)));`),
406
+ };
407
+ }
@@ -0,0 +1,30 @@
1
+ import type { Field } from '../core/fields';
2
+ import { type Names } from '../core/names';
3
+ import type { Project } from '../core/project';
4
+ /** A value object holding one value (`--type`). */
5
+ export declare function singleValueObject(project: Project, file: string, n: Names, context: Names, given: Field): string;
6
+ /** A value object made of several values (`--fields`). */
7
+ export declare function compositeValueObject(project: Project, file: string, n: Names, context: Names, fields: Field[]): string;
8
+ export declare function valueObjectSpec(project: Project, file: string, voFile: string, n: Names, fields: Field[] | null, single: Field | null): string;
9
+ export declare const ENTITY_RESERVED_FIELDS: string[];
10
+ export declare function entityFile(project: Project, file: string, n: Names, aggregate: Names, fields: Field[]): string;
11
+ export declare function entitySpec(project: Project, file: string, entityFilePath: string, n: Names, fields: Field[]): string;
12
+ /** TypeScript type of an event member. Enum values are written inline: 'a' | 'b'. */
13
+ export declare function eventMemberType(field: Field): string;
14
+ export declare function customUseCase(project: Project, file: string, n: Names, aggregate: {
15
+ names: Names;
16
+ plural: Names;
17
+ portsIndex: string;
18
+ } | null): string;
19
+ export declare function customUseCaseSpec(project: Project, file: string, useCaseFile: string, n: Names, aggregate: {
20
+ names: Names;
21
+ repositoryFile: string;
22
+ } | null): string;
23
+ export declare function domainService(n: Names, context: Names): string;
24
+ export declare function domainServiceSpec(project: Project, file: string, serviceFile: string, n: Names): string;
25
+ export declare function eventHandler(project: Project, file: string, className: string, event: {
26
+ className: string;
27
+ file: string;
28
+ contextPascal: string;
29
+ }, context: Names): string;
30
+ export declare function eventHandlerSpec(project: Project, file: string, handlerFile: string, className: string, eventClassName: string): string;