@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.
- package/.claude/rules/configurable-features.md +5 -1
- package/.claude/rules/package-management.md +38 -12
- package/.claude/rules/role-system.md +12 -0
- package/.claude/rules/testing.md +4 -4
- package/CLAUDE.md +10 -1
- package/FRAMEWORK-API.md +2 -1
- package/dist/core/common/decorators/rest-user.decorator.js +4 -0
- package/dist/core/common/decorators/rest-user.decorator.js.map +1 -1
- package/dist/core/common/filters/http-exception-log.filter.js +3 -0
- package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
- package/dist/core/common/helpers/context.helper.js +9 -0
- package/dist/core/common/helpers/context.helper.js.map +1 -1
- package/dist/core/common/helpers/decorator.helper.js +4 -0
- package/dist/core/common/helpers/decorator.helper.js.map +1 -1
- package/dist/core/common/helpers/execution-context-request.helper.d.ts +14 -1
- package/dist/core/common/helpers/execution-context-request.helper.js +36 -0
- package/dist/core/common/helpers/execution-context-request.helper.js.map +1 -1
- package/dist/core/common/helpers/graphql-upload.helper.d.ts +10 -0
- package/dist/core/common/helpers/graphql-upload.helper.js +237 -0
- package/dist/core/common/helpers/graphql-upload.helper.js.map +1 -0
- package/dist/core/common/helpers/redact-secrets.helper.js +7 -2
- package/dist/core/common/helpers/redact-secrets.helper.js.map +1 -1
- package/dist/core/common/interceptors/translate-response.interceptor.js +4 -0
- package/dist/core/common/interceptors/translate-response.interceptor.js.map +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +11 -0
- package/dist/core/common/middleware/request-context.middleware.js +3 -0
- package/dist/core/common/middleware/request-context.middleware.js.map +1 -1
- package/dist/core/common/plugins/complexity.plugin.js +73 -9
- package/dist/core/common/plugins/complexity.plugin.js.map +1 -1
- package/dist/core/common/services/request-context.service.d.ts +2 -0
- package/dist/core/common/services/request-context.service.js +3 -0
- package/dist/core/common/services/request-context.service.js.map +1 -1
- package/dist/core/modules/ai/core-ai-mcp.controller.js +4 -2
- package/dist/core/modules/ai/core-ai-mcp.controller.js.map +1 -1
- package/dist/core/modules/ai/core-ai.constants.d.ts +1 -0
- package/dist/core/modules/ai/core-ai.constants.js +1 -0
- package/dist/core/modules/ai/core-ai.constants.js.map +1 -1
- package/dist/core/modules/ai/core-ai.module.js +2 -0
- package/dist/core/modules/ai/core-ai.module.js.map +1 -1
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.d.ts +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js +8 -0
- package/dist/core/modules/ai/decorators/ai-agent-function.decorator.js.map +1 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.d.ts +12 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js +23 -0
- package/dist/core/modules/ai/helpers/ai-verified-user.helper.js.map +1 -0
- package/dist/core/modules/ai/index.d.ts +8 -0
- package/dist/core/modules/ai/index.js +8 -0
- package/dist/core/modules/ai/index.js.map +1 -1
- package/dist/core/modules/ai/interfaces/llm-provider.interface.d.ts +1 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js +2 -0
- package/dist/core/modules/ai/models/core-ai-mcp-oauth.models.js.map +1 -1
- package/dist/core/modules/ai/providers/ai-egress.helper.d.ts +6 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js +58 -0
- package/dist/core/modules/ai/providers/ai-egress.helper.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.d.ts +16 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js +99 -0
- package/dist/core/modules/ai/providers/ai-sdk.packages.js.map +1 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.d.ts +51 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js +244 -0
- package/dist/core/modules/ai/providers/ai-sdk.provider.js.map +1 -0
- package/dist/core/modules/ai/providers/llm-provider.factory.d.ts +11 -1
- package/dist/core/modules/ai/providers/llm-provider.factory.js +44 -3
- package/dist/core/modules/ai/providers/llm-provider.factory.js.map +1 -1
- package/dist/core/modules/ai/providers/openai-compatible.provider.js +4 -21
- package/dist/core/modules/ai/providers/openai-compatible.provider.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.d.ts +34 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js +130 -0
- package/dist/core/modules/ai/services/core-ai-agent-function.bridge.js.map +1 -0
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.d.ts +28 -3
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js +141 -15
- package/dist/core/modules/ai/services/core-ai-mcp-oauth.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js +2 -1
- package/dist/core/modules/ai/services/core-ai-mcp.service.js.map +1 -1
- package/dist/core/modules/ai/services/core-ai.service.js +2 -7
- package/dist/core/modules/ai/services/core-ai.service.js.map +1 -1
- package/dist/core/modules/ai/tools/ai-tool-result.helper.d.ts +2 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js +117 -0
- package/dist/core/modules/ai/tools/ai-tool-result.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.d.ts +36 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js +81 -0
- package/dist/core/modules/ai/tools/ai-tool-schema.helper.js.map +1 -0
- package/dist/core/modules/ai/tools/ai-tool.registry.js +2 -1
- package/dist/core/modules/ai/tools/ai-tool.registry.js.map +1 -1
- package/dist/core/modules/auth/guards/auth.guard.js +10 -2
- package/dist/core/modules/auth/guards/auth.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js +4 -1
- package/dist/core/modules/auth/guards/legacy-auth-rate-limit.guard.js.map +1 -1
- package/dist/core/modules/auth/guards/roles.guard.js +11 -1
- package/dist/core/modules/auth/guards/roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js +15 -1
- package/dist/core/modules/better-auth/better-auth-roles.guard.js.map +1 -1
- package/dist/core/modules/better-auth/better-auth.config.js +78 -0
- package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
- package/dist/core/modules/tenant/core-tenant.guard.js +9 -1
- package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
- package/dist/core.module.js +2 -1
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/types/graphql-upload.d.ts +34 -2
- package/docs/REQUEST-LIFECYCLE.md +59 -10
- package/migration-guides/12.10.0-to-12.10.1.md +182 -0
- package/migration-guides/12.9.3-to-12.9.4.md +3 -1
- package/migration-guides/12.9.x-to-12.10.x.md +271 -0
- package/package.json +46 -21
- package/src/core/common/decorators/rest-user.decorator.ts +6 -0
- package/src/core/common/filters/http-exception-log.filter.ts +8 -0
- package/src/core/common/helpers/context.helper.ts +14 -0
- package/src/core/common/helpers/decorator.helper.ts +5 -0
- package/src/core/common/helpers/execution-context-request.helper.ts +97 -1
- package/src/core/common/helpers/graphql-upload.helper.ts +520 -0
- package/src/core/common/helpers/redact-secrets.helper.ts +22 -3
- package/src/core/common/interceptors/translate-response.interceptor.ts +8 -0
- package/src/core/common/interfaces/server-options.interface.ts +98 -0
- package/src/core/common/middleware/request-context.middleware.ts +3 -0
- package/src/core/common/plugins/complexity.plugin.ts +150 -9
- package/src/core/common/services/request-context.service.ts +11 -0
- package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +16 -0
- package/src/core/modules/ai/README.md +101 -0
- package/src/core/modules/ai/core-ai-mcp.controller.ts +7 -2
- package/src/core/modules/ai/core-ai.constants.ts +4 -0
- package/src/core/modules/ai/core-ai.module.ts +3 -0
- package/src/core/modules/ai/decorators/ai-agent-function.decorator.ts +44 -0
- package/src/core/modules/ai/helpers/ai-verified-user.helper.ts +47 -0
- package/src/core/modules/ai/index.ts +8 -0
- package/src/core/modules/ai/interfaces/ai-tool.interface.ts +5 -1
- package/src/core/modules/ai/interfaces/llm-provider.interface.ts +6 -0
- package/src/core/modules/ai/models/core-ai-mcp-oauth.models.ts +4 -0
- package/src/core/modules/ai/providers/ai-egress.helper.ts +98 -0
- package/src/core/modules/ai/providers/ai-sdk.packages.ts +153 -0
- package/src/core/modules/ai/providers/ai-sdk.provider.ts +383 -0
- package/src/core/modules/ai/providers/llm-provider.factory.ts +93 -2
- package/src/core/modules/ai/providers/openai-compatible.provider.ts +5 -23
- package/src/core/modules/ai/services/core-ai-agent-function.bridge.ts +170 -0
- package/src/core/modules/ai/services/core-ai-mcp-oauth.service.ts +240 -20
- package/src/core/modules/ai/services/core-ai-mcp.service.ts +3 -1
- package/src/core/modules/ai/services/core-ai.service.ts +5 -7
- package/src/core/modules/ai/tools/ai-tool-result.helper.ts +153 -0
- package/src/core/modules/ai/tools/ai-tool-schema.helper.ts +134 -0
- package/src/core/modules/ai/tools/ai-tool.registry.ts +6 -1
- package/src/core/modules/auth/guards/auth.guard.ts +19 -2
- package/src/core/modules/auth/guards/legacy-auth-rate-limit.guard.ts +9 -2
- package/src/core/modules/auth/guards/roles.guard.ts +23 -1
- package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +11 -0
- package/src/core/modules/better-auth/README.md +204 -0
- package/src/core/modules/better-auth/better-auth-roles.guard.ts +29 -1
- package/src/core/modules/better-auth/better-auth.config.ts +138 -1
- package/src/core/modules/tenant/core-tenant.guard.ts +13 -1
- package/src/core.module.ts +5 -1
- package/src/index.ts +1 -0
- 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
|
-
/**
|
|
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
|
+
}
|