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
package/dist/run.js ADDED
@@ -0,0 +1,506 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.version = version;
37
+ exports.run = run;
38
+ const fs = __importStar(require("node:fs"));
39
+ const path = __importStar(require("node:path"));
40
+ const node_util_1 = require("node:util");
41
+ const errors_1 = require("./core/errors");
42
+ const fields_1 = require("./core/fields");
43
+ const output_1 = require("./core/output");
44
+ const project_1 = require("./core/project");
45
+ const domain_1 = require("./generators/domain");
46
+ const analyze_1 = require("./generators/analyze");
47
+ const apply_1 = require("./generators/apply");
48
+ const project_2 = require("./generators/project");
49
+ function version() {
50
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'));
51
+ return pkg.version;
52
+ }
53
+ const OPTIONS = {
54
+ context: { type: 'string', short: 'c' },
55
+ fields: { type: 'string', short: 'f' },
56
+ aggregate: { type: 'string', short: 'a' },
57
+ type: { type: 'string', short: 't' },
58
+ on: { type: 'string' },
59
+ from: { type: 'string' },
60
+ route: { type: 'string', short: 'r' },
61
+ 'test-runner': { type: 'string' },
62
+ 'module-system': { type: 'string' },
63
+ src: { type: 'string' },
64
+ cwd: { type: 'string' },
65
+ 'dry-run': { type: 'boolean', short: 'd' },
66
+ force: { type: 'boolean' },
67
+ 'skip-tests': { type: 'boolean' },
68
+ install: { type: 'boolean' },
69
+ model: { type: 'string', short: 'm' },
70
+ example: { type: 'string', short: 'e' },
71
+ json: { type: 'boolean' },
72
+ fix: { type: 'boolean' },
73
+ strict: { type: 'boolean' },
74
+ out: { type: 'string', short: 'o' },
75
+ format: { type: 'string' },
76
+ help: { type: 'boolean', short: 'h' },
77
+ version: { type: 'boolean', short: 'v' },
78
+ };
79
+ const COMMON = ['dry-run', 'force', 'cwd', 'src', 'test-runner', 'module-system'];
80
+ const str = (value) => (typeof value === 'string' ? value : undefined);
81
+ const COMMANDS = [
82
+ {
83
+ name: 'new',
84
+ aliases: ['create'],
85
+ usage: 'new <project-name> [--example <name> | --model <file>]',
86
+ summary: 'Create a new Express + TypeScript API, ready for DDD',
87
+ options: [...COMMON, 'example', 'model', 'skip-tests', 'install'],
88
+ details: [
89
+ 'Creates the folder with package.json, tsconfig, app.ts/server.ts, the shared kernel, a test setup and domain.ddd.',
90
+ 'With --example or --model, the whole domain is generated too: a running, tested API in one command.',
91
+ 'Default test runner: vitest (ESM). --test-runner jest uses CommonJS; --test-runner node uses node:test + tsx.',
92
+ ],
93
+ examples: [
94
+ 'ddd-express new clinic-api --example healthcare',
95
+ 'ddd-express new shop-api --example shop --test-runner jest',
96
+ 'ddd-express new my-api --model ./domain.ddd --install',
97
+ ],
98
+ run: (name, values, common) => (0, project_2.generateNew)(name, { ...common, install: values.install === true, model: str(values.model), example: str(values.example) }),
99
+ },
100
+ {
101
+ name: 'init',
102
+ aliases: [],
103
+ usage: 'init',
104
+ summary: 'Add the DDD foundation to an existing Express project',
105
+ options: COMMON,
106
+ details: [
107
+ 'Writes ddd.config.json, the shared kernel (src/shared) and src/contexts.ts. Existing files are never touched.',
108
+ 'Detects the test runner (vitest/jest/node) and ESM/CommonJS from package.json.',
109
+ ],
110
+ examples: ['ddd-express init', 'ddd-express init --src app --test-runner jest'],
111
+ run: (_name, _values, common) => (0, project_2.generateInit)(common),
112
+ },
113
+ {
114
+ name: 'apply',
115
+ aliases: ['sync'],
116
+ usage: 'apply [file]',
117
+ summary: 'Generate what domain.ddd describes and the code does not have yet',
118
+ options: [...COMMON, 'skip-tests'],
119
+ details: [
120
+ 'Reads domain.ddd (or the given file), checks it, then adds the missing contexts, aggregates, commands,',
121
+ 'entities, value objects, events, services and policies. Existing code is never deleted or rewritten',
122
+ '(new commands are added to existing aggregates). --force regenerates every aggregate of the model.',
123
+ ],
124
+ examples: ['ddd-express apply', 'ddd-express apply docs/domain.ddd --dry-run'],
125
+ run: (name, _values, common) => (0, apply_1.generateApply)(name, common),
126
+ },
127
+ {
128
+ name: 'model',
129
+ aliases: [],
130
+ usage: 'model [--example <name>]',
131
+ summary: 'Write a domain.ddd to start from (a starter, or a complete example)',
132
+ options: [...COMMON, 'example'],
133
+ details: ['Then edit it and run "ddd-express apply".'],
134
+ examples: ['ddd-express model', 'ddd-express model --example shop'],
135
+ run: (_name, values, common) => (0, apply_1.generateModelFile)({ ...common, example: str(values.example) }),
136
+ },
137
+ {
138
+ name: 'check',
139
+ aliases: ['lint', 'guard'],
140
+ usage: 'check [--fix] [--strict] [--json]',
141
+ summary: 'Guard the architecture: layers, context boundaries, ubiquitous language',
142
+ options: ['cwd', 'src', 'dry-run', 'fix', 'strict', 'json'],
143
+ details: [
144
+ 'Zero-config rules that know the DDD layout (exit code 1 on errors — add it to CI):',
145
+ ...(0, analyze_1.rulesHelp)(),
146
+ '--fix adds missing terms to the GLOSSARY.md files.',
147
+ `Configure in ddd.config.json: "check": { "rules": { "event-naming": "off" }, "allowInDomain": ["decimal.js"], "ignore": ["src/legacy"] }`,
148
+ ],
149
+ examples: ['ddd-express check', 'ddd-express check --fix', 'ddd-express check --strict --json > report.json'],
150
+ run: (_name, values, common, io) => (0, analyze_1.runCheck)({ ...common, json: values.json === true, fix: values.fix === true, strict: values.strict === true }, io),
151
+ },
152
+ {
153
+ name: 'map',
154
+ aliases: ['docs'],
155
+ usage: 'map [--format md|html|json] [--out <file>]',
156
+ summary: 'Living documentation: context map, event flow and life cycles, from the code',
157
+ options: ['cwd', 'src', 'dry-run', 'format', 'out'],
158
+ details: [
159
+ 'Reads the code and writes docs/DOMAIN.md: the context map, the event flow between contexts (Event Storming',
160
+ 'colours), the state diagram of every aggregate, behaviour and event tables, and the glossaries.',
161
+ 'GitHub renders the Mermaid diagrams. --format html writes one page to open in a browser; --out - prints.',
162
+ ],
163
+ examples: ['ddd-express map', 'ddd-express map --format html', 'ddd-express map --format json --out -'],
164
+ run: (_name, values, common, io) => (0, analyze_1.generateMap)({ ...common, out: str(values.out), format: str(values.format) }, io),
165
+ },
166
+ {
167
+ name: 'openapi',
168
+ aliases: ['swagger'],
169
+ usage: 'openapi [--format json|html] [--out <file>]',
170
+ summary: 'OpenAPI 3.1 for every route, from the code',
171
+ options: ['cwd', 'src', 'dry-run', 'format', 'out'],
172
+ details: [
173
+ 'Writes openapi.json: schemas from the aggregates and request parsers, CRUD and behaviour routes, errors.',
174
+ '--format html writes docs/api.html, an interactive API reference you can open in a browser.',
175
+ ],
176
+ examples: ['ddd-express openapi', 'ddd-express openapi --format html'],
177
+ run: (_name, values, common, io) => (0, analyze_1.generateOpenApi)({ ...common, out: str(values.out), format: str(values.format) }, io),
178
+ },
179
+ {
180
+ name: 'module',
181
+ aliases: ['m', 'mod', 'aggregate', 'agg'],
182
+ usage: 'module <name> [--context <context>] [--fields "<fields>"]',
183
+ summary: 'Generate an aggregate with everything around it (the main command)',
184
+ options: [...COMMON, 'context', 'fields', 'route', 'skip-tests'],
185
+ details: [
186
+ 'Generates, inside the bounded context (created if needed; defaults to the module name):',
187
+ ' domain/ the aggregate root, its Created/Updated/Deleted events, the repository port',
188
+ ' application/ create, get, list, update and delete use cases + a DTO',
189
+ ' infrastructure/ an in-memory repository + mapper, Express routes + request validation',
190
+ ' tests aggregate, use-case and HTTP tests (unless --skip-tests)',
191
+ 'and wires it all in <context>.module.ts.',
192
+ `Field types: ${fields_1.SUPPORTED_TYPES_HELP}.`,
193
+ ],
194
+ examples: [
195
+ 'ddd-express module patient --fields "fullName:string, birthDate:date, phone?:string"',
196
+ 'ddd-express module visit --context scheduling --fields "clientId:string, scheduledStart:date, status:enum(scheduled|completed|cancelled)"',
197
+ ],
198
+ run: (name, values, common) => (0, domain_1.generateModule)(name, {
199
+ ...common,
200
+ context: str(values.context),
201
+ fields: str(values.fields),
202
+ route: str(values.route),
203
+ }),
204
+ },
205
+ {
206
+ name: 'command',
207
+ aliases: ['cmd', 'behaviour', 'behavior'],
208
+ usage: 'command "<name>[(params)][: from -> to] [emits Event]" [--aggregate <aggregate>] [--context <context>]',
209
+ summary: 'Add a behaviour to an aggregate: method, state change, event, use case, route and tests',
210
+ options: [...COMMON, 'context', 'aggregate', 'skip-tests'],
211
+ details: [
212
+ 'Uses the same syntax as a command in domain.ddd:',
213
+ ' complete(durationMinutes: integer): in_progress -> completed emits VisitCompleted',
214
+ ' - parameters that have the name of a field update that field',
215
+ ' - ": from -> to" changes the state field (only allowed from the listed states)',
216
+ ' - "emits Event(a, b)" records an event carrying parameters/fields (default: all parameters)',
217
+ 'Generates POST /<route>/:id/<command> and its tests.',
218
+ ],
219
+ examples: [
220
+ 'ddd-express command "start: scheduled -> in_progress" --aggregate visit',
221
+ 'ddd-express command "reschedule(scheduledStart: date) emits VisitRescheduled" --aggregate visit',
222
+ 'ddd-express command "cancel(reason: string): scheduled, in_progress -> cancelled emits VisitCancelled" -a visit -c scheduling',
223
+ ],
224
+ run: (name, values, common) => (0, domain_1.generateCommand)(name, { ...common, context: str(values.context), aggregate: str(values.aggregate) }),
225
+ },
226
+ {
227
+ name: 'adapter',
228
+ aliases: ['db'],
229
+ usage: 'adapter postgres [--aggregate <aggregate>] [--context <context>]',
230
+ summary: 'Generate a PostgreSQL repository for an aggregate (+ migration + integration test)',
231
+ options: [...COMMON, 'context', 'aggregate', 'skip-tests'],
232
+ details: [
233
+ 'Implements the repository port with node-postgres: one schema per bounded context, upserts on save,',
234
+ 'paging on findAll. Writes migrations/<timestamp>_create_<context>_<table>.sql and a test that runs',
235
+ 'against DATABASE_URL. Swapping the adapter is one line in <context>.module.ts.',
236
+ ],
237
+ examples: ['ddd-express adapter postgres --aggregate visit --context scheduling'],
238
+ run: (name, values, common) => (0, domain_1.generateAdapter)(name, { ...common, context: str(values.context), aggregate: str(values.aggregate) }),
239
+ },
240
+ {
241
+ name: 'context',
242
+ aliases: ['ctx', 'bc', 'bounded-context'],
243
+ usage: 'context <name>',
244
+ summary: 'Create an empty bounded context (module file, GLOSSARY.md) and mount it',
245
+ options: COMMON,
246
+ details: ['Usually not needed: "module" creates the context when it does not exist.'],
247
+ examples: ['ddd-express context billing'],
248
+ run: (name, _values, common) => (0, domain_1.generateContext)(name, common),
249
+ },
250
+ {
251
+ name: 'value-object',
252
+ aliases: ['vo'],
253
+ usage: 'value-object <Name> [--type <type> | --fields "<fields>"] [--context <context>]',
254
+ summary: 'Generate an immutable, self-validating value object',
255
+ options: [...COMMON, 'context', 'type', 'fields', 'skip-tests'],
256
+ details: ['One value with --type (default: string), or several with --fields.'],
257
+ examples: [
258
+ 'ddd-express value-object PhoneNumber --context patients',
259
+ 'ddd-express vo VisitTime --context scheduling --fields "start:date, end:date"',
260
+ ],
261
+ run: (name, values, common) => (0, domain_1.generateValueObject)(name, { ...common, context: str(values.context), type: str(values.type), fields: str(values.fields) }),
262
+ },
263
+ {
264
+ name: 'entity',
265
+ aliases: ['ent'],
266
+ usage: 'entity <Name> [--aggregate <aggregate>] [--fields "<fields>"] [--context <context>]',
267
+ summary: 'Generate an entity inside an existing aggregate',
268
+ options: [...COMMON, 'context', 'aggregate', 'fields', 'skip-tests'],
269
+ details: ['The entity lives in the aggregate folder and is exported from its index.ts.'],
270
+ examples: ['ddd-express entity Task --context scheduling --aggregate visit --fields "description:string, done:boolean"'],
271
+ run: (name, values, common) => (0, domain_1.generateEntity)(name, {
272
+ ...common,
273
+ context: str(values.context),
274
+ aggregate: str(values.aggregate),
275
+ fields: str(values.fields),
276
+ }),
277
+ },
278
+ {
279
+ name: 'event',
280
+ aliases: ['ev', 'domain-event'],
281
+ usage: 'event <Name> [--fields "<fields>"] [--context <context>]',
282
+ summary: 'Generate a domain event (past tense: VisitCompleted)',
283
+ options: [...COMMON, 'context', 'fields'],
284
+ details: ['Every event carries aggregateId and occurredAt; --fields adds what listeners need.'],
285
+ examples: ['ddd-express event VisitCompleted --context scheduling --fields "durationMinutes:integer"'],
286
+ run: (name, values, common) => (0, domain_1.generateEvent)(name, { ...common, context: str(values.context), fields: str(values.fields) }),
287
+ },
288
+ {
289
+ name: 'use-case',
290
+ aliases: ['uc', 'usecase'],
291
+ usage: 'use-case <Name> [--aggregate <aggregate>] [--context <context>]',
292
+ summary: 'Generate a use case (load → behaviour → save → publish)',
293
+ options: [...COMMON, 'context', 'aggregate', 'skip-tests'],
294
+ details: ['The aggregate is detected from the name (CompleteVisit → Visit) or given with --aggregate.'],
295
+ examples: ['ddd-express use-case CompleteVisit --context scheduling'],
296
+ run: (name, values, common) => (0, domain_1.generateUseCase)(name, { ...common, context: str(values.context), aggregate: str(values.aggregate) }),
297
+ },
298
+ {
299
+ name: 'service',
300
+ aliases: ['svc', 'domain-service'],
301
+ usage: 'service <Name> [--context <context>]',
302
+ summary: 'Generate a stateless domain service',
303
+ options: [...COMMON, 'context', 'skip-tests'],
304
+ details: ['For business logic that involves several aggregates and belongs to none of them.'],
305
+ examples: ['ddd-express service CaregiverMatching --context scheduling'],
306
+ run: (name, values, common) => (0, domain_1.generateService)(name, { ...common, context: str(values.context) }),
307
+ },
308
+ {
309
+ name: 'handler',
310
+ aliases: ['event-handler', 'policy'],
311
+ usage: 'handler [Name] --on <Event> [--from <context>] [--context <context>]',
312
+ summary: 'React to a domain event, from this or another context',
313
+ options: [...COMMON, 'context', 'on', 'from', 'skip-tests'],
314
+ details: [
315
+ 'Creates application/<name>-on-<event>.handler.ts in --context and subscribes it to the event bus',
316
+ 'in <context>.module.ts. --from tells where the event lives when several contexts have it.',
317
+ ],
318
+ examples: ['ddd-express handler CreateInvoice --on VisitCompleted --context billing'],
319
+ run: (name, values, common) => (0, domain_1.generateHandler)(name, {
320
+ ...common,
321
+ context: str(values.context),
322
+ on: str(values.on),
323
+ from: str(values.from),
324
+ }),
325
+ },
326
+ ];
327
+ const OPTION_HELP = {
328
+ context: '-c, --context <name> bounded context to use',
329
+ fields: '-f, --fields "<list>" e.g. "title:string, dueAt?:date, status:enum(open|done)"',
330
+ aggregate: '-a, --aggregate <name> aggregate inside the context',
331
+ type: '-t, --type <type> type of a single-value value object (default: string)',
332
+ on: ' --on <Event> the domain event to react to',
333
+ from: ' --from <context> the context that publishes the event',
334
+ route: '-r, --route </path> mount path of the routes (default: /<plural>)',
335
+ 'test-runner': ` --test-runner <name> ${project_1.TEST_RUNNERS.join(' | ')} (default: detected)`,
336
+ 'module-system': ` --module-system <m> ${project_1.MODULE_SYSTEMS.join(' | ')} (default: detected)`,
337
+ src: ' --src <dir> source folder (default: src)',
338
+ cwd: ' --cwd <dir> run as if started in <dir>',
339
+ 'dry-run': '-d, --dry-run show what would change, write nothing',
340
+ force: ' --force overwrite generated files that already exist',
341
+ 'skip-tests': ' --skip-tests do not generate test files',
342
+ install: ' --install run npm install in the new project',
343
+ model: '-m, --model <file> build the project from a domain model file',
344
+ example: '-e, --example <name> start from an example model: healthcare, shop',
345
+ json: ' --json machine-readable output',
346
+ fix: ' --fix fix what can be fixed automatically',
347
+ strict: ' --strict warnings fail too (exit code 1)',
348
+ out: '-o, --out <file> where to write the result',
349
+ format: ' --format <format> output format',
350
+ help: '-h, --help show help',
351
+ version: '-v, --version show the version',
352
+ };
353
+ function findCommand(name) {
354
+ return COMMANDS.find((command) => command.name === name || command.aliases.includes(name));
355
+ }
356
+ const GROUPS = [
357
+ { title: 'Start', commands: ['new', 'init', 'model'] },
358
+ { title: 'Design the domain (domain.ddd)', commands: ['apply'] },
359
+ { title: 'Generate', commands: ['module', 'command', 'context', 'value-object', 'entity', 'event', 'use-case', 'service', 'handler', 'adapter'] },
360
+ { title: 'Guard and document', commands: ['check', 'map', 'openapi'] },
361
+ ];
362
+ function mainHelp(io) {
363
+ const b = (text) => (0, output_1.paint)(io, 'bold', text);
364
+ const width = Math.max(...COMMANDS.map((command) => command.name.length)) + 2;
365
+ const row = (command) => ` ${(0, output_1.paint)(io, 'cyan', command.name.padEnd(width))}${command.summary}${command.aliases.length ? (0, output_1.paint)(io, 'gray', ` (${command.aliases.join(', ')})`) : ''}`;
366
+ return [
367
+ `${b('ddd-express')} ${version()} — Domain-Driven Design for Express + TypeScript`,
368
+ (0, output_1.paint)(io, 'gray', 'Model the domain, generate a tested API, keep the architecture honest.'),
369
+ '',
370
+ `${b('Usage')} ddd-express <command> [name] [options]`,
371
+ ...GROUPS.flatMap((group) => [
372
+ '',
373
+ b(group.title),
374
+ ...group.commands.map((name) => COMMANDS.find((command) => command.name === name)).filter((command) => Boolean(command)).map(row),
375
+ ]),
376
+ '',
377
+ b('Quick start'),
378
+ ' npx ddd-express new clinic-api --example healthcare # 4 contexts, ~200 tests, running API',
379
+ ' cd clinic-api && npm install && npm test && npm run dev',
380
+ '',
381
+ 'Run "ddd-express <command> --help" for the options and examples of a command.',
382
+ 'Docs: https://github.com/Moustafa1997/ddd-express#readme',
383
+ ].join('\n');
384
+ }
385
+ function commandHelp(io, command) {
386
+ const b = (text) => (0, output_1.paint)(io, 'bold', text);
387
+ return [
388
+ `${b('ddd-express ' + command.usage)}`,
389
+ '',
390
+ command.summary + '.',
391
+ ...command.details,
392
+ '',
393
+ b('Options'),
394
+ ...[
395
+ ...command.options.filter((option) => !COMMON.includes(option)),
396
+ ...command.options.filter((option) => COMMON.includes(option)),
397
+ 'help',
398
+ ].map((option) => ` ${OPTION_HELP[option]}`),
399
+ '',
400
+ b('Examples'),
401
+ ...command.examples.map((example) => ` ${example}`),
402
+ command.aliases.length ? `\nAliases: ${command.aliases.join(', ')}` : '',
403
+ ]
404
+ .join('\n')
405
+ .replace(/\n+$/, '');
406
+ }
407
+ function printOutcome(io, outcome, startedAt) {
408
+ io.out(`${(0, output_1.paint)(io, 'bold', outcome.title)}\n`);
409
+ outcome.writer.report(io);
410
+ const created = outcome.writer.count('create') + outcome.writer.count('overwrite');
411
+ const updated = outcome.writer.count('update');
412
+ if (created + updated > 0 && !outcome.writer.dryRun) {
413
+ const parts = [created > 0 ? `${created} file${created === 1 ? '' : 's'} written` : '', updated > 0 ? `${updated} updated` : '']
414
+ .filter(Boolean)
415
+ .join(', ');
416
+ io.out((0, output_1.paint)(io, 'green', `\n ✔ ${parts} in ${Date.now() - startedAt} ms`));
417
+ }
418
+ if (outcome.warnings.length > 0) {
419
+ io.out('');
420
+ for (const warning of outcome.warnings)
421
+ io.out((0, output_1.paint)(io, 'yellow', ` ${warning.startsWith(' ') ? warning : `! ${warning}`}`));
422
+ }
423
+ if (outcome.notes.length > 0) {
424
+ io.out(`\n${(0, output_1.paint)(io, 'bold', 'Next')}`);
425
+ for (const note of outcome.notes)
426
+ io.out(note === '' ? '' : ` ${note}`);
427
+ }
428
+ }
429
+ /** Runs the CLI with `argv` (without "node" and the script). Returns the exit code. */
430
+ function run(argv, io = (0, output_1.defaultIo)(), cwd = process.cwd()) {
431
+ const startedAt = Date.now();
432
+ try {
433
+ let parsed;
434
+ try {
435
+ parsed = (0, node_util_1.parseArgs)({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
436
+ }
437
+ catch (error) {
438
+ const message = error instanceof Error ? error.message.split('\n')[0] : String(error);
439
+ throw new errors_1.CliError(message.replace(/^TypeError( \[[A-Z_]+\])?: /, ''), 'Run "ddd-express --help" to see the options.');
440
+ }
441
+ const { values } = parsed;
442
+ let positionals = [...parsed.positionals];
443
+ if (positionals[0] === 'g' || positionals[0] === 'generate')
444
+ positionals = positionals.slice(1);
445
+ if (values.version && positionals.length === 0) {
446
+ io.out(version());
447
+ return 0;
448
+ }
449
+ if (positionals.length === 0 || positionals[0] === 'help') {
450
+ const topic = positionals[1] ? findCommand(positionals[1]) : undefined;
451
+ io.out(topic ? commandHelp(io, topic) : mainHelp(io));
452
+ return 0;
453
+ }
454
+ const [commandName, name, ...rest] = positionals;
455
+ const command = findCommand(commandName);
456
+ if (!command) {
457
+ throw new errors_1.CliError(`Unknown command "${commandName}".`, 'Run "ddd-express --help" to see the commands.');
458
+ }
459
+ if (values.help) {
460
+ io.out(commandHelp(io, command));
461
+ return 0;
462
+ }
463
+ if (rest.length > 0) {
464
+ throw new errors_1.CliError(`Too many arguments: ${rest.join(' ')}`, 'Quote lists with spaces, e.g. --fields "name:string, age:integer".');
465
+ }
466
+ for (const option of Object.keys(values)) {
467
+ if (option === 'help' || option === 'version')
468
+ continue;
469
+ if (!command.options.includes(option)) {
470
+ throw new errors_1.CliError(`Option --${option} does not apply to "${command.name}".`, `Run "ddd-express ${command.name} --help".`);
471
+ }
472
+ }
473
+ const testRunner = str(values['test-runner']);
474
+ if (testRunner !== undefined && !project_1.TEST_RUNNERS.includes(testRunner)) {
475
+ throw new errors_1.CliError(`Unknown test runner "${testRunner}".`, `Use one of: ${project_1.TEST_RUNNERS.join(', ')}.`);
476
+ }
477
+ const moduleSystem = str(values['module-system']);
478
+ if (moduleSystem !== undefined && !project_1.MODULE_SYSTEMS.includes(moduleSystem)) {
479
+ throw new errors_1.CliError(`Unknown module system "${moduleSystem}".`, `Use one of: ${project_1.MODULE_SYSTEMS.join(', ')}.`);
480
+ }
481
+ const common = {
482
+ cwd: path.resolve(cwd, str(values.cwd) ?? '.'),
483
+ dryRun: values['dry-run'] === true,
484
+ force: values.force === true,
485
+ skipTests: values['skip-tests'] === true,
486
+ srcDir: str(values.src),
487
+ testRunner: testRunner,
488
+ moduleSystem: moduleSystem,
489
+ };
490
+ const result = command.run(name, values, common, io);
491
+ if (typeof result === 'number')
492
+ return result;
493
+ if (result)
494
+ printOutcome(io, result, startedAt);
495
+ return 0;
496
+ }
497
+ catch (error) {
498
+ if (error instanceof errors_1.CliError) {
499
+ io.err((0, output_1.paint)(io, 'red', `✖ ${error.message}`));
500
+ if (error.hint)
501
+ io.err(` ${error.hint}`);
502
+ return 1;
503
+ }
504
+ throw error;
505
+ }
506
+ }
@@ -0,0 +1,77 @@
1
+ import type { Field } from '../core/fields';
2
+ import type { Project } from '../core/project';
3
+ /** What the code says about the domain — the input of `map`, `openapi` and `check`. */
4
+ export interface ScannedCommand {
5
+ name: string;
6
+ /** States the behaviour is allowed in (empty = any). */
7
+ from: string[];
8
+ to: string | null;
9
+ events: string[];
10
+ /** HTTP route relative to the aggregate route, e.g. "/:id/check-out". */
11
+ route: string | null;
12
+ params: Field[];
13
+ }
14
+ export interface ScannedAggregate {
15
+ name: string;
16
+ kebab: string;
17
+ file: string;
18
+ fields: Field[];
19
+ stateField: string | null;
20
+ initialState: string | null;
21
+ route: string | null;
22
+ commands: ScannedCommand[];
23
+ entities: string[];
24
+ /** Has the generated CRUD routes (POST /, GET /, GET /:id, PATCH /:id, DELETE /:id). */
25
+ crud: {
26
+ create: boolean;
27
+ list: boolean;
28
+ get: boolean;
29
+ update: boolean;
30
+ delete: boolean;
31
+ };
32
+ }
33
+ export interface ScannedEvent {
34
+ name: string;
35
+ file: string;
36
+ fields: Field[];
37
+ }
38
+ export interface ScannedHandler {
39
+ className: string;
40
+ event: string;
41
+ /** Context that publishes the event (kebab), when known. */
42
+ eventContext: string | null;
43
+ }
44
+ export interface ScannedContext {
45
+ name: string;
46
+ pascal: string;
47
+ dir: string;
48
+ /** Path prefix the context is mounted on in contexts.ts ("" when mounted at the root). */
49
+ prefix: string;
50
+ aggregates: ScannedAggregate[];
51
+ events: ScannedEvent[];
52
+ valueObjects: string[];
53
+ services: string[];
54
+ handlers: ScannedHandler[];
55
+ glossary: {
56
+ file: string | null;
57
+ terms: {
58
+ term: string;
59
+ meaning: string;
60
+ }[];
61
+ };
62
+ }
63
+ export interface ScannedProject {
64
+ name: string;
65
+ version: string;
66
+ root: string;
67
+ src: string;
68
+ /** Prefix of all contexts in app.ts (e.g. "/api"), "" when none. */
69
+ basePath: string;
70
+ contexts: ScannedContext[];
71
+ }
72
+ export declare function parseGlossary(source: string): {
73
+ term: string;
74
+ meaning: string;
75
+ }[];
76
+ /** Reads the whole project. Never throws on unexpected code: what it cannot read is left out. */
77
+ export declare function scanProject(project: Project): ScannedProject;