raiton 6.11.0-beta.29 → 6.12.0-beta.31

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 (74) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/benchmarks/README.md +3 -3
  3. package/build/bin/index.mjs +2329 -361
  4. package/build/types/core/artifact-mount.d.ts +19 -0
  5. package/build/types/core/bridge/classifier.d.ts +30 -0
  6. package/build/types/core/bridge/definition.d.ts +10 -0
  7. package/build/types/core/bridge/diagnostics.d.ts +43 -0
  8. package/build/types/core/bridge/index.d.ts +8 -0
  9. package/build/types/core/bridge/loader.d.ts +75 -0
  10. package/build/types/core/bridge/packages.d.ts +27 -0
  11. package/build/types/core/bridge/paths.d.ts +37 -0
  12. package/build/types/core/bridge/registry.d.ts +50 -0
  13. package/build/types/core/bridge/resolver.d.ts +32 -0
  14. package/build/types/core/builder.d.ts +8 -1
  15. package/build/types/core/controller/builder.d.ts +9 -0
  16. package/build/types/core/controller/compiler.d.ts +8 -1
  17. package/build/types/core/controller/tracker.d.ts +10 -3
  18. package/build/types/core/hooks.d.ts +2 -0
  19. package/build/types/core/index.d.ts +1 -0
  20. package/build/types/core/injection/injection.d.ts +24 -0
  21. package/build/types/core/middleware/pipeline.d.ts +12 -1
  22. package/build/types/core/scheduler/manager.d.ts +5 -0
  23. package/build/types/framework/artifacts.d.ts +5 -0
  24. package/build/types/framework/constants/decorators.constant.d.ts +8 -0
  25. package/build/types/manifest/schema.d.ts +77 -0
  26. package/build/types/types/artifact.d.ts +16 -0
  27. package/build/types/types/bridge.d.ts +109 -0
  28. package/build/types/types/index.d.ts +1 -0
  29. package/docs/AGENTS.md +1 -1
  30. package/docs/CLAUDE.md +1 -1
  31. package/docs/generated/config-schema.json +26 -0
  32. package/docs/generated/manifest-schema.json +110 -0
  33. package/docs/generated/manifest.json +1 -1
  34. package/docs/llms-full.txt +176 -2
  35. package/docs/llms.txt +1 -1
  36. package/docs/user-guide/README.md +1 -0
  37. package/docs/user-guide/artifact-bridge.md +170 -0
  38. package/package.json +1 -1
  39. package/source/bin/project-utils.ts +9 -0
  40. package/source/commands/artifact.command.ts +24 -9
  41. package/source/commands/build.command.ts +3 -1
  42. package/source/commands/docs.command.ts +1 -0
  43. package/source/commands/doctor.command.ts +53 -1
  44. package/source/commands/inspect.command.ts +3 -0
  45. package/source/commands/start.command.ts +3 -1
  46. package/source/commands/why.command.ts +4 -0
  47. package/source/core/artifact-mount.ts +126 -0
  48. package/source/core/bridge/classifier.ts +112 -0
  49. package/source/core/bridge/definition.ts +35 -0
  50. package/source/core/bridge/diagnostics.ts +175 -0
  51. package/source/core/bridge/index.ts +8 -0
  52. package/source/core/bridge/loader.ts +914 -0
  53. package/source/core/bridge/packages.ts +196 -0
  54. package/source/core/bridge/paths.ts +152 -0
  55. package/source/core/bridge/registry.ts +177 -0
  56. package/source/core/bridge/resolver.ts +183 -0
  57. package/source/core/builder.ts +146 -7
  58. package/source/core/config/schema.ts +54 -9
  59. package/source/core/controller/builder.ts +49 -31
  60. package/source/core/controller/compiler.ts +13 -4
  61. package/source/core/controller/tracker.ts +29 -7
  62. package/source/core/hooks.ts +5 -0
  63. package/source/core/index.ts +2 -1
  64. package/source/core/injection/injection.ts +67 -0
  65. package/source/core/middleware/pipeline.ts +33 -2
  66. package/source/core/scheduler/manager.ts +15 -0
  67. package/source/core/thread.ts +21 -0
  68. package/source/framework/artifacts.ts +10 -0
  69. package/source/framework/constants/decorators.constant.ts +35 -27
  70. package/source/manifest/manifest.ts +46 -0
  71. package/source/manifest/schema.ts +48 -0
  72. package/source/types/artifact.ts +16 -0
  73. package/source/types/bridge.ts +136 -0
  74. package/source/types/index.ts +1 -0
@@ -0,0 +1,914 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import {Logger} from "@protorians/logger";
4
+ import {Injection} from "../injection/injection.ts";
5
+ import {Raiton} from "../raiton.ts";
6
+ import {RaitonConfig} from "../config/config.ts";
7
+ import {isNodeUsed} from "../../bin/constants.ts";
8
+ import type {ApplicationInterface} from "../../types/application.ts";
9
+ import type {
10
+ ArtifactBridgeDefinition,
11
+ ArtifactBridgeDescriptor,
12
+ ArtifactBridgeEntry,
13
+ BridgeDiagnostic,
14
+ HookBridgeDescriptor,
15
+ MiddlewareBridgeDescriptor,
16
+ PluginBridgeDescriptor,
17
+ ResolvedBridgeArtifact,
18
+ } from "../../types/bridge.ts";
19
+ import {ArtifactRegistry, artifactKey, type MountedArtifactRecord} from "./registry.ts";
20
+ import {classifyConstruct, exportNames, isBridgeDefinition, isClass, resolveArtifacts} from "./classifier.ts";
21
+ import {BridgeError, bridgeDiagnostic, SUPPORTED_HOOK_NAMES} from "./diagnostics.ts";
22
+ import {
23
+ importBridgeModule,
24
+ isLocalPathSpecifier,
25
+ packageNameFromSpecifier,
26
+ resolveBridgeModule,
27
+ type ResolvedBridgeModule,
28
+ } from "./resolver.ts";
29
+ import {
30
+ compiledBridgeFile,
31
+ relativeTo,
32
+ resolveRuntimeBridge,
33
+ } from "./paths.ts";
34
+ import {discoverPackageArtifacts} from "./packages.ts";
35
+ import {mountArtifact} from "../artifact-mount.ts";
36
+ import {ControllerRouteTracker} from "../controller/tracker.ts";
37
+ import {McpRouteTracker} from "../mcp/tracker.ts";
38
+ import {getSocketMetadata, unregisterSocket} from "../socket/metadata.ts";
39
+ import {unregisterMcpServer} from "../mcp/metadata.ts";
40
+ import {unregisterScheduler, getSchedulerMetadata} from "../scheduler/metadata.ts";
41
+ import {SchedulerManager} from "../scheduler/manager.ts";
42
+ import {MiddlewarePipeline} from "../middleware/pipeline.ts";
43
+ import {HookStore} from "../hooks.ts";
44
+
45
+ export interface BridgeLoadOptions {
46
+ workdir?: string;
47
+ development?: boolean;
48
+ /** Force a cache-busting import of local bridge modules. */
49
+ cacheBust?: boolean;
50
+ }
51
+
52
+ export interface BridgeState {
53
+ descriptor: ArtifactBridgeDescriptor | null;
54
+ sourceFile: string | null;
55
+ runtimeFile: string | null;
56
+ loaded: boolean;
57
+ disabled: boolean;
58
+ missing: boolean;
59
+ packages: string[];
60
+ artifacts: ResolvedBridgeArtifact[];
61
+ unresolved: ArtifactBridgeDescriptor["unresolved"];
62
+ diagnostics: BridgeDiagnostic[];
63
+ localFiles: string[];
64
+ }
65
+
66
+ export interface EntryContext {
67
+ origin: "bridge" | "package";
68
+ package?: string;
69
+ directories: Array<string | undefined>;
70
+ cacheBust: boolean;
71
+ location?: string;
72
+ packageRoot?: string;
73
+ }
74
+
75
+ const EMPTY_STATE: BridgeState = {
76
+ descriptor: null,
77
+ sourceFile: null,
78
+ runtimeFile: null,
79
+ loaded: false,
80
+ disabled: false,
81
+ missing: false,
82
+ packages: [],
83
+ artifacts: [],
84
+ unresolved: [],
85
+ diagnostics: [],
86
+ localFiles: [],
87
+ };
88
+
89
+ function developmentMode(options: BridgeLoadOptions): boolean {
90
+ if (options.development !== undefined) return options.development;
91
+ const thread = Raiton.thread as any;
92
+ return Boolean(
93
+ RaitonConfig.get("develop")
94
+ || thread?.builder?.options?.hmr
95
+ || thread?.builder?.options?.serve
96
+ || process.env.NODE_ENV === "development"
97
+ );
98
+ }
99
+
100
+ function describeEntry(entry: unknown): string {
101
+ if (typeof entry === "string") return entry;
102
+ if (typeof entry === "function") return entry.name || "anonymous function";
103
+ if (entry && typeof entry === "object") {
104
+ const kind = ["middleware", "hook", "plugin"].find(key => key in (entry as any));
105
+ if (kind) return `${kind}(${(entry as any)[kind]?.name ?? "anonymous"})`;
106
+ return Object.keys(entry as object).join(",") || "object";
107
+ }
108
+ return String(entry);
109
+ }
110
+
111
+ function isDescriptor(value: unknown): boolean {
112
+ return Boolean(value)
113
+ && typeof value === "object"
114
+ && ["middleware", "hook", "plugin"].some(key => key in (value as any));
115
+ }
116
+
117
+ export class BridgeLoader {
118
+ protected static _state: BridgeState = {...EMPTY_STATE};
119
+
120
+ static get state(): BridgeState {
121
+ return this._state;
122
+ }
123
+
124
+ static get current(): ArtifactBridgeDescriptor | null {
125
+ return this._state.descriptor;
126
+ }
127
+
128
+ static async reset(): Promise<void> {
129
+ this._state = {...EMPTY_STATE};
130
+ ArtifactRegistry.setExcludedFiles([]);
131
+ }
132
+
133
+ /**
134
+ * Resolve, import and validate the bridge. This never mounts artifacts and
135
+ * never throws for a missing default bridge file.
136
+ */
137
+ static async load(options: BridgeLoadOptions = {}): Promise<BridgeState> {
138
+ const workdir = options.workdir ?? process.cwd();
139
+ const development = developmentMode(options);
140
+ const resolution = resolveRuntimeBridge(workdir);
141
+
142
+ this._state = {
143
+ ...EMPTY_STATE,
144
+ sourceFile: resolution.file,
145
+ runtimeFile: resolution.runtimeFile,
146
+ disabled: resolution.disabled,
147
+ missing: Boolean(resolution.explicit && !resolution.file),
148
+ };
149
+
150
+ const artifacts: ResolvedBridgeArtifact[] = [];
151
+ const unresolved: ArtifactBridgeDescriptor["unresolved"] = [];
152
+ const diagnostics: BridgeDiagnostic[] = [];
153
+ const seen = new Map<unknown, ResolvedBridgeArtifact>();
154
+ const logical = new Map<string, ResolvedBridgeArtifact>();
155
+
156
+ const register = (artifact: ResolvedBridgeArtifact) => {
157
+ const identity = this.identityOf(artifact);
158
+ const duplicate = seen.get(identity);
159
+ if (duplicate) {
160
+ diagnostics.push(bridgeDiagnostic("BRIDGE_ARTIFACT_DUPLICATE", {
161
+ entry: artifact.name,
162
+ message: `Bridge artifact "${artifact.name}" is declared more than once`,
163
+ }));
164
+ return;
165
+ }
166
+
167
+ // A class imported statically by the bridge and resolved again from
168
+ // a module string has two identities but one logical artifact. Keep
169
+ // the located copy (file/package metadata) and never mount both.
170
+ const logicalKey = `${artifact.kind}|${artifact.name}|${artifact.package ?? ""}`;
171
+ const existing = logical.get(logicalKey);
172
+ if (existing) {
173
+ if (existing.construct === artifact.construct) {
174
+ diagnostics.push(bridgeDiagnostic("BRIDGE_ARTIFACT_DUPLICATE", {
175
+ entry: artifact.name,
176
+ message: `Bridge artifact "${artifact.name}" is declared more than once`,
177
+ }));
178
+ return;
179
+ }
180
+ if (existing.file && artifact.file && existing.file !== artifact.file) {
181
+ throw new BridgeError("BRIDGE_NAME_COLLISION", {
182
+ message: `Bridge artifact "${artifact.name}" is declared from two different files`,
183
+ action: "Use a unique class name or remove the duplicate declaration.",
184
+ location: artifact.file,
185
+ entry: artifact.name,
186
+ package: artifact.package,
187
+ });
188
+ }
189
+ if (!existing.file && artifact.file) {
190
+ const index = artifacts.indexOf(existing);
191
+ if (index !== -1) artifacts[index] = artifact;
192
+ seen.delete(this.identityOf(existing));
193
+ logical.set(logicalKey, artifact);
194
+ seen.set(identity, artifact);
195
+ return;
196
+ }
197
+ diagnostics.push(bridgeDiagnostic("BRIDGE_ARTIFACT_DUPLICATE", {
198
+ entry: artifact.name,
199
+ message: `Bridge artifact "${artifact.name}" is declared more than once`,
200
+ }));
201
+ return;
202
+ }
203
+
204
+ seen.set(identity, artifact);
205
+ logical.set(logicalKey, artifact);
206
+ artifacts.push(artifact);
207
+ };
208
+
209
+ let definition: ArtifactBridgeDefinition | null = null;
210
+ let runtimeFile: string | null = resolution.runtimeFile;
211
+ let descriptorFile: string | null = null;
212
+ let baseDirectories: Array<string | undefined> = [resolution.rootDir, workdir];
213
+
214
+ if (!resolution.disabled && !resolution.file && resolution.explicit) {
215
+ const message = `Configured artifacts bridge was not found: ${resolution.expected}`;
216
+ if (development) {
217
+ const diagnostic = bridgeDiagnostic("BRIDGE_FILE_NOT_FOUND", {
218
+ severity: "warning",
219
+ message,
220
+ location: resolution.expected ?? workdir,
221
+ });
222
+ diagnostics.push(diagnostic);
223
+ Logger.warn(`[bridge] ${message}`);
224
+ } else {
225
+ throw new BridgeError("BRIDGE_FILE_NOT_FOUND", {
226
+ message,
227
+ location: resolution.expected ?? workdir,
228
+ entry: resolution.expected ?? undefined,
229
+ });
230
+ }
231
+ } else if (!resolution.disabled && resolution.file) {
232
+ if (isNodeUsed && !fs.existsSync(compiledBridgeFile(workdir))) {
233
+ throw new BridgeError("BRIDGE_NOT_BUNDLED", {
234
+ message: `The artifacts bridge has not been compiled for Node.js: ${relativeTo(workdir, resolution.file)}`,
235
+ location: resolution.file,
236
+ entry: relativeTo(workdir, resolution.file),
237
+ action: "Run `raiton build` first, then start the compiled application.",
238
+ });
239
+ }
240
+
241
+ runtimeFile = resolution.runtimeFile ?? resolution.file;
242
+ descriptorFile = relativeTo(workdir, resolution.file) ?? resolution.file;
243
+ baseDirectories = [path.dirname(resolution.file), resolution.rootDir, workdir];
244
+
245
+ const imported = await importBridgeModule({
246
+ file: runtimeFile,
247
+ package: undefined,
248
+ external: runtimeFile.includes(`${path.sep}node_modules${path.sep}`),
249
+ }, {cacheBust: Boolean(options.cacheBust && !isNodeUsed)});
250
+
251
+ definition = this.definitionFrom(imported, runtimeFile);
252
+ const context: EntryContext = {
253
+ origin: "bridge",
254
+ directories: baseDirectories,
255
+ cacheBust: Boolean(options.cacheBust && !isNodeUsed),
256
+ location: descriptorFile,
257
+ };
258
+ const resolved = await this.resolveEntries(definition.artifacts, context, {diagnostics, unresolved});
259
+ for (const artifact of resolved) register(artifact);
260
+ }
261
+
262
+ // Package self-description is independent from the bridge file: a
263
+ // direct dependency declaring `package.json#raiton.artifacts` is
264
+ // discovered even when the project has no bridge file.
265
+ const packageDiscovery = discoverPackageArtifacts(workdir, {
266
+ enabled: RaitonConfig.get("artifacts")?.packages ?? true,
267
+ allowlist: RaitonConfig.get("artifacts")?.packageAllowlist,
268
+ verbose: Boolean(RaitonConfig.get("verbose")),
269
+ });
270
+ diagnostics.push(...packageDiscovery.diagnostics);
271
+
272
+ const fatal = packageDiscovery.diagnostics.find(diagnostic => diagnostic.severity === "error");
273
+ if (fatal) {
274
+ throw new BridgeError(fatal.code, {
275
+ message: fatal.message,
276
+ action: fatal.action,
277
+ location: fatal.location,
278
+ package: fatal.package,
279
+ });
280
+ }
281
+
282
+ for (const entry of packageDiscovery.entries) {
283
+ const packageContext: EntryContext = {
284
+ origin: "package",
285
+ package: entry.package,
286
+ packageRoot: entry.packageRoot,
287
+ directories: [entry.packageRoot, ...baseDirectories],
288
+ cacheBust: Boolean(options.cacheBust && !isNodeUsed),
289
+ location: entry.location,
290
+ };
291
+ const packageResolved = await this.resolveEntries([entry.entry], packageContext, {diagnostics, unresolved});
292
+ for (const artifact of packageResolved) register(artifact);
293
+ }
294
+
295
+ const localFiles = artifacts
296
+ .map(artifact => artifact.file)
297
+ .filter((file): file is string => Boolean(file) && !file!.includes(`${path.sep}node_modules${path.sep}`));
298
+
299
+ ArtifactRegistry.setExcludedFiles(localFiles);
300
+
301
+ const loaded = Boolean(definition) || artifacts.length > 0;
302
+
303
+ this._state = {
304
+ descriptor: definition && descriptorFile
305
+ ? {
306
+ file: descriptorFile,
307
+ runtimeFile: relativeTo(workdir, runtimeFile),
308
+ loaded: true,
309
+ packages: packageDiscovery.packages,
310
+ artifacts,
311
+ unresolved,
312
+ localFiles,
313
+ }
314
+ : null,
315
+ sourceFile: resolution.file,
316
+ runtimeFile,
317
+ loaded,
318
+ disabled: resolution.disabled,
319
+ missing: Boolean(resolution.explicit && !resolution.file),
320
+ packages: packageDiscovery.packages,
321
+ artifacts,
322
+ unresolved,
323
+ diagnostics,
324
+ localFiles,
325
+ };
326
+
327
+ if (loaded) {
328
+ const summary = `[bridge] ${artifacts.length} artifact(s), ${packageDiscovery.packages.length} package(s), ${diagnostics.filter(d => d.severity !== "info").length} warning(s)`;
329
+ if (RaitonConfig.get("verbose")) Logger.info(summary);
330
+ }
331
+ return this._state;
332
+ }
333
+
334
+ /**
335
+ * Mount every resolved artifact through the existing pipelines. Idempotent
336
+ * against the scan and against repeated calls.
337
+ */
338
+ static async mount(application: ApplicationInterface): Promise<BridgeLoader> {
339
+ if (!this._state.loaded) return this;
340
+ this.adoptAll(this._state.artifacts);
341
+ for (const artifact of this._state.artifacts) {
342
+ await this.mountArtifact(artifact, application, true);
343
+ }
344
+ return this;
345
+ }
346
+
347
+ /**
348
+ * Development hot reload: load the new manifest, diff by stable key and
349
+ * reconcile bridge-owned routes/middleware/hooks only.
350
+ */
351
+ static async reload(options: BridgeLoadOptions = {}): Promise<BridgeState> {
352
+ const thread = Raiton.thread as any;
353
+ const application = thread?.application as ApplicationInterface | undefined;
354
+ if (!application) return this._state;
355
+
356
+ if (isNodeUsed) {
357
+ thread?.restart?.();
358
+ return this._state;
359
+ }
360
+
361
+ const previous = this._state;
362
+ const previousArtifacts = [...previous.artifacts];
363
+ let nextState: BridgeState;
364
+ try {
365
+ nextState = await this.load({...options, cacheBust: true, development: true});
366
+ } catch (error) {
367
+ // A broken edit must not discard the working bridge in development.
368
+ this._state = previous;
369
+ ArtifactRegistry.setExcludedFiles(previous.localFiles);
370
+ throw error;
371
+ }
372
+ if (!nextState.loaded) {
373
+ for (const artifact of previousArtifacts) {
374
+ this.unmountArtifact(this.mountedRecord(artifact), application);
375
+ }
376
+ return nextState;
377
+ }
378
+
379
+ const previousByKey = new Map(previousArtifacts.map(artifact => [this.stableKey(artifact), artifact]));
380
+ const nextByKey = new Map(nextState.artifacts.map(artifact => [this.stableKey(artifact), artifact]));
381
+
382
+ const removed: ResolvedBridgeArtifact[] = [];
383
+ const updated: ResolvedBridgeArtifact[] = [];
384
+ for (const [key, previousArtifact] of previousByKey) {
385
+ const nextArtifact = nextByKey.get(key);
386
+ if (!nextArtifact) {
387
+ removed.push(previousArtifact);
388
+ continue;
389
+ }
390
+ if (this.identityOf(previousArtifact) !== this.identityOf(nextArtifact)) {
391
+ updated.push(nextArtifact);
392
+ }
393
+ }
394
+
395
+ for (const artifact of removed) {
396
+ this.unmountArtifact(this.mountedRecord(artifact), application);
397
+ }
398
+ for (const artifact of updated) {
399
+ this.unmountArtifact(this.mountedRecord(artifact), application);
400
+ }
401
+
402
+ // Hot-reloaded classes have new identities but keep their injection
403
+ // name. Replace owned definitions before adoption re-checks collisions.
404
+ for (const artifact of updated) {
405
+ if (typeof artifact.construct === "function" && Injection.has(artifact.name)) {
406
+ Injection.replace(artifact.name, artifact.construct as any);
407
+ }
408
+ }
409
+
410
+ // Adopt every injectable before compiling any controller: declaration
411
+ // order must not make a service unavailable to an earlier controller.
412
+ this.adoptAll(nextState.artifacts);
413
+
414
+ const updatedKeys = new Set(updated.map(artifact => this.stableKey(artifact)));
415
+ for (const artifact of nextState.artifacts) {
416
+ const key = this.stableKey(artifact);
417
+ const previousArtifact = previousByKey.get(key);
418
+ const changed = !previousArtifact || updatedKeys.has(key)
419
+ || this.identityOf(previousArtifact) !== this.identityOf(artifact);
420
+ if (changed) await this.mountArtifact(artifact, application, true);
421
+ }
422
+
423
+ if (RaitonConfig.get("verbose")) {
424
+ Logger.info(`[bridge] reloaded: +${nextState.artifacts.length - previousArtifacts.length} -${removed.length} ~${updated.length}`);
425
+ }
426
+ return nextState;
427
+ }
428
+
429
+ /**
430
+ * Non-throwing checks used by `raiton doctor`.
431
+ */
432
+ static diagnose(workdir = process.cwd()): BridgeDiagnostic[] {
433
+ const diagnostics: BridgeDiagnostic[] = [];
434
+ const resolution = resolveRuntimeBridge(workdir);
435
+
436
+ if (typeof (Reflect as any).getMetadata !== "function") {
437
+ diagnostics.push(bridgeDiagnostic("BRIDGE_RUNTIME_UNSUPPORTED", {
438
+ message: "reflect-metadata is not loaded in this runtime",
439
+ action: "Import `reflect-metadata` at the top of the application entry point.",
440
+ }));
441
+ }
442
+
443
+ if (resolution.disabled) return diagnostics;
444
+
445
+ if (resolution.explicit && !resolution.file) {
446
+ diagnostics.push(bridgeDiagnostic("BRIDGE_FILE_NOT_FOUND", {
447
+ location: resolution.expected ?? workdir,
448
+ }));
449
+ } else if (resolution.file && isNodeUsed && !fs.existsSync(compiledBridgeFile(workdir))) {
450
+ diagnostics.push(bridgeDiagnostic("BRIDGE_NOT_BUNDLED", {
451
+ location: resolution.file,
452
+ entry: relativeTo(workdir, resolution.file),
453
+ }));
454
+ }
455
+
456
+ const packageDiscovery = discoverPackageArtifacts(workdir, {
457
+ enabled: RaitonConfig.get("artifacts")?.packages ?? true,
458
+ allowlist: RaitonConfig.get("artifacts")?.packageAllowlist,
459
+ });
460
+ diagnostics.push(...packageDiscovery.diagnostics);
461
+
462
+ for (const diagnostic of this._state.diagnostics) {
463
+ if (!diagnostics.some(existing => existing.code === diagnostic.code && existing.message === diagnostic.message)) {
464
+ diagnostics.push(diagnostic);
465
+ }
466
+ }
467
+
468
+ return diagnostics;
469
+ }
470
+
471
+ protected static definitionFrom(imported: any, runtimeFile: string): ArtifactBridgeDefinition {
472
+ const candidate = imported?.default ?? imported;
473
+ if (!candidate || typeof candidate !== "object" || !Array.isArray(candidate.artifacts)) {
474
+ throw new BridgeError("BRIDGE_FILE_INVALID_EXPORT", {
475
+ message: `The artifacts bridge must default-export defineArtifactBridge({ artifacts: [...] }) (${relativeTo(process.cwd(), runtimeFile) ?? runtimeFile})`,
476
+ location: runtimeFile,
477
+ entry: relativeTo(process.cwd(), runtimeFile),
478
+ });
479
+ }
480
+ return {
481
+ ...candidate,
482
+ artifacts: candidate.artifacts,
483
+ } as ArtifactBridgeDefinition;
484
+ }
485
+
486
+ protected static async resolveEntries(
487
+ entries: ArtifactBridgeEntry[],
488
+ context: EntryContext,
489
+ state: {
490
+ diagnostics: BridgeDiagnostic[];
491
+ unresolved: ArtifactBridgeDescriptor["unresolved"];
492
+ },
493
+ depth = 0,
494
+ ): Promise<ResolvedBridgeArtifact[]> {
495
+ if (depth > 8) {
496
+ throw new BridgeError("BRIDGE_FILE_INVALID_EXPORT", {
497
+ message: "Bridge definitions are nested too deeply",
498
+ location: context.location,
499
+ });
500
+ }
501
+
502
+ const output: ResolvedBridgeArtifact[] = [];
503
+
504
+ for (const entry of entries) {
505
+ if (typeof entry === "string") {
506
+ output.push(...await this.resolveModuleEntry(entry, context, state, depth));
507
+ continue;
508
+ }
509
+
510
+ if (typeof entry === "function") {
511
+ const classified = classifyConstruct(entry);
512
+ if (!classified) {
513
+ throw new BridgeError("BRIDGE_ARTIFACT_AMBIGUOUS", {
514
+ message: `Bridge entry "${entry.name || "anonymous"}" is a function without artifact metadata or descriptor`,
515
+ action: "Decorate the class, or declare it as `{ middleware }`, `{ hook }` or `{ plugin }`.",
516
+ location: context.location,
517
+ entry: entry.name || "anonymous",
518
+ });
519
+ }
520
+ output.push({
521
+ name: classified.name,
522
+ kind: classified.kind,
523
+ construct: entry,
524
+ origin: context.origin,
525
+ ...(context.package ? {package: context.package} : {}),
526
+ ...(this.fileForConstruct(entry) ? {file: this.fileForConstruct(entry)!} : {}),
527
+ });
528
+ continue;
529
+ }
530
+
531
+ if (entry && typeof entry === "object") {
532
+ if (isBridgeDefinition(entry)) {
533
+ output.push(...await this.resolveEntries(
534
+ (entry as ArtifactBridgeDefinition).artifacts,
535
+ context,
536
+ state,
537
+ depth + 1,
538
+ ));
539
+ continue;
540
+ }
541
+ output.push(this.resolveDescriptor(entry as any, context));
542
+ continue;
543
+ }
544
+
545
+ throw new BridgeError("BRIDGE_ENTRY_INVALID", {
546
+ message: `Unsupported bridge entry: ${describeEntry(entry)}`,
547
+ action: "Use a decorated class/function, a module specifier, a local path, or a middleware/hook/plugin descriptor.",
548
+ location: context.location,
549
+ entry: describeEntry(entry),
550
+ });
551
+ }
552
+
553
+ return output;
554
+ }
555
+
556
+ protected static async resolveModuleEntry(
557
+ specifier: string,
558
+ context: EntryContext,
559
+ state: {
560
+ diagnostics: BridgeDiagnostic[];
561
+ unresolved: ArtifactBridgeDescriptor["unresolved"];
562
+ },
563
+ depth: number,
564
+ ): Promise<ResolvedBridgeArtifact[]> {
565
+ const resolved: ResolvedBridgeModule = resolveBridgeModule(specifier, {
566
+ directories: context.directories,
567
+ workdir: context.directories[context.directories.length - 1] ?? process.cwd(),
568
+ });
569
+
570
+ if (resolved.file.startsWith("node:")) {
571
+ throw new BridgeError("BRIDGE_MODULE_NOT_FOUND", {
572
+ message: `Runtime builtins cannot expose bridge artifacts: ${specifier}`,
573
+ entry: specifier,
574
+ module: specifier,
575
+ });
576
+ }
577
+
578
+ if (isNodeUsed && /\.(ts|mts|cts|tsx)$/i.test(resolved.file)) {
579
+ throw new BridgeError("BRIDGE_RUNTIME_UNSUPPORTED", {
580
+ message: `Bridge local entry is TypeScript but the current runtime cannot import it: ${specifier}`,
581
+ action: "Import the class directly in the bridge (recommended) or compile the file to JavaScript.",
582
+ location: resolved.file,
583
+ entry: specifier,
584
+ });
585
+ }
586
+
587
+ if (isLocalPathSpecifier(specifier) || !resolved.external) {
588
+ ArtifactRegistry.excludeFile(resolved.file);
589
+ context = {
590
+ ...context,
591
+ directories: [...context.directories, path.dirname(resolved.file)],
592
+ };
593
+ }
594
+
595
+ const imported = await importBridgeModule(resolved, {
596
+ // External packages are not watched: always use the runtime module
597
+ // cache so a package class imported by the bridge and resolved
598
+ // dynamically is the exact same object.
599
+ cacheBust: Boolean(context.cacheBust && !resolved.external),
600
+ });
601
+ const candidate = imported?.default ?? imported;
602
+ if (isBridgeDefinition(candidate)) {
603
+ return this.resolveEntries(candidate.artifacts, {
604
+ ...context,
605
+ location: resolved.file,
606
+ ...(resolved.package ? {package: resolved.package} : {}),
607
+ }, state, depth + 1);
608
+ }
609
+
610
+ const artifacts = resolveArtifacts(imported);
611
+ if (!artifacts.length) {
612
+ throw new BridgeError("BRIDGE_ARTIFACT_NOT_FOUND", {
613
+ message: `Module "${specifier}" exposes no decorated artifact (exports: ${exportNames(imported).join(", ") || "none"})`,
614
+ action: "Export a decorated controller/socket/MCP/scheduler/injectable, or remove the entry.",
615
+ location: resolved.file,
616
+ entry: specifier,
617
+ module: resolved.package ?? specifier,
618
+ });
619
+ }
620
+
621
+ const packageName = context.package ?? resolved.package ?? packageNameFromSpecifier(specifier);
622
+ return artifacts.map(artifact => ({
623
+ name: artifact.name,
624
+ kind: artifact.kind,
625
+ construct: artifact.construct,
626
+ origin: context.origin,
627
+ ...(packageName ? {package: packageName} : {}),
628
+ file: resolved.file,
629
+ }));
630
+ }
631
+
632
+ protected static resolveDescriptor(
633
+ entry: MiddlewareBridgeDescriptor | HookBridgeDescriptor | PluginBridgeDescriptor | Record<string, any>,
634
+ context: EntryContext,
635
+ ): ResolvedBridgeArtifact {
636
+ const keys = ["plugin", "middleware", "hook"].filter(key => key in entry);
637
+ if (keys.length !== 1) {
638
+ throw new BridgeError("BRIDGE_ENTRY_INVALID", {
639
+ message: `Ambiguous bridge descriptor: expected exactly one of middleware, hook or plugin (${describeEntry(entry)})`,
640
+ action: "Declare `{ middleware }`, `{ hook, handler }` or `{ plugin }`.",
641
+ location: context.location,
642
+ entry: describeEntry(entry),
643
+ });
644
+ }
645
+
646
+ if (keys[0] === "plugin") {
647
+ const descriptor = entry as PluginBridgeDescriptor;
648
+ if (!descriptor.plugin || typeof descriptor.plugin !== "object" || typeof descriptor.plugin.setup !== "function") {
649
+ throw new BridgeError("BRIDGE_ENTRY_INVALID", {
650
+ message: "A plugin descriptor requires an object with a `setup` function",
651
+ action: "Pass `{ plugin: myPlugin }`.",
652
+ location: context.location,
653
+ entry: "plugin",
654
+ });
655
+ }
656
+ return {
657
+ name: descriptor.name || descriptor.plugin.name || "plugin",
658
+ kind: "plugin",
659
+ plugin: descriptor.plugin,
660
+ origin: context.origin,
661
+ ...(context.package ? {package: context.package} : {}),
662
+ };
663
+ }
664
+
665
+ if (keys[0] === "hook") {
666
+ const descriptor = entry as HookBridgeDescriptor;
667
+ if (!SUPPORTED_HOOK_NAMES.includes(descriptor.hook as any)) {
668
+ throw new BridgeError("BRIDGE_HOOK_UNKNOWN", {
669
+ message: `Unsupported bridge hook "${String(descriptor.hook)}"`,
670
+ action: `Use one of: ${SUPPORTED_HOOK_NAMES.join(", ")}.`,
671
+ location: context.location,
672
+ entry: String(descriptor.hook),
673
+ });
674
+ }
675
+ if (typeof descriptor.handler !== "function") {
676
+ throw new BridgeError("BRIDGE_ENTRY_INVALID", {
677
+ message: "A hook descriptor requires a `handler` function",
678
+ action: "Pass `{ hook: \"onRequest\", handler: myHook }`.",
679
+ location: context.location,
680
+ entry: "hook",
681
+ });
682
+ }
683
+ return {
684
+ name: descriptor.name || descriptor.handler.name || `bridge-${descriptor.hook}`,
685
+ kind: "hook",
686
+ hook: descriptor.hook,
687
+ handler: descriptor.handler,
688
+ origin: context.origin,
689
+ ...(context.package ? {package: context.package} : {}),
690
+ };
691
+ }
692
+
693
+ const descriptor = entry as MiddlewareBridgeDescriptor;
694
+ const middleware = descriptor.middleware;
695
+ if (typeof middleware !== "function" && (typeof middleware !== "object" || middleware === null)) {
696
+ throw new BridgeError("BRIDGE_ENTRY_INVALID", {
697
+ message: "A middleware descriptor requires a function, class or middleware object",
698
+ action: "Pass `{ middleware: myMiddleware }`.",
699
+ location: context.location,
700
+ entry: "middleware",
701
+ });
702
+ }
703
+ return {
704
+ name: descriptor.name || (middleware as any).name || "middleware",
705
+ kind: "middleware",
706
+ ...(isClass(middleware) ? {construct: middleware} : {middleware: middleware as any}),
707
+ origin: context.origin,
708
+ ...(context.package ? {package: context.package} : {}),
709
+ };
710
+ }
711
+
712
+ protected static adoptAll(artifacts: ResolvedBridgeArtifact[]): void {
713
+ for (const artifact of artifacts) {
714
+ if (typeof artifact.construct !== "function") continue;
715
+ const adopted = Injection.adopt(artifact.construct as any);
716
+ if (adopted.status === "collision") {
717
+ const previousFile = adopted.existing
718
+ ? Injection.getArtifactPath(adopted.name)
719
+ : undefined;
720
+ throw new BridgeError("BRIDGE_NAME_COLLISION", {
721
+ message: `Injection name "${adopted.name}" is already used by another class (${artifact.name})`,
722
+ action: "Rename one class or declare a unique name with @Injectable(lifetime, \"vendor:name\").",
723
+ location: artifact.file ?? previousFile,
724
+ entry: artifact.name,
725
+ package: artifact.package,
726
+ });
727
+ }
728
+ }
729
+ }
730
+
731
+ protected static async mountArtifact(
732
+ artifact: ResolvedBridgeArtifact,
733
+ application: ApplicationInterface,
734
+ strict: boolean,
735
+ ): Promise<void> {
736
+ const root: any = (application as any).root;
737
+
738
+ if (artifact.kind === "plugin") {
739
+ if (artifact.plugin) application.register(artifact.plugin);
740
+ ArtifactRegistry.add({
741
+ key: artifactKey({kind: "plugin", name: artifact.name, file: artifact.file, package: artifact.package}),
742
+ name: artifact.name,
743
+ kind: "plugin",
744
+ origin: artifact.origin,
745
+ pluginName: artifact.name,
746
+ ...(artifact.file ? {file: artifact.file} : {}),
747
+ ...(artifact.package ? {package: artifact.package} : {}),
748
+ });
749
+ return;
750
+ }
751
+
752
+ if (artifact.kind === "middleware") {
753
+ const pipeline: MiddlewarePipeline | undefined = root?.middleware;
754
+ if (!pipeline) return;
755
+ const instance = this.middlewareInstance(artifact);
756
+ if (this.hasMiddleware(pipeline, artifact.name, instance)) {
757
+ this._state.diagnostics.push(bridgeDiagnostic("BRIDGE_DUPLICATE_MOUNT", {
758
+ entry: artifact.name,
759
+ message: `Middleware "${artifact.name}" is already registered`,
760
+ }));
761
+ return;
762
+ }
763
+ pipeline.use(instance as any);
764
+ ArtifactRegistry.add({
765
+ key: artifactKey({kind: "middleware", name: artifact.name, file: artifact.file, package: artifact.package}),
766
+ name: artifact.name,
767
+ kind: "middleware",
768
+ origin: artifact.origin,
769
+ construct: artifact.construct,
770
+ middlewareName: artifact.name,
771
+ handler: instance as any,
772
+ ...(artifact.file ? {file: artifact.file} : {}),
773
+ ...(artifact.package ? {package: artifact.package} : {}),
774
+ });
775
+ return;
776
+ }
777
+
778
+ if (artifact.kind === "hook") {
779
+ const hooks: HookStore | undefined = root?.hooks;
780
+ if (!hooks || !artifact.hook || !artifact.handler) return;
781
+ if (hooks.hasHandler?.(artifact.hook, artifact.handler)) {
782
+ this._state.diagnostics.push(bridgeDiagnostic("BRIDGE_DUPLICATE_MOUNT", {
783
+ entry: artifact.name,
784
+ message: `Hook "${artifact.hook}" handler is already registered`,
785
+ }));
786
+ return;
787
+ }
788
+ hooks.add(artifact.hook, artifact.handler);
789
+ ArtifactRegistry.add({
790
+ key: artifactKey({kind: "hook", name: artifact.name, file: artifact.file, package: artifact.package}),
791
+ name: artifact.name,
792
+ kind: "hook",
793
+ origin: artifact.origin,
794
+ hookName: artifact.hook,
795
+ handler: artifact.handler,
796
+ ...(artifact.file ? {file: artifact.file} : {}),
797
+ ...(artifact.package ? {package: artifact.package} : {}),
798
+ });
799
+ return;
800
+ }
801
+
802
+ const construct = artifact.construct;
803
+ if (typeof construct !== "function") {
804
+ throw new BridgeError("BRIDGE_ARTIFACT_NOT_FOUND", {
805
+ message: `Bridge artifact "${artifact.name}" has no construct and cannot be mounted`,
806
+ entry: artifact.name,
807
+ location: artifact.file,
808
+ });
809
+ }
810
+
811
+ if (ArtifactRegistry.hasConstruct(construct)) {
812
+ this._state.diagnostics.push(bridgeDiagnostic("BRIDGE_DUPLICATE_MOUNT", {
813
+ entry: artifact.name,
814
+ message: `Artifact "${artifact.name}" is already mounted`,
815
+ }));
816
+ return;
817
+ }
818
+
819
+ await mountArtifact(construct as any, artifact.kind, application, {
820
+ origin: artifact.origin,
821
+ file: artifact.file,
822
+ package: artifact.package,
823
+ strictInjectables: strict,
824
+ });
825
+ }
826
+
827
+ protected static unmountArtifact(
828
+ record: MountedArtifactRecord | undefined,
829
+ application: ApplicationInterface,
830
+ ): void {
831
+ if (!record) return;
832
+ const root: any = (application as any).root;
833
+
834
+ if (record.kind === "controller") {
835
+ ControllerRouteTracker.removeRoutes(record.name, root?.router, "bridge", `bridge:${record.name}`);
836
+ Injection.invalidateCascade(record.name);
837
+ } else if (record.kind === "mcp") {
838
+ McpRouteTracker.removeRoutes(record.name, root?.router);
839
+ unregisterMcpServer(record.name);
840
+ Injection.invalidateCascade(record.name);
841
+ } else if (record.kind === "socket") {
842
+ const metadata = record.construct ? getSocketMetadata((record.construct as any).prototype ?? record.construct) : undefined;
843
+ if (metadata?.namespace) unregisterSocket(metadata.namespace);
844
+ Injection.invalidateCascade(record.name);
845
+ } else if (record.kind === "scheduler") {
846
+ unregisterScheduler(record.name);
847
+ const metadata = record.construct
848
+ ? getSchedulerMetadata((record.construct as any).prototype ?? record.construct)
849
+ : undefined;
850
+ if (metadata?.jobs?.length) {
851
+ SchedulerManager.current.unregister?.(metadata.jobs.map(job => job.name));
852
+ }
853
+ Injection.invalidateCascade(record.name);
854
+ } else if (record.kind === "middleware") {
855
+ if (record.handler) {
856
+ root?.middleware?.remove(record.handler as any);
857
+ } else if (record.middlewareName) {
858
+ root?.middleware?.remove(record.middlewareName);
859
+ }
860
+ } else if (record.kind === "hook") {
861
+ if (record.hookName && record.handler) root?.hooks?.remove(record.hookName, record.handler);
862
+ } else if (record.kind === "di") {
863
+ const definition = Injection.definition(record.name);
864
+ if (definition?.construct === record.construct) {
865
+ Injection.unregister(record.name);
866
+ } else {
867
+ Injection.invalidateCascade(record.name);
868
+ }
869
+ }
870
+
871
+ ArtifactRegistry.remove(record.key);
872
+ }
873
+
874
+ protected static mountedRecord(artifact: ResolvedBridgeArtifact): MountedArtifactRecord | undefined {
875
+ return ArtifactRegistry.getByKey(this.stableKey(artifact));
876
+ }
877
+
878
+ protected static stableKey(artifact: ResolvedBridgeArtifact): string {
879
+ return artifactKey({
880
+ kind: artifact.kind,
881
+ name: artifact.name,
882
+ file: artifact.file,
883
+ package: artifact.package,
884
+ });
885
+ }
886
+
887
+ protected static identityOf(artifact: ResolvedBridgeArtifact): unknown {
888
+ return artifact.construct ?? artifact.handler
889
+ ?? artifact.plugin ?? artifact.middleware ?? artifact.name;
890
+ }
891
+
892
+ protected static fileForConstruct(construct: unknown): string | undefined {
893
+ if (typeof construct !== "function") return undefined;
894
+ return Injection.getArtifactPath((construct as any).name);
895
+ }
896
+
897
+ protected static middlewareInstance(artifact: ResolvedBridgeArtifact): any {
898
+ const candidate: any = artifact.construct ?? artifact.middleware;
899
+ if (artifact.construct && isClass(artifact.construct)) {
900
+ try {
901
+ return Injection.resolve(artifact.construct as any);
902
+ } catch {
903
+ return new (artifact.construct as any)();
904
+ }
905
+ }
906
+ return candidate;
907
+ }
908
+
909
+ protected static hasMiddleware(pipeline: MiddlewarePipeline, name: string, instance: any): boolean {
910
+ if (pipeline.has?.(instance)) return true;
911
+ if (name && pipeline.hasName?.(name)) return true;
912
+ return false;
913
+ }
914
+ }