@webiny/api-core 6.6.0-alpha.1 → 6.6.0-alpha.10
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/ApiCoreFeature.js +6 -2
- package/ApiCoreFeature.js.map +1 -1
- package/exports/api/tasks.d.ts +1 -0
- package/exports/api/tasks.js +1 -1
- package/exports/api.d.ts +1 -1
- package/exports/api.js +1 -1
- package/features/ai/Ai.d.ts +3 -1
- package/features/ai/Ai.js +36 -28
- package/features/ai/Ai.js.map +1 -1
- package/features/ai/AiModelRegistry.d.ts +14 -0
- package/features/ai/AiModelRegistry.js +39 -0
- package/features/ai/AiModelRegistry.js.map +1 -0
- package/features/ai/AiSdkToolHandlerResolver.d.ts +11 -0
- package/features/ai/AiSdkToolHandlerResolver.js +19 -0
- package/features/ai/AiSdkToolHandlerResolver.js.map +1 -0
- package/features/ai/AiSdkTools.d.ts +4 -3
- package/features/ai/AiSdkTools.js +11 -9
- package/features/ai/AiSdkTools.js.map +1 -1
- package/features/ai/AnthropicSdkFactory.js +12 -4
- package/features/ai/AnthropicSdkFactory.js.map +1 -1
- package/features/ai/DEVELOPERS.md +183 -0
- package/features/ai/GoogleSdkFactory.d.ts +10 -0
- package/features/ai/GoogleSdkFactory.js +65 -0
- package/features/ai/GoogleSdkFactory.js.map +1 -0
- package/features/ai/OpenAiSdkFactory.js +51 -11
- package/features/ai/OpenAiSdkFactory.js.map +1 -1
- package/features/ai/OpenRouterSdkFactory.d.ts +10 -0
- package/features/ai/OpenRouterSdkFactory.js +112 -0
- package/features/ai/OpenRouterSdkFactory.js.map +1 -0
- package/features/ai/RemoteAiModelCatalog.d.ts +13 -0
- package/features/ai/RemoteAiModelCatalog.js +74 -0
- package/features/ai/RemoteAiModelCatalog.js.map +1 -0
- package/features/ai/abstractions.d.ts +82 -6
- package/features/ai/abstractions.js +6 -2
- package/features/ai/abstractions.js.map +1 -1
- package/features/ai/feature.js +10 -0
- package/features/ai/feature.js.map +1 -1
- package/features/ai/index.d.ts +2 -4
- package/features/ai/index.js +1 -1
- package/features/debugger/Debugger.d.ts +30 -0
- package/features/debugger/Debugger.js +142 -0
- package/features/debugger/Debugger.js.map +1 -0
- package/features/debugger/DebuggerRouteDecorator.d.ts +45 -0
- package/features/debugger/DebuggerRouteDecorator.js +102 -0
- package/features/debugger/DebuggerRouteDecorator.js.map +1 -0
- package/features/debugger/GraphQLDebuggerTransport.d.ts +28 -0
- package/features/debugger/GraphQLDebuggerTransport.js +45 -0
- package/features/debugger/GraphQLDebuggerTransport.js.map +1 -0
- package/features/debugger/__tests__/matchNamespace.test.d.ts +1 -0
- package/features/debugger/__tests__/matchNamespace.test.js +68 -0
- package/features/debugger/__tests__/matchNamespace.test.js.map +1 -0
- package/features/debugger/__tests__/serialize.test.d.ts +1 -0
- package/features/debugger/__tests__/serialize.test.js +220 -0
- package/features/debugger/__tests__/serialize.test.js.map +1 -0
- package/features/debugger/abstractions.d.ts +100 -0
- package/features/debugger/abstractions.js +6 -0
- package/features/debugger/abstractions.js.map +1 -0
- package/features/debugger/feature.d.ts +5 -0
- package/features/debugger/feature.js +15 -0
- package/features/debugger/feature.js.map +1 -0
- package/features/debugger/index.d.ts +12 -0
- package/features/debugger/index.js +7 -0
- package/features/debugger/limits.d.ts +18 -0
- package/features/debugger/limits.js +11 -0
- package/features/debugger/limits.js.map +1 -0
- package/features/debugger/matchNamespace.d.ts +14 -0
- package/features/debugger/matchNamespace.js +35 -0
- package/features/debugger/matchNamespace.js.map +1 -0
- package/features/debugger/parseNamespaceHeader.d.ts +7 -0
- package/features/debugger/parseNamespaceHeader.js +16 -0
- package/features/debugger/parseNamespaceHeader.js.map +1 -0
- package/features/debugger/permissions.d.ts +14 -0
- package/features/debugger/permissions.js +8 -0
- package/features/debugger/permissions.js.map +1 -0
- package/features/debugger/permissionsSchema.d.ts +17 -0
- package/features/debugger/permissionsSchema.js +18 -0
- package/features/debugger/permissionsSchema.js.map +1 -0
- package/features/debugger/serialize.d.ts +11 -0
- package/features/debugger/serialize.js +121 -0
- package/features/debugger/serialize.js.map +1 -0
- package/features/encryption/BuildParamsEncryptionConfig.d.ts +13 -0
- package/features/encryption/BuildParamsEncryptionConfig.js +19 -0
- package/features/encryption/BuildParamsEncryptionConfig.js.map +1 -0
- package/features/encryption/EncryptionKeyCacheFeature.d.ts +8 -0
- package/features/encryption/EncryptionKeyCacheFeature.js +11 -0
- package/features/encryption/EncryptionKeyCacheFeature.js.map +1 -0
- package/features/encryption/EncryptionService.d.ts +3 -2
- package/features/encryption/EncryptionService.js +15 -13
- package/features/encryption/EncryptionService.js.map +1 -1
- package/features/encryption/MemoryEncryptionKeyCache.d.ts +13 -0
- package/features/encryption/MemoryEncryptionKeyCache.js +26 -0
- package/features/encryption/MemoryEncryptionKeyCache.js.map +1 -0
- package/features/encryption/abstractions.d.ts +26 -0
- package/features/encryption/abstractions.js +3 -1
- package/features/encryption/abstractions.js.map +1 -1
- package/features/encryption/feature.js +2 -0
- package/features/encryption/feature.js.map +1 -1
- package/features/encryption/index.d.ts +3 -0
- package/features/encryption/index.js +3 -1
- package/features/featureFlags/decorators/FeatureFlagsWithLicenseDecorator.js +13 -1
- package/features/featureFlags/decorators/FeatureFlagsWithLicenseDecorator.js.map +1 -1
- package/features/hashing/BuildParamsHashingConfig.d.ts +11 -0
- package/features/hashing/BuildParamsHashingConfig.js +18 -0
- package/features/hashing/BuildParamsHashingConfig.js.map +1 -0
- package/features/hashing/ScryptHasher.d.ts +2 -2
- package/features/hashing/ScryptHasher.js +6 -8
- package/features/hashing/ScryptHasher.js.map +1 -1
- package/features/hashing/abstractions.d.ts +15 -0
- package/features/hashing/abstractions.js +2 -1
- package/features/hashing/abstractions.js.map +1 -1
- package/features/hashing/feature.js +2 -0
- package/features/hashing/feature.js.map +1 -1
- package/features/hashing/index.d.ts +1 -0
- package/features/hashing/index.js +1 -1
- package/features/httpClient/HttpClient.d.ts +7 -0
- package/features/httpClient/HttpClient.js +72 -0
- package/features/httpClient/HttpClient.js.map +1 -0
- package/features/httpClient/HttpRequestError.d.ts +10 -0
- package/features/httpClient/HttpRequestError.js +13 -0
- package/features/httpClient/HttpRequestError.js.map +1 -0
- package/features/httpClient/HttpStatusError.d.ts +12 -0
- package/features/httpClient/HttpStatusError.js +12 -0
- package/features/httpClient/HttpStatusError.js.map +1 -0
- package/features/httpClient/abstractions.d.ts +32 -0
- package/features/httpClient/abstractions.js +5 -0
- package/features/httpClient/abstractions.js.map +1 -0
- package/features/{logger → httpClient}/feature.d.ts +1 -1
- package/features/httpClient/feature.js +11 -0
- package/features/httpClient/feature.js.map +1 -0
- package/features/httpClient/index.d.ts +3 -0
- package/features/httpClient/index.js +3 -0
- package/features/keyValueStore/GlobalKeyValueStore.d.ts +9 -3
- package/features/keyValueStore/GlobalKeyValueStore.js +12 -2
- package/features/keyValueStore/GlobalKeyValueStore.js.map +1 -1
- package/features/keyValueStore/KeyValueStore.d.ts +6 -2
- package/features/keyValueStore/KeyValueStore.js +13 -3
- package/features/keyValueStore/KeyValueStore.js.map +1 -1
- package/features/keyValueStore/KeyValueStoreRepository.d.ts +8 -2
- package/features/keyValueStore/KeyValueStoreRepository.js +82 -4
- package/features/keyValueStore/KeyValueStoreRepository.js.map +1 -1
- package/features/keyValueStore/abstractions.d.ts +132 -14
- package/features/keyValueStore/abstractions.js.map +1 -1
- package/features/keyValueStore/errors.d.ts +29 -0
- package/features/keyValueStore/errors.js +49 -1
- package/features/keyValueStore/errors.js.map +1 -1
- package/features/keyValueStore/index.d.ts +4 -1
- package/features/keyValueStore/index.js +1 -1
- package/features/logger/NullLogger.d.ts +10 -0
- package/features/logger/NullLogger.js +12 -0
- package/features/logger/NullLogger.js.map +1 -0
- package/features/logger/index.d.ts +1 -0
- package/features/logger/index.js +1 -0
- package/features/publicUrls/NullPublicUrls.d.ts +11 -0
- package/features/publicUrls/NullPublicUrls.js +17 -0
- package/features/publicUrls/NullPublicUrls.js.map +1 -0
- package/features/publicUrls/PublicUrl.d.ts +24 -0
- package/features/publicUrls/PublicUrl.js +43 -0
- package/features/publicUrls/PublicUrl.js.map +1 -0
- package/features/publicUrls/__tests__/PublicUrl.test.d.ts +1 -0
- package/features/publicUrls/__tests__/PublicUrl.test.js +38 -0
- package/features/publicUrls/__tests__/PublicUrl.test.js.map +1 -0
- package/features/publicUrls/__tests__/PublicUrls.test.d.ts +1 -0
- package/features/publicUrls/__tests__/PublicUrls.test.js +14 -0
- package/features/publicUrls/__tests__/PublicUrls.test.js.map +1 -0
- package/features/publicUrls/abstractions.d.ts +27 -0
- package/features/publicUrls/abstractions.js +5 -0
- package/features/publicUrls/abstractions.js.map +1 -0
- package/features/publicUrls/feature.d.ts +8 -0
- package/features/publicUrls/feature.js +11 -0
- package/features/publicUrls/feature.js.map +1 -0
- package/features/publicUrls/index.d.ts +3 -0
- package/features/publicUrls/index.js +3 -0
- package/features/requestContext/RawAssumePermissions.d.ts +14 -0
- package/features/requestContext/RawAssumePermissions.js +19 -0
- package/features/requestContext/RawAssumePermissions.js.map +1 -0
- package/features/requestContext/abstractions.d.ts +22 -0
- package/features/requestContext/abstractions.js +2 -1
- package/features/requestContext/abstractions.js.map +1 -1
- package/features/requestContext/extractAssumePermissions.d.ts +14 -0
- package/features/requestContext/extractAssumePermissions.js +32 -0
- package/features/requestContext/extractAssumePermissions.js.map +1 -0
- package/features/requestContext/feature.d.ts +2 -1
- package/features/requestContext/feature.js +2 -0
- package/features/requestContext/feature.js.map +1 -1
- package/features/requestContext/index.d.ts +3 -1
- package/features/requestContext/index.js +2 -1
- package/features/security/IdentityContext/IdentityContext.d.ts +6 -2
- package/features/security/IdentityContext/IdentityContext.js +24 -7
- package/features/security/IdentityContext/IdentityContext.js.map +1 -1
- package/features/security/IdentityContext/abstractions.d.ts +6 -1
- package/features/security/IdentityContext/abstractions.js.map +1 -1
- package/features/security/authorization/AuthorizationContext/AuthorizationContext.d.ts +13 -3
- package/features/security/authorization/AuthorizationContext/AuthorizationContext.js +35 -22
- package/features/security/authorization/AuthorizationContext/AuthorizationContext.js.map +1 -1
- package/features/security/authorization/AuthorizationContext/abstractions.d.ts +2 -0
- package/features/security/authorization/AuthorizationContext/abstractions.js.map +1 -1
- package/features/security/authorization/AuthorizationContext/feature.js +6 -1
- package/features/security/authorization/AuthorizationContext/feature.js.map +1 -1
- package/features/security/authorization/GroupsTeamsAuthorizer/AssumedPermissions.d.ts +30 -0
- package/features/security/authorization/GroupsTeamsAuthorizer/AssumedPermissions.js +60 -0
- package/features/security/authorization/GroupsTeamsAuthorizer/AssumedPermissions.js.map +1 -0
- package/features/security/authorization/GroupsTeamsAuthorizer/feature.js +2 -0
- package/features/security/authorization/GroupsTeamsAuthorizer/feature.js.map +1 -1
- package/features/security/roles/Installer/RolesInstaller.js +1 -0
- package/features/security/roles/Installer/RolesInstaller.js.map +1 -1
- package/features/task/TaskDefinition/abstractions.d.ts +13 -20
- package/features/task/TaskDefinition/abstractions.js.map +1 -1
- package/features/tenancy/TenantContext/TenantContext.d.ts +5 -1
- package/features/tenancy/TenantContext/TenantContext.js +31 -23
- package/features/tenancy/TenantContext/TenantContext.js.map +1 -1
- package/features/users/shared/loaders.js.map +1 -1
- package/features/users/shared/types.d.ts +9 -7
- package/features/wcp/WcpContext/WcpContext.d.ts +6 -1
- package/features/wcp/WcpContext/WcpContext.js +17 -2
- package/features/wcp/WcpContext/WcpContext.js.map +1 -1
- package/features/wcp/WcpContext/decorators/WcpContextWithFeatureFlagsDecorator.d.ts +9 -73
- package/features/wcp/WcpContext/decorators/WcpContextWithFeatureFlagsDecorator.js +25 -5
- package/features/wcp/WcpContext/decorators/WcpContextWithFeatureFlagsDecorator.js.map +1 -1
- package/features/wcp/WcpLicenseLoader.js.map +1 -1
- package/features/wcp/resolveWcpProjectEnvironment.d.ts +1 -1
- package/features/wcp/resolveWcpProjectEnvironment.js.map +1 -1
- package/graphql/ApiCoreSchemaFactory.d.ts +1 -0
- package/graphql/ApiCoreSchemaFactory.js +7 -1
- package/graphql/ApiCoreSchemaFactory.js.map +1 -1
- package/graphql/featureFlags/FeatureFlagsSchemaFactory.d.ts +1 -0
- package/graphql/featureFlags/FeatureFlagsSchemaFactory.js +4 -0
- package/graphql/featureFlags/FeatureFlagsSchemaFactory.js.map +1 -1
- package/graphql/security/SecuritySchemaFactory.d.ts +1 -0
- package/graphql/security/SecuritySchemaFactory.js +4 -0
- package/graphql/security/SecuritySchemaFactory.js.map +1 -1
- package/graphql/system/SystemSchemaFactory.d.ts +1 -0
- package/graphql/system/SystemSchemaFactory.js +4 -0
- package/graphql/system/SystemSchemaFactory.js.map +1 -1
- package/graphql/users/UsersSchemaFactory.d.ts +1 -0
- package/graphql/users/UsersSchemaFactory.js +4 -0
- package/graphql/users/UsersSchemaFactory.js.map +1 -1
- package/graphql/wcp/WcpSchemaFactory.d.ts +1 -0
- package/graphql/wcp/WcpSchemaFactory.js +5 -1
- package/graphql/wcp/WcpSchemaFactory.js.map +1 -1
- package/idp/JwksCache.d.ts +14 -3
- package/idp/JwksCache.js +97 -17
- package/idp/JwksCache.js.map +1 -1
- package/idp/JwksStoreFeature.d.ts +8 -0
- package/idp/JwksStoreFeature.js +11 -0
- package/idp/JwksStoreFeature.js.map +1 -0
- package/idp/MemoryJwksStore.d.ts +14 -0
- package/idp/MemoryJwksStore.js +21 -0
- package/idp/MemoryJwksStore.js.map +1 -0
- package/idp/OidcJwtIdentityProvider.js +5 -1
- package/idp/OidcJwtIdentityProvider.js.map +1 -1
- package/idp/abstractions.d.ts +24 -0
- package/idp/abstractions.js +2 -1
- package/idp/abstractions.js.map +1 -1
- package/idp/feature.js +1 -2
- package/idp/feature.js.map +1 -1
- package/idp/index.d.ts +1 -0
- package/idp/index.js +1 -0
- package/package.json +21 -21
- package/types/users.d.ts +2 -3
- package/features/logger/LoggerService.d.ts +0 -14
- package/features/logger/LoggerService.js +0 -48
- package/features/logger/LoggerService.js.map +0 -1
- package/features/logger/feature.js +0 -11
- package/features/logger/feature.js.map +0 -1
|
@@ -1,10 +1,23 @@
|
|
|
1
|
+
import type { Constructor } from "@webiny/di";
|
|
1
2
|
import type { generateText } from "ai";
|
|
2
3
|
import type { streamText } from "ai";
|
|
3
4
|
import type { LanguageModel } from "ai";
|
|
4
5
|
import type { FlexibleSchema, ToolSet } from "ai";
|
|
6
|
+
/**
|
|
7
|
+
* What a model accepts, as published in the model catalog. A capability that isn't listed is unknown,
|
|
8
|
+
* and unknown is treated as unsupported: a parameter the model may reject is not sent.
|
|
9
|
+
*/
|
|
10
|
+
export interface IAiModelSupports {
|
|
11
|
+
tools?: boolean;
|
|
12
|
+
vision?: boolean;
|
|
13
|
+
temperature?: boolean;
|
|
14
|
+
}
|
|
5
15
|
export interface IAiSdkModel {
|
|
6
16
|
id: string;
|
|
7
17
|
name: string;
|
|
18
|
+
deprecated?: Date;
|
|
19
|
+
endOfLife?: Date;
|
|
20
|
+
supports?: IAiModelSupports;
|
|
8
21
|
}
|
|
9
22
|
export interface IAiSdk {
|
|
10
23
|
languageModel(modelId: string): LanguageModel;
|
|
@@ -55,6 +68,9 @@ export interface AiModel {
|
|
|
55
68
|
providerName: string;
|
|
56
69
|
modelId: string;
|
|
57
70
|
modelName: string;
|
|
71
|
+
deprecated: Date | undefined;
|
|
72
|
+
endOfLife: Date | undefined;
|
|
73
|
+
supports: IAiModelSupports | undefined;
|
|
58
74
|
}
|
|
59
75
|
export interface IAi {
|
|
60
76
|
generateText(params: AiGenerateTextParams): ReturnType<typeof generateText>;
|
|
@@ -70,6 +86,28 @@ export declare namespace Ai {
|
|
|
70
86
|
type GenerateTextParams = AiGenerateTextParams;
|
|
71
87
|
type StreamTextParams = AiStreamTextParams;
|
|
72
88
|
}
|
|
89
|
+
export interface IAiModelRegistry {
|
|
90
|
+
listModels(): Promise<AiModel[]>;
|
|
91
|
+
}
|
|
92
|
+
/** Single source of truth for available AI models. Decoratable to restrict the model list. */
|
|
93
|
+
export declare const AiModelRegistry: import("@webiny/di").Abstraction<IAiModelRegistry>;
|
|
94
|
+
export declare namespace AiModelRegistry {
|
|
95
|
+
type Interface = IAiModelRegistry;
|
|
96
|
+
}
|
|
97
|
+
export interface AiCatalogProvider {
|
|
98
|
+
id: string;
|
|
99
|
+
name: string;
|
|
100
|
+
models: IAiSdkModel[];
|
|
101
|
+
}
|
|
102
|
+
export interface IAiModelCatalog {
|
|
103
|
+
/** Returns `undefined` when the catalog can't be loaded. */
|
|
104
|
+
listProviders(): Promise<AiCatalogProvider[] | undefined>;
|
|
105
|
+
}
|
|
106
|
+
/** The published list of providers and models Webiny supports. SDK factories still gate what is offered. */
|
|
107
|
+
export declare const AiModelCatalog: import("@webiny/di").Abstraction<IAiModelCatalog>;
|
|
108
|
+
export declare namespace AiModelCatalog {
|
|
109
|
+
type Interface = IAiModelCatalog;
|
|
110
|
+
}
|
|
73
111
|
/**
|
|
74
112
|
* Behavioural hints about a tool. Purely advisory — they never replace a permission check.
|
|
75
113
|
* Names mirror the MCP tool annotations so they can be forwarded verbatim to MCP clients,
|
|
@@ -85,21 +123,59 @@ export interface IAiSdkToolAnnotations {
|
|
|
85
123
|
/** Tool interacts with entities outside its own closed world. */
|
|
86
124
|
openWorldHint?: boolean;
|
|
87
125
|
}
|
|
88
|
-
|
|
126
|
+
/**
|
|
127
|
+
* What a tool DOES. This is the half that injects use cases, so it is built only for a tool the
|
|
128
|
+
* model actually calls, and only at the moment it calls it.
|
|
129
|
+
*/
|
|
130
|
+
export interface IAiSdkToolHandler<TInput = any> {
|
|
131
|
+
execute(input: TInput): Promise<unknown>;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* What a tool IS: everything the model is told about it, plus the class that runs it.
|
|
135
|
+
*
|
|
136
|
+
* Carries no behaviour and no dependencies, which is what makes the registry cheap to read.
|
|
137
|
+
* `AiSdkTools` builds every definition to assemble the tool set, and builds a handler only for a
|
|
138
|
+
* tool the model actually calls.
|
|
139
|
+
*/
|
|
140
|
+
export interface IAiSdkToolDefinition<TInput = any> {
|
|
89
141
|
readonly name: string;
|
|
90
142
|
readonly description: string;
|
|
91
143
|
readonly inputSchema: FlexibleSchema<TInput>;
|
|
92
144
|
/** Human-friendly display name. Falls back to `name` when omitted. */
|
|
93
145
|
readonly title?: string;
|
|
94
146
|
readonly annotations?: IAiSdkToolAnnotations;
|
|
95
|
-
|
|
147
|
+
readonly handler: Constructor<IAiSdkToolHandler<TInput>>;
|
|
96
148
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
149
|
+
export declare const AiSdkToolDefinition: import("@webiny/di").Abstraction<IAiSdkToolDefinition<any>>;
|
|
150
|
+
/**
|
|
151
|
+
* The behaviour half of a tool, built on demand through {@link AiSdkToolHandlerResolver}.
|
|
152
|
+
*
|
|
153
|
+
* Implementations are NOT registered against this abstraction. The definition points at the class
|
|
154
|
+
* directly, exactly as `HttpRouteDefinition` points at its `HttpRouteHandler`. Declaring them
|
|
155
|
+
* through it is what attaches their dependency metadata.
|
|
156
|
+
*/
|
|
157
|
+
export declare const AiSdkToolHandler: import("@webiny/di").Abstraction<IAiSdkToolHandler<any>>;
|
|
158
|
+
export declare namespace AiSdkToolDefinition {
|
|
159
|
+
type Interface<TInput = any> = IAiSdkToolDefinition<TInput>;
|
|
101
160
|
type Annotations = IAiSdkToolAnnotations;
|
|
102
161
|
}
|
|
162
|
+
export declare namespace AiSdkToolHandler {
|
|
163
|
+
type Interface<TInput = any> = IAiSdkToolHandler<TInput>;
|
|
164
|
+
}
|
|
165
|
+
export interface IAiSdkToolHandlerResolver {
|
|
166
|
+
resolve<TInput>(handler: Constructor<IAiSdkToolHandler<TInput>>): IAiSdkToolHandler<TInput>;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Builds the behaviour half of a tool on demand.
|
|
170
|
+
*
|
|
171
|
+
* Something has to turn `tool.handler` (a class) into an instance, and that needs the container.
|
|
172
|
+
* Rather than injecting the container into the tool registry, it lives behind this one narrow
|
|
173
|
+
* abstraction, so everything else depends on `resolve(handler)` and stays testable with a stub.
|
|
174
|
+
*/
|
|
175
|
+
export declare const AiSdkToolHandlerResolver: import("@webiny/di").Abstraction<IAiSdkToolHandlerResolver>;
|
|
176
|
+
export declare namespace AiSdkToolHandlerResolver {
|
|
177
|
+
type Interface = IAiSdkToolHandlerResolver;
|
|
178
|
+
}
|
|
103
179
|
export interface IAiSdkTools {
|
|
104
180
|
getToolSet(): ToolSet;
|
|
105
181
|
}
|
|
@@ -3,8 +3,12 @@ const AiSdk = createAbstraction("AiSdk");
|
|
|
3
3
|
const AiSdkFactory = createAbstraction("AiSdkFactory");
|
|
4
4
|
const AiConnectionFactory = createAbstraction("AiConnectionFactory");
|
|
5
5
|
const Ai = createAbstraction("Ai");
|
|
6
|
-
const
|
|
6
|
+
const AiModelRegistry = createAbstraction("AiModelRegistry");
|
|
7
|
+
const AiModelCatalog = createAbstraction("AiModelCatalog");
|
|
8
|
+
const AiSdkToolDefinition = createAbstraction("AiSdkToolDefinition");
|
|
9
|
+
const AiSdkToolHandler = createAbstraction("AiSdkToolHandler");
|
|
10
|
+
const AiSdkToolHandlerResolver = createAbstraction("AiSdkToolHandlerResolver");
|
|
7
11
|
const AiSdkTools = createAbstraction("AiSdkTools");
|
|
8
|
-
export { Ai, AiConnectionFactory, AiSdk, AiSdkFactory,
|
|
12
|
+
export { Ai, AiConnectionFactory, AiModelCatalog, AiModelRegistry, AiSdk, AiSdkFactory, AiSdkToolDefinition, AiSdkToolHandler, AiSdkToolHandlerResolver, AiSdkTools };
|
|
9
13
|
|
|
10
14
|
//# sourceMappingURL=abstractions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/ai/abstractions.js","sources":["../../../src/features/ai/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { generateText } from \"ai\";\nimport type { streamText } from \"ai\";\nimport type { LanguageModel } from \"ai\";\nimport type { FlexibleSchema, ToolSet } from \"ai\";\n\n// AiSdk\n\nexport interface IAiSdkModel {\n id: string; // raw model id, e.g. \"claude-sonnet-4-5\"\n name: string; // human-friendly name, e.g. \"Claude Sonnet 4.5\"\n}\n\nexport interface IAiSdk {\n languageModel(modelId: string): LanguageModel;\n}\n\n/** A single AI SDK instance (e.g. OpenAI, Anthropic) that resolves model instances. */\nexport const AiSdk = createAbstraction<IAiSdk>(\"AiSdk\");\n\nexport namespace AiSdk {\n export type Interface = IAiSdk;\n}\n\n// AiSdkFactory\n\nexport interface IAiSdkFactory {\n readonly id: string; // machine id, e.g. \"anthropic\"\n readonly name: string; // human-friendly name, e.g. \"Anthropic\"\n readonly models: readonly IAiSdkModel[]; // static model list, no API call needed\n execute(apiKey?: string): Promise<IAiSdk>;\n}\n\n/** Factory that asynchronously initialises an AI SDK. Register one per provider namespace. */\nexport const AiSdkFactory = createAbstraction<IAiSdkFactory>(\"AiSdkFactory\");\n\nexport namespace AiSdkFactory {\n export type Interface = IAiSdkFactory;\n}\n\n// AiConnection\n\nexport interface IAiConnectionInline {\n readonly sdkName: string;\n readonly apiKey?: string;\n}\n\nexport interface IAiConnection extends IAiConnectionInline {\n readonly id: string;\n}\n\n// AiConnectionFactory\n\nexport interface IAiConnectionFactory {\n execute(): Promise<IAiConnection>;\n}\n\n/** Factory that asynchronously produces an AiConnection. */\nexport const AiConnectionFactory = createAbstraction<IAiConnectionFactory>(\"AiConnectionFactory\");\n\nexport namespace AiConnectionFactory {\n export type Interface = IAiConnectionFactory;\n}\n\n// Ai\n\ntype SDKGenerateTextParams = Parameters<typeof generateText>[0];\ntype SDKStreamTextParams = Parameters<typeof streamText>[0];\n\nexport type AiGenerateTextParams = Omit<SDKGenerateTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\nexport type AiStreamTextParams = Omit<SDKStreamTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\n\nexport interface AiModel {\n providerId: string; // e.g. \"anthropic\"\n providerName: string; // e.g. \"Anthropic\"\n modelId: string; // e.g. \"claude-sonnet-4-5\"\n modelName: string; // e.g. \"Claude Sonnet 4.5\"\n}\n\nexport interface IAi {\n generateText(params: AiGenerateTextParams): ReturnType<typeof generateText>;\n streamText(params: AiStreamTextParams): Promise<ReturnType<typeof streamText>>;\n listModels(): Promise<AiModel[]>;\n listModelsByConnections(): Promise<AiModel[]>;\n listModelsByConnection(connection: string | IAiConnectionInline): Promise<AiModel[]>;\n}\n\n/** Interact with AI language models using registered providers. */\nexport const Ai = createAbstraction<IAi>(\"Ai\");\n\nexport namespace Ai {\n export type Interface = IAi;\n export type GenerateTextParams = AiGenerateTextParams;\n export type StreamTextParams = AiStreamTextParams;\n}\n\n//
|
|
1
|
+
{"version":3,"file":"features/ai/abstractions.js","sources":["../../../src/features/ai/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Constructor } from \"@webiny/di\";\nimport type { generateText } from \"ai\";\nimport type { streamText } from \"ai\";\nimport type { LanguageModel } from \"ai\";\nimport type { FlexibleSchema, ToolSet } from \"ai\";\n\n// AiSdk\n\n/**\n * What a model accepts, as published in the model catalog. A capability that isn't listed is unknown,\n * and unknown is treated as unsupported: a parameter the model may reject is not sent.\n */\nexport interface IAiModelSupports {\n tools?: boolean;\n vision?: boolean;\n temperature?: boolean;\n}\n\nexport interface IAiSdkModel {\n id: string; // raw model id, e.g. \"claude-sonnet-4-5\"\n name: string; // human-friendly name, e.g. \"Claude Sonnet 4.5\"\n deprecated?: Date;\n endOfLife?: Date;\n supports?: IAiModelSupports;\n}\n\nexport interface IAiSdk {\n languageModel(modelId: string): LanguageModel;\n}\n\n/** A single AI SDK instance (e.g. OpenAI, Anthropic) that resolves model instances. */\nexport const AiSdk = createAbstraction<IAiSdk>(\"AiSdk\");\n\nexport namespace AiSdk {\n export type Interface = IAiSdk;\n}\n\n// AiSdkFactory\n\nexport interface IAiSdkFactory {\n readonly id: string; // machine id, e.g. \"anthropic\"\n readonly name: string; // human-friendly name, e.g. \"Anthropic\"\n readonly models: readonly IAiSdkModel[]; // static model list, no API call needed\n execute(apiKey?: string): Promise<IAiSdk>;\n}\n\n/** Factory that asynchronously initialises an AI SDK. Register one per provider namespace. */\nexport const AiSdkFactory = createAbstraction<IAiSdkFactory>(\"AiSdkFactory\");\n\nexport namespace AiSdkFactory {\n export type Interface = IAiSdkFactory;\n}\n\n// AiConnection\n\nexport interface IAiConnectionInline {\n readonly sdkName: string;\n readonly apiKey?: string;\n}\n\nexport interface IAiConnection extends IAiConnectionInline {\n readonly id: string;\n}\n\n// AiConnectionFactory\n\nexport interface IAiConnectionFactory {\n execute(): Promise<IAiConnection>;\n}\n\n/** Factory that asynchronously produces an AiConnection. */\nexport const AiConnectionFactory = createAbstraction<IAiConnectionFactory>(\"AiConnectionFactory\");\n\nexport namespace AiConnectionFactory {\n export type Interface = IAiConnectionFactory;\n}\n\n// Ai\n\ntype SDKGenerateTextParams = Parameters<typeof generateText>[0];\ntype SDKStreamTextParams = Parameters<typeof streamText>[0];\n\nexport type AiGenerateTextParams = Omit<SDKGenerateTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\nexport type AiStreamTextParams = Omit<SDKStreamTextParams, \"model\"> & {\n model: string;\n connection?: string | IAiConnectionInline;\n};\n\nexport interface AiModel {\n providerId: string; // e.g. \"anthropic\"\n providerName: string; // e.g. \"Anthropic\"\n modelId: string; // e.g. \"claude-sonnet-4-5\"\n modelName: string; // e.g. \"Claude Sonnet 4.5\"\n deprecated: Date | undefined;\n endOfLife: Date | undefined;\n supports: IAiModelSupports | undefined;\n}\n\nexport interface IAi {\n generateText(params: AiGenerateTextParams): ReturnType<typeof generateText>;\n streamText(params: AiStreamTextParams): Promise<ReturnType<typeof streamText>>;\n listModels(): Promise<AiModel[]>;\n listModelsByConnections(): Promise<AiModel[]>;\n listModelsByConnection(connection: string | IAiConnectionInline): Promise<AiModel[]>;\n}\n\n/** Interact with AI language models using registered providers. */\nexport const Ai = createAbstraction<IAi>(\"Ai\");\n\nexport namespace Ai {\n export type Interface = IAi;\n export type GenerateTextParams = AiGenerateTextParams;\n export type StreamTextParams = AiStreamTextParams;\n}\n\n// AiModelRegistry\n\nexport interface IAiModelRegistry {\n listModels(): Promise<AiModel[]>;\n}\n\n/** Single source of truth for available AI models. Decoratable to restrict the model list. */\nexport const AiModelRegistry = createAbstraction<IAiModelRegistry>(\"AiModelRegistry\");\n\nexport namespace AiModelRegistry {\n export type Interface = IAiModelRegistry;\n}\n\n// AiModelCatalog\n\nexport interface AiCatalogProvider {\n id: string; // Matches `AiSdkFactory.id`, e.g. \"anthropic\".\n name: string; // Human-friendly name, e.g. \"Anthropic\".\n models: IAiSdkModel[];\n}\n\nexport interface IAiModelCatalog {\n /** Returns `undefined` when the catalog can't be loaded. */\n listProviders(): Promise<AiCatalogProvider[] | undefined>;\n}\n\n/** The published list of providers and models Webiny supports. SDK factories still gate what is offered. */\nexport const AiModelCatalog = createAbstraction<IAiModelCatalog>(\"AiModelCatalog\");\n\nexport namespace AiModelCatalog {\n export type Interface = IAiModelCatalog;\n}\n\n// AiSdkToolDefinition\n\n/**\n * Behavioural hints about a tool. Purely advisory — they never replace a permission check.\n * Names mirror the MCP tool annotations so they can be forwarded verbatim to MCP clients,\n * which use them to decide what to auto-approve and what to confirm with the user.\n */\nexport interface IAiSdkToolAnnotations {\n /** Tool does not modify state. */\n readOnlyHint?: boolean;\n /** Tool may perform destructive updates (only meaningful when not read-only). */\n destructiveHint?: boolean;\n /** Repeated calls with the same arguments have no additional effect. */\n idempotentHint?: boolean;\n /** Tool interacts with entities outside its own closed world. */\n openWorldHint?: boolean;\n}\n\n/**\n * What a tool DOES. This is the half that injects use cases, so it is built only for a tool the\n * model actually calls, and only at the moment it calls it.\n */\nexport interface IAiSdkToolHandler<TInput = any> {\n execute(input: TInput): Promise<unknown>;\n}\n\n/**\n * What a tool IS: everything the model is told about it, plus the class that runs it.\n *\n * Carries no behaviour and no dependencies, which is what makes the registry cheap to read.\n * `AiSdkTools` builds every definition to assemble the tool set, and builds a handler only for a\n * tool the model actually calls.\n */\nexport interface IAiSdkToolDefinition<TInput = any> {\n readonly name: string;\n readonly description: string;\n readonly inputSchema: FlexibleSchema<TInput>;\n /** Human-friendly display name. Falls back to `name` when omitted. */\n readonly title?: string;\n readonly annotations?: IAiSdkToolAnnotations;\n readonly handler: Constructor<IAiSdkToolHandler<TInput>>;\n}\n\nexport const AiSdkToolDefinition = createAbstraction<IAiSdkToolDefinition>(\"AiSdkToolDefinition\");\n\n/**\n * The behaviour half of a tool, built on demand through {@link AiSdkToolHandlerResolver}.\n *\n * Implementations are NOT registered against this abstraction. The definition points at the class\n * directly, exactly as `HttpRouteDefinition` points at its `HttpRouteHandler`. Declaring them\n * through it is what attaches their dependency metadata.\n */\nexport const AiSdkToolHandler = createAbstraction<IAiSdkToolHandler>(\"AiSdkToolHandler\");\n\nexport namespace AiSdkToolDefinition {\n export type Interface<TInput = any> = IAiSdkToolDefinition<TInput>;\n export type Annotations = IAiSdkToolAnnotations;\n}\n\nexport namespace AiSdkToolHandler {\n export type Interface<TInput = any> = IAiSdkToolHandler<TInput>;\n}\n\n// AiSdkToolHandlerResolver\n\nexport interface IAiSdkToolHandlerResolver {\n resolve<TInput>(handler: Constructor<IAiSdkToolHandler<TInput>>): IAiSdkToolHandler<TInput>;\n}\n\n/**\n * Builds the behaviour half of a tool on demand.\n *\n * Something has to turn `tool.handler` (a class) into an instance, and that needs the container.\n * Rather than injecting the container into the tool registry, it lives behind this one narrow\n * abstraction, so everything else depends on `resolve(handler)` and stays testable with a stub.\n */\nexport const AiSdkToolHandlerResolver = createAbstraction<IAiSdkToolHandlerResolver>(\n \"AiSdkToolHandlerResolver\"\n);\n\nexport namespace AiSdkToolHandlerResolver {\n export type Interface = IAiSdkToolHandlerResolver;\n}\n\n// AiSdkTools\n\nexport interface IAiSdkTools {\n getToolSet(): ToolSet;\n}\n\n/** Collection of AI SDK tools. Returns a ready-to-use ToolSet for generateText/streamText. */\nexport const AiSdkTools = createAbstraction<IAiSdkTools>(\"AiSdkTools\");\n\nexport namespace AiSdkTools {\n export type Interface = IAiSdkTools;\n}\n"],"names":["AiSdk","createAbstraction","AiSdkFactory","AiConnectionFactory","Ai","AiModelRegistry","AiModelCatalog","AiSdkToolDefinition","AiSdkToolHandler","AiSdkToolHandlerResolver","AiSdkTools"],"mappings":";AAgCO,MAAMA,QAAQC,kBAA0B;AAgBxC,MAAMC,eAAeD,kBAAiC;AAwBtD,MAAME,sBAAsBF,kBAAwC;AAuCpE,MAAMG,KAAKH,kBAAuB;AAelC,MAAMI,kBAAkBJ,kBAAoC;AAoB5D,MAAMK,iBAAiBL,kBAAmC;AAiD1D,MAAMM,sBAAsBN,kBAAwC;AASpE,MAAMO,mBAAmBP,kBAAqC;AAwB9D,MAAMQ,2BAA2BR,kBACpC;AAcG,MAAMS,aAAaT,kBAA+B"}
|
package/features/ai/feature.js
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { createFeature } from "@webiny/feature/api";
|
|
2
2
|
import { OpenAiSdkFactory } from "./OpenAiSdkFactory.js";
|
|
3
3
|
import { AnthropicSdkFactory } from "./AnthropicSdkFactory.js";
|
|
4
|
+
import { GoogleSdkFactory } from "./GoogleSdkFactory.js";
|
|
5
|
+
import { OpenRouterSdkFactory } from "./OpenRouterSdkFactory.js";
|
|
4
6
|
import { Ai } from "./Ai.js";
|
|
7
|
+
import { AiModelRegistry } from "./AiModelRegistry.js";
|
|
8
|
+
import { RemoteAiModelCatalog } from "./RemoteAiModelCatalog.js";
|
|
5
9
|
import { AiSdkTools } from "./AiSdkTools.js";
|
|
10
|
+
import { AiSdkToolHandlerResolver } from "./AiSdkToolHandlerResolver.js";
|
|
6
11
|
import { AiOutputToolRegistry } from "./toolPipeline/AiOutputToolRegistry.js";
|
|
7
12
|
import { AiToolPipelineRunner } from "./toolPipeline/AiToolPipelineRunner.js";
|
|
8
13
|
import { DefaultTextExtractor } from "./TextExtractor/DefaultTextExtractor.js";
|
|
@@ -11,8 +16,13 @@ const AiFeature = createFeature({
|
|
|
11
16
|
register (container) {
|
|
12
17
|
container.register(OpenAiSdkFactory);
|
|
13
18
|
container.register(AnthropicSdkFactory);
|
|
19
|
+
container.register(GoogleSdkFactory);
|
|
20
|
+
container.register(OpenRouterSdkFactory);
|
|
14
21
|
container.register(Ai);
|
|
22
|
+
container.register(RemoteAiModelCatalog);
|
|
23
|
+
container.register(AiModelRegistry);
|
|
15
24
|
container.register(AiSdkTools);
|
|
25
|
+
container.register(AiSdkToolHandlerResolver);
|
|
16
26
|
container.register(AiOutputToolRegistry);
|
|
17
27
|
container.register(AiToolPipelineRunner);
|
|
18
28
|
container.register(DefaultTextExtractor);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"features/ai/feature.js","sources":["../../../src/features/ai/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { OpenAiSdkFactory } from \"./OpenAiSdkFactory.js\";\nimport { AnthropicSdkFactory } from \"./AnthropicSdkFactory.js\";\nimport { Ai } from \"./Ai.js\";\nimport { AiSdkTools } from \"./AiSdkTools.js\";\nimport { AiOutputToolRegistry } from \"./toolPipeline/AiOutputToolRegistry.js\";\nimport { AiToolPipelineRunner } from \"./toolPipeline/AiToolPipelineRunner.js\";\nimport { DefaultTextExtractor } from \"./TextExtractor/DefaultTextExtractor.js\";\n\nexport const AiFeature = createFeature({\n name: \"AiFeature\",\n register(container) {\n container.register(OpenAiSdkFactory);\n container.register(AnthropicSdkFactory);\n container.register(Ai);\n container.register(AiSdkTools);\n container.register(AiOutputToolRegistry);\n container.register(AiToolPipelineRunner);\n container.register(DefaultTextExtractor);\n }\n});\n"],"names":["AiFeature","createFeature","container","OpenAiSdkFactory","AnthropicSdkFactory","Ai","AiSdkTools","AiOutputToolRegistry","AiToolPipelineRunner","DefaultTextExtractor"],"mappings":"
|
|
1
|
+
{"version":3,"file":"features/ai/feature.js","sources":["../../../src/features/ai/feature.ts"],"sourcesContent":["import { createFeature } from \"@webiny/feature/api\";\nimport { OpenAiSdkFactory } from \"./OpenAiSdkFactory.js\";\nimport { AnthropicSdkFactory } from \"./AnthropicSdkFactory.js\";\nimport { GoogleSdkFactory } from \"./GoogleSdkFactory.js\";\nimport { OpenRouterSdkFactory } from \"./OpenRouterSdkFactory.js\";\nimport { Ai } from \"./Ai.js\";\nimport { AiModelRegistry } from \"./AiModelRegistry.js\";\nimport { RemoteAiModelCatalog } from \"./RemoteAiModelCatalog.js\";\nimport { AiSdkTools } from \"./AiSdkTools.js\";\nimport { AiSdkToolHandlerResolver } from \"./AiSdkToolHandlerResolver.js\";\nimport { AiOutputToolRegistry } from \"./toolPipeline/AiOutputToolRegistry.js\";\nimport { AiToolPipelineRunner } from \"./toolPipeline/AiToolPipelineRunner.js\";\nimport { DefaultTextExtractor } from \"./TextExtractor/DefaultTextExtractor.js\";\n\nexport const AiFeature = createFeature({\n name: \"AiFeature\",\n register(container) {\n container.register(OpenAiSdkFactory);\n container.register(AnthropicSdkFactory);\n container.register(GoogleSdkFactory);\n container.register(OpenRouterSdkFactory);\n container.register(Ai);\n container.register(RemoteAiModelCatalog);\n container.register(AiModelRegistry);\n container.register(AiSdkTools);\n container.register(AiSdkToolHandlerResolver);\n container.register(AiOutputToolRegistry);\n container.register(AiToolPipelineRunner);\n container.register(DefaultTextExtractor);\n }\n});\n"],"names":["AiFeature","createFeature","container","OpenAiSdkFactory","AnthropicSdkFactory","GoogleSdkFactory","OpenRouterSdkFactory","Ai","RemoteAiModelCatalog","AiModelRegistry","AiSdkTools","AiSdkToolHandlerResolver","AiOutputToolRegistry","AiToolPipelineRunner","DefaultTextExtractor"],"mappings":";;;;;;;;;;;;;AAcO,MAAMA,YAAYC,cAAc;IACnC,MAAM;IACN,UAASC,SAAS;QACdA,UAAU,QAAQ,CAACC;QACnBD,UAAU,QAAQ,CAACE;QACnBF,UAAU,QAAQ,CAACG;QACnBH,UAAU,QAAQ,CAACI;QACnBJ,UAAU,QAAQ,CAACK;QACnBL,UAAU,QAAQ,CAACM;QACnBN,UAAU,QAAQ,CAACO;QACnBP,UAAU,QAAQ,CAACQ;QACnBR,UAAU,QAAQ,CAACS;QACnBT,UAAU,QAAQ,CAACU;QACnBV,UAAU,QAAQ,CAACW;QACnBX,UAAU,QAAQ,CAACY;IACvB;AACJ"}
|
package/features/ai/index.d.ts
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
export { AiSdk, AiSdkFactory, AiConnectionFactory, Ai,
|
|
2
|
-
export type { IAiConnection, IAiConnectionInline, AiModel, IAiSdkModel
|
|
1
|
+
export { AiSdk, AiSdkFactory, AiConnectionFactory, Ai, AiModelRegistry, AiModelCatalog, AiSdkToolDefinition, AiSdkToolHandler, AiSdkToolHandlerResolver, AiSdkTools } from "./abstractions.js";
|
|
2
|
+
export type { IAiConnection, IAiConnectionInline, AiModel, IAiSdkModel } from "./abstractions.js";
|
|
3
3
|
export { AiOutputTool, AiOutputToolRegistry, AiToolPipelineRunner } from "./toolPipeline/index.js";
|
|
4
|
-
export type { IAiOutputTool, IAiOutputToolRegistry, IAiToolPipelineRunner } from "./toolPipeline/index.js";
|
|
5
4
|
export { TextExtractor, DefaultTextExtractor } from "./TextExtractor/index.js";
|
|
6
|
-
export type { ITextExtractor, TextExtractorResult } from "./TextExtractor/index.js";
|
|
7
5
|
export { AiBeforeGenerateTextEvent, AiBeforeGenerateTextEventHandler, AiAfterGenerateTextEvent, AiAfterGenerateTextEventHandler, AiGenerateTextErrorEvent, AiGenerateTextErrorEventHandler, AiBeforeStreamTextEvent, AiBeforeStreamTextEventHandler } from "./events.js";
|
|
8
6
|
export type { AiBeforeGenerateTextPayload, AiAfterGenerateTextPayload, AiGenerateTextErrorPayload, AiBeforeStreamTextPayload } from "./events.js";
|
|
9
7
|
export { AiFeature } from "./feature.js";
|
package/features/ai/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { Ai, AiConnectionFactory, AiSdk, AiSdkFactory,
|
|
1
|
+
export { Ai, AiConnectionFactory, AiModelCatalog, AiModelRegistry, AiSdk, AiSdkFactory, AiSdkToolDefinition, AiSdkToolHandler, AiSdkToolHandlerResolver, AiSdkTools } from "./abstractions.js";
|
|
2
2
|
export { AiOutputTool, AiOutputToolRegistry, AiToolPipelineRunner } from "./toolPipeline/index.js";
|
|
3
3
|
export { DefaultTextExtractor, TextExtractor } from "./TextExtractor/index.js";
|
|
4
4
|
export { AiAfterGenerateTextEvent, AiAfterGenerateTextEventHandler, AiBeforeGenerateTextEvent, AiBeforeGenerateTextEventHandler, AiBeforeStreamTextEvent, AiBeforeStreamTextEventHandler, AiGenerateTextErrorEvent, AiGenerateTextErrorEventHandler } from "./events.js";
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Debugger as DebuggerAbstraction } from "./abstractions.js";
|
|
2
|
+
import { DebuggerTransport } from "./abstractions.js";
|
|
3
|
+
import type { DebugNamespace } from "./abstractions.js";
|
|
4
|
+
import type { IDebugDeliveryTarget } from "./abstractions.js";
|
|
5
|
+
import type { IDebuggerStartParams } from "./abstractions.js";
|
|
6
|
+
import type { IDebugPayloadFactory } from "./abstractions.js";
|
|
7
|
+
import { IdentityContext } from "../../features/security/IdentityContext/index.js";
|
|
8
|
+
import { BuildParams } from "../../features/buildParams/index.js";
|
|
9
|
+
import { Logger } from "../../features/logger/index.js";
|
|
10
|
+
export declare class DebuggerImpl implements DebuggerAbstraction.Interface {
|
|
11
|
+
private readonly identityContext;
|
|
12
|
+
private readonly buildParams;
|
|
13
|
+
private readonly logger;
|
|
14
|
+
private readonly transports;
|
|
15
|
+
private session;
|
|
16
|
+
private readonly limits;
|
|
17
|
+
constructor(identityContext: IdentityContext.Interface, buildParams: BuildParams.Interface, logger: Logger.Interface, transports: DebuggerTransport.Interface[]);
|
|
18
|
+
start(params: IDebuggerStartParams): void;
|
|
19
|
+
isEnabled(namespace: DebugNamespace): boolean;
|
|
20
|
+
log(namespace: DebugNamespace, payload: IDebugPayloadFactory): void;
|
|
21
|
+
flush(target: IDebugDeliveryTarget): Promise<void>;
|
|
22
|
+
discard(): void;
|
|
23
|
+
private isDisabled;
|
|
24
|
+
/**
|
|
25
|
+
* Drops entries from the front until the session fits the byte budget. The client reproduces the
|
|
26
|
+
* bug, so the failure is at the end of the session and the tail is what matters.
|
|
27
|
+
*/
|
|
28
|
+
private enforceBudget;
|
|
29
|
+
}
|
|
30
|
+
export declare const Debugger: import("@webiny/di").Implementation<typeof DebuggerImpl>;
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { createImplementation } from "@webiny/feature/api";
|
|
2
|
+
import { Debugger, DebuggerTransport } from "./abstractions.js";
|
|
3
|
+
import { IdentityContext } from "../security/IdentityContext/index.js";
|
|
4
|
+
import { BuildParams } from "../buildParams/index.js";
|
|
5
|
+
import { Logger } from "../logger/index.js";
|
|
6
|
+
import { createNamespaceFilter } from "./matchNamespace.js";
|
|
7
|
+
import { DEFAULT_LIMITS } from "./limits.js";
|
|
8
|
+
import { serialize } from "./serialize.js";
|
|
9
|
+
const FLUSH_TIMEOUT_MS = 2000;
|
|
10
|
+
const describeError = (error)=>{
|
|
11
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
12
|
+
return "Unknown error.";
|
|
13
|
+
};
|
|
14
|
+
class DebuggerImpl {
|
|
15
|
+
constructor(identityContext, buildParams, logger, transports){
|
|
16
|
+
this.identityContext = identityContext;
|
|
17
|
+
this.buildParams = buildParams;
|
|
18
|
+
this.logger = logger;
|
|
19
|
+
this.transports = transports;
|
|
20
|
+
this.session = void 0;
|
|
21
|
+
this.limits = DEFAULT_LIMITS;
|
|
22
|
+
}
|
|
23
|
+
start(params) {
|
|
24
|
+
if (this.isDisabled()) return;
|
|
25
|
+
if (0 === params.namespaces.length) return;
|
|
26
|
+
this.session = {
|
|
27
|
+
namespaces: params.namespaces,
|
|
28
|
+
filter: createNamespaceFilter(params.namespaces),
|
|
29
|
+
startedAt: Date.now(),
|
|
30
|
+
entries: [],
|
|
31
|
+
bytes: 0,
|
|
32
|
+
dropped: 0,
|
|
33
|
+
truncated: false,
|
|
34
|
+
seq: 0
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
isEnabled(namespace) {
|
|
38
|
+
const session = this.session;
|
|
39
|
+
if (!session) return false;
|
|
40
|
+
if (this.identityContext.getIdentity().isAnonymous()) return false;
|
|
41
|
+
return session.filter.matches(namespace);
|
|
42
|
+
}
|
|
43
|
+
log(namespace, payload) {
|
|
44
|
+
try {
|
|
45
|
+
const session = this.session;
|
|
46
|
+
if (!session || !this.isEnabled(namespace)) return;
|
|
47
|
+
if (session.entries.length >= this.limits.entryCount) return;
|
|
48
|
+
const { json, bytes, truncated } = serialize(payload(), this.limits);
|
|
49
|
+
const entry = {
|
|
50
|
+
seq: ++session.seq,
|
|
51
|
+
namespace,
|
|
52
|
+
timestamp: Date.now(),
|
|
53
|
+
elapsed: Date.now() - session.startedAt,
|
|
54
|
+
json,
|
|
55
|
+
bytes
|
|
56
|
+
};
|
|
57
|
+
session.entries.push(entry);
|
|
58
|
+
session.bytes += bytes;
|
|
59
|
+
session.truncated = session.truncated || truncated;
|
|
60
|
+
this.enforceBudget(session);
|
|
61
|
+
} catch (ex) {
|
|
62
|
+
this.logger.error({
|
|
63
|
+
namespace,
|
|
64
|
+
error: describeError(ex)
|
|
65
|
+
}, "Debugger failed to capture a payload.");
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async flush(target) {
|
|
69
|
+
const session = this.session;
|
|
70
|
+
this.session = void 0;
|
|
71
|
+
if (!session) return;
|
|
72
|
+
const transports = this.transports.filter((transport)=>{
|
|
73
|
+
try {
|
|
74
|
+
return transport.canDeliver(target);
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
if (0 === transports.length) return;
|
|
80
|
+
const frozen = Object.freeze({
|
|
81
|
+
namespaces: session.namespaces,
|
|
82
|
+
startedAt: session.startedAt,
|
|
83
|
+
entries: session.entries,
|
|
84
|
+
bytes: session.bytes,
|
|
85
|
+
dropped: session.dropped,
|
|
86
|
+
truncated: session.truncated
|
|
87
|
+
});
|
|
88
|
+
const delivery = Promise.allSettled(transports.map(async (transport)=>await transport.deliver({
|
|
89
|
+
target,
|
|
90
|
+
session: frozen
|
|
91
|
+
})));
|
|
92
|
+
let timer;
|
|
93
|
+
const timeout = new Promise((resolve)=>{
|
|
94
|
+
timer = setTimeout(resolve, FLUSH_TIMEOUT_MS);
|
|
95
|
+
});
|
|
96
|
+
try {
|
|
97
|
+
const results = await Promise.race([
|
|
98
|
+
delivery,
|
|
99
|
+
timeout
|
|
100
|
+
]);
|
|
101
|
+
if (Array.isArray(results)) {
|
|
102
|
+
for (const result of results)if ("rejected" === result.status) this.logger.error({
|
|
103
|
+
error: describeError(result.reason)
|
|
104
|
+
}, "Debugger transport failed to deliver.");
|
|
105
|
+
}
|
|
106
|
+
} finally{
|
|
107
|
+
if (timer) clearTimeout(timer);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
discard() {
|
|
111
|
+
this.session = void 0;
|
|
112
|
+
}
|
|
113
|
+
isDisabled() {
|
|
114
|
+
return true === this.buildParams.get("DebuggerDisabled");
|
|
115
|
+
}
|
|
116
|
+
enforceBudget(session) {
|
|
117
|
+
while(session.bytes > this.limits.totalBytes && session.entries.length > 0){
|
|
118
|
+
const removed = session.entries.shift();
|
|
119
|
+
if (!removed) break;
|
|
120
|
+
session.bytes -= removed.bytes;
|
|
121
|
+
session.dropped++;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const Debugger_Debugger = createImplementation({
|
|
126
|
+
abstraction: Debugger,
|
|
127
|
+
implementation: DebuggerImpl,
|
|
128
|
+
dependencies: [
|
|
129
|
+
IdentityContext,
|
|
130
|
+
BuildParams,
|
|
131
|
+
Logger,
|
|
132
|
+
[
|
|
133
|
+
DebuggerTransport,
|
|
134
|
+
{
|
|
135
|
+
multiple: true
|
|
136
|
+
}
|
|
137
|
+
]
|
|
138
|
+
]
|
|
139
|
+
});
|
|
140
|
+
export { DebuggerImpl, Debugger_Debugger as Debugger };
|
|
141
|
+
|
|
142
|
+
//# sourceMappingURL=Debugger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/debugger/Debugger.js","sources":["../../../src/features/debugger/Debugger.ts"],"sourcesContent":["import { createImplementation } from \"@webiny/feature/api\";\nimport { Debugger as DebuggerAbstraction } from \"./abstractions.js\";\nimport { DebuggerTransport } from \"./abstractions.js\";\nimport type { DebugNamespace } from \"./abstractions.js\";\nimport type { IDebugDeliveryTarget } from \"./abstractions.js\";\nimport type { IDebugEntry } from \"./abstractions.js\";\nimport type { IDebuggerStartParams } from \"./abstractions.js\";\nimport type { IDebugPayloadFactory } from \"./abstractions.js\";\nimport type { IDebugSession } from \"./abstractions.js\";\nimport { IdentityContext } from \"~/features/security/IdentityContext/index.js\";\nimport { BuildParams } from \"~/features/buildParams/index.js\";\nimport { Logger } from \"~/features/logger/index.js\";\nimport { createNamespaceFilter } from \"./matchNamespace.js\";\nimport type { INamespaceFilter } from \"./matchNamespace.js\";\nimport { DEFAULT_LIMITS } from \"./limits.js\";\nimport type { IDebuggerLimits } from \"./limits.js\";\nimport { serialize } from \"./serialize.js\";\n\nconst FLUSH_TIMEOUT_MS = 2000;\n\n/**\n * Renders an error for logging without touching anything that could hold a captured payload.\n *\n * Deliberately not the error object itself: loggers spread it, so an error carrying a `data`\n * property would put debug payloads into the logs - the one sink they must never reach.\n */\nconst describeError = (error: unknown): string => {\n if (error instanceof Error) {\n return `${error.name}: ${error.message}`;\n }\n return \"Unknown error.\";\n};\n\ninterface IActiveSession extends IDebugSession {\n filter: INamespaceFilter;\n seq: number;\n}\n\nexport class DebuggerImpl implements DebuggerAbstraction.Interface {\n private session: IActiveSession | undefined = undefined;\n private readonly limits: IDebuggerLimits = DEFAULT_LIMITS;\n\n public constructor(\n private readonly identityContext: IdentityContext.Interface,\n private readonly buildParams: BuildParams.Interface,\n private readonly logger: Logger.Interface,\n private readonly transports: DebuggerTransport.Interface[]\n ) {}\n\n public start(params: IDebuggerStartParams): void {\n if (this.isDisabled()) {\n return;\n }\n\n if (params.namespaces.length === 0) {\n return;\n }\n\n /**\n * Always replace. A session surviving into the next request would mean one identity\n * receiving another's entries.\n */\n this.session = {\n namespaces: params.namespaces,\n filter: createNamespaceFilter(params.namespaces),\n startedAt: Date.now(),\n entries: [],\n bytes: 0,\n dropped: 0,\n truncated: false,\n seq: 0\n };\n }\n\n public isEnabled(namespace: DebugNamespace): boolean {\n const session = this.session;\n if (!session) {\n return false;\n }\n\n /**\n * An anonymous identity must never accumulate payloads. The flush-time permission check is\n * authoritative, but this earlier gate means there is nothing to leak if a future code path\n * delivers a session without passing through it.\n */\n if (this.identityContext.getIdentity().isAnonymous()) {\n return false;\n }\n\n return session.filter.matches(namespace);\n }\n\n public log(namespace: DebugNamespace, payload: IDebugPayloadFactory): void {\n /**\n * The debugger must never be able to break the request it is observing, and payload\n * factories are written in a hurry during an incident.\n */\n try {\n const session = this.session;\n if (!session || !this.isEnabled(namespace)) {\n return;\n }\n\n if (session.entries.length >= this.limits.entryCount) {\n return;\n }\n\n /**\n * Invoke and serialize immediately: this releases the closure and the payload graph, and\n * it is what makes the entry's size known, which is what makes the budget enforceable.\n */\n const { json, bytes, truncated } = serialize(payload(), this.limits);\n\n const entry: IDebugEntry = {\n seq: ++session.seq,\n namespace,\n timestamp: Date.now(),\n elapsed: Date.now() - session.startedAt,\n json,\n bytes\n };\n\n session.entries.push(entry);\n session.bytes += bytes;\n session.truncated = session.truncated || truncated;\n\n this.enforceBudget(session);\n } catch (ex) {\n this.logger.error(\n { namespace, error: describeError(ex) },\n \"Debugger failed to capture a payload.\"\n );\n }\n }\n\n public async flush(target: IDebugDeliveryTarget): Promise<void> {\n const session = this.session;\n this.session = undefined;\n\n if (!session) {\n return;\n }\n\n const transports = this.transports.filter(transport => {\n try {\n return transport.canDeliver(target);\n } catch {\n return false;\n }\n });\n\n if (transports.length === 0) {\n return;\n }\n\n const frozen: IDebugSession = Object.freeze({\n namespaces: session.namespaces,\n startedAt: session.startedAt,\n entries: session.entries,\n bytes: session.bytes,\n dropped: session.dropped,\n truncated: session.truncated\n });\n\n const delivery = Promise.allSettled(\n transports.map(async transport => {\n return await transport.deliver({ target, session: frozen });\n })\n );\n\n /**\n * In-memory delivery is instant, but a future network sink is not, and debug data is never\n * worth making the app feel broken. The timer is cleared so it cannot hold the event loop\n * open after the response, which on Lambda would delay the freeze.\n */\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<void>(resolve => {\n timer = setTimeout(resolve, FLUSH_TIMEOUT_MS);\n });\n\n try {\n const results = await Promise.race([delivery, timeout]);\n if (Array.isArray(results)) {\n for (const result of results) {\n if (result.status === \"rejected\") {\n /**\n * Only the error - never the session or any entry. The logger writes to\n * CloudWatch or the server's output, which is the one place debug payloads\n * must never reach.\n */\n this.logger.error(\n { error: describeError(result.reason) },\n \"Debugger transport failed to deliver.\"\n );\n }\n }\n }\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n }\n\n public discard(): void {\n this.session = undefined;\n }\n\n private isDisabled(): boolean {\n return this.buildParams.get<boolean>(\"DebuggerDisabled\") === true;\n }\n\n /**\n * Drops entries from the front until the session fits the byte budget. The client reproduces the\n * bug, so the failure is at the end of the session and the tail is what matters.\n */\n private enforceBudget(session: IActiveSession): void {\n while (session.bytes > this.limits.totalBytes && session.entries.length > 0) {\n const removed = session.entries.shift();\n if (!removed) {\n break;\n }\n session.bytes -= removed.bytes;\n session.dropped++;\n }\n }\n}\n\nexport const Debugger = createImplementation({\n abstraction: DebuggerAbstraction,\n implementation: DebuggerImpl,\n dependencies: [IdentityContext, BuildParams, Logger, [DebuggerTransport, { multiple: true }]]\n});\n"],"names":["FLUSH_TIMEOUT_MS","describeError","error","Error","DebuggerImpl","identityContext","buildParams","logger","transports","undefined","DEFAULT_LIMITS","params","createNamespaceFilter","Date","namespace","session","payload","json","bytes","truncated","serialize","entry","ex","target","transport","frozen","Object","delivery","Promise","timer","timeout","resolve","setTimeout","results","Array","result","clearTimeout","removed","Debugger","createImplementation","DebuggerAbstraction","IdentityContext","BuildParams","Logger","DebuggerTransport"],"mappings":"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"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { HttpRouteHandler } from "@webiny/event-handler-core";
|
|
2
|
+
import { HandlerExecution } from "@webiny/event-handler-core";
|
|
3
|
+
import type { IHttpResponse } from "@webiny/event-handler-core";
|
|
4
|
+
import type { IHttpResponseBuilder } from "@webiny/event-handler-core";
|
|
5
|
+
import { Debugger } from "./abstractions.js";
|
|
6
|
+
import { IdentityContext } from "../../features/security/IdentityContext/index.js";
|
|
7
|
+
import { Logger } from "../../features/logger/index.js";
|
|
8
|
+
export declare const DEBUG_HEADER = "x-webiny-debug";
|
|
9
|
+
type RouteResult = IHttpResponse | IHttpResponseBuilder | void;
|
|
10
|
+
/**
|
|
11
|
+
* Opens a capture session around every HTTP route and hands it over once the route has produced its
|
|
12
|
+
* response.
|
|
13
|
+
*
|
|
14
|
+
* It wraps the route rather than the GraphQL execution, because CMS resolvers run nested GraphQL
|
|
15
|
+
* executions internally. Attaching there would put the session on a result that is then thrown
|
|
16
|
+
* away; at the route there is exactly one response per request.
|
|
17
|
+
*/
|
|
18
|
+
declare class DebuggerRouteDecoratorImpl implements HttpRouteHandler.Interface {
|
|
19
|
+
private readonly debuggerService;
|
|
20
|
+
private readonly identityContext;
|
|
21
|
+
private readonly logger;
|
|
22
|
+
private readonly handlerExecution;
|
|
23
|
+
private readonly decoratee;
|
|
24
|
+
constructor(debuggerService: Debugger.Interface, identityContext: IdentityContext.Interface, logger: Logger.Interface, handlerExecution: HandlerExecution.Interface, decoratee: HttpRouteHandler.Interface);
|
|
25
|
+
handle(request: HttpRouteHandler.Request, response: HttpRouteHandler.Response): Promise<RouteResult>;
|
|
26
|
+
/**
|
|
27
|
+
* A session starts on every request, and the permission check at flush decides whether anything
|
|
28
|
+
* is delivered or the whole thing is discarded.
|
|
29
|
+
*
|
|
30
|
+
* Nothing is required from the client. The header is honoured when present, so a direct API
|
|
31
|
+
* client can narrow what it captures.
|
|
32
|
+
*/
|
|
33
|
+
private start;
|
|
34
|
+
/**
|
|
35
|
+
* Performs the permission gate and hands the session to the transports.
|
|
36
|
+
*
|
|
37
|
+
* The whole body is guarded: an error here would turn a working response into a 500, and only
|
|
38
|
+
* for the identities that are allowed to debug.
|
|
39
|
+
*/
|
|
40
|
+
private flush;
|
|
41
|
+
}
|
|
42
|
+
export declare const DebuggerRouteDecorator: typeof DebuggerRouteDecoratorImpl & {
|
|
43
|
+
__abstraction: import("@webiny/di").Abstraction<import("@webiny/event-handler-core").IHttpRoute>;
|
|
44
|
+
};
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { HandlerExecution, HttpRouteHandler } from "@webiny/event-handler-core";
|
|
2
|
+
import { Debugger } from "./abstractions.js";
|
|
3
|
+
import { IdentityContext } from "../security/IdentityContext/index.js";
|
|
4
|
+
import { Logger } from "../logger/index.js";
|
|
5
|
+
import { parseNamespaceHeader } from "./parseNamespaceHeader.js";
|
|
6
|
+
import { canCaptureDebugData } from "./permissions.js";
|
|
7
|
+
import { GRAPHQL_TARGET } from "./GraphQLDebuggerTransport.js";
|
|
8
|
+
const DEBUG_HEADER = "x-webiny-debug";
|
|
9
|
+
const isPlainObject = (value)=>"object" == typeof value && null !== value && !Array.isArray(value);
|
|
10
|
+
const isGraphQLResult = (value)=>isPlainObject(value) && ("data" in value || "errors" in value);
|
|
11
|
+
const isResponseBuilder = (value)=>isPlainObject(value) && "function" == typeof value.toResponse;
|
|
12
|
+
const readBody = (result, response)=>{
|
|
13
|
+
if (isResponseBuilder(result)) return result.toResponse().body;
|
|
14
|
+
if (result) return result.body;
|
|
15
|
+
return response.toResponse().body;
|
|
16
|
+
};
|
|
17
|
+
const resolveTarget = (body)=>{
|
|
18
|
+
const candidate = Array.isArray(body) ? body.at(-1) : body;
|
|
19
|
+
if (isGraphQLResult(candidate)) return candidate;
|
|
20
|
+
};
|
|
21
|
+
const readOperationNames = (body)=>{
|
|
22
|
+
const operations = Array.isArray(body) ? body : [
|
|
23
|
+
body
|
|
24
|
+
];
|
|
25
|
+
return operations.map((operation)=>{
|
|
26
|
+
if (isPlainObject(operation) && "string" == typeof operation.operationName) return operation.operationName;
|
|
27
|
+
}).filter((name)=>Boolean(name));
|
|
28
|
+
};
|
|
29
|
+
const readDebugHeader = (headers)=>{
|
|
30
|
+
if (!headers) return;
|
|
31
|
+
for (const key of Object.keys(headers))if (key.toLowerCase() === DEBUG_HEADER) return headers[key];
|
|
32
|
+
};
|
|
33
|
+
const describeError = (error)=>{
|
|
34
|
+
if (error instanceof Error) return `${error.name}: ${error.message}`;
|
|
35
|
+
return "Unknown error.";
|
|
36
|
+
};
|
|
37
|
+
class DebuggerRouteDecoratorImpl {
|
|
38
|
+
constructor(debuggerService, identityContext, logger, handlerExecution, decoratee){
|
|
39
|
+
this.debuggerService = debuggerService;
|
|
40
|
+
this.identityContext = identityContext;
|
|
41
|
+
this.logger = logger;
|
|
42
|
+
this.handlerExecution = handlerExecution;
|
|
43
|
+
this.decoratee = decoratee;
|
|
44
|
+
}
|
|
45
|
+
async handle(request, response) {
|
|
46
|
+
this.start(request);
|
|
47
|
+
let result;
|
|
48
|
+
try {
|
|
49
|
+
result = await this.decoratee.handle(request, response);
|
|
50
|
+
} catch (ex) {
|
|
51
|
+
this.debuggerService.discard();
|
|
52
|
+
throw ex;
|
|
53
|
+
}
|
|
54
|
+
await this.flush(request, readBody(result, response));
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
start(request) {
|
|
58
|
+
try {
|
|
59
|
+
const requested = parseNamespaceHeader(readDebugHeader(request.headers));
|
|
60
|
+
const namespaces = requested.length > 0 ? requested : [
|
|
61
|
+
"*"
|
|
62
|
+
];
|
|
63
|
+
this.debuggerService.start({
|
|
64
|
+
namespaces
|
|
65
|
+
});
|
|
66
|
+
} catch {}
|
|
67
|
+
}
|
|
68
|
+
async flush(request, body) {
|
|
69
|
+
try {
|
|
70
|
+
const result = resolveTarget(body);
|
|
71
|
+
if (!result) return void this.debuggerService.discard();
|
|
72
|
+
if (this.identityContext.getIdentity().isAnonymous()) return void this.debuggerService.discard();
|
|
73
|
+
const isAuthorized = this.identityContext.isAuthorizationEnabled() && await canCaptureDebugData(this.identityContext);
|
|
74
|
+
if (!isAuthorized) return void this.debuggerService.discard();
|
|
75
|
+
const target = {
|
|
76
|
+
type: GRAPHQL_TARGET,
|
|
77
|
+
result,
|
|
78
|
+
requestId: this.handlerExecution.getId(),
|
|
79
|
+
operations: readOperationNames(request.body),
|
|
80
|
+
url: request.path
|
|
81
|
+
};
|
|
82
|
+
await this.debuggerService.flush(target);
|
|
83
|
+
} catch (ex) {
|
|
84
|
+
this.logger.error({
|
|
85
|
+
error: describeError(ex)
|
|
86
|
+
}, "Debugger failed to flush.");
|
|
87
|
+
this.debuggerService.discard();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const DebuggerRouteDecorator = HttpRouteHandler.createDecorator({
|
|
92
|
+
decorator: DebuggerRouteDecoratorImpl,
|
|
93
|
+
dependencies: [
|
|
94
|
+
Debugger,
|
|
95
|
+
IdentityContext,
|
|
96
|
+
Logger,
|
|
97
|
+
HandlerExecution
|
|
98
|
+
]
|
|
99
|
+
});
|
|
100
|
+
export { DEBUG_HEADER, DebuggerRouteDecorator };
|
|
101
|
+
|
|
102
|
+
//# sourceMappingURL=DebuggerRouteDecorator.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"features/debugger/DebuggerRouteDecorator.js","sources":["../../../src/features/debugger/DebuggerRouteDecorator.ts"],"sourcesContent":["import { HttpRouteHandler } from \"@webiny/event-handler-core\";\nimport { HandlerExecution } from \"@webiny/event-handler-core\";\nimport type { IHttpResponse } from \"@webiny/event-handler-core\";\nimport type { IHttpResponseBuilder } from \"@webiny/event-handler-core\";\nimport { Debugger } from \"./abstractions.js\";\nimport { IdentityContext } from \"~/features/security/IdentityContext/index.js\";\nimport { Logger } from \"~/features/logger/index.js\";\nimport { parseNamespaceHeader } from \"./parseNamespaceHeader.js\";\nimport { canCaptureDebugData } from \"./permissions.js\";\nimport { GRAPHQL_TARGET } from \"./GraphQLDebuggerTransport.js\";\nimport type { IGraphQLDeliveryTarget } from \"./GraphQLDebuggerTransport.js\";\n\nexport const DEBUG_HEADER = \"x-webiny-debug\";\n\ntype RouteResult = IHttpResponse | IHttpResponseBuilder | void;\n\nconst isPlainObject = (value: unknown): value is Record<string, any> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\n/**\n * A GraphQL result carries `data` or `errors`. Anything else (asset delivery, a plain string body)\n * is not ours to write to.\n */\nconst isGraphQLResult = (value: unknown): value is Record<string, any> => {\n return isPlainObject(value) && (\"data\" in value || \"errors\" in value);\n};\n\nconst isResponseBuilder = (value: unknown): value is IHttpResponseBuilder => {\n return isPlainObject(value) && typeof value.toResponse === \"function\";\n};\n\n/**\n * Finds the body a route produced, whichever of its three return styles it used. The body object is\n * the same reference the transport later serializes, so writing to it is enough.\n */\nconst readBody = (result: RouteResult, response: IHttpResponseBuilder): unknown => {\n if (isResponseBuilder(result)) {\n return result.toResponse().body;\n }\n if (result) {\n return result.body;\n }\n return response.toResponse().body;\n};\n\n/**\n * Batched requests produce an array of results. The session spans the whole HTTP request, so it is\n * attached once, to the last element. Duplicating it per operation would multiply it against the\n * byte budget.\n */\nconst resolveTarget = (body: unknown): Record<string, any> | undefined => {\n const candidate = Array.isArray(body) ? body.at(-1) : body;\n if (isGraphQLResult(candidate)) {\n return candidate;\n }\n return undefined;\n};\n\nconst readOperationNames = (body: unknown): string[] => {\n const operations = Array.isArray(body) ? body : [body];\n return operations\n .map(operation => {\n if (isPlainObject(operation) && typeof operation.operationName === \"string\") {\n return operation.operationName;\n }\n return undefined;\n })\n .filter((name): name is string => Boolean(name));\n};\n\n/**\n * Header names are case-insensitive, and the casing that reaches a route depends on the transport.\n */\nconst readDebugHeader = (headers: Record<string, string> | undefined): string | undefined => {\n if (!headers) {\n return undefined;\n }\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === DEBUG_HEADER) {\n return headers[key];\n }\n }\n return undefined;\n};\n\nconst describeError = (error: unknown): string => {\n if (error instanceof Error) {\n return `${error.name}: ${error.message}`;\n }\n return \"Unknown error.\";\n};\n\n/**\n * Opens a capture session around every HTTP route and hands it over once the route has produced its\n * response.\n *\n * It wraps the route rather than the GraphQL execution, because CMS resolvers run nested GraphQL\n * executions internally. Attaching there would put the session on a result that is then thrown\n * away; at the route there is exactly one response per request.\n */\nclass DebuggerRouteDecoratorImpl implements HttpRouteHandler.Interface {\n public constructor(\n private readonly debuggerService: Debugger.Interface,\n private readonly identityContext: IdentityContext.Interface,\n private readonly logger: Logger.Interface,\n private readonly handlerExecution: HandlerExecution.Interface,\n private readonly decoratee: HttpRouteHandler.Interface\n ) {}\n\n public async handle(\n request: HttpRouteHandler.Request,\n response: HttpRouteHandler.Response\n ): Promise<RouteResult> {\n this.start(request);\n\n let result: RouteResult;\n try {\n result = await this.decoratee.handle(request, response);\n } catch (ex) {\n this.debuggerService.discard();\n throw ex;\n }\n\n await this.flush(request, readBody(result, response));\n\n return result;\n }\n\n /**\n * A session starts on every request, and the permission check at flush decides whether anything\n * is delivered or the whole thing is discarded.\n *\n * Nothing is required from the client. The header is honoured when present, so a direct API\n * client can narrow what it captures.\n */\n private start(request: HttpRouteHandler.Request): void {\n /**\n * Must never throw: a malformed header must not turn into a 500 for the whole request.\n */\n try {\n const requested = parseNamespaceHeader(readDebugHeader(request.headers));\n const namespaces = requested.length > 0 ? requested : [\"*\"];\n\n this.debuggerService.start({ namespaces });\n } catch {\n // A debugger that cannot start is not a reason to fail the request.\n }\n }\n\n /**\n * Performs the permission gate and hands the session to the transports.\n *\n * The whole body is guarded: an error here would turn a working response into a 500, and only\n * for the identities that are allowed to debug.\n */\n private async flush(request: HttpRouteHandler.Request, body: unknown): Promise<void> {\n try {\n const result = resolveTarget(body);\n if (!result) {\n this.debuggerService.discard();\n return;\n }\n\n /**\n * Anonymous callers are rejected before permissions are resolved, because listing them\n * runs every registered authorizer, and some of those hit the database.\n */\n if (this.identityContext.getIdentity().isAnonymous()) {\n this.debuggerService.discard();\n return;\n }\n\n /**\n * Permission lookups return a wildcard whenever authorization is disabled, so a flush\n * running inside a `withoutAuthorization` scope would pass for anyone.\n */\n const isAuthorized =\n this.identityContext.isAuthorizationEnabled() &&\n (await canCaptureDebugData(this.identityContext));\n\n if (!isAuthorized) {\n /**\n * Nothing is written. Reporting the denial would tell every unauthorized caller that\n * the feature exists, and the Admin app already knows from the identity's own\n * permissions whether capture is available to it.\n */\n this.debuggerService.discard();\n return;\n }\n\n const target: IGraphQLDeliveryTarget = {\n type: GRAPHQL_TARGET,\n result,\n requestId: this.handlerExecution.getId(),\n operations: readOperationNames(request.body),\n /**\n * Which endpoint this was. An Admin session talks to several (the main API and the\n * CMS manage, read and preview endpoints) and knowing which one produced an entry is\n * most of the context when reading a report.\n */\n url: request.path\n };\n\n await this.debuggerService.flush(target);\n } catch (ex) {\n /**\n * Only the message, never the session or the payload.\n */\n this.logger.error({ error: describeError(ex) }, \"Debugger failed to flush.\");\n this.debuggerService.discard();\n }\n }\n}\n\nexport const DebuggerRouteDecorator = HttpRouteHandler.createDecorator({\n decorator: DebuggerRouteDecoratorImpl,\n dependencies: [Debugger, IdentityContext, Logger, HandlerExecution]\n});\n"],"names":["DEBUG_HEADER","isPlainObject","value","Array","isGraphQLResult","isResponseBuilder","readBody","result","response","resolveTarget","body","candidate","readOperationNames","operations","operation","name","Boolean","readDebugHeader","headers","key","Object","describeError","error","Error","DebuggerRouteDecoratorImpl","debuggerService","identityContext","logger","handlerExecution","decoratee","request","ex","requested","parseNamespaceHeader","namespaces","isAuthorized","canCaptureDebugData","target","GRAPHQL_TARGET","DebuggerRouteDecorator","HttpRouteHandler","Debugger","IdentityContext","Logger","HandlerExecution"],"mappings":"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"}
|