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.
- package/CHANGELOG.md +34 -0
- package/LICENSE +21 -0
- package/README.ar.md +117 -0
- package/README.md +314 -2
- package/dist/analyze/check.d.ts +74 -0
- package/dist/analyze/check.js +503 -0
- package/dist/analyze/document.d.ts +26 -0
- package/dist/analyze/document.js +126 -0
- package/dist/analyze/map.d.ts +19 -0
- package/dist/analyze/map.js +283 -0
- package/dist/analyze/openapi.d.ts +7 -0
- package/dist/analyze/openapi.js +236 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +12 -0
- package/dist/core/errors.d.ts +5 -0
- package/dist/core/errors.js +13 -0
- package/dist/core/fields.d.ts +38 -0
- package/dist/core/fields.js +233 -0
- package/dist/core/markers.d.ts +25 -0
- package/dist/core/markers.js +60 -0
- package/dist/core/names.d.ts +30 -0
- package/dist/core/names.js +168 -0
- package/dist/core/output.d.ts +21 -0
- package/dist/core/output.js +29 -0
- package/dist/core/project.d.ts +135 -0
- package/dist/core/project.js +287 -0
- package/dist/core/writer.d.ts +39 -0
- package/dist/core/writer.js +138 -0
- package/dist/generators/analyze.d.ts +16 -0
- package/dist/generators/analyze.js +174 -0
- package/dist/generators/apply.d.ts +28 -0
- package/dist/generators/apply.js +234 -0
- package/dist/generators/common.d.ts +49 -0
- package/dist/generators/common.js +173 -0
- package/dist/generators/domain.d.ts +30 -0
- package/dist/generators/domain.js +198 -0
- package/dist/generators/engine.d.ts +71 -0
- package/dist/generators/engine.js +552 -0
- package/dist/generators/project.d.ts +10 -0
- package/dist/generators/project.js +214 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +14 -0
- package/dist/model/commands.d.ts +28 -0
- package/dist/model/commands.js +228 -0
- package/dist/model/examples.d.ts +6 -0
- package/dist/model/examples.js +152 -0
- package/dist/model/parser.d.ts +28 -0
- package/dist/model/parser.js +222 -0
- package/dist/model/types.d.ts +98 -0
- package/dist/model/types.js +2 -0
- package/dist/model/validate.d.ts +30 -0
- package/dist/model/validate.js +215 -0
- package/dist/run.d.ts +4 -0
- package/dist/run.js +506 -0
- package/dist/scan/project-scan.d.ts +77 -0
- package/dist/scan/project-scan.js +226 -0
- package/dist/scan/source.d.ts +60 -0
- package/dist/scan/source.js +274 -0
- package/dist/templates/aggregate.d.ts +51 -0
- package/dist/templates/aggregate.js +407 -0
- package/dist/templates/building-blocks.d.ts +30 -0
- package/dist/templates/building-blocks.js +155 -0
- package/dist/templates/code.d.ts +14 -0
- package/dist/templates/code.js +51 -0
- package/dist/templates/command.d.ts +47 -0
- package/dist/templates/command.js +376 -0
- package/dist/templates/context.d.ts +16 -0
- package/dist/templates/context.js +43 -0
- package/dist/templates/field-code.d.ts +47 -0
- package/dist/templates/field-code.js +227 -0
- package/dist/templates/postgres.d.ts +25 -0
- package/dist/templates/postgres.js +113 -0
- package/dist/templates/project.d.ts +20 -0
- package/dist/templates/project.js +153 -0
- package/dist/templates/shared-kernel.d.ts +6 -0
- package/dist/templates/shared-kernel.js +44 -0
- package/package.json +58 -4
|
@@ -0,0 +1,226 @@
|
|
|
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.parseGlossary = parseGlossary;
|
|
37
|
+
exports.scanProject = scanProject;
|
|
38
|
+
const fs = __importStar(require("node:fs"));
|
|
39
|
+
const path = __importStar(require("node:path"));
|
|
40
|
+
const names_1 = require("../core/names");
|
|
41
|
+
const project_1 = require("../core/project");
|
|
42
|
+
const source_1 = require("./source");
|
|
43
|
+
const read = (file) => (fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null);
|
|
44
|
+
const rel = (project, file) => path.relative(project.root, file).split(path.sep).join('/');
|
|
45
|
+
function listTs(dir, filter = () => true) {
|
|
46
|
+
if (!fs.existsSync(dir))
|
|
47
|
+
return [];
|
|
48
|
+
return fs
|
|
49
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
50
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts'))
|
|
51
|
+
.map((entry) => entry.name)
|
|
52
|
+
.filter((name) => !name.endsWith('.spec.ts') && !name.endsWith('.test.ts') && name !== 'index.ts')
|
|
53
|
+
.filter(filter)
|
|
54
|
+
.map((name) => path.join(dir, name));
|
|
55
|
+
}
|
|
56
|
+
function parseGlossary(source) {
|
|
57
|
+
const terms = [];
|
|
58
|
+
for (const line of source.split('\n')) {
|
|
59
|
+
const match = /^\|\s*\*\*([^*|]+)\*\*\s*\|\s*(.*?)\s*\|\s*$/.exec(line.trim());
|
|
60
|
+
if (match)
|
|
61
|
+
terms.push({ term: match[1].trim(), meaning: match[2].trim() });
|
|
62
|
+
}
|
|
63
|
+
return terms;
|
|
64
|
+
}
|
|
65
|
+
/** Fields of a command, from its request parser (or its use-case input when there is no body). */
|
|
66
|
+
function commandParams(contextDir, command, aggregateKebab) {
|
|
67
|
+
const base = `${(0, names_1.namesFromWords)((0, names_1.splitWords)(command)).kebab}-${aggregateKebab}`;
|
|
68
|
+
const useCase = read(path.join(contextDir, 'application', `${base}.use-case.ts`));
|
|
69
|
+
if (!useCase)
|
|
70
|
+
return [];
|
|
71
|
+
const inputName = /export interface (\w+Input) \{/.exec(useCase)?.[1];
|
|
72
|
+
if (!inputName)
|
|
73
|
+
return [];
|
|
74
|
+
const members = (0, source_1.interfaceMembers)(useCase, inputName) ?? [];
|
|
75
|
+
const request = read(path.join(contextDir, 'infrastructure/http', `${base}.request.ts`)) ?? '';
|
|
76
|
+
const fields = (0, source_1.membersToFields)(members, useCase);
|
|
77
|
+
for (const field of fields) {
|
|
78
|
+
if (field.type === 'number' && new RegExp(`'${field.names.camel}', asInteger\\)`).test(request))
|
|
79
|
+
field.type = 'integer';
|
|
80
|
+
}
|
|
81
|
+
return fields;
|
|
82
|
+
}
|
|
83
|
+
function routerRoutes(source) {
|
|
84
|
+
const routes = [];
|
|
85
|
+
const pattern = /router\.(get|post|put|patch|delete)\(\s*'([^']*)'/g;
|
|
86
|
+
const matches = [...source.matchAll(pattern)];
|
|
87
|
+
matches.forEach((match, index) => {
|
|
88
|
+
const end = index + 1 < matches.length ? matches[index + 1].index : source.length;
|
|
89
|
+
const block = source.slice(match.index, end);
|
|
90
|
+
const useCase = /useCases\.(\w+)\.execute/.exec(block)?.[1] ?? null;
|
|
91
|
+
routes.push({ method: match[1].toUpperCase(), path: match[2], useCase });
|
|
92
|
+
});
|
|
93
|
+
return routes;
|
|
94
|
+
}
|
|
95
|
+
function scanAggregate(project, contextDir, moduleSource, kebab) {
|
|
96
|
+
const names = (0, names_1.namesFromWords)((0, names_1.splitWords)(kebab));
|
|
97
|
+
const file = path.join(contextDir, 'domain', kebab, `${kebab}.ts`);
|
|
98
|
+
const source = read(file);
|
|
99
|
+
if (!source)
|
|
100
|
+
return null;
|
|
101
|
+
const shape = (0, source_1.readAggregate)(source, names.pascal);
|
|
102
|
+
if (!shape)
|
|
103
|
+
return null;
|
|
104
|
+
const state = shape.fields.find((field) => field.managed) ?? null;
|
|
105
|
+
const initial = state ? (new RegExp(`${state.names.camel}: '([^']+)',\\s*\\n\\s*createdAt: now`).exec(source)?.[1] ?? state.values[0]) : null;
|
|
106
|
+
const plural = (0, names_1.pluralize)(names).pascal;
|
|
107
|
+
const route = new RegExp(`router\\.use\\(\\s*'([^']+)',\\s*create${plural}Router\\(`).exec(moduleSource)?.[1] ?? null;
|
|
108
|
+
const routerSource = read(path.join(contextDir, 'infrastructure/http', `${(0, names_1.pluralize)(names).kebab}.router.ts`)) ?? '';
|
|
109
|
+
const routes = routerRoutes(routerSource);
|
|
110
|
+
const has = (method, routePath) => routes.some((item) => item.method === method && item.path === routePath);
|
|
111
|
+
const behaviours = (0, source_1.methodBehaviours)(source, state?.names.camel ?? null).filter((method) => !['update', 'delete', 'create', 'rehydrate'].includes(method.name));
|
|
112
|
+
const commands = behaviours.map((method) => ({
|
|
113
|
+
name: method.name,
|
|
114
|
+
from: method.from,
|
|
115
|
+
to: method.to,
|
|
116
|
+
events: method.events,
|
|
117
|
+
route: routes.find((item) => item.useCase === method.name)?.path ?? null,
|
|
118
|
+
params: commandParams(contextDir, method.name, kebab),
|
|
119
|
+
}));
|
|
120
|
+
const entities = listTs(path.join(contextDir, 'domain', kebab), (name) => name !== `${kebab}.ts`)
|
|
121
|
+
.flatMap((entityFile) => (0, source_1.exportedClasses)(read(entityFile) ?? ''))
|
|
122
|
+
.filter((item) => item.base === 'Entity')
|
|
123
|
+
.map((item) => item.name);
|
|
124
|
+
return {
|
|
125
|
+
name: names.pascal,
|
|
126
|
+
kebab,
|
|
127
|
+
file: rel(project, file),
|
|
128
|
+
fields: shape.fields,
|
|
129
|
+
stateField: state?.names.camel ?? null,
|
|
130
|
+
initialState: initial,
|
|
131
|
+
route,
|
|
132
|
+
commands,
|
|
133
|
+
entities,
|
|
134
|
+
crud: {
|
|
135
|
+
create: has('POST', '/'),
|
|
136
|
+
list: has('GET', '/'),
|
|
137
|
+
get: has('GET', '/:id'),
|
|
138
|
+
update: has('PATCH', '/:id'),
|
|
139
|
+
delete: has('DELETE', '/:id'),
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
function scanHandlers(moduleSource, contextName) {
|
|
144
|
+
const imports = new Map();
|
|
145
|
+
for (const match of moduleSource.matchAll(/import \{ (\w+) \} from '([^']+)'/g))
|
|
146
|
+
imports.set(match[1], match[2]);
|
|
147
|
+
const variables = new Map();
|
|
148
|
+
for (const match of moduleSource.matchAll(/const (\w+) = new (\w+)\(/g))
|
|
149
|
+
variables.set(match[1], match[2]);
|
|
150
|
+
const handlers = [];
|
|
151
|
+
for (const match of moduleSource.matchAll(/subscribe\(\s*(\w+),\s*\(?\w*\)?\s*=>\s*(\w+)\.handle\(/g)) {
|
|
152
|
+
const event = match[1];
|
|
153
|
+
const from = imports.get(event) ?? '';
|
|
154
|
+
let eventContext = null;
|
|
155
|
+
const cross = /^\.\.\/([^/]+)\//.exec(from);
|
|
156
|
+
if (cross)
|
|
157
|
+
eventContext = cross[1];
|
|
158
|
+
else if (from.startsWith('./'))
|
|
159
|
+
eventContext = contextName;
|
|
160
|
+
handlers.push({ className: variables.get(match[2]) ?? match[2], event, eventContext });
|
|
161
|
+
}
|
|
162
|
+
return handlers;
|
|
163
|
+
}
|
|
164
|
+
/** Reads the whole project. Never throws on unexpected code: what it cannot read is left out. */
|
|
165
|
+
function scanProject(project) {
|
|
166
|
+
const pkg = (0, project_1.readJson)(path.join(project.root, 'package.json')) ?? {};
|
|
167
|
+
const registry = read(path.join(project.src, 'contexts.ts')) ?? '';
|
|
168
|
+
const app = read(path.join(project.src, 'app.ts')) ?? '';
|
|
169
|
+
const basePath = /app\.use\(\s*'([^']+)',\s*createContextsRouter\(/.exec(app)?.[1] ?? '';
|
|
170
|
+
const contexts = [];
|
|
171
|
+
for (const kebab of (0, project_1.findContexts)(project)) {
|
|
172
|
+
const names = (0, names_1.namesFromWords)((0, names_1.splitWords)(kebab));
|
|
173
|
+
const paths = (0, project_1.contextPaths)(project, names);
|
|
174
|
+
const moduleSource = read(`${paths.module}.ts`) ?? '';
|
|
175
|
+
const prefix = new RegExp(`router\\.use\\(\\s*'([^']+)',\\s*create${names.pascal}Module\\(`).exec(registry)?.[1] ?? '';
|
|
176
|
+
const aggregateDirs = fs.existsSync(paths.domain)
|
|
177
|
+
? fs
|
|
178
|
+
.readdirSync(paths.domain, { withFileTypes: true })
|
|
179
|
+
.filter((entry) => entry.isDirectory() && !['events', 'ports', 'services', 'value-objects'].includes(entry.name))
|
|
180
|
+
.map((entry) => entry.name)
|
|
181
|
+
.sort()
|
|
182
|
+
: [];
|
|
183
|
+
const aggregates = aggregateDirs
|
|
184
|
+
.map((dir) => scanAggregate(project, paths.dir, moduleSource, dir))
|
|
185
|
+
.filter((item) => item !== null);
|
|
186
|
+
const events = listTs(paths.events)
|
|
187
|
+
.map((file) => {
|
|
188
|
+
const source = read(file) ?? '';
|
|
189
|
+
const cls = (0, source_1.exportedClasses)(source).find((item) => item.base === 'DomainEvent');
|
|
190
|
+
if (!cls)
|
|
191
|
+
return null;
|
|
192
|
+
const members = (0, source_1.readonlyMembers)(source).filter((member) => member.name !== 'aggregateId');
|
|
193
|
+
return { name: cls.name, file: rel(project, file), fields: (0, source_1.membersToFields)(members, source) };
|
|
194
|
+
})
|
|
195
|
+
.filter((item) => item !== null)
|
|
196
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
197
|
+
const valueObjects = listTs(paths.valueObjects)
|
|
198
|
+
.flatMap((file) => (0, source_1.exportedClasses)(read(file) ?? ''))
|
|
199
|
+
.filter((item) => item.base === 'ValueObject')
|
|
200
|
+
.map((item) => item.name);
|
|
201
|
+
const services = listTs(paths.services)
|
|
202
|
+
.flatMap((file) => (0, source_1.exportedClasses)(read(file) ?? ''))
|
|
203
|
+
.map((item) => item.name);
|
|
204
|
+
const glossarySource = read(paths.glossary);
|
|
205
|
+
contexts.push({
|
|
206
|
+
name: kebab,
|
|
207
|
+
pascal: names.pascal,
|
|
208
|
+
dir: rel(project, paths.dir),
|
|
209
|
+
prefix,
|
|
210
|
+
aggregates,
|
|
211
|
+
events,
|
|
212
|
+
valueObjects,
|
|
213
|
+
services,
|
|
214
|
+
handlers: scanHandlers(moduleSource, kebab),
|
|
215
|
+
glossary: { file: glossarySource === null ? null : rel(project, paths.glossary), terms: glossarySource ? parseGlossary(glossarySource) : [] },
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
name: pkg.name ?? path.basename(project.root),
|
|
220
|
+
version: pkg.version ?? '0.0.0',
|
|
221
|
+
root: project.root,
|
|
222
|
+
src: rel(project, project.src) || '.',
|
|
223
|
+
basePath,
|
|
224
|
+
contexts,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { DefaultValue, Field } from '../core/fields';
|
|
2
|
+
/**
|
|
3
|
+
* Readers for the code ddd-express generates. They use the conventions of the generated files
|
|
4
|
+
* (interfaces, Guard calls, markers) and degrade gracefully when the code was edited by hand.
|
|
5
|
+
*/
|
|
6
|
+
/** Lines of `export interface <name> { ... }`, or null. */
|
|
7
|
+
export declare function interfaceBody(source: string, name: string): string[] | null;
|
|
8
|
+
export interface Member {
|
|
9
|
+
name: string;
|
|
10
|
+
optional: boolean;
|
|
11
|
+
type: string;
|
|
12
|
+
}
|
|
13
|
+
/** Members of an interface: "name?: type;" lines (comments skipped). */
|
|
14
|
+
export declare function interfaceMembers(source: string, name: string): Member[] | null;
|
|
15
|
+
/** `export const NAME = ['a', 'b'] as const;` → { NAME: [a, b] } */
|
|
16
|
+
export declare function enumConsts(source: string): Record<string, string[]>;
|
|
17
|
+
/** `export type Name = (typeof CONST)[number];` → { Name: CONST } */
|
|
18
|
+
export declare function enumTypes(source: string): Record<string, string>;
|
|
19
|
+
/** The Guard method used for each field in a `validate` body: { clientId: 'text', ... }. */
|
|
20
|
+
export declare function guardKinds(source: string): Record<string, string>;
|
|
21
|
+
/** Defaults written as "input.x ?? <value>" in a validate body. */
|
|
22
|
+
export declare function defaults(source: string): Record<string, DefaultValue>;
|
|
23
|
+
/** Turns interface members into fields, resolving enum type aliases and integer guards. */
|
|
24
|
+
export declare function membersToFields(members: Member[], source: string, options?: {
|
|
25
|
+
inputNames?: Set<string>;
|
|
26
|
+
}): Field[];
|
|
27
|
+
export interface AggregateShapeFromCode {
|
|
28
|
+
className: string;
|
|
29
|
+
fields: Field[];
|
|
30
|
+
methods: string[];
|
|
31
|
+
hasEnsureState: boolean;
|
|
32
|
+
}
|
|
33
|
+
/** Reads the fields and behaviour methods of a generated aggregate. Null when it does not look like one. */
|
|
34
|
+
export declare function readAggregate(source: string, pascal: string): AggregateShapeFromCode | null;
|
|
35
|
+
/** Public method names of the first class in the file (2-space indented members). */
|
|
36
|
+
export declare function classMethods(source: string): string[];
|
|
37
|
+
/** Behaviour of an aggregate method: the states it accepts, the state it sets, the events it records. */
|
|
38
|
+
export interface MethodBehaviour {
|
|
39
|
+
name: string;
|
|
40
|
+
from: string[];
|
|
41
|
+
to: string | null;
|
|
42
|
+
events: string[];
|
|
43
|
+
}
|
|
44
|
+
export declare function methodBehaviours(source: string, stateField: string | null): MethodBehaviour[];
|
|
45
|
+
/** Classes exported by a file: `export class Name extends Base`. */
|
|
46
|
+
export declare function exportedClasses(source: string): {
|
|
47
|
+
name: string;
|
|
48
|
+
base: string | null;
|
|
49
|
+
}[];
|
|
50
|
+
/** Readonly members of a class (event payloads): "readonly name: type;" */
|
|
51
|
+
export declare function readonlyMembers(source: string): Member[];
|
|
52
|
+
/** Removes comments but keeps line numbers (for import scanning). */
|
|
53
|
+
export declare function stripComments(source: string): string;
|
|
54
|
+
export interface ImportRef {
|
|
55
|
+
specifier: string;
|
|
56
|
+
line: number;
|
|
57
|
+
typeOnly: boolean;
|
|
58
|
+
}
|
|
59
|
+
/** import/export-from/require/dynamic import specifiers, with their line numbers. */
|
|
60
|
+
export declare function importsOf(source: string): ImportRef[];
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.interfaceBody = interfaceBody;
|
|
4
|
+
exports.interfaceMembers = interfaceMembers;
|
|
5
|
+
exports.enumConsts = enumConsts;
|
|
6
|
+
exports.enumTypes = enumTypes;
|
|
7
|
+
exports.guardKinds = guardKinds;
|
|
8
|
+
exports.defaults = defaults;
|
|
9
|
+
exports.membersToFields = membersToFields;
|
|
10
|
+
exports.readAggregate = readAggregate;
|
|
11
|
+
exports.classMethods = classMethods;
|
|
12
|
+
exports.methodBehaviours = methodBehaviours;
|
|
13
|
+
exports.exportedClasses = exportedClasses;
|
|
14
|
+
exports.readonlyMembers = readonlyMembers;
|
|
15
|
+
exports.stripComments = stripComments;
|
|
16
|
+
exports.importsOf = importsOf;
|
|
17
|
+
const names_1 = require("../core/names");
|
|
18
|
+
/**
|
|
19
|
+
* Readers for the code ddd-express generates. They use the conventions of the generated files
|
|
20
|
+
* (interfaces, Guard calls, markers) and degrade gracefully when the code was edited by hand.
|
|
21
|
+
*/
|
|
22
|
+
/** Lines of `export interface <name> { ... }`, or null. */
|
|
23
|
+
function interfaceBody(source, name) {
|
|
24
|
+
const start = source.search(new RegExp(`export interface ${name}\\s*\\{`));
|
|
25
|
+
if (start === -1)
|
|
26
|
+
return null;
|
|
27
|
+
const open = source.indexOf('{', start);
|
|
28
|
+
let depth = 0;
|
|
29
|
+
for (let i = open; i < source.length; i += 1) {
|
|
30
|
+
if (source[i] === '{')
|
|
31
|
+
depth += 1;
|
|
32
|
+
if (source[i] === '}') {
|
|
33
|
+
depth -= 1;
|
|
34
|
+
if (depth === 0)
|
|
35
|
+
return source.slice(open + 1, i).split('\n');
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
/** Members of an interface: "name?: type;" lines (comments skipped). */
|
|
41
|
+
function interfaceMembers(source, name) {
|
|
42
|
+
const body = interfaceBody(source, name);
|
|
43
|
+
if (!body)
|
|
44
|
+
return null;
|
|
45
|
+
const members = [];
|
|
46
|
+
for (const raw of body) {
|
|
47
|
+
const line = raw.trim();
|
|
48
|
+
const match = /^(?:readonly\s+)?([A-Za-z_$][\w$]*)(\?)?:\s*(.+?);?$/.exec(line);
|
|
49
|
+
if (match)
|
|
50
|
+
members.push({ name: match[1], optional: Boolean(match[2]), type: match[3].replace(/;$/, '').trim() });
|
|
51
|
+
}
|
|
52
|
+
return members;
|
|
53
|
+
}
|
|
54
|
+
/** `export const NAME = ['a', 'b'] as const;` → { NAME: [a, b] } */
|
|
55
|
+
function enumConsts(source) {
|
|
56
|
+
const out = {};
|
|
57
|
+
for (const match of source.matchAll(/export const (\w+) = \[([^\]]*)\] as const;/g)) {
|
|
58
|
+
out[match[1]] = [...match[2].matchAll(/'([^']*)'/g)].map((value) => value[1]);
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
/** `export type Name = (typeof CONST)[number];` → { Name: CONST } */
|
|
63
|
+
function enumTypes(source) {
|
|
64
|
+
const out = {};
|
|
65
|
+
for (const match of source.matchAll(/export type (\w+) = \(typeof (\w+)\)\[number\];/g))
|
|
66
|
+
out[match[1]] = match[2];
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/** The Guard method used for each field in a `validate` body: { clientId: 'text', ... }. */
|
|
70
|
+
function guardKinds(source) {
|
|
71
|
+
const out = {};
|
|
72
|
+
for (const match of source.matchAll(/(\w+): Guard\.optional\([^,]+, \(value\) => Guard\.(\w+)\(/g))
|
|
73
|
+
out[match[1]] = match[2];
|
|
74
|
+
for (const match of source.matchAll(/(\w+): Guard\.(text|number|integer|boolean|date|oneOf)\(/g)) {
|
|
75
|
+
if (!out[match[1]])
|
|
76
|
+
out[match[1]] = match[2];
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
/** Defaults written as "input.x ?? <value>" in a validate body. */
|
|
81
|
+
function defaults(source) {
|
|
82
|
+
const out = {};
|
|
83
|
+
for (const match of source.matchAll(/input\.(\w+) \?\? ([^,)]+)[,)]/g)) {
|
|
84
|
+
const raw = match[2].trim();
|
|
85
|
+
if (raw === 'now')
|
|
86
|
+
out[match[1]] = { now: true };
|
|
87
|
+
else if (raw === 'true' || raw === 'false')
|
|
88
|
+
out[match[1]] = raw === 'true';
|
|
89
|
+
else if (/^'.*'$/.test(raw))
|
|
90
|
+
out[match[1]] = raw.slice(1, -1);
|
|
91
|
+
else if (raw !== '' && Number.isFinite(Number(raw)))
|
|
92
|
+
out[match[1]] = Number(raw);
|
|
93
|
+
}
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
const scalar = (type) => {
|
|
97
|
+
switch (type) {
|
|
98
|
+
case 'string':
|
|
99
|
+
return 'string';
|
|
100
|
+
case 'number':
|
|
101
|
+
return 'number';
|
|
102
|
+
case 'boolean':
|
|
103
|
+
return 'boolean';
|
|
104
|
+
case 'Date':
|
|
105
|
+
return 'date';
|
|
106
|
+
default:
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
/** Turns interface members into fields, resolving enum type aliases and integer guards. */
|
|
111
|
+
function membersToFields(members, source, options = {}) {
|
|
112
|
+
const consts = enumConsts(source);
|
|
113
|
+
const types = enumTypes(source);
|
|
114
|
+
const guards = guardKinds(source);
|
|
115
|
+
const fieldDefaults = defaults(source);
|
|
116
|
+
const fields = [];
|
|
117
|
+
for (const member of members) {
|
|
118
|
+
if (member.name === 'createdAt' || member.name === 'updatedAt')
|
|
119
|
+
continue;
|
|
120
|
+
const nullable = /\|\s*null$/.test(member.type);
|
|
121
|
+
const base = member.type.replace(/\|\s*null$/, '').trim();
|
|
122
|
+
let type = scalar(base);
|
|
123
|
+
let values = [];
|
|
124
|
+
if (!type) {
|
|
125
|
+
const inline = [...base.matchAll(/'([^']*)'/g)].map((value) => value[1]);
|
|
126
|
+
if (types[base] && consts[types[base]]) {
|
|
127
|
+
type = 'enum';
|
|
128
|
+
values = consts[types[base]];
|
|
129
|
+
}
|
|
130
|
+
else if (inline.length > 0 && /^'[^']*'(\s*\|\s*'[^']*')*$/.test(base)) {
|
|
131
|
+
type = 'enum';
|
|
132
|
+
values = inline;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
continue; // a type the generator does not know (entities, value objects, arrays...)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (type === 'number' && guards[member.name] === 'integer')
|
|
139
|
+
type = 'integer';
|
|
140
|
+
const field = { names: (0, names_1.namesFromWords)((0, names_1.splitWords)(member.name)), type, optional: nullable || member.optional, values };
|
|
141
|
+
// the camel name must stay exactly the member name
|
|
142
|
+
field.names = { ...field.names, camel: member.name };
|
|
143
|
+
if (fieldDefaults[member.name] !== undefined)
|
|
144
|
+
field.defaultValue = fieldDefaults[member.name];
|
|
145
|
+
if (options.inputNames && !options.inputNames.has(member.name))
|
|
146
|
+
field.managed = true;
|
|
147
|
+
fields.push(field);
|
|
148
|
+
}
|
|
149
|
+
return fields;
|
|
150
|
+
}
|
|
151
|
+
/** Reads the fields and behaviour methods of a generated aggregate. Null when it does not look like one. */
|
|
152
|
+
function readAggregate(source, pascal) {
|
|
153
|
+
if (!new RegExp(`export class ${pascal} extends AggregateRoot`).test(source))
|
|
154
|
+
return null;
|
|
155
|
+
const props = interfaceMembers(source, `${pascal}Props`);
|
|
156
|
+
if (!props)
|
|
157
|
+
return null;
|
|
158
|
+
const create = interfaceMembers(source, `Create${pascal}Props`);
|
|
159
|
+
const inputNames = new Set((create ?? props).map((member) => member.name));
|
|
160
|
+
const fields = membersToFields(props, source, { inputNames });
|
|
161
|
+
return { className: pascal, fields, methods: classMethods(source), hasEnsureState: /private ensureState\(/.test(source) };
|
|
162
|
+
}
|
|
163
|
+
/** Public method names of the first class in the file (2-space indented members). */
|
|
164
|
+
function classMethods(source) {
|
|
165
|
+
const names = new Set();
|
|
166
|
+
for (const match of source.matchAll(/^ {2}(?!private |static |get |set |protected |readonly )(?:async )?([A-Za-z_$][\w$]*)\(/gm)) {
|
|
167
|
+
if (match[1] !== 'constructor')
|
|
168
|
+
names.add(match[1]);
|
|
169
|
+
}
|
|
170
|
+
return [...names];
|
|
171
|
+
}
|
|
172
|
+
function methodBehaviours(source, stateField) {
|
|
173
|
+
const out = [];
|
|
174
|
+
const lines = source.split('\n');
|
|
175
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
176
|
+
const head = /^ {2}(?!private |static |get |set |protected |readonly )([A-Za-z_$][\w$]*)\(/.exec(lines[i]);
|
|
177
|
+
if (!head || head[1] === 'constructor')
|
|
178
|
+
continue;
|
|
179
|
+
let end = i + 1;
|
|
180
|
+
while (end < lines.length && !/^ {2}\}/.test(lines[end]))
|
|
181
|
+
end += 1;
|
|
182
|
+
const body = lines.slice(i, end + 1).join('\n');
|
|
183
|
+
const from = /this\.ensureState\(\[([^\]]*)\]/.exec(body);
|
|
184
|
+
const to = stateField ? new RegExp(`${stateField}: '([^']+)'`).exec(body) : null;
|
|
185
|
+
out.push({
|
|
186
|
+
name: head[1],
|
|
187
|
+
from: from ? [...from[1].matchAll(/'([^']*)'/g)].map((value) => value[1]) : [],
|
|
188
|
+
to: to ? to[1] : null,
|
|
189
|
+
events: [...body.matchAll(/this\.record\(new (\w+)\(/g)].map((match) => match[1]),
|
|
190
|
+
});
|
|
191
|
+
i = end;
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
/** Classes exported by a file: `export class Name extends Base`. */
|
|
196
|
+
function exportedClasses(source) {
|
|
197
|
+
return [...source.matchAll(/export (?:abstract )?class (\w+)(?:\s+extends\s+(\w+))?/g)].map((match) => ({
|
|
198
|
+
name: match[1],
|
|
199
|
+
base: match[2] ?? null,
|
|
200
|
+
}));
|
|
201
|
+
}
|
|
202
|
+
/** Readonly members of a class (event payloads): "readonly name: type;" */
|
|
203
|
+
function readonlyMembers(source) {
|
|
204
|
+
return [...source.matchAll(/^ {2}readonly (\w+)(\?)?: ([^;]+);/gm)].map((match) => ({
|
|
205
|
+
name: match[1],
|
|
206
|
+
optional: Boolean(match[2]),
|
|
207
|
+
type: match[3].trim(),
|
|
208
|
+
}));
|
|
209
|
+
}
|
|
210
|
+
/** Removes comments but keeps line numbers (for import scanning). */
|
|
211
|
+
function stripComments(source) {
|
|
212
|
+
let out = '';
|
|
213
|
+
let i = 0;
|
|
214
|
+
let quote = null;
|
|
215
|
+
while (i < source.length) {
|
|
216
|
+
const char = source[i];
|
|
217
|
+
const next = source[i + 1];
|
|
218
|
+
if (quote) {
|
|
219
|
+
out += char;
|
|
220
|
+
if (char === '\\') {
|
|
221
|
+
out += next ?? '';
|
|
222
|
+
i += 2;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (char === quote)
|
|
226
|
+
quote = null;
|
|
227
|
+
i += 1;
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if (char === '"' || char === "'" || char === '`') {
|
|
231
|
+
quote = char;
|
|
232
|
+
out += char;
|
|
233
|
+
i += 1;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (char === '/' && next === '/') {
|
|
237
|
+
while (i < source.length && source[i] !== '\n')
|
|
238
|
+
i += 1;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (char === '/' && next === '*') {
|
|
242
|
+
i += 2;
|
|
243
|
+
while (i < source.length && !(source[i] === '*' && source[i + 1] === '/')) {
|
|
244
|
+
if (source[i] === '\n')
|
|
245
|
+
out += '\n';
|
|
246
|
+
i += 1;
|
|
247
|
+
}
|
|
248
|
+
i += 2;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
out += char;
|
|
252
|
+
i += 1;
|
|
253
|
+
}
|
|
254
|
+
return out;
|
|
255
|
+
}
|
|
256
|
+
/** import/export-from/require/dynamic import specifiers, with their line numbers. */
|
|
257
|
+
function importsOf(source) {
|
|
258
|
+
const code = stripComments(source);
|
|
259
|
+
const out = [];
|
|
260
|
+
const lineAt = (index) => code.slice(0, index).split('\n').length;
|
|
261
|
+
const patterns = [
|
|
262
|
+
/\bimport\s+(type\s+)?[^'"`;]*?\bfrom\s*['"]([^'"]+)['"]/g,
|
|
263
|
+
/\bexport\s+(type\s+)?[^'"`;]*?\bfrom\s*['"]([^'"]+)['"]/g,
|
|
264
|
+
/\bimport\s*()['"]([^'"]+)['"]/g,
|
|
265
|
+
/\brequire\(\s*()['"]([^'"]+)['"]\s*\)/g,
|
|
266
|
+
/\bimport\(\s*()['"]([^'"]+)['"]\s*\)/g,
|
|
267
|
+
];
|
|
268
|
+
for (const pattern of patterns) {
|
|
269
|
+
for (const match of code.matchAll(pattern)) {
|
|
270
|
+
out.push({ specifier: match[2], line: lineAt(match.index ?? 0), typeOnly: Boolean(match[1]) });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
return out.sort((a, b) => a.line - b.line);
|
|
274
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type Field } from '../core/fields';
|
|
2
|
+
import type { AggregatePaths, ContextPaths, Project } from '../core/project';
|
|
3
|
+
import type { CommandSpec } from '../model/types';
|
|
4
|
+
import { type CommandModel } from './command';
|
|
5
|
+
/** Everything the templates of one aggregate need. */
|
|
6
|
+
export interface AggregateModel {
|
|
7
|
+
project: Project;
|
|
8
|
+
context: ContextPaths;
|
|
9
|
+
paths: AggregatePaths;
|
|
10
|
+
/** All fields; the state-machine field (if any) is `managed`. */
|
|
11
|
+
fields: Field[];
|
|
12
|
+
commands: CommandSpec[];
|
|
13
|
+
/** Mount path of the HTTP routes, e.g. "/visits". */
|
|
14
|
+
route: string;
|
|
15
|
+
}
|
|
16
|
+
/** Field names the aggregate manages itself (they cannot be declared). */
|
|
17
|
+
export declare const AGGREGATE_RESERVED_FIELDS: string[];
|
|
18
|
+
export declare const eventClass: (m: {
|
|
19
|
+
paths: AggregatePaths;
|
|
20
|
+
}, suffix: 'Created' | 'Updated' | 'Deleted') => string;
|
|
21
|
+
export declare function commandModels(m: AggregateModel): CommandModel[];
|
|
22
|
+
export declare function stateTypeName(m: {
|
|
23
|
+
paths: AggregatePaths;
|
|
24
|
+
}, state: Field): string;
|
|
25
|
+
export declare function aggregateFile(m: AggregateModel): string;
|
|
26
|
+
export declare function articleFor(word: string): string;
|
|
27
|
+
export declare function aggregateIndex(m: AggregateModel): string;
|
|
28
|
+
export declare function aggregateSpec(m: AggregateModel): string;
|
|
29
|
+
export interface EventMember {
|
|
30
|
+
name: string;
|
|
31
|
+
type: string;
|
|
32
|
+
}
|
|
33
|
+
/** A Domain Event class. Used for the aggregate's own events, command events and `ddd-express event`. */
|
|
34
|
+
export declare function eventFile(project: Project, file: string, className: string, contextPascal: string, description: string[], members: EventMember[]): string;
|
|
35
|
+
export declare function aggregateEvents(m: AggregateModel): Map<string, string>;
|
|
36
|
+
export declare function portFile(m: AggregateModel): string;
|
|
37
|
+
export declare function dtoFile(m: AggregateModel): string;
|
|
38
|
+
export declare function useCaseFiles(m: AggregateModel): Map<string, string>;
|
|
39
|
+
/** application/<aggregate>.use-cases.ts — every use case of the aggregate, built in one place. */
|
|
40
|
+
export declare function facadeFile(m: AggregateModel): string;
|
|
41
|
+
export declare function useCasesSpec(m: AggregateModel): string;
|
|
42
|
+
export declare function mapperFile(m: AggregateModel): string;
|
|
43
|
+
export declare function repositoryFile(m: AggregateModel): string;
|
|
44
|
+
export declare function requestFile(m: AggregateModel): string;
|
|
45
|
+
export declare function routerFile(m: AggregateModel): string;
|
|
46
|
+
export declare function routerSpec(m: AggregateModel): string;
|
|
47
|
+
export declare function wiringFor(m: AggregateModel): {
|
|
48
|
+
imports: string[];
|
|
49
|
+
block: string;
|
|
50
|
+
key: string;
|
|
51
|
+
};
|