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,30 @@
1
+ import { type Names } from '../core/names';
2
+ import { type CommonOptions, type Outcome } from './common';
3
+ export declare function generateContext(name: string | undefined, options: CommonOptions): Outcome;
4
+ export interface ModuleOptions extends CommonOptions {
5
+ context?: string;
6
+ fields?: string;
7
+ route?: string;
8
+ }
9
+ export declare function generateModule(name: string | undefined, options: ModuleOptions): Outcome;
10
+ export interface CommandOptions extends CommonOptions {
11
+ context?: string;
12
+ aggregate?: string;
13
+ }
14
+ export declare function generateCommand(text: string | undefined, options: CommandOptions): Outcome;
15
+ export interface BlockOptions extends CommonOptions {
16
+ context?: string;
17
+ fields?: string;
18
+ type?: string;
19
+ aggregate?: string;
20
+ on?: string;
21
+ from?: string;
22
+ }
23
+ export declare function generateValueObject(name: string | undefined, options: BlockOptions): Outcome;
24
+ export declare function generateEntity(name: string | undefined, options: BlockOptions): Outcome;
25
+ export declare function isPresentTense(names: Names): boolean;
26
+ export declare function generateEvent(name: string | undefined, options: BlockOptions): Outcome;
27
+ export declare function generateUseCase(name: string | undefined, options: BlockOptions): Outcome;
28
+ export declare function generateService(name: string | undefined, options: BlockOptions): Outcome;
29
+ export declare function generateHandler(name: string | undefined, options: BlockOptions): Outcome;
30
+ export declare function generateAdapter(kind: string | undefined, options: BlockOptions): Outcome;
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.generateContext = generateContext;
4
+ exports.generateModule = generateModule;
5
+ exports.generateCommand = generateCommand;
6
+ exports.generateValueObject = generateValueObject;
7
+ exports.generateEntity = generateEntity;
8
+ exports.isPresentTense = isPresentTense;
9
+ exports.generateEvent = generateEvent;
10
+ exports.generateUseCase = generateUseCase;
11
+ exports.generateService = generateService;
12
+ exports.generateHandler = generateHandler;
13
+ exports.generateAdapter = generateAdapter;
14
+ const errors_1 = require("../core/errors");
15
+ const fields_1 = require("../core/fields");
16
+ const names_1 = require("../core/names");
17
+ const project_1 = require("../core/project");
18
+ const writer_1 = require("../core/writer");
19
+ const commands_1 = require("../model/commands");
20
+ const building_blocks_1 = require("../templates/building-blocks");
21
+ const common_1 = require("./common");
22
+ const engine_1 = require("./engine");
23
+ function openEngine(options, title = '') {
24
+ const project = (0, project_1.loadProject)(options.cwd, (0, common_1.overrides)(options));
25
+ const writer = new writer_1.Writer({ root: project.root, dryRun: options.dryRun, force: options.force });
26
+ return new engine_1.Engine(project, writer, title);
27
+ }
28
+ const writeOptions = (options) => ({ force: options.force, skipTests: options.skipTests });
29
+ // =============================================================================================
30
+ // ddd-express context <name>
31
+ // =============================================================================================
32
+ function generateContext(name, options) {
33
+ const names = (0, common_1.contextNames)(name ?? '');
34
+ const engine = openEngine(options, `Bounded context ${names.pascal}`);
35
+ const existed = engine.writer.exists((0, project_1.ts)((0, project_1.contextPaths)(engine.project, names).module));
36
+ const context = engine.context(names);
37
+ if (existed)
38
+ engine.outcome.notes.push(`The context "${names.kebab}" already exists — nothing to do.`);
39
+ else {
40
+ engine.outcome.notes.push(`Describe its words in ${(0, engine_1.relativeFile)(engine.project, context.glossary)}, then add an aggregate:`, `npx ddd-express module <aggregate> --context ${names.kebab} --fields "name: string"`);
41
+ }
42
+ return engine.outcome;
43
+ }
44
+ function generateModule(name, options) {
45
+ const aggregate = (0, names_1.toNames)(name, 'module (aggregate) name');
46
+ let fields = (0, fields_1.parseFields)(options.fields);
47
+ const defaulted = fields.length === 0;
48
+ if (defaulted)
49
+ fields = (0, fields_1.parseFields)('name:string');
50
+ const engine = openEngine(options);
51
+ const ctxNames = (0, common_1.contextNames)(options.context ?? aggregate.kebab);
52
+ engine.outcome.title = `Module ${aggregate.pascal} in the ${ctxNames.pascal} context`;
53
+ const elsewhere = engine.aggregateElsewhere((0, project_1.contextPaths)(engine.project, ctxNames), aggregate);
54
+ const model = engine.aggregate(ctxNames, aggregate, fields, [], { ...writeOptions(options), route: options.route ?? null });
55
+ const context = model.context;
56
+ for (const other of elsewhere) {
57
+ engine.outcome.warnings.push(`${aggregate.pascal} also exists in the ${other} context. That can be right (each context has its own model), but check the names.`);
58
+ }
59
+ if (defaulted) {
60
+ engine.outcome.warnings.push('No --fields given: generated one field, "name: string". Example: --fields "title: string, dueAt?: date, done: boolean = false"');
61
+ }
62
+ engine.outcome.notes.push(`Routes (mounted by ${(0, engine_1.relativeFile)(engine.project, (0, project_1.ts)(context.module))}):`, ` POST ${model.route} GET ${model.route}?limit=&offset=`, ` GET ${model.route}/:id PATCH ${model.route}/:id DELETE ${model.route}/:id`, '', `Add behaviour: npx ddd-express command "approve: draft -> approved emits ${aggregate.pascal}Approved" --aggregate ${aggregate.kebab}${options.context ? ` --context ${ctxNames.kebab}` : ''}`, 'Run the tests: npm test');
63
+ return engine.outcome;
64
+ }
65
+ function generateCommand(text, options) {
66
+ if (!text) {
67
+ throw new errors_1.CliError('Missing the command.', 'Example: ddd-express command "complete(durationMinutes: integer): in_progress -> completed emits VisitCompleted" --aggregate visit');
68
+ }
69
+ const raw = (0, commands_1.parseCommand)(text);
70
+ const engine = openEngine(options);
71
+ const context = engine.requireContext(options.context);
72
+ const aggregate = engine.resolveAggregate(context, options.aggregate, 'A command is behaviour of an aggregate.');
73
+ engine.outcome.title = `Behaviour ${aggregate.pascal}.${raw.names.camel}() in the ${context.names.pascal} context`;
74
+ engine.foundation();
75
+ const command = engine.command(context, aggregate, raw, writeOptions(options));
76
+ const route = engine.routeOf(context, aggregate) ?? `/${(0, names_1.pluralize)(aggregate).kebab}`;
77
+ engine.outcome.notes.push(`Route: POST ${route}/:id/${command.names.kebab}`, `Write its business rules in ${aggregate.pascal}.${command.names.camel}() — then: npm test`);
78
+ return engine.outcome;
79
+ }
80
+ function generateValueObject(name, options) {
81
+ const n = (0, names_1.toNames)(name, 'value object name');
82
+ const fields = (0, fields_1.parseFields)(options.fields, ['props', 'equals', 'constructor', 'toString', 'create']);
83
+ if (fields.length > 0 && options.type) {
84
+ throw new errors_1.CliError('Use either --type (one value) or --fields (several values), not both.');
85
+ }
86
+ const single = fields.length === 0 ? (0, fields_1.parseField)(`${n.camel}:${options.type ?? 'string'}`) : null;
87
+ if (single?.optional)
88
+ throw new errors_1.CliError('A single-value value object cannot be optional.');
89
+ if (single?.defaultValue !== undefined)
90
+ throw new errors_1.CliError('A single-value value object has no default.');
91
+ const engine = openEngine(options);
92
+ const context = engine.requireContext(options.context);
93
+ engine.outcome.title = `Value object ${n.pascal} in the ${context.names.pascal} context`;
94
+ engine.valueObject(context, n, single, fields, writeOptions(options));
95
+ engine.outcome.notes.push(`Use it in an aggregate of ${context.names.kebab}: import { ${n.pascal} } from '${engine.valueObjectImportHint(context)}';`);
96
+ return engine.outcome;
97
+ }
98
+ function generateEntity(name, options) {
99
+ const n = (0, names_1.toNames)(name, 'entity name');
100
+ let fields = (0, fields_1.parseFields)(options.fields, building_blocks_1.ENTITY_RESERVED_FIELDS);
101
+ const defaulted = fields.length === 0;
102
+ if (defaulted)
103
+ fields = (0, fields_1.parseFields)('name:string');
104
+ const engine = openEngine(options);
105
+ const context = engine.requireContext(options.context);
106
+ const aggregate = engine.resolveAggregate(context, options.aggregate, 'An entity lives inside an aggregate.');
107
+ engine.outcome.title = `Entity ${n.pascal} inside the ${aggregate.pascal} aggregate (${context.names.pascal})`;
108
+ engine.entity(context, aggregate, n, fields, writeOptions(options));
109
+ if (defaulted)
110
+ engine.outcome.warnings.push('No --fields given: generated one field, "name: string".');
111
+ engine.outcome.notes.push(`Hold it in ${aggregate.pascal}Props (e.g. "${(0, names_1.pluralize)(n).camel}: ${n.pascal}[]") and change it only through ${aggregate.pascal} methods.`);
112
+ return engine.outcome;
113
+ }
114
+ function isPresentTense(names) {
115
+ return (0, names_1.readsLikeCommand)(names.words);
116
+ }
117
+ function generateEvent(name, options) {
118
+ const n = (0, names_1.toNames)(name, 'event name', ['event']);
119
+ const fields = (0, fields_1.parseFields)(options.fields, ['aggregateId', 'occurredAt', 'eventName', 'constructor']);
120
+ const engine = openEngine(options);
121
+ const context = engine.requireContext(options.context);
122
+ engine.outcome.title = `Domain event ${n.pascal} in the ${context.names.pascal} context`;
123
+ engine.event(context, n, fields, writeOptions(options));
124
+ if (isPresentTense(n)) {
125
+ engine.outcome.warnings.push('Events are facts that already happened: name them in the past tense, noun first (OrderPlaced, VisitCompleted).');
126
+ }
127
+ engine.outcome.notes.push(`Record it inside an aggregate method: this.record(new ${n.pascal}(this.id${fields.map((field) => `, ${field.names.camel}`).join('')}));`, `React to it elsewhere: npx ddd-express handler <Name> --on ${n.pascal} --context <context>`);
128
+ return engine.outcome;
129
+ }
130
+ function generateUseCase(name, options) {
131
+ const n = (0, names_1.toNames)(name, 'use case name', ['use', 'case']);
132
+ const engine = openEngine(options);
133
+ const context = engine.requireContext(options.context);
134
+ const aggregates = engine.aggregates(context);
135
+ let aggregate = null;
136
+ if (options.aggregate)
137
+ aggregate = engine.resolveAggregate(context, options.aggregate, '');
138
+ else {
139
+ const matches = aggregates
140
+ .map((kebab) => (0, names_1.toNames)(kebab, 'aggregate'))
141
+ .filter((candidate) => n.pascal.includes(candidate.pascal))
142
+ .sort((a, b) => b.pascal.length - a.pascal.length);
143
+ aggregate = matches[0] ?? null;
144
+ }
145
+ engine.outcome.title = `Use case ${n.pascal}${aggregate ? ` on ${aggregate.pascal}` : ''} in the ${context.names.pascal} context`;
146
+ const aggPaths = engine.useCase(context, n, aggregate, writeOptions(options));
147
+ if (aggregate && aggPaths) {
148
+ const action = n.words.filter((word) => !aggregate?.words.includes(word)).join('-') || n.kebab;
149
+ engine.outcome.notes.push(`Tip: for a behaviour of ${aggregate.pascal}, "ddd-express command" generates the method, the route and the tests too:`, ` npx ddd-express command "${action}" --aggregate ${aggregate.kebab} --context ${context.names.kebab}`);
150
+ }
151
+ else {
152
+ engine.outcome.notes.push(aggregates.length > 0
153
+ ? `Tip: pass --aggregate (${aggregates.join(', ')}) to get the load → behaviour → save → publish skeleton.`
154
+ : 'Tip: create an aggregate first (ddd-express module) to get the load → behaviour → save → publish skeleton.');
155
+ }
156
+ return engine.outcome;
157
+ }
158
+ function generateService(name, options) {
159
+ const n = (0, names_1.toNames)(name, 'domain service name', ['service']);
160
+ const engine = openEngine(options);
161
+ const context = engine.requireContext(options.context);
162
+ engine.outcome.title = `Domain service ${n.pascal}Service in the ${context.names.pascal} context`;
163
+ engine.service(context, n, writeOptions(options));
164
+ engine.outcome.notes.push('A use case loads the aggregates, passes them to the service, then saves the result.');
165
+ return engine.outcome;
166
+ }
167
+ function generateHandler(name, options) {
168
+ if (!options.on) {
169
+ throw new errors_1.CliError('Missing --on <Event>.', 'Example: ddd-express handler CreateInvoice --on VisitCompleted --context billing');
170
+ }
171
+ const event = (0, names_1.toNames)(options.on, 'event name', ['event']);
172
+ const engine = openEngine(options);
173
+ const context = engine.requireContext(options.context);
174
+ const found = engine.findEvent(event, options.from ?? null);
175
+ const { className } = engine.handlerNames(name ?? null, event);
176
+ engine.outcome.title =
177
+ `${className}: ${context.names.pascal} reacts to ${event.pascal}` +
178
+ (found.context.kebab === context.names.kebab ? '' : ` from ${found.context.pascal}`);
179
+ const file = engine.handler(context, name ?? null, event, options.from ?? null, writeOptions(options));
180
+ engine.outcome.notes.push(`Write the reaction in ${file} — it is already subscribed to the event bus.`);
181
+ return engine.outcome;
182
+ }
183
+ // =============================================================================================
184
+ // ddd-express adapter postgres --aggregate <aggregate>
185
+ // =============================================================================================
186
+ function generateAdapter(kind, options) {
187
+ if (kind !== 'postgres') {
188
+ throw new errors_1.CliError(kind ? `Unknown adapter "${kind}".` : 'Which adapter?', 'Available: postgres — e.g. ddd-express adapter postgres --aggregate visit');
189
+ }
190
+ const engine = openEngine(options);
191
+ const context = engine.requireContext(options.context);
192
+ const aggregate = engine.resolveAggregate(context, options.aggregate, 'An adapter stores an aggregate.');
193
+ engine.outcome.title = `PostgreSQL adapter for ${aggregate.pascal} (${context.names.pascal})`;
194
+ const { file, migration } = engine.postgres(context, aggregate, writeOptions(options));
195
+ const moduleFile = (0, engine_1.relativeFile)(engine.project, (0, project_1.ts)(context.module));
196
+ engine.outcome.notes.push('1. Install the driver: npm install pg && npm install -D @types/pg', `2. Create the table: psql "$DATABASE_URL" -f ${migration}`, `3. Use it in ${moduleFile}:`, ` import { Postgres${aggregate.pascal}Repository } from './infrastructure/persistence/postgres-${aggregate.kebab}.repository${engine.project.config.moduleSystem === 'esm' ? '.js' : ''}';`, ` const ${aggregate.camel}Repository = new Postgres${aggregate.pascal}Repository(deps.db); // add "db: Pool" to ${context.names.pascal}ModuleDeps`, ` and pass a Pool from your app: createContextsRouter({ eventBus, db: new Pool({ connectionString: process.env.DATABASE_URL }) })`, `4. Its integration test runs when DATABASE_URL is set (see ${file.replace(/\.ts$/, '.spec.ts')}).`);
197
+ return engine.outcome;
198
+ }
@@ -0,0 +1,71 @@
1
+ import { type Field } from '../core/fields';
2
+ import { type Names } from '../core/names';
3
+ import { type AggregatePaths, type ContextPaths, type Project } from '../core/project';
4
+ import type { Writer } from '../core/writer';
5
+ import type { CommandSpec, RawCommand } from '../model/types';
6
+ import { type AggregateModel } from '../templates/aggregate';
7
+ import { type Outcome } from './common';
8
+ export interface WriteOptions {
9
+ force: boolean;
10
+ skipTests: boolean;
11
+ }
12
+ export declare function relativeFile(project: Project, file: string): string;
13
+ export declare function normalizeRoute(route: string): string;
14
+ /** Generates code into one project. Used by every command and by `apply`. */
15
+ export declare class Engine {
16
+ readonly project: Project;
17
+ readonly writer: Writer;
18
+ readonly outcome: Outcome;
19
+ private foundationChecked;
20
+ constructor(project: Project, writer: Writer, title?: string);
21
+ /** Shared kernel + contexts registry + config, written once when missing. */
22
+ foundation(): void;
23
+ /** The context, created (and mounted) when it does not exist. */
24
+ context(names: Names): ContextPaths;
25
+ /** An existing context: --context, or the only one of the project. Writes nothing. */
26
+ requireContext(given: string | undefined): ContextPaths;
27
+ aggregates(context: ContextPaths): string[];
28
+ /** --aggregate, or the only aggregate of the context. */
29
+ resolveAggregate(context: ContextPaths, given: string | undefined, purpose: string): Names;
30
+ private wire;
31
+ private barrel;
32
+ private glossary;
33
+ /** Inserts `snippet` above `marker` in `file`; reports when the marker is missing. */
34
+ private insert;
35
+ /** Generates an aggregate with everything around it (and its commands). */
36
+ aggregate(contextName: Names, names: Names, fields: Field[], rawCommands: RawCommand[], options: WriteOptions & {
37
+ route?: string | null;
38
+ declaredEvents?: Map<string, Field[]>;
39
+ }): AggregateModel;
40
+ /** The event class a command records (created when missing). */
41
+ private commandEvent;
42
+ /** Adds a behaviour to an existing aggregate (method, event, use case, route, tests). */
43
+ command(context: ContextPaths, aggregateNames: Names, raw: RawCommand, options: WriteOptions, declaredEvents?: Map<string, Field[]>): CommandSpec;
44
+ /** The mount path of an aggregate's router, read from the context module. */
45
+ routeOf(context: ContextPaths, aggregate: Names): string | null;
46
+ /** A PostgreSQL repository for an existing aggregate, its migration and an integration test. */
47
+ postgres(context: ContextPaths, aggregateNames: Names, options: WriteOptions): {
48
+ file: string;
49
+ migration: string;
50
+ };
51
+ valueObject(context: ContextPaths, names: Names, single: Field | null, fields: Field[], options: WriteOptions): void;
52
+ entity(context: ContextPaths, aggregate: Names, names: Names, fields: Field[], options: WriteOptions): void;
53
+ event(context: ContextPaths, names: Names, fields: Field[], options: WriteOptions): void;
54
+ useCase(context: ContextPaths, names: Names, aggregate: Names | null, options: WriteOptions): AggregatePaths | null;
55
+ service(context: ContextPaths, names: Names, options: WriteOptions): void;
56
+ /** Where an event class lives: --from, or the one context that has it. */
57
+ findEvent(event: Names, from: string | null): {
58
+ context: Names;
59
+ file: string;
60
+ };
61
+ /** Handler class and file for "<Name> on <Event>". */
62
+ handlerNames(name: string | null, event: Names): {
63
+ className: string;
64
+ fileBase: string;
65
+ };
66
+ handler(context: ContextPaths, name: string | null, event: Names, from: string | null, options: WriteOptions): string;
67
+ /** Import path from an aggregate file of `context` to its value objects barrel (for hints). */
68
+ valueObjectImportHint(context: ContextPaths): string;
69
+ /** Is there an aggregate file for `names` in another context? (for a gentle warning) */
70
+ aggregateElsewhere(context: ContextPaths, names: Names): string[];
71
+ }