@fougere/core 0.8.2-alpha.0 → 0.8.4-alpha.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 (222) hide show
  1. package/dist/boot/Emissions.d.ts.map +1 -1
  2. package/dist/boot/Emissions.js +3 -3
  3. package/dist/boot/Emissions.js.map +1 -1
  4. package/dist/boot/auth.d.ts +1 -1
  5. package/dist/boot/auth.d.ts.map +1 -1
  6. package/dist/boot/bootstrap.d.ts.map +1 -1
  7. package/dist/boot/bootstrap.js +339 -595
  8. package/dist/boot/bootstrap.js.map +1 -1
  9. package/dist/boot/card.js +1 -1
  10. package/dist/boot/card.js.map +1 -1
  11. package/dist/boot/hosted.d.ts +1 -1
  12. package/dist/boot/hosted.d.ts.map +1 -1
  13. package/dist/boot/install.d.ts +40 -0
  14. package/dist/boot/install.d.ts.map +1 -0
  15. package/dist/boot/install.js +298 -0
  16. package/dist/boot/install.js.map +1 -0
  17. package/dist/boot/ownership.d.ts +1 -1
  18. package/dist/boot/ownership.d.ts.map +1 -1
  19. package/dist/boot/ownership.js +14 -1
  20. package/dist/boot/ownership.js.map +1 -1
  21. package/dist/boot/seed.d.ts +7 -1
  22. package/dist/boot/seed.d.ts.map +1 -1
  23. package/dist/boot/seed.js +7 -2
  24. package/dist/boot/seed.js.map +1 -1
  25. package/dist/boot/statement-drift.d.ts +1 -1
  26. package/dist/boot/statement-drift.d.ts.map +1 -1
  27. package/dist/boot/together.d.ts +1 -1
  28. package/dist/boot/together.d.ts.map +1 -1
  29. package/dist/boot/together.js +1 -1
  30. package/dist/boot/together.js.map +1 -1
  31. package/dist/boot/types.d.ts +2 -2
  32. package/dist/boot/types.d.ts.map +1 -1
  33. package/dist/config-loader.d.ts +1 -1
  34. package/dist/config-loader.d.ts.map +1 -1
  35. package/dist/contract.d.ts +2 -2
  36. package/dist/contract.d.ts.map +1 -1
  37. package/dist/contract.js +1 -1
  38. package/dist/contract.js.map +1 -1
  39. package/dist/conventions.d.ts.map +1 -0
  40. package/dist/conventions.js.map +1 -0
  41. package/dist/crypto/encoding.d.ts +0 -1
  42. package/dist/crypto/encoding.d.ts.map +1 -1
  43. package/dist/crypto/encoding.js +0 -7
  44. package/dist/crypto/encoding.js.map +1 -1
  45. package/dist/declare.js +1 -1
  46. package/dist/declare.js.map +1 -1
  47. package/dist/descriptor/index.d.ts +15 -0
  48. package/dist/descriptor/index.d.ts.map +1 -0
  49. package/dist/descriptor/index.js +14 -0
  50. package/dist/descriptor/index.js.map +1 -0
  51. package/dist/descriptor/surface.d.ts +8 -0
  52. package/dist/descriptor/surface.d.ts.map +1 -0
  53. package/dist/descriptor/surface.js +16 -0
  54. package/dist/descriptor/surface.js.map +1 -0
  55. package/dist/dispatch/HandlerFacade.d.ts +2 -0
  56. package/dist/dispatch/HandlerFacade.d.ts.map +1 -1
  57. package/dist/dispatch/HandlerFacade.js +7 -2
  58. package/dist/dispatch/HandlerFacade.js.map +1 -1
  59. package/dist/dispatch/StorageGuard.d.ts.map +1 -1
  60. package/dist/dispatch/StorageGuard.js +9 -23
  61. package/dist/dispatch/StorageGuard.js.map +1 -1
  62. package/dist/dispatch/presenterArguments.d.ts +7 -1
  63. package/dist/dispatch/presenterArguments.d.ts.map +1 -1
  64. package/dist/dispatch/presenterArguments.js +15 -4
  65. package/dist/dispatch/presenterArguments.js.map +1 -1
  66. package/dist/dispatch/validateInput.d.ts.map +1 -1
  67. package/dist/dispatch/validateInput.js +2 -2
  68. package/dist/dispatch/validateInput.js.map +1 -1
  69. package/dist/effective-operation.d.ts +1 -1
  70. package/dist/effective-operation.d.ts.map +1 -1
  71. package/dist/effective-operation.js +2 -12
  72. package/dist/effective-operation.js.map +1 -1
  73. package/dist/index.d.ts +7 -9
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +4 -2
  76. package/dist/index.js.map +1 -1
  77. package/dist/node.d.ts +2 -12
  78. package/dist/node.d.ts.map +1 -1
  79. package/dist/node.js +2 -12
  80. package/dist/node.js.map +1 -1
  81. package/dist/prefab/crud.d.ts +1 -1
  82. package/dist/prefab/crud.d.ts.map +1 -1
  83. package/dist/prefab/mirror.d.ts +10 -11
  84. package/dist/prefab/mirror.d.ts.map +1 -1
  85. package/dist/prefab/mirror.js +1 -27
  86. package/dist/prefab/mirror.js.map +1 -1
  87. package/dist/prefab/repository.d.ts +1 -1
  88. package/dist/prefab/repository.d.ts.map +1 -1
  89. package/dist/{scan/result.d.ts → scan.d.ts} +2 -2
  90. package/dist/scan.d.ts.map +1 -0
  91. package/dist/scan.js +2 -0
  92. package/dist/scan.js.map +1 -0
  93. package/dist/source.d.ts +1 -1
  94. package/dist/source.d.ts.map +1 -1
  95. package/dist/storage/criterion.d.ts.map +1 -0
  96. package/dist/{criterion.js → storage/criterion.js} +2 -2
  97. package/dist/storage/criterion.js.map +1 -0
  98. package/dist/{storage.d.ts → storage/port.d.ts} +6 -3
  99. package/dist/storage/port.d.ts.map +1 -0
  100. package/dist/{storage.js → storage/port.js} +13 -6
  101. package/dist/storage/port.js.map +1 -0
  102. package/dist/{store.d.ts → storage/store.d.ts} +1 -1
  103. package/dist/storage/store.d.ts.map +1 -0
  104. package/dist/{store.js → storage/store.js} +33 -17
  105. package/dist/storage/store.js.map +1 -0
  106. package/dist/verify.js +1 -1
  107. package/dist/verify.js.map +1 -1
  108. package/dist/wire/emit.d.ts.map +1 -0
  109. package/dist/wire/emit.js.map +1 -0
  110. package/dist/wire/errors.js +2 -2
  111. package/dist/wire/errors.js.map +1 -1
  112. package/package.json +10 -4
  113. package/src/boot/Emissions.ts +3 -3
  114. package/src/boot/auth.ts +1 -1
  115. package/src/boot/bootstrap.ts +386 -674
  116. package/src/boot/card.ts +1 -1
  117. package/src/boot/hosted.ts +1 -1
  118. package/src/boot/install.ts +390 -0
  119. package/src/boot/ownership.ts +17 -2
  120. package/src/boot/seed.ts +18 -3
  121. package/src/boot/statement-drift.ts +1 -1
  122. package/src/boot/together.ts +1 -1
  123. package/src/boot/types.ts +2 -2
  124. package/src/config-loader.ts +1 -1
  125. package/src/contract.ts +2 -2
  126. package/src/crypto/encoding.ts +0 -7
  127. package/src/declare.ts +1 -1
  128. package/src/descriptor/index.ts +15 -0
  129. package/src/descriptor/surface.ts +23 -0
  130. package/src/dispatch/HandlerFacade.ts +9 -2
  131. package/src/dispatch/StorageGuard.ts +8 -21
  132. package/src/dispatch/presenterArguments.ts +21 -9
  133. package/src/dispatch/validateInput.ts +2 -2
  134. package/src/effective-operation.ts +3 -14
  135. package/src/index.ts +10 -9
  136. package/src/node.ts +2 -16
  137. package/src/prefab/crud.ts +1 -1
  138. package/src/prefab/mirror.ts +12 -38
  139. package/src/prefab/repository.ts +1 -1
  140. package/src/{scan/result.ts → scan.ts} +1 -1
  141. package/src/source.ts +1 -1
  142. package/src/{criterion.ts → storage/criterion.ts} +2 -2
  143. package/src/{storage.ts → storage/port.ts} +20 -5
  144. package/src/{store.ts → storage/store.ts} +35 -16
  145. package/src/verify.ts +1 -1
  146. package/src/wire/call.ts +1 -1
  147. package/src/wire/errors.ts +2 -2
  148. package/dist/boot/boot.d.ts +0 -45
  149. package/dist/boot/boot.d.ts.map +0 -1
  150. package/dist/boot/boot.js +0 -63
  151. package/dist/boot/boot.js.map +0 -1
  152. package/dist/criterion.d.ts.map +0 -1
  153. package/dist/criterion.js.map +0 -1
  154. package/dist/declarations.d.ts +0 -29
  155. package/dist/declarations.d.ts.map +0 -1
  156. package/dist/declarations.js +0 -69
  157. package/dist/declarations.js.map +0 -1
  158. package/dist/emit.d.ts.map +0 -1
  159. package/dist/emit.js.map +0 -1
  160. package/dist/imports.d.ts +0 -16
  161. package/dist/imports.d.ts.map +0 -1
  162. package/dist/imports.js +0 -78
  163. package/dist/imports.js.map +0 -1
  164. package/dist/placement.d.ts +0 -25
  165. package/dist/placement.d.ts.map +0 -1
  166. package/dist/placement.js +0 -69
  167. package/dist/placement.js.map +0 -1
  168. package/dist/scan/adapters.d.ts +0 -3
  169. package/dist/scan/adapters.d.ts.map +0 -1
  170. package/dist/scan/adapters.js +0 -25
  171. package/dist/scan/adapters.js.map +0 -1
  172. package/dist/scan/bundling.d.ts +0 -3
  173. package/dist/scan/bundling.d.ts.map +0 -1
  174. package/dist/scan/bundling.js +0 -15
  175. package/dist/scan/bundling.js.map +0 -1
  176. package/dist/scan/contract.d.ts +0 -27
  177. package/dist/scan/contract.d.ts.map +0 -1
  178. package/dist/scan/contract.js +0 -46
  179. package/dist/scan/contract.js.map +0 -1
  180. package/dist/scan/conventions.d.ts.map +0 -1
  181. package/dist/scan/conventions.js.map +0 -1
  182. package/dist/scan/emit.d.ts +0 -10
  183. package/dist/scan/emit.d.ts.map +0 -1
  184. package/dist/scan/emit.js +0 -144
  185. package/dist/scan/emit.js.map +0 -1
  186. package/dist/scan/handler-parser.d.ts +0 -26
  187. package/dist/scan/handler-parser.d.ts.map +0 -1
  188. package/dist/scan/handler-parser.js +0 -607
  189. package/dist/scan/handler-parser.js.map +0 -1
  190. package/dist/scan/result.d.ts.map +0 -1
  191. package/dist/scan/result.js +0 -2
  192. package/dist/scan/result.js.map +0 -1
  193. package/dist/scan/scanner.d.ts +0 -12
  194. package/dist/scan/scanner.d.ts.map +0 -1
  195. package/dist/scan/scanner.js +0 -569
  196. package/dist/scan/scanner.js.map +0 -1
  197. package/dist/scan/statement.d.ts +0 -4
  198. package/dist/scan/statement.d.ts.map +0 -1
  199. package/dist/scan/statement.js +0 -135
  200. package/dist/scan/statement.js.map +0 -1
  201. package/dist/storage.d.ts.map +0 -1
  202. package/dist/storage.js.map +0 -1
  203. package/dist/store.d.ts.map +0 -1
  204. package/dist/store.js.map +0 -1
  205. package/src/boot/boot.ts +0 -110
  206. package/src/declarations.ts +0 -102
  207. package/src/imports.ts +0 -94
  208. package/src/placement.ts +0 -86
  209. package/src/scan/adapters.ts +0 -32
  210. package/src/scan/bundling.ts +0 -14
  211. package/src/scan/contract.ts +0 -80
  212. package/src/scan/emit.ts +0 -160
  213. package/src/scan/handler-parser.ts +0 -695
  214. package/src/scan/scanner.ts +0 -694
  215. package/src/scan/statement.ts +0 -159
  216. /package/dist/{scan/conventions.d.ts → conventions.d.ts} +0 -0
  217. /package/dist/{scan/conventions.js → conventions.js} +0 -0
  218. /package/dist/{criterion.d.ts → storage/criterion.d.ts} +0 -0
  219. /package/dist/{emit.d.ts → wire/emit.d.ts} +0 -0
  220. /package/dist/{emit.js → wire/emit.js} +0 -0
  221. /package/src/{scan/conventions.ts → conventions.ts} +0 -0
  222. /package/src/{emit.ts → wire/emit.ts} +0 -0
@@ -1,695 +0,0 @@
1
- /** Handler signature parser — extracts method signatures from handler source files. */
2
- import type { TypeRef, Param, Signature } from '../wire/signature.js';
3
- import type ts from '@typescript/typescript6';
4
- import { readFileSync, existsSync, statSync } from 'node:fs';
5
- import { join, dirname, resolve as resolvePath } from 'node:path';
6
-
7
- /** Lazy-loaded TypeScript module — avoids bundling the 9MB compiler. */
8
- let _ts: typeof ts | undefined;
9
- async function loadTS(): Promise<typeof ts> {
10
- if (!_ts) _ts = (await import('@typescript/typescript6')).default;
11
- return _ts;
12
- }
13
- function getTS(): typeof ts {
14
- if (!_ts) throw new Error('TypeScript not loaded — call an async parse function first');
15
- return _ts;
16
- }
17
-
18
- interface TypeProject {
19
- roots: Set<string>;
20
- options: ts.CompilerOptions;
21
- program: ts.Program;
22
- }
23
-
24
- /** One checked program per project/configuration during a scan. */
25
- const typeProjects = new Map<string, TypeProject>();
26
- const compilerProjects = new Map<string, { key: string; roots: string[]; options: ts.CompilerOptions }>();
27
-
28
- /** What survives a run. */
29
- const sourceFiles = new Map<string, { mtime: number; file: ts.SourceFile }>();
30
- const retained = new Map<string, { host: ts.CompilerHost; program: ts.Program }>();
31
-
32
- export function resetTypePrograms(): void {
33
- typeProjects.clear();
34
- compilerProjects.clear();
35
- }
36
-
37
- /** Drop what runs share. For a test that must prove a cold read. */
38
- export function forgetParsedSources(): void {
39
- sourceFiles.clear();
40
- retained.clear();
41
- }
42
-
43
- function keptHost(key: string, options: ts.CompilerOptions): ts.CompilerHost {
44
- const cached = retained.get(key);
45
- if (cached) return cached.host;
46
- const typescript = getTS();
47
- const base = typescript.createCompilerHost(options);
48
- const host: ts.CompilerHost = {
49
- ...base,
50
- getSourceFile(fileName, languageVersion, onError, shouldCreate) {
51
- const path = resolvePath(fileName);
52
- const mtime = statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? -1;
53
- const cached = sourceFiles.get(path);
54
- if (cached && cached.mtime === mtime) return cached.file;
55
- const file = base.getSourceFile(fileName, languageVersion, onError, shouldCreate);
56
- if (file && mtime >= 0) sourceFiles.set(path, { mtime, file });
57
- return file;
58
- },
59
- };
60
- retained.set(key, { host, program: undefined as unknown as ts.Program });
61
- return host;
62
- }
63
-
64
- function builtProgram(key: string, roots: readonly string[], options: ts.CompilerOptions): ts.Program {
65
- const typescript = getTS();
66
- const host = keptHost(key, options);
67
- const program = typescript.createProgram({
68
- rootNames: [...roots], options, host, oldProgram: retained.get(key)?.program,
69
- });
70
- retained.set(key, { host, program });
71
- return program;
72
- }
73
-
74
- function compilerProjectOf(filePath: string, projectRoot?: string): { key: string; roots: string[]; options: ts.CompilerOptions } {
75
- const typescript = getTS();
76
- const absolute = resolvePath(filePath);
77
- const configPath = typescript.findConfigFile(dirname(absolute), typescript.sys.fileExists);
78
-
79
- if (configPath) {
80
- const key = `${configPath}:${projectRoot ?? ''}`;
81
- const cached = compilerProjects.get(key);
82
- if (cached) return cached;
83
-
84
- const read = typescript.readConfigFile(configPath, typescript.sys.readFile);
85
- if (read.error) throw new Error(typescript.flattenDiagnosticMessageText(read.error.messageText, '\n'));
86
- const parsed = typescript.parseJsonConfigFileContent(read.config, typescript.sys, dirname(configPath));
87
- const configured = {
88
- key,
89
- // Compiler options belong to the project; its entire include glob does not belong
90
- // to this scan. Each declaration inspected below becomes a root and TypeScript
91
- // follows its imports. Seeding the monorepo here made a one-file scan compile it all.
92
- roots: [],
93
- // Handlers may be authored or emitted as JavaScript. They still need to belong to
94
- // the checked program so constructor parsing does not fail on the first cold scan.
95
- options: { ...parsed.options, allowJs: true, noEmit: true },
96
- };
97
- compilerProjects.set(key, configured);
98
- return configured;
99
- }
100
-
101
- const key = projectRoot ?? dirname(absolute);
102
- const cached = compilerProjects.get(key);
103
- if (cached) return cached;
104
- const configured = {
105
- key,
106
- roots: [],
107
- options: {
108
- target: typescript.ScriptTarget.ES2022,
109
- module: typescript.ModuleKind.Node16,
110
- moduleResolution: typescript.ModuleResolutionKind.Node16,
111
- strict: true,
112
- skipLibCheck: true,
113
- allowJs: true,
114
- noEmit: true,
115
- },
116
- };
117
- compilerProjects.set(key, configured);
118
- return configured;
119
- }
120
-
121
- /** Declare every file a run will read, so one program covers it. */
122
- export async function seedTypeProgram(filePaths: readonly string[], projectRoot?: string): Promise<void> {
123
- const typescript = await loadTS();
124
- const grouped = new Map<string, { options: ts.CompilerOptions; paths: string[] }>();
125
-
126
- for (const filePath of filePaths) {
127
- const absolute = resolvePath(filePath);
128
- const configured = compilerProjectOf(absolute, projectRoot);
129
- const group = grouped.get(configured.key) ?? { options: configured.options, paths: [] };
130
- group.paths.push(absolute);
131
- grouped.set(configured.key, group);
132
- }
133
-
134
- for (const [key, { options, paths }] of grouped) {
135
- const roots = new Set(typeProjects.get(key)?.roots ?? []);
136
- for (const path of paths) roots.add(path);
137
- typeProjects.set(key, { roots, options, program: builtProgram(key, [...roots], options) });
138
- }
139
- }
140
-
141
- function checkedSourceOf(filePath: string, projectRoot?: string): { source: ts.SourceFile; checker: ts.TypeChecker } {
142
- const typescript = getTS();
143
- const absolute = resolvePath(filePath);
144
- const configured = compilerProjectOf(absolute, projectRoot);
145
- let project = typeProjects.get(configured.key);
146
-
147
- if (!project) {
148
- // `path.resolve` is variadic, so handing it directly to `map` also passed the
149
- // index and the whole roots array as path segments. A fixture without a warm scan
150
- // cache exposed that first-run-only failure.
151
- const roots = new Set(configured.roots.map((root) => resolvePath(root)));
152
- roots.add(absolute);
153
- const program = builtProgram(configured.key, [...roots], configured.options);
154
- project = { roots, options: configured.options, program };
155
- typeProjects.set(configured.key, project);
156
- } else if (!project.roots.has(absolute)) {
157
- project.roots.add(absolute);
158
- project.program = builtProgram(configured.key, [...project.roots], project.options);
159
- }
160
-
161
- const source = project.program.getSourceFile(absolute);
162
- if (!source) throw new Error(`TypeScript did not include '${absolute}' in its program.`);
163
- return { source, checker: project.program.getTypeChecker() };
164
- }
165
-
166
- /** A file, opened. Five places read and parsed one, each spelling the same two calls. */
167
- function sourceOf(filePath: string): ts.SourceFile {
168
- const ts = getTS();
169
- return ts.createSourceFile(filePath, readFileSync(filePath, 'utf-8'), ts.ScriptTarget.Latest, true);
170
- }
171
-
172
- /** One declared parameter — a constructor's and a method's are read the same way. */
173
- function parsedParam(param: ts.ParameterDeclaration, source: ts.SourceFile, checker?: ts.TypeChecker): Param {
174
- const ts = getTS();
175
- const type = param.type ? parseTypeNode(param.type, source, checker) : { raw: 'unknown', name: 'unknown' };
176
- return {
177
- name: ts.isIdentifier(param.name) ? param.name.text : param.name.getText(source),
178
- type,
179
- // `user?: User` and `user: User | undefined` are the same declaration of
180
- // absence. A type alias may carry the latter, so only the checker can see it.
181
- optional: param.questionToken !== undefined || param.initializer !== undefined || type.undefined === true,
182
- };
183
- }
184
-
185
-
186
- /** Parse a TypeScript type node into a TypeRef. */
187
- function parseTypeNode(node: ts.TypeNode, source: ts.SourceFile, checker?: ts.TypeChecker): TypeRef {
188
- const ts = getTS();
189
- const raw = node.getText(source);
190
-
191
- if (checker) {
192
- // `Fact<T>` is deliberately transparent in TypeScript (`type Fact<T> = T`), because
193
- // a subscriber receives the payload itself. The checker erases that marker, while
194
- // the binding plan still needs it to distinguish a fact from an ordinary body.
195
- if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.text === 'Fact') {
196
- return {
197
- raw,
198
- name: 'Fact',
199
- generics: node.typeArguments?.map((arg) => parseTypeNode(arg, source, checker)) ?? [],
200
- };
201
- }
202
- return parseCheckedType(checker.getTypeFromTypeNode(node), raw, checker);
203
- }
204
-
205
- // Union types — extract nullable, strip Promise
206
- if (ts.isUnionTypeNode(node)) {
207
- const nonNull = node.types.filter(
208
- (t) => !(ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword)
209
- && !(t.kind === ts.SyntaxKind.UndefinedKeyword)
210
- && !(t.kind === ts.SyntaxKind.VoidKeyword)
211
- && !(t.kind === ts.SyntaxKind.NullKeyword),
212
- );
213
- const nullable = node.types.some((t) =>
214
- (ts.isLiteralTypeNode(t) && t.literal.kind === ts.SyntaxKind.NullKeyword)
215
- || t.kind === ts.SyntaxKind.NullKeyword,
216
- );
217
- const undefinable = node.types.some((t) =>
218
- t.kind === ts.SyntaxKind.UndefinedKeyword || t.kind === ts.SyntaxKind.VoidKeyword,
219
- );
220
- if (nonNull.length === 1) {
221
- const inner = parseTypeNode(nonNull[0], source);
222
- return { ...inner, nullable: nullable || inner.nullable, undefined: undefinable || inner.undefined, raw };
223
- }
224
- return { raw, name: raw, nullable, undefined: undefinable };
225
- }
226
-
227
- // Promise<T> — unwrap
228
- if (ts.isTypeReferenceNode(node)) {
229
- const typeName = node.typeName.getText(source);
230
-
231
- if (typeName === 'Promise' && node.typeArguments?.length === 1) {
232
- const inner = parseTypeNode(node.typeArguments[0], source);
233
- return { ...inner, promise: true, raw };
234
- }
235
-
236
- // Array<T>
237
- if (typeName === 'Array' && node.typeArguments?.length === 1) {
238
- const inner = parseTypeNode(node.typeArguments[0], source);
239
- return { ...inner, array: true, arrayDepth: (inner.arrayDepth ?? 0) + 1, raw };
240
- }
241
-
242
- // Generic type: Foo<Bar, Baz>
243
- if (node.typeArguments && node.typeArguments.length > 0) {
244
- const generics = node.typeArguments.map((arg) => parseTypeNode(arg, source));
245
- return { raw, name: typeName, generics };
246
- }
247
-
248
- // Simple type reference: Post, string, etc.
249
- return { raw, name: typeName };
250
- }
251
-
252
- // T[]
253
- if (ts.isArrayTypeNode(node)) {
254
- const inner = parseTypeNode(node.elementType, source);
255
- return { ...inner, array: true, arrayDepth: (inner.arrayDepth ?? 0) + 1, raw };
256
- }
257
-
258
- // Keyword types: string, number, boolean, void
259
- switch (node.kind) {
260
- case ts.SyntaxKind.StringKeyword: return { raw, name: 'string' };
261
- case ts.SyntaxKind.NumberKeyword: return { raw, name: 'number' };
262
- case ts.SyntaxKind.BooleanKeyword: return { raw, name: 'boolean' };
263
- case ts.SyntaxKind.VoidKeyword: return { raw, name: 'void', undefined: true };
264
- case ts.SyntaxKind.UndefinedKeyword: return { raw, name: 'undefined', undefined: true };
265
- case ts.SyntaxKind.NullKeyword: return { raw, name: 'null', nullable: true };
266
- case ts.SyntaxKind.AnyKeyword: return { raw, name: 'any' };
267
- case ts.SyntaxKind.UnknownKeyword: return { raw, name: 'unknown' };
268
- }
269
-
270
- // Object literal type: { title: string; limit: number }
271
- if (ts.isTypeLiteralNode(node)) {
272
- return { raw, name: raw };
273
- }
274
-
275
- // Fallback
276
- return { raw, name: raw };
277
- }
278
-
279
- function meaningfulSymbolName(type: ts.Type, checker: ts.TypeChecker): string {
280
- const typescript = getTS();
281
- const symbol = type.aliasSymbol ?? type.getSymbol();
282
- if (symbol && symbol.name !== 'default' && !symbol.name.startsWith('__')) return symbol.name;
283
-
284
- for (const declaration of symbol?.declarations ?? []) {
285
- if (
286
- (typescript.isClassDeclaration(declaration)
287
- || typescript.isInterfaceDeclaration(declaration)
288
- || typescript.isTypeAliasDeclaration(declaration))
289
- && declaration.name
290
- ) return declaration.name.text;
291
- }
292
-
293
- return checker.typeToString(type, undefined, typescript.TypeFormatFlags.NoTruncation);
294
- }
295
-
296
- /** Turn a checked TypeScript type into the small, serializable vocabulary the runtime reads. */
297
- function parseCheckedType(type: ts.Type, raw: string, checker: ts.TypeChecker, depth = 0): TypeRef {
298
- const typescript = getTS();
299
- if (depth > 12) return { raw, name: checker.typeToString(type) };
300
-
301
- if (type.isUnion()) {
302
- const nullable = type.types.some((member) => (member.flags & typescript.TypeFlags.Null) !== 0);
303
- const undefinable = type.types.some((member) =>
304
- (member.flags & (typescript.TypeFlags.Undefined | typescript.TypeFlags.Void)) !== 0,
305
- );
306
- const members = type.types.filter((member) =>
307
- (member.flags & (typescript.TypeFlags.Null | typescript.TypeFlags.Undefined | typescript.TypeFlags.Void)) === 0,
308
- );
309
- // The checker represents the `boolean` keyword itself as `false | true`. Preserve
310
- // the primitive vocabulary consumed by binding and presenter metadata.
311
- if (
312
- members.length > 0
313
- && members.every((member) => (member.flags & typescript.TypeFlags.BooleanLiteral) !== 0)
314
- ) {
315
- return { raw, name: 'boolean', nullable, undefined: undefinable };
316
- }
317
- if (members.length === 1) {
318
- const inner = parseCheckedType(members[0]!, raw, checker, depth + 1);
319
- return {
320
- ...inner,
321
- raw,
322
- nullable: nullable || inner.nullable,
323
- undefined: undefinable || inner.undefined,
324
- };
325
- }
326
- return {
327
- raw,
328
- name: members.map((member) => meaningfulSymbolName(member, checker)).join(' | ') || raw,
329
- nullable,
330
- undefined: undefinable,
331
- };
332
- }
333
-
334
- // Present at runtime in the supported compiler versions, but intentionally omitted
335
- // from TypeScript's public TypeChecker declaration.
336
- const promised = (checker as ts.TypeChecker & {
337
- getPromisedTypeOfPromise(candidate: ts.Type): ts.Type | undefined;
338
- }).getPromisedTypeOfPromise(type);
339
- if (promised) return { ...parseCheckedType(promised, raw, checker, depth + 1), raw, promise: true };
340
-
341
- if (checker.isArrayType(type)) {
342
- const [element] = checker.getTypeArguments(type as ts.TypeReference);
343
- const inner = element ? parseCheckedType(element, raw, checker, depth + 1) : { raw, name: 'unknown' };
344
- return { ...inner, raw, array: true, arrayDepth: (inner.arrayDepth ?? 0) + 1 };
345
- }
346
-
347
- if ((type.flags & typescript.TypeFlags.StringLike) !== 0) return { raw, name: 'string' };
348
- if ((type.flags & typescript.TypeFlags.NumberLike) !== 0) return { raw, name: 'number' };
349
- if ((type.flags & typescript.TypeFlags.BooleanLike) !== 0) return { raw, name: 'boolean' };
350
- if ((type.flags & typescript.TypeFlags.Void) !== 0) return { raw, name: 'void', undefined: true };
351
- if ((type.flags & typescript.TypeFlags.Undefined) !== 0) return { raw, name: 'undefined', undefined: true };
352
- if ((type.flags & typescript.TypeFlags.Null) !== 0) return { raw, name: 'null', nullable: true };
353
- if ((type.flags & typescript.TypeFlags.Any) !== 0) return { raw, name: 'any' };
354
- if ((type.flags & typescript.TypeFlags.Unknown) !== 0) return { raw, name: 'unknown' };
355
-
356
- const reference = type as ts.TypeReference;
357
- // A declared alias such as `Emit<PostPublished>` may reduce to a function or object
358
- // type, so it is no longer a TypeReference. The checker keeps its arguments beside
359
- // `aliasSymbol`; losing them turns DI keys into bare `Emit`/`Facade`.
360
- const args = (type as ts.Type & { aliasTypeArguments?: readonly ts.Type[] }).aliasTypeArguments
361
- ?? checker.getTypeArguments(reference);
362
- return {
363
- raw,
364
- name: meaningfulSymbolName(type, checker),
365
- ...(args.length && { generics: args.map((arg) => parseCheckedType(arg, checker.typeToString(arg), checker, depth + 1)) }),
366
- };
367
- }
368
-
369
- // ── Module resolution ────────────────────────
370
-
371
- const TS_KEYWORDS = new Set([
372
- 'string', 'number', 'boolean', 'void', 'undefined', 'null', 'any', 'unknown',
373
- 'never', 'object', 'symbol', 'bigint',
374
- ]);
375
-
376
-
377
- /** Resolve an import specifier to an absolute file path. */
378
- function resolveSpecifier(specifier: string, fromFile: string, projectRoot: string): string | undefined {
379
- // Relative import
380
- if (specifier.startsWith('.')) {
381
- const dir = dirname(fromFile);
382
- let resolved = resolvePath(dir, specifier);
383
- // .js → .ts
384
- if (resolved.endsWith('.js')) resolved = resolved.slice(0, -3) + '.ts';
385
- if (!resolved.endsWith('.ts')) resolved += '.ts';
386
- if (existsSync(resolved)) return resolved;
387
- return undefined;
388
- }
389
-
390
- // Workspace package: @fougere/core → packages/core/src/index.ts
391
- const match = specifier.match(/^@fougere\/([^/]+)$/);
392
- if (match) {
393
- const pkgDir = join(projectRoot, 'packages', match[1], 'src');
394
- const indexPath = join(pkgDir, 'index.ts');
395
- if (existsSync(indexPath)) return indexPath;
396
- }
397
-
398
- return undefined;
399
- }
400
-
401
-
402
-
403
- // ── Mixin / heritage parsing ─────────────────
404
-
405
- /** The class a returned expression carries, however it is wrapped. */
406
- function classInExpression(expr: ts.Node, depth = 0): ts.ClassExpression | undefined {
407
- const ts = getTS();
408
- if (depth > 8) return undefined;
409
- if (ts.isClassExpression(expr)) return expr;
410
- if (ts.isCallExpression(expr)) {
411
- for (const arg of expr.arguments) {
412
- const found = classInExpression(arg, depth + 1);
413
- if (found) return found;
414
- }
415
- return undefined;
416
- }
417
- if (ts.isAsExpression(expr) || ts.isSatisfiesExpression(expr) || ts.isParenthesizedExpression(expr)) {
418
- return classInExpression(expr.expression, depth + 1);
419
- }
420
- return undefined;
421
- }
422
-
423
- /** Find a class declaration inside a function (mixin pattern). */
424
- function findClassInFunction(source: ts.SourceFile, functionName: string): ts.ClassDeclaration | ts.ClassExpression | undefined {
425
- const ts = getTS();
426
- for (const stmt of source.statements) {
427
- if (!ts.isFunctionDeclaration(stmt)) continue;
428
- if (stmt.name?.text !== functionName) continue;
429
- if (!stmt.body) continue;
430
-
431
- // Walk statements inside the function
432
- for (const inner of stmt.body.statements) {
433
- // return class CrudHandler { … }, or the same class behind a wrapper
434
- if (ts.isReturnStatement(inner) && inner.expression) {
435
- const found = classInExpression(inner.expression);
436
- if (found) return found;
437
- }
438
- // class CrudHandler { ... } (followed by return)
439
- if (ts.isClassDeclaration(inner)) return inner;
440
- }
441
- }
442
- return undefined;
443
- }
444
-
445
-
446
-
447
-
448
- /**
449
- * Extract methods from a class node (no file reading — works on already-parsed AST).
450
- */
451
- function extractClassMethods(
452
- cls: ts.ClassDeclaration | ts.ClassExpression,
453
- source: ts.SourceFile,
454
- skip: Set<string>,
455
- checker?: ts.TypeChecker,
456
- ): Signature[] {
457
- const ts = getTS();
458
- const results: Signature[] = [];
459
-
460
- for (const member of cls.members) {
461
- if (!ts.isMethodDeclaration(member)) continue;
462
- if (!member.name || !ts.isIdentifier(member.name)) continue;
463
- // `private`/`protected` is a statement about the surface, and the AST carries it —
464
- // it was read past. Every helper a handler names by intent (`mustOwn`, `readMany`,
465
- // `refuse`) became a callable op: measured on the bench, `list.readMany` executed
466
- // and `list.mayPublish` validated its argument. A door is what the author declares
467
- // public, and TypeScript already has the word for it. `#name` is private too, but
468
- // it is not an identifier, so it never reached here in the first place.
469
- if (member.modifiers?.some((m) => m.kind === ts.SyntaxKind.PrivateKeyword || m.kind === ts.SyntaxKind.ProtectedKeyword)) continue;
470
-
471
- const name = member.name.text;
472
- if (skip.has(name)) continue;
473
-
474
- const params = member.parameters.map((p) => parsedParam(p, source, checker));
475
- const returnType = member.type ? parseTypeNode(member.type, source, checker) : undefined;
476
- results.push({
477
- name, params, returnType,
478
- description: docSentenceOf(member, source),
479
- });
480
- }
481
-
482
- return results;
483
- }
484
-
485
- /** The first sentence of a member's doc comment, or nothing. */
486
- function docSentenceOf(member: ts.Node, source: ts.SourceFile): string | undefined {
487
- const ts = getTS();
488
- const ranges = ts.getLeadingCommentRanges(source.text, member.pos) ?? [];
489
- const block = ranges.filter((r) => source.text.slice(r.pos, r.pos + 3) === '/**').pop();
490
- if (!block) return undefined;
491
-
492
- const body = source.text
493
- .slice(block.pos + 3, block.end - 2)
494
- .split('\n')
495
- .map((line) => line.replace(/^\s*\*/, '').trim())
496
- .join(' ')
497
- .trim();
498
-
499
- const [sentence] = body.split(/(?<=\.)\s/);
500
-
501
- return sentence?.trim() || undefined;
502
- }
503
-
504
- /**
505
- * Parse inherited methods from a class's heritage clause.
506
- * Handles both `extends Crud(Entity)` (mixin) and `extends BaseClass` patterns.
507
- */
508
- /** Where a name used here is declared. */
509
- function declarationFileOf(node: ts.Node, checker: ts.TypeChecker): string | undefined {
510
- const typescript = getTS();
511
- let symbol = checker.getSymbolAtLocation(node);
512
- if (!symbol) return undefined;
513
- if (symbol.flags & typescript.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol);
514
- return symbol.declarations?.[0]?.getSourceFile().fileName;
515
- }
516
-
517
- /** The methods a base class contributes, read from the INSTANTIATED type. */
518
- function inheritedFromBase(
519
- base: ts.ExpressionWithTypeArguments,
520
- checker: ts.TypeChecker,
521
- skip: Set<string>,
522
- ): Signature[] {
523
- const typescript = getTS();
524
- const results: Signature[] = [];
525
-
526
- for (const property of checker.getPropertiesOfType(checker.getTypeAtLocation(base))) {
527
- if (skip.has(property.name)) continue;
528
-
529
- // `private`/`protected` is a statement about the surface, and the declaration carries
530
- // it. A door is what the author declares public.
531
- const declaration = property.declarations?.[0];
532
- if (declaration && typescript.canHaveModifiers(declaration)
533
- && typescript.getModifiers(declaration)?.some((m) => m.kind === typescript.SyntaxKind.PrivateKeyword
534
- || m.kind === typescript.SyntaxKind.ProtectedKeyword)) continue;
535
-
536
- const signature = checker.getTypeOfSymbolAtLocation(property, base).getCallSignatures()[0];
537
- if (!signature) continue;
538
-
539
- const returned = signature.getReturnType();
540
- const sentence = typescript.displayPartsToString(property.getDocumentationComment(checker)).trim();
541
- results.push({
542
- name: property.name,
543
- params: signature.getParameters().map((parameter) => {
544
- const type = checker.getTypeOfSymbolAtLocation(parameter, base);
545
- return {
546
- name: parameter.name,
547
- type: parseCheckedType(type, checker.typeToString(type), checker),
548
- optional: (parameter.flags & typescript.SymbolFlags.Optional) !== 0,
549
- };
550
- }),
551
- returnType: parseCheckedType(returned, checker.typeToString(returned), checker),
552
- ...(sentence ? { description: sentence.split(/(?<=\.)\s/)[0] } : {}),
553
- });
554
- }
555
- return results;
556
- }
557
-
558
- function parseInheritedMethods(
559
- cls: ts.ClassDeclaration,
560
- source: ts.SourceFile,
561
- checker: ts.TypeChecker,
562
- skip: Set<string>,
563
- /**
564
- * Base classes this pass could not open — an INSTALLED one, typically, whose source is not in
565
- * the workspace.
566
- */
567
- unresolved: string[],
568
- ): Signature[] {
569
- const ts = getTS();
570
- if (!cls.heritageClauses) return [];
571
-
572
- for (const clause of cls.heritageClauses) {
573
- if (clause.token !== ts.SyntaxKind.ExtendsKeyword) continue;
574
-
575
- for (const base of clause.types) {
576
- const fromType = inheritedFromBase(base, checker, skip);
577
- if (fromType.length > 0) return fromType;
578
-
579
- // A factory that ERASES its own type — `assertShape<unknown>(class …)`, `as unknown`
580
- // — leaves the checker with nothing to enumerate. The written class is still there,
581
- // so read it. This is the one case where what the author wrote beats what it means.
582
- const expression = base.expression;
583
- const declared = ts.isCallExpression(expression) && ts.isIdentifier(expression.expression)
584
- ? declarationFileOf(expression.expression, checker)
585
- : ts.isIdentifier(expression) ? declarationFileOf(expression, checker) : undefined;
586
- if (!declared) { unresolved.push(expression.getText(source)); continue; }
587
-
588
- const declaredSource = sourceOf(declared);
589
- const written = ts.isCallExpression(expression) && ts.isIdentifier(expression.expression)
590
- ? findClassInFunction(declaredSource, expression.expression.text)
591
- : findDefaultClass(declaredSource);
592
- if (!written) { unresolved.push(expression.getText(source)); continue; }
593
-
594
- return extractClassMethods(written, declaredSource, skip);
595
- }
596
- }
597
-
598
- return [];
599
- }
600
-
601
- // ── Class finding ────────────────────────────
602
-
603
- /** Find the default exported class in a source file. */
604
- function findDefaultClass(source: ts.SourceFile): ts.ClassDeclaration | undefined {
605
- const ts = getTS();
606
- for (const stmt of source.statements) {
607
- // export default class Foo { ... }
608
- if (ts.isClassDeclaration(stmt) && stmt.modifiers?.some(
609
- (m) => m.kind === ts.SyntaxKind.ExportKeyword,
610
- ) && stmt.modifiers?.some(
611
- (m) => m.kind === ts.SyntaxKind.DefaultKeyword,
612
- )) {
613
- return stmt;
614
- }
615
- }
616
-
617
- // export default Foo (separate statement) — find the class it points to
618
- for (const stmt of source.statements) {
619
- if (ts.isExportAssignment(stmt) && !stmt.isExportEquals && ts.isIdentifier(stmt.expression)) {
620
- const name = stmt.expression.text;
621
- for (const s of source.statements) {
622
- if (ts.isClassDeclaration(s) && s.name?.text === name) return s;
623
- }
624
- }
625
- }
626
-
627
- return undefined;
628
- }
629
-
630
- /** What a handler file yielded — its methods, AND what the pass could not open. */
631
- export interface HandlerParse {
632
- methods: Signature[];
633
- /** Base classes whose source this pass could not open. Empty is a claim. */
634
- unresolvedHeritage: string[];
635
- }
636
-
637
- /**
638
- * Every method a handler declares, its inherited ones included — the raw material of a
639
- * binding plan. With a `projectRoot`, the heritage clause is followed too.
640
- */
641
- export async function parseAllHandlerMethods(filePath: string, projectRoot?: string): Promise<HandlerParse> {
642
- await loadTS();
643
- return parseClassMethods(filePath, CONSTRUCTOR_ONLY, projectRoot);
644
- }
645
-
646
- /** Parse a presenter source file and extract all method signatures. */
647
- export async function parsePresenterMethods(filePath: string, projectRoot?: string): Promise<Signature[]> {
648
- await loadTS();
649
- // No `projectRoot`, so no heritage pass and nothing to report: a presenter's
650
- // computed fields are its own methods.
651
- return parseClassMethods(filePath, CONSTRUCTOR_ONLY, undefined, projectRoot).methods;
652
- }
653
-
654
- /**
655
- * Parse constructor parameter types from a source file's default class.
656
- * Returns type names (e.g. ['PostStorage', 'Logger']) for DI resolution.
657
- */
658
- export async function parseConstructorParams(filePath: string, projectRoot?: string): Promise<Param[]> {
659
- const ts = await loadTS();
660
- const { source, checker } = checkedSourceOf(filePath, projectRoot);
661
- const cls = findDefaultClass(source);
662
- if (!cls) return [];
663
-
664
- const ctor = cls.members.find(ts.isConstructorDeclaration);
665
- return ctor ? ctor.parameters.map((p) => parsedParam(p, source, checker)) : [];
666
- }
667
-
668
- const CONSTRUCTOR_ONLY = new Set(['constructor']);
669
-
670
- function parseClassMethods(
671
- filePath: string,
672
- skip: Set<string>,
673
- heritageRoot?: string,
674
- typeRoot: string | undefined = heritageRoot,
675
- ): HandlerParse {
676
- const unresolved: string[] = [];
677
- const { source, checker } = checkedSourceOf(filePath, typeRoot);
678
- const cls = findDefaultClass(source);
679
- if (!cls) return { methods: [], unresolvedHeritage: unresolved };
680
-
681
- const childMethods = extractClassMethods(cls, source, skip, checker);
682
- const childNames = new Set(childMethods.map((m) => m.name));
683
-
684
- // Parse inherited methods (if projectRoot is provided for resolution)
685
- if (heritageRoot) {
686
- const inherited = parseInheritedMethods(cls, source, checker, skip, unresolved);
687
- // Merge: child methods win over inherited
688
- const parentOnly = inherited
689
- .filter((m) => !childNames.has(m.name))
690
- .map((m) => ({ ...m, inherited: true }));
691
- return { methods: [...childMethods, ...parentOnly], unresolvedHeritage: unresolved };
692
- }
693
-
694
- return { methods: childMethods, unresolvedHeritage: unresolved };
695
- }