@lenne.tech/nest-server 12.9.4 → 12.10.1

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 (152) hide show
  1. package/.claude/rules/configurable-features.md +5 -1
  2. package/.claude/rules/package-management.md +38 -12
  3. package/.claude/rules/role-system.md +12 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/CLAUDE.md +10 -1
  6. package/FRAMEWORK-API.md +2 -1
  7. package/dist/core/common/decorators/rest-user.decorator.js +4 -0
  8. package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
  9. package/dist/core/common/filters/http-exception-log.filter.js +3 -0
  10. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  11. package/dist/core/common/helpers/context.helper.js +9 -0
  12. package/dist/core/common/helpers/context.helper.js.map +1 -1
  13. package/dist/core/common/helpers/decorator.helper.js +4 -0
  14. package/dist/core/common/helpers/decorator.helper.js.map +1 -1
  15. package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
  16. package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
  17. package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
  18. package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
  19. package/dist/core/common/helpers/graphql-upload.helper.js +237 -0
  20. package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
  21. package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
  22. package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
  23. package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
  24. package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
  25. package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
  26. package/dist/core/common/middleware/request-context.middleware.js +3 -0
  27. package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
  28. package/dist/core/common/plugins/complexity.plugin.js +73 -9
  29. package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
  30. package/dist/core/common/services/request-context.service.d.ts +2 -0
  31. package/dist/core/common/services/request-context.service.js +3 -0
  32. package/dist/core/common/services/request-context.service.js.map +1 -1
  33. package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
  34. package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
  35. package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
  36. package/dist/core/modules/ai/core-ai.constants.js +1 -0
  37. package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
  38. package/dist/core/modules/ai/core-ai.module.js +2 -0
  39. package/dist/core/modules/ai/core-ai.module.js.map +1 -1
  40. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
  41. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
  42. package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
  43. package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
  44. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
  45. package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
  46. package/dist/core/modules/ai/index.d.ts +8 -0
  47. package/dist/core/modules/ai/index.js +8 -0
  48. package/dist/core/modules/ai/index.js.map +1 -1
  49. package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
  50. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
  51. package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
  52. package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
  53. package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
  54. package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
  55. package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
  56. package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
  57. package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
  58. package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
  59. package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
  60. package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
  61. package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
  62. package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
  63. package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
  64. package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
  65. package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
  66. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
  67. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
  68. package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
  69. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
  70. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
  71. package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
  72. package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
  73. package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
  74. package/dist/core/modules/ai/services/core-ai.service.js +2 -7
  75. package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
  76. package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
  77. package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
  78. package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
  79. package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
  80. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
  81. package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
  82. package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
  83. package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
  84. package/dist/core/modules/auth/guards/auth.guard.js +10 -2
  85. package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
  86. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
  87. package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
  88. package/dist/core/modules/auth/guards/roles.guard.js +11 -1
  89. package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
  90. package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
  91. package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
  92. package/dist/core/modules/better-auth/better-auth.config.js +78 -0
  93. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  94. package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
  95. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  96. package/dist/core.module.js +2 -1
  97. package/dist/core.module.js.map +1 -1
  98. package/dist/index.d.ts +1 -0
  99. package/dist/index.js +1 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/types/graphql-upload.d.ts +34 -2
  102. package/docs/REQUEST-LIFECYCLE.md +59 -10
  103. package/migration-guides/12.10.0-to-12.10.1.md +182 -0
  104. package/migration-guides/12.9.3-to-12.9.4.md +3 -1
  105. package/migration-guides/12.9.x-to-12.10.x.md +271 -0
  106. package/package.json +46 -21
  107. package/src/core/common/decorators/rest-user.decorator.ts +6 -0
  108. package/src/core/common/filters/http-exception-log.filter.ts +8 -0
  109. package/src/core/common/helpers/context.helper.ts +14 -0
  110. package/src/core/common/helpers/decorator.helper.ts +5 -0
  111. package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
  112. package/src/core/common/helpers/graphql-upload.helper.ts +520 -0
  113. package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
  114. package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
  115. package/src/core/common/interfaces/server-options.interface.ts +98 -0
  116. package/src/core/common/middleware/request-context.middleware.ts +3 -0
  117. package/src/core/common/plugins/complexity.plugin.ts +150 -9
  118. package/src/core/common/services/request-context.service.ts +11 -0
  119. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
  120. package/src/core/modules/ai/README.md +101 -0
  121. package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
  122. package/src/core/modules/ai/core-ai.constants.ts +4 -0
  123. package/src/core/modules/ai/core-ai.module.ts +3 -0
  124. package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
  125. package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
  126. package/src/core/modules/ai/index.ts +8 -0
  127. package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
  128. package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
  129. package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
  130. package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
  131. package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
  132. package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
  133. package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
  134. package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
  135. package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
  136. package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
  137. package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
  138. package/src/core/modules/ai/services/core-ai.service.ts +5 -7
  139. package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
  140. package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
  141. package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
  142. package/src/core/modules/auth/guards/auth.guard.ts +19 -2
  143. package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
  144. package/src/core/modules/auth/guards/roles.guard.ts +23 -1
  145. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
  146. package/src/core/modules/better-auth/README.md +204 -0
  147. package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
  148. package/src/core/modules/better-auth/better-auth.config.ts +138 -1
  149. package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
  150. package/src/core.module.ts +5 -1
  151. package/src/index.ts +1 -0
  152. package/src/types/graphql-upload.d.ts +34 -2
@@ -20,6 +20,7 @@ export type {
20
20
  McpOAuthConsentTexts,
21
21
  } from './helpers/ai-mcp-oauth-consent.helper.js';
22
22
  export * from './helpers/ai-tool-authorization.helper.js';
23
+ export * from './helpers/ai-verified-user.helper.js';
23
24
  export * from './core-ai.controller.js';
24
25
  export * from './core-ai.module.js';
25
26
  export * from './core-ai.resolver.js';
@@ -66,10 +67,15 @@ export * from './models/core-ai-user-setting.model.js';
66
67
  export * from './models/core-ai-response.model.js';
67
68
  export * from './models/core-ai-usage-info.model.js';
68
69
  export * from './models/core-ai-usage.model.js';
70
+ export * from './decorators/ai-agent-function.decorator.js';
71
+ export * from './providers/ai-egress.helper.js';
72
+ export * from './providers/ai-sdk.packages.js';
73
+ export * from './providers/ai-sdk.provider.js';
69
74
  export * from './providers/claude-cli.provider.js';
70
75
  export * from './providers/llm-provider.factory.js';
71
76
  export * from './providers/openai-compatible.provider.js';
72
77
  export * from './services/ai-crypto.service.js';
78
+ export * from './services/core-ai-agent-function.bridge.js';
73
79
  export * from './services/core-ai-budget.service.js';
74
80
  export * from './services/core-ai-connection-preference.service.js';
75
81
  export * from './services/core-ai-connection-resolver.service.js';
@@ -89,6 +95,8 @@ export * from './services/core-ai-mode.service.js';
89
95
  export * from './services/core-ai-tool-policy.service.js';
90
96
  export * from './services/core-ai-user-setting.service.js';
91
97
  export * from './services/core-ai.service.js';
98
+ export * from './tools/ai-tool-result.helper.js';
99
+ export * from './tools/ai-tool-schema.helper.js';
92
100
  export * from './tools/ai-tool.base.js';
93
101
  export * from './tools/ai-tool.registry.js';
94
102
  export * from './tools/ask-user-question.tool.js';
@@ -129,7 +129,11 @@ export interface IAiTool {
129
129
  /** Unique tool name (snake_case recommended, stable across versions). */
130
130
  readonly name: string;
131
131
 
132
- /** JSON schema of the tool's input arguments (JSON-schema shape). */
132
+ /**
133
+ * The tool's input arguments: a JSON Schema object, or (12.10.0) a Standard Schema with JSON Schema — Zod 4.2+,
134
+ * ArkType, Valibot via `toStandardJsonSchema()`. `AiToolRegistry.register()` stores a Standard Schema as its JSON
135
+ * Schema and validates the arguments before `authorize()` and `execute()` (`withStandardSchemaParameters()`).
136
+ */
133
137
  readonly parameters: Record<string, any>;
134
138
 
135
139
  /**
@@ -145,6 +145,12 @@ export interface LlmCompletionOptions {
145
145
 
146
146
  /** Per-request timeout in milliseconds. */
147
147
  timeoutMs?: number;
148
+
149
+ /**
150
+ * Cancels the call (12.10.0). Honoured by the AI SDK transport (`AiSdkProvider`); a provider that ignores it still
151
+ * ends at `timeoutMs`.
152
+ */
153
+ abortSignal?: AbortSignal;
148
154
  }
149
155
 
150
156
  /**
@@ -29,6 +29,8 @@ export const AiMcpOAuthCodeSchema = createSchema(
29
29
  codeChallenge: { type: String },
30
30
  // The TTL: MongoDB gets its index from the service, a SQL table its sweep (`CorePersistenceLifecycle`)
31
31
  createdAt: { expires: AI_MCP_OAUTH_CODE_TTL_SECONDS, type: Date },
32
+ // RFC 8707 resource the code is bound to (12.10.0); absent on a code from before
33
+ resource: { type: String },
32
34
  userId: { type: String },
33
35
  },
34
36
  { autoIndex: false, collection: 'aiMcpOAuthCodes', versionKey: false },
@@ -39,6 +41,8 @@ export const AiMcpOAuthRefreshTokenSchema = createSchema(
39
41
  {
40
42
  clientId: { type: String },
41
43
  createdAt: { type: Date },
44
+ // RFC 8707 resource the grant is bound to (12.10.0); absent on a token from before — then /ai/mcp only
45
+ resource: { type: String },
42
46
  token: { index: { unique: true }, type: String },
43
47
  userId: { type: String },
44
48
  },
@@ -0,0 +1,98 @@
1
+ import { Logger, ServiceUnavailableException } from '@nestjs/common';
2
+
3
+ import { ConfigService } from '../../../common/services/config.service.js';
4
+ import { ErrorCode } from '../../error-code/error-codes.js';
5
+
6
+ /**
7
+ * The AI egress allowlist (`ai.allowedBaseUrlHosts`) as functions, for every outbound path the AI module constructs —
8
+ * the OpenAI-compatible provider and the AI SDK transport alike (nestjs-ai plan §2). One implementation, so a model
9
+ * provider a project builds with the AI SDK (`createAnthropic({ fetch })`) is held to exactly the rule the built-in
10
+ * provider is.
11
+ */
12
+
13
+ const logger = new Logger('AiEgress');
14
+
15
+ /**
16
+ * Lowercase, trim, and drop a fully-qualifying trailing dot — applied to BOTH the allowlist entry and the URL, so
17
+ * neither side wins by spelling one DNS name differently (`llm.example.com.` vs `llm.example.com`).
18
+ */
19
+ export function normaliseAiEgressHost(value: string): string {
20
+ return value
21
+ .trim()
22
+ .toLowerCase()
23
+ .replace(/\.(?=$|:)/, '');
24
+ }
25
+
26
+ /**
27
+ * The configured allowlist as normalised entries; `[]` when unset (permissive — a local Ollama works out of the box).
28
+ *
29
+ * A comma-separated STRING is split rather than rejected: `NSC__AI__ALLOWED_BASE_URL_HOSTS` arrives as one, and reading
30
+ * it as "not configured" silently switched the control off until 11.39.x. A value that is neither array nor string
31
+ * carries no hostnames: the list is empty and that is LOGGED, because from the outside it looks exactly like "unset".
32
+ */
33
+ export function resolveAiEgressAllowlist(log: Pick<Logger, 'error'> = logger): string[] {
34
+ const configured = ConfigService.get<unknown>('ai.allowedBaseUrlHosts');
35
+ if (configured === undefined || configured === null) {
36
+ return [];
37
+ }
38
+ const entries = typeof configured === 'string' ? configured.split(',') : configured;
39
+ if (!Array.isArray(entries)) {
40
+ log.error(
41
+ `ai.allowedBaseUrlHosts is a ${typeof configured} and carries no hostnames — the SSRF egress ` +
42
+ 'allowlist is NOT active. Use an array or a comma-separated string.',
43
+ );
44
+ return [];
45
+ }
46
+ return entries.map((host) => normaliseAiEgressHost(String(host))).filter(Boolean);
47
+ }
48
+
49
+ /**
50
+ * The spellings of a URL's host an allowlist entry may name: `host` (with a non-default port), `hostname` (any port),
51
+ * and `hostname:<default port>` for an operator who wrote the port out. Nothing here widens the set of reachable hosts.
52
+ */
53
+ export function aiEgressHostCandidates(url: URL): string[] {
54
+ const defaultPort = url.protocol === 'https:' ? '443' : url.protocol === 'http:' ? '80' : '';
55
+ const candidates = [url.host, url.hostname];
56
+ if (defaultPort && url.host === url.hostname) {
57
+ candidates.push(`${url.hostname}:${defaultPort}`);
58
+ }
59
+ return candidates;
60
+ }
61
+
62
+ /**
63
+ * Throws `ServiceUnavailableException` (`AI_CONNECTION_NOT_AVAILABLE`) when an allowlist is configured and the URL's
64
+ * host is not on it, `AI_CONNECTION_INVALID_URL` when the URL does not parse. No allowlist → every URL passes.
65
+ */
66
+ export function assertAiEgressAllowed(url: string | URL, connectionName = 'AI connection'): void {
67
+ const allowedHosts = resolveAiEgressAllowlist();
68
+ if (!allowedHosts.length) {
69
+ return;
70
+ }
71
+ let parsed: URL;
72
+ try {
73
+ parsed = url instanceof URL ? url : new URL(url);
74
+ } catch {
75
+ throw new ServiceUnavailableException(ErrorCode.AI_CONNECTION_INVALID_URL);
76
+ }
77
+ const candidates = aiEgressHostCandidates(parsed).map(normaliseAiEgressHost);
78
+ if (!candidates.some((candidate) => allowedHosts.includes(candidate))) {
79
+ logger.warn(`AI connection "${connectionName}" host "${parsed.host}" is not in ai.allowedBaseUrlHosts`);
80
+ throw new ServiceUnavailableException(ErrorCode.AI_CONNECTION_NOT_AVAILABLE);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * A `fetch` that refuses every URL outside `ai.allowedBaseUrlHosts` before sending — for a model provider a project
86
+ * builds itself (`createAnthropic({ apiKey, fetch })`). Hand it to the provider; the AI SDK provider packages send every
87
+ * request through the `fetch` they were given. The allowlist is read on every call, so a configuration change applies
88
+ * without a restart.
89
+ */
90
+ export function createAiEgressFetch(connectionName = 'AI connection', base: typeof fetch = fetch): typeof fetch {
91
+ // async: a refusal is a rejected promise, as every fetch failure is — never a synchronous throw
92
+ const guarded = async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
93
+ const url = typeof input === 'string' || input instanceof URL ? input : input.url;
94
+ assertAiEgressAllowed(url, connectionName);
95
+ return base(input, init);
96
+ };
97
+ return guarded as typeof fetch;
98
+ }
@@ -0,0 +1,153 @@
1
+ import { createRequire } from 'node:module';
2
+ import { join } from 'node:path';
3
+
4
+ /**
5
+ * The optional AI SDK and NestJS AI packages, loaded lazily and checked against the versions this release was tested
6
+ * with (nestjs-ai plan §2, principle 2).
7
+ *
8
+ * `ai`, `@nestjs/ai` and `@nestjs/resilience` are OPTIONAL peers: a project that does not install them loads nothing
9
+ * here. A project that does gets a loud error naming the package and the tested range when the installed version lies
10
+ * outside it, or when the members the framework calls are missing — never a quiet misbehaviour of a 0.0.x release.
11
+ * Each check runs once per process.
12
+ */
13
+
14
+ /** The version ranges each package was tested with: `[lowest inclusive, highest exclusive]`. */
15
+ export const AI_SDK_TESTED_RANGES = {
16
+ '@nestjs/ai': ['0.0.2', '0.0.3'],
17
+ '@nestjs/resilience': ['0.0.3', '0.0.4'],
18
+ ai: ['7.0.0', '8.0.0'],
19
+ } as const satisfies Record<string, readonly [string, string]>;
20
+
21
+ export type AiSdkPackageName = keyof typeof AI_SDK_TESTED_RANGES;
22
+
23
+ /** A package is missing, outside its tested range, or lacks a member the framework calls. */
24
+ export class AiSdkPackageError extends Error {
25
+ constructor(message: string) {
26
+ super(message);
27
+ this.name = 'AiSdkPackageError';
28
+ }
29
+ }
30
+
31
+ const checked = new Map<AiSdkPackageName, Promise<any>>();
32
+
33
+ /** The tested range of a package, as people read it (`>=0.0.2 <0.0.3`). */
34
+ export function aiSdkTestedRange(name: AiSdkPackageName): string {
35
+ const [low, high] = AI_SDK_TESTED_RANGES[name];
36
+ return `>=${low} <${high}`;
37
+ }
38
+
39
+ /**
40
+ * Compares two release versions numerically. A pre-release (`1.2.3-beta.1`) compares as lower than its release, so
41
+ * `7.0.0-beta` is outside `>=7.0.0` — a pre-release was not tested.
42
+ */
43
+ export function compareReleaseVersions(a: string, b: string): number {
44
+ const parse = (value: string) => {
45
+ const [core, pre] = value.split('-', 2);
46
+ return { parts: core.split('.').map((part) => Number.parseInt(part, 10) || 0), pre: pre !== undefined };
47
+ };
48
+ const left = parse(a);
49
+ const right = parse(b);
50
+ for (let i = 0; i < 3; i++) {
51
+ const diff = (left.parts[i] ?? 0) - (right.parts[i] ?? 0);
52
+ if (diff !== 0) {
53
+ return diff;
54
+ }
55
+ }
56
+ return left.pre === right.pre ? 0 : left.pre ? -1 : 1;
57
+ }
58
+
59
+ /** Whether `version` lies in the tested range of `name`. */
60
+ export function isTestedAiSdkVersion(name: AiSdkPackageName, version: string): boolean {
61
+ const [low, high] = AI_SDK_TESTED_RANGES[name];
62
+ return compareReleaseVersions(version, low) >= 0 && compareReleaseVersions(version, high) < 0;
63
+ }
64
+
65
+ /**
66
+ * The installed version of a package, resolved from the project (`process.cwd()`), the way the framework loads project
67
+ * files (`.claude/rules/architecture.md` → Module Format). `undefined` when its `package.json` cannot be read — the
68
+ * member check below still runs then.
69
+ */
70
+ function installedVersion(name: AiSdkPackageName): string | undefined {
71
+ try {
72
+ const requireFromProject = createRequire(join(process.cwd(), 'package.json'));
73
+ return requireFromProject(`${name}/package.json`)?.version;
74
+ } catch {
75
+ return undefined;
76
+ }
77
+ }
78
+
79
+ /** The members of each package the framework calls; a release without them is refused. */
80
+ const REQUIRED_MEMBERS: Record<AiSdkPackageName, (module: any) => string[]> = {
81
+ '@nestjs/ai': (module) => [
82
+ typeof module.AiModels?.prototype?.get === 'function' ? '' : 'AiModels.get()',
83
+ typeof module.AiTools?.prototype?.call === 'function' ? '' : 'AiTools.call()',
84
+ 'tools' in (module.AiTools?.prototype ?? {}) ? '' : 'AiTools.tools',
85
+ ],
86
+ '@nestjs/resilience': (module) => [
87
+ typeof module.ResiliencePolicy?.wrap === 'function' ? '' : 'ResiliencePolicy.wrap()',
88
+ typeof module.RetryPolicy === 'function' ? '' : 'RetryPolicy',
89
+ typeof module.TimeoutPolicy === 'function' ? '' : 'TimeoutPolicy',
90
+ ],
91
+ ai: (module) => [
92
+ typeof module.generateText === 'function' ? '' : 'generateText()',
93
+ typeof module.jsonSchema === 'function' ? '' : 'jsonSchema()',
94
+ ],
95
+ };
96
+
97
+ /**
98
+ * Checks a loaded package: tested version range and the members the framework calls. Exported for the tests; the
99
+ * loaders below call it once per package.
100
+ */
101
+ export function assertAiSdkPackage(name: AiSdkPackageName, module: unknown, version: string | undefined): void {
102
+ if (version !== undefined && !isTestedAiSdkVersion(name, version)) {
103
+ throw new AiSdkPackageError(
104
+ `${name}@${version} is installed, but @lenne.tech/nest-server was tested with ${name} ${aiSdkTestedRange(name)}. ` +
105
+ `Install a version in that range, or update @lenne.tech/nest-server. The framework refuses to run an untested ` +
106
+ `release of a 0.x package rather than misbehave with it.`,
107
+ );
108
+ }
109
+ const missing = REQUIRED_MEMBERS[name](module).filter(Boolean);
110
+ if (missing.length) {
111
+ throw new AiSdkPackageError(
112
+ `${name}${version ? `@${version}` : ''} lacks ${missing.join(', ')}, which @lenne.tech/nest-server calls. ` +
113
+ `Tested range: ${name} ${aiSdkTestedRange(name)}.`,
114
+ );
115
+ }
116
+ }
117
+
118
+ async function load(name: AiSdkPackageName, importer: () => Promise<unknown>, feature: string): Promise<any> {
119
+ let pending = checked.get(name);
120
+ if (!pending) {
121
+ pending = importer().then(
122
+ (module) => {
123
+ assertAiSdkPackage(name, module, installedVersion(name));
124
+ return module;
125
+ },
126
+ (error: unknown) => {
127
+ throw new AiSdkPackageError(
128
+ `${feature} needs the package "${name}" (tested range ${aiSdkTestedRange(name)}), which could not be loaded: ` +
129
+ `${(error as Error)?.message ?? error}. Install it in the project.`,
130
+ );
131
+ },
132
+ );
133
+ // A failure is not cached: the next attempt (after the project installed the package) tries again
134
+ pending.catch(() => checked.delete(name));
135
+ checked.set(name, pending);
136
+ }
137
+ return pending;
138
+ }
139
+
140
+ /** The AI SDK (`ai`). `feature` names what needs it, in configuration words, for the error message. */
141
+ export function loadAiSdk(feature: string): Promise<any> {
142
+ return load('ai', () => import('ai'), feature);
143
+ }
144
+
145
+ /** `@nestjs/ai`. */
146
+ export function loadNestjsAi(feature: string): Promise<any> {
147
+ return load('@nestjs/ai', () => import('@nestjs/ai'), feature);
148
+ }
149
+
150
+ /** `@nestjs/resilience` (a required peer of `@nestjs/ai`). */
151
+ export function loadNestjsResilience(feature: string): Promise<any> {
152
+ return load('@nestjs/resilience', () => import('@nestjs/resilience'), feature);
153
+ }