@databricks/appkit 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +1 -0
- package/dist/analytics/analytics.d.ts +11 -1
- package/dist/analytics/analytics.d.ts.map +1 -1
- package/dist/analytics/analytics.js +12 -5
- package/dist/analytics/analytics.js.map +1 -1
- package/dist/appkit/package.js +1 -1
- package/dist/cache/index.js +11 -10
- package/dist/cache/index.js.map +1 -1
- package/dist/cache/storage/memory.js +4 -2
- package/dist/cache/storage/memory.js.map +1 -1
- package/dist/cache/storage/persistent.js +7 -0
- package/dist/cache/storage/persistent.js.map +1 -1
- package/dist/connectors/lakebase/client.js +8 -4
- package/dist/connectors/lakebase/client.js.map +1 -1
- package/dist/connectors/sql-warehouse/client.js +5 -2
- package/dist/connectors/sql-warehouse/client.js.map +1 -1
- package/dist/context/execution-context.d.ts +17 -0
- package/dist/context/execution-context.d.ts.map +1 -0
- package/dist/context/service-context.d.ts +21 -0
- package/dist/context/service-context.d.ts.map +1 -0
- package/dist/context/service-context.js +2 -6
- package/dist/context/service-context.js.map +1 -1
- package/dist/context/user-context.d.ts +29 -0
- package/dist/context/user-context.d.ts.map +1 -0
- package/dist/core/appkit.d.ts.map +1 -1
- package/dist/core/appkit.js +35 -12
- package/dist/core/appkit.js.map +1 -1
- package/dist/errors/authentication.js +3 -6
- package/dist/errors/authentication.js.map +1 -1
- package/dist/errors/base.js +4 -0
- package/dist/errors/base.js.map +1 -1
- package/dist/errors/configuration.js +3 -6
- package/dist/errors/configuration.js.map +1 -1
- package/dist/errors/connection.js +3 -6
- package/dist/errors/connection.js.map +1 -1
- package/dist/errors/execution.js +3 -6
- package/dist/errors/execution.js.map +1 -1
- package/dist/errors/initialization.js +3 -6
- package/dist/errors/initialization.js.map +1 -1
- package/dist/errors/server.js +3 -6
- package/dist/errors/server.js.map +1 -1
- package/dist/errors/tunnel.js +3 -6
- package/dist/errors/tunnel.js.map +1 -1
- package/dist/errors/validation.js +3 -6
- package/dist/errors/validation.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/logging/wide-event-emitter.js +1 -3
- package/dist/logging/wide-event-emitter.js.map +1 -1
- package/dist/logging/wide-event.js +2 -0
- package/dist/logging/wide-event.js.map +1 -1
- package/dist/plugin/dev-reader.js +3 -6
- package/dist/plugin/dev-reader.js.map +1 -1
- package/dist/plugin/interceptors/retry.js +3 -0
- package/dist/plugin/interceptors/retry.js.map +1 -1
- package/dist/plugin/plugin.d.ts +10 -24
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/plugin/plugin.js +23 -30
- package/dist/plugin/plugin.js.map +1 -1
- package/dist/server/base-server.js +2 -0
- package/dist/server/base-server.js.map +1 -1
- package/dist/server/index.d.ts +23 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +29 -13
- package/dist/server/index.js.map +1 -1
- package/dist/server/remote-tunnel/remote-tunnel-controller.js +30 -15
- package/dist/server/remote-tunnel/remote-tunnel-controller.js.map +1 -1
- package/dist/server/remote-tunnel/remote-tunnel-manager.js +5 -1
- package/dist/server/remote-tunnel/remote-tunnel-manager.js.map +1 -1
- package/dist/server/static-server.js +1 -0
- package/dist/server/static-server.js.map +1 -1
- package/dist/server/vite-dev-server.js +1 -0
- package/dist/server/vite-dev-server.js.map +1 -1
- package/dist/shared/src/plugin.d.ts +25 -1
- package/dist/shared/src/plugin.d.ts.map +1 -1
- package/dist/stream/arrow-stream-processor.js +5 -10
- package/dist/stream/arrow-stream-processor.js.map +1 -1
- package/dist/stream/buffers.js +7 -0
- package/dist/stream/buffers.js.map +1 -1
- package/dist/stream/stream-manager.js +5 -0
- package/dist/stream/stream-manager.js.map +1 -1
- package/dist/stream/stream-registry.js +1 -0
- package/dist/stream/stream-registry.js.map +1 -1
- package/dist/stream/validator.js +2 -6
- package/dist/stream/validator.js.map +1 -1
- package/dist/telemetry/noop.js +1 -0
- package/dist/telemetry/noop.js.map +1 -1
- package/dist/telemetry/telemetry-manager.js +4 -6
- package/dist/telemetry/telemetry-manager.js.map +1 -1
- package/dist/telemetry/telemetry-provider.js +3 -0
- package/dist/telemetry/telemetry-provider.js.map +1 -1
- package/dist/type-generator/spinner.js +9 -11
- package/dist/type-generator/spinner.js.map +1 -1
- package/docs/docs/api/appkit/Class.AppKitError/index.html +5 -3
- package/docs/docs/api/appkit/Class.AppKitError.md +7 -0
- package/docs/docs/api/appkit/Class.AuthenticationError/index.html +3 -3
- package/docs/docs/api/appkit/Class.ConfigurationError/index.html +3 -3
- package/docs/docs/api/appkit/Class.ConnectionError/index.html +3 -3
- package/docs/docs/api/appkit/Class.ExecutionError/index.html +3 -3
- package/docs/docs/api/appkit/Class.InitializationError/index.html +3 -3
- package/docs/docs/api/appkit/Class.Plugin/index.html +28 -21
- package/docs/docs/api/appkit/Class.Plugin.md +34 -34
- package/docs/docs/api/appkit/Class.ServerError/index.html +3 -3
- package/docs/docs/api/appkit/Class.TunnelError/index.html +3 -3
- package/docs/docs/api/appkit/Class.ValidationError/index.html +3 -3
- package/docs/docs/api/appkit/Function.appKitTypesPlugin/index.html +3 -3
- package/docs/docs/api/appkit/Function.createApp/index.html +4 -4
- package/docs/docs/api/appkit/Function.getExecutionContext/index.html +26 -0
- package/docs/docs/api/appkit/Function.getExecutionContext.md +19 -0
- package/docs/docs/api/appkit/Function.isSQLTypeMarker/index.html +4 -4
- package/docs/docs/api/appkit/Interface.BasePluginConfig/index.html +3 -3
- package/docs/docs/api/appkit/Interface.CacheConfig/index.html +3 -3
- package/docs/docs/api/appkit/Interface.ITelemetry/index.html +3 -3
- package/docs/docs/api/appkit/Interface.StreamExecutionSettings/index.html +3 -3
- package/docs/docs/api/appkit/Interface.TelemetryConfig/index.html +3 -3
- package/docs/docs/api/appkit/TypeAlias.IAppRouter/index.html +3 -3
- package/docs/docs/api/appkit/Variable.sql/index.html +3 -3
- package/docs/docs/api/appkit/index.html +4 -4
- package/docs/docs/api/appkit-ui/data/AreaChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/BarChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/DataTable/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/DonutChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/HeatmapChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/LineChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/PieChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/RadarChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/data/ScatterChart/index.html +2 -2
- package/docs/docs/api/appkit-ui/index.html +2 -2
- package/docs/docs/api/appkit-ui/styling/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Accordion/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Alert/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/AlertDialog/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/AspectRatio/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Avatar/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Badge/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Breadcrumb/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Button/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/ButtonGroup/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Calendar/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Card/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Carousel/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/ChartContainer/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Checkbox/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Collapsible/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Command/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/ContextMenu/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Dialog/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Drawer/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/DropdownMenu/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Empty/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Field/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/FormControl/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/HoverCard/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Input/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/InputGroup/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/InputOTP/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Item/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Kbd/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Label/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Menubar/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/NavigationMenu/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Pagination/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Popover/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Progress/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/RadioGroup/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/ResizableHandle/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/ScrollArea/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Select/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Separator/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Sheet/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Sidebar/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Skeleton/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Slider/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Spinner/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Switch/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Table/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Tabs/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Textarea/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Toaster/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Toggle/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/ToggleGroup/index.html +2 -2
- package/docs/docs/api/appkit-ui/ui/Tooltip/index.html +2 -2
- package/docs/docs/api/appkit.md +6 -5
- package/docs/docs/api/index.html +2 -2
- package/docs/docs/app-management/index.html +2 -2
- package/docs/docs/architecture/index.html +2 -2
- package/docs/docs/category/development/index.html +2 -2
- package/docs/docs/configuration/index.html +2 -2
- package/docs/docs/core-principles/index.html +2 -2
- package/docs/docs/development/index.html +2 -2
- package/docs/docs/development/llm-guide/index.html +2 -2
- package/docs/docs/development/local-development/index.html +2 -2
- package/docs/docs/development/project-setup/index.html +2 -2
- package/docs/docs/development/remote-bridge/index.html +2 -2
- package/docs/docs/development/type-generation/index.html +2 -2
- package/docs/docs/index.html +2 -2
- package/docs/docs/plugins/index.html +7 -3
- package/docs/docs/plugins.md +36 -11
- package/llms.txt +1 -0
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":[],"sources":["../../src/errors/server.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when server lifecycle operations fail.\n * Use for server start/stop issues, configuration conflicts, etc.\n *\n * @example\n * ```typescript\n * throw new ServerError(\"Cannot get server when autoStart is true\");\n * throw new ServerError(\"Server not started\");\n * ```\n */\nexport class ServerError extends AppKitError {\n readonly code = \"SERVER_ERROR\";\n readonly statusCode = 500;\n readonly isRetryable = false;\n\n /**\n * Create a server error for autoStart conflict\n */\n static autoStartConflict(operation: string): ServerError {\n return new ServerError(`Cannot ${operation} when autoStart is true`, {\n context: { operation },\n });\n }\n\n /**\n * Create a server error for server not started\n */\n static notStarted(): ServerError {\n return new ServerError(\n \"Server not started. Please start the server first by calling the start() method\",\n );\n }\n\n /**\n * Create a server error for Vite dev server not initialized\n */\n static viteNotInitialized(): ServerError {\n return new ServerError(\"Vite dev server not initialized\");\n }\n\n /**\n * Create a server error for missing client directory\n */\n static clientDirectoryNotFound(searchedPaths: string[]): ServerError {\n return new ServerError(\n `Could not find client directory. Searched for vite.config.ts/js + index.html in: ${searchedPaths.join(\", \")}`,\n { context: { searchedPaths } },\n );\n }\n}\n"],"mappings":";;;;;;YAAqC;CAYxB,cAAb,MAAa,oBAAoB,YAAY
|
|
1
|
+
{"version":3,"file":"server.js","names":[],"sources":["../../src/errors/server.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when server lifecycle operations fail.\n * Use for server start/stop issues, configuration conflicts, etc.\n *\n * @example\n * ```typescript\n * throw new ServerError(\"Cannot get server when autoStart is true\");\n * throw new ServerError(\"Server not started\");\n * ```\n */\nexport class ServerError extends AppKitError {\n readonly code = \"SERVER_ERROR\";\n readonly statusCode = 500;\n readonly isRetryable = false;\n\n /**\n * Create a server error for autoStart conflict\n */\n static autoStartConflict(operation: string): ServerError {\n return new ServerError(`Cannot ${operation} when autoStart is true`, {\n context: { operation },\n });\n }\n\n /**\n * Create a server error for server not started\n */\n static notStarted(): ServerError {\n return new ServerError(\n \"Server not started. Please start the server first by calling the start() method\",\n );\n }\n\n /**\n * Create a server error for Vite dev server not initialized\n */\n static viteNotInitialized(): ServerError {\n return new ServerError(\"Vite dev server not initialized\");\n }\n\n /**\n * Create a server error for missing client directory\n */\n static clientDirectoryNotFound(searchedPaths: string[]): ServerError {\n return new ServerError(\n `Could not find client directory. Searched for vite.config.ts/js + index.html in: ${searchedPaths.join(\", \")}`,\n { context: { searchedPaths } },\n );\n }\n}\n"],"mappings":";;;;;;YAAqC;CAYxB,cAAb,MAAa,oBAAoB,YAAY;EAC3C,AAAS,OAAO;EAChB,AAAS,aAAa;EACtB,AAAS,cAAc;;;;EAKvB,OAAO,kBAAkB,WAAgC;AACvD,UAAO,IAAI,YAAY,UAAU,UAAU,0BAA0B,EACnE,SAAS,EAAE,WAAW,EACvB,CAAC;;;;;EAMJ,OAAO,aAA0B;AAC/B,UAAO,IAAI,YACT,kFACD;;;;;EAMH,OAAO,qBAAkC;AACvC,UAAO,IAAI,YAAY,kCAAkC;;;;;EAM3D,OAAO,wBAAwB,eAAsC;AACnE,UAAO,IAAI,YACT,oFAAoF,cAAc,KAAK,KAAK,IAC5G,EAAE,SAAS,EAAE,eAAe,EAAE,CAC/B"}
|
package/dist/errors/tunnel.js
CHANGED
|
@@ -6,12 +6,9 @@ var TunnelError;
|
|
|
6
6
|
var init_tunnel = __esmMin((() => {
|
|
7
7
|
init_base();
|
|
8
8
|
TunnelError = class TunnelError extends AppKitError {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
this.statusCode = 502;
|
|
13
|
-
this.isRetryable = true;
|
|
14
|
-
}
|
|
9
|
+
code = "TUNNEL_ERROR";
|
|
10
|
+
statusCode = 502;
|
|
11
|
+
isRetryable = true;
|
|
15
12
|
/**
|
|
16
13
|
* Create a tunnel error for missing tunnel getter
|
|
17
14
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tunnel.js","names":[],"sources":["../../src/errors/tunnel.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when remote tunnel operations fail.\n * Use for tunnel connection issues, message parsing failures, etc.\n *\n * @example\n * ```typescript\n * throw new TunnelError(\"No tunnel connection available\");\n * throw new TunnelError(\"Failed to parse WebSocket message\", { cause: parseError });\n * ```\n */\nexport class TunnelError extends AppKitError {\n readonly code = \"TUNNEL_ERROR\";\n readonly statusCode = 502;\n readonly isRetryable = true;\n\n /**\n * Create a tunnel error for missing tunnel getter\n */\n static getterNotRegistered(): TunnelError {\n return new TunnelError(\n \"Tunnel getter not registered for DevFileReader singleton\",\n );\n }\n\n /**\n * Create a tunnel error for no available connection\n */\n static noConnection(): TunnelError {\n return new TunnelError(\"No tunnel connection available for file read\");\n }\n\n /**\n * Create a tunnel error for asset fetch failure\n */\n static fetchFailed(path: string, cause?: Error): TunnelError {\n return new TunnelError(\"Failed to fetch asset\", {\n cause,\n context: { path },\n });\n }\n\n /**\n * Create a tunnel error for message parsing failure\n */\n static parseError(messageType: string, cause?: Error): TunnelError {\n return new TunnelError(`Failed to parse ${messageType} message`, {\n cause,\n context: { messageType },\n });\n }\n}\n"],"mappings":";;;;;;YAAqC;CAYxB,cAAb,MAAa,oBAAoB,YAAY
|
|
1
|
+
{"version":3,"file":"tunnel.js","names":[],"sources":["../../src/errors/tunnel.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when remote tunnel operations fail.\n * Use for tunnel connection issues, message parsing failures, etc.\n *\n * @example\n * ```typescript\n * throw new TunnelError(\"No tunnel connection available\");\n * throw new TunnelError(\"Failed to parse WebSocket message\", { cause: parseError });\n * ```\n */\nexport class TunnelError extends AppKitError {\n readonly code = \"TUNNEL_ERROR\";\n readonly statusCode = 502;\n readonly isRetryable = true;\n\n /**\n * Create a tunnel error for missing tunnel getter\n */\n static getterNotRegistered(): TunnelError {\n return new TunnelError(\n \"Tunnel getter not registered for DevFileReader singleton\",\n );\n }\n\n /**\n * Create a tunnel error for no available connection\n */\n static noConnection(): TunnelError {\n return new TunnelError(\"No tunnel connection available for file read\");\n }\n\n /**\n * Create a tunnel error for asset fetch failure\n */\n static fetchFailed(path: string, cause?: Error): TunnelError {\n return new TunnelError(\"Failed to fetch asset\", {\n cause,\n context: { path },\n });\n }\n\n /**\n * Create a tunnel error for message parsing failure\n */\n static parseError(messageType: string, cause?: Error): TunnelError {\n return new TunnelError(`Failed to parse ${messageType} message`, {\n cause,\n context: { messageType },\n });\n }\n}\n"],"mappings":";;;;;;YAAqC;CAYxB,cAAb,MAAa,oBAAoB,YAAY;EAC3C,AAAS,OAAO;EAChB,AAAS,aAAa;EACtB,AAAS,cAAc;;;;EAKvB,OAAO,sBAAmC;AACxC,UAAO,IAAI,YACT,2DACD;;;;;EAMH,OAAO,eAA4B;AACjC,UAAO,IAAI,YAAY,+CAA+C;;;;;EAMxE,OAAO,YAAY,MAAc,OAA4B;AAC3D,UAAO,IAAI,YAAY,yBAAyB;IAC9C;IACA,SAAS,EAAE,MAAM;IAClB,CAAC;;;;;EAMJ,OAAO,WAAW,aAAqB,OAA4B;AACjE,UAAO,IAAI,YAAY,mBAAmB,YAAY,WAAW;IAC/D;IACA,SAAS,EAAE,aAAa;IACzB,CAAC"}
|
|
@@ -6,12 +6,9 @@ var ValidationError;
|
|
|
6
6
|
var init_validation = __esmMin((() => {
|
|
7
7
|
init_base();
|
|
8
8
|
ValidationError = class ValidationError extends AppKitError {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
this.statusCode = 400;
|
|
13
|
-
this.isRetryable = false;
|
|
14
|
-
}
|
|
9
|
+
code = "VALIDATION_ERROR";
|
|
10
|
+
statusCode = 400;
|
|
11
|
+
isRetryable = false;
|
|
15
12
|
/**
|
|
16
13
|
* Create a validation error for a missing required field
|
|
17
14
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","names":[],"sources":["../../src/errors/validation.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when input validation fails.\n * Use for invalid parameters, missing required fields, or type mismatches.\n *\n * @example\n * ```typescript\n * throw new ValidationError(\"Statement is required\", { context: { field: \"statement\" } });\n * throw new ValidationError(\"maxPoolSize must be at least 1\", { context: { value: config.maxPoolSize } });\n * ```\n */\nexport class ValidationError extends AppKitError {\n readonly code = \"VALIDATION_ERROR\";\n readonly statusCode = 400;\n readonly isRetryable = false;\n\n /**\n * Create a validation error for a missing required field\n */\n static missingField(fieldName: string): ValidationError {\n return new ValidationError(`Missing required field: ${fieldName}`, {\n context: { field: fieldName },\n });\n }\n\n /**\n * Create a validation error for an invalid field value.\n * Note: The actual value is not stored in context for security reasons.\n * Only the value's type is recorded.\n */\n static invalidValue(\n fieldName: string,\n value: unknown,\n expected?: string,\n ): ValidationError {\n const msg = expected\n ? `Invalid value for ${fieldName}: expected ${expected}`\n : `Invalid value for ${fieldName}`;\n return new ValidationError(msg, {\n context: {\n field: fieldName,\n valueType: value === null ? \"null\" : typeof value,\n expected,\n },\n });\n }\n\n /**\n * Create a validation error for missing environment variables\n */\n static missingEnvVars(vars: string[]): ValidationError {\n return new ValidationError(\n `Missing required environment variables: ${vars.join(\", \")}`,\n { context: { missingVars: vars } },\n );\n }\n}\n"],"mappings":";;;;;;YAAqC;CAYxB,kBAAb,MAAa,wBAAwB,YAAY
|
|
1
|
+
{"version":3,"file":"validation.js","names":[],"sources":["../../src/errors/validation.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when input validation fails.\n * Use for invalid parameters, missing required fields, or type mismatches.\n *\n * @example\n * ```typescript\n * throw new ValidationError(\"Statement is required\", { context: { field: \"statement\" } });\n * throw new ValidationError(\"maxPoolSize must be at least 1\", { context: { value: config.maxPoolSize } });\n * ```\n */\nexport class ValidationError extends AppKitError {\n readonly code = \"VALIDATION_ERROR\";\n readonly statusCode = 400;\n readonly isRetryable = false;\n\n /**\n * Create a validation error for a missing required field\n */\n static missingField(fieldName: string): ValidationError {\n return new ValidationError(`Missing required field: ${fieldName}`, {\n context: { field: fieldName },\n });\n }\n\n /**\n * Create a validation error for an invalid field value.\n * Note: The actual value is not stored in context for security reasons.\n * Only the value's type is recorded.\n */\n static invalidValue(\n fieldName: string,\n value: unknown,\n expected?: string,\n ): ValidationError {\n const msg = expected\n ? `Invalid value for ${fieldName}: expected ${expected}`\n : `Invalid value for ${fieldName}`;\n return new ValidationError(msg, {\n context: {\n field: fieldName,\n valueType: value === null ? \"null\" : typeof value,\n expected,\n },\n });\n }\n\n /**\n * Create a validation error for missing environment variables\n */\n static missingEnvVars(vars: string[]): ValidationError {\n return new ValidationError(\n `Missing required environment variables: ${vars.join(\", \")}`,\n { context: { missingVars: vars } },\n );\n }\n}\n"],"mappings":";;;;;;YAAqC;CAYxB,kBAAb,MAAa,wBAAwB,YAAY;EAC/C,AAAS,OAAO;EAChB,AAAS,aAAa;EACtB,AAAS,cAAc;;;;EAKvB,OAAO,aAAa,WAAoC;AACtD,UAAO,IAAI,gBAAgB,2BAA2B,aAAa,EACjE,SAAS,EAAE,OAAO,WAAW,EAC9B,CAAC;;;;;;;EAQJ,OAAO,aACL,WACA,OACA,UACiB;AAIjB,UAAO,IAAI,gBAHC,WACR,qBAAqB,UAAU,aAAa,aAC5C,qBAAqB,aACO,EAC9B,SAAS;IACP,OAAO;IACP,WAAW,UAAU,OAAO,SAAS,OAAO;IAC5C;IACD,EACF,CAAC;;;;;EAMJ,OAAO,eAAe,MAAiC;AACrD,UAAO,IAAI,gBACT,2CAA2C,KAAK,KAAK,KAAK,IAC1D,EAAE,SAAS,EAAE,aAAa,MAAM,EAAE,CACnC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -20,4 +20,5 @@ import { TunnelError } from "./errors/tunnel.js";
|
|
|
20
20
|
import { ValidationError } from "./errors/validation.js";
|
|
21
21
|
import { server } from "./server/index.js";
|
|
22
22
|
import { appKitTypesPlugin } from "./type-generator/vite-plugin.js";
|
|
23
|
-
|
|
23
|
+
import { getExecutionContext } from "./context/execution-context.js";
|
|
24
|
+
export { AppKitError, AuthenticationError, type BasePluginConfig, type CacheConfig, CacheManager, ConfigurationError, ConnectionError, type Counter, ExecutionError, type Histogram, type IAppRouter, type ITelemetry, InitializationError, Plugin, ServerError, SeverityNumber, type Span, SpanStatusCode, type StreamExecutionSettings, type TelemetryConfig, TunnelError, ValidationError, analytics, appKitTypesPlugin, createApp, getExecutionContext, isSQLTypeMarker, server, sql, toPlugin };
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,8 @@ import { ServerError } from "./errors/server.js";
|
|
|
10
10
|
import { TunnelError } from "./errors/tunnel.js";
|
|
11
11
|
import { ValidationError } from "./errors/validation.js";
|
|
12
12
|
import { init_errors } from "./errors/index.js";
|
|
13
|
+
import { getExecutionContext } from "./context/execution-context.js";
|
|
14
|
+
import { init_context } from "./context/index.js";
|
|
13
15
|
import { CacheManager } from "./cache/index.js";
|
|
14
16
|
import { Plugin } from "./plugin/plugin.js";
|
|
15
17
|
import { toPlugin } from "./plugin/to-plugin.js";
|
|
@@ -23,7 +25,8 @@ import { server } from "./server/index.js";
|
|
|
23
25
|
|
|
24
26
|
//#region src/index.ts
|
|
25
27
|
init_errors();
|
|
28
|
+
init_context();
|
|
26
29
|
|
|
27
30
|
//#endregion
|
|
28
|
-
export { AppKitError, AuthenticationError, CacheManager, ConfigurationError, ConnectionError, ExecutionError, InitializationError, Plugin, ServerError, SeverityNumber, SpanStatusCode, TunnelError, ValidationError, analytics, appKitTypesPlugin, createApp, isSQLTypeMarker, server, sql, toPlugin };
|
|
31
|
+
export { AppKitError, AuthenticationError, CacheManager, ConfigurationError, ConnectionError, ExecutionError, InitializationError, Plugin, ServerError, SeverityNumber, SpanStatusCode, TunnelError, ValidationError, analytics, appKitTypesPlugin, createApp, getExecutionContext, isSQLTypeMarker, server, sql, toPlugin };
|
|
29
32
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * Core library for building Databricks applications with type-safe SQL queries,\n * plugin architecture, and React integration.\n */\n\n// Types from shared\nexport type {\n BasePluginConfig,\n CacheConfig,\n IAppRouter,\n StreamExecutionSettings,\n} from \"shared\";\nexport { isSQLTypeMarker, sql } from \"shared\";\nexport { analytics } from \"./analytics\";\nexport { CacheManager } from \"./cache\";\nexport { createApp } from \"./core\";\n// Errors\nexport {\n AppKitError,\n AuthenticationError,\n ConfigurationError,\n ConnectionError,\n ExecutionError,\n InitializationError,\n ServerError,\n TunnelError,\n ValidationError,\n} from \"./errors\";\n// Plugin authoring\nexport { Plugin, toPlugin } from \"./plugin\";\nexport { server } from \"./server\";\n// Telemetry (for advanced custom telemetry)\nexport {\n type Counter,\n type Histogram,\n type ITelemetry,\n SeverityNumber,\n type Span,\n SpanStatusCode,\n type TelemetryConfig,\n} from \"./telemetry\";\n\n// Vite plugin and type generation\nexport { appKitTypesPlugin } from \"./type-generator/vite-plugin\";\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @packageDocumentation\n *\n * Core library for building Databricks applications with type-safe SQL queries,\n * plugin architecture, and React integration.\n */\n\n// Types from shared\nexport type {\n BasePluginConfig,\n CacheConfig,\n IAppRouter,\n StreamExecutionSettings,\n} from \"shared\";\nexport { isSQLTypeMarker, sql } from \"shared\";\nexport { analytics } from \"./analytics\";\nexport { CacheManager } from \"./cache\";\nexport { createApp } from \"./core\";\n// Errors\nexport {\n AppKitError,\n AuthenticationError,\n ConfigurationError,\n ConnectionError,\n ExecutionError,\n InitializationError,\n ServerError,\n TunnelError,\n ValidationError,\n} from \"./errors\";\n// Plugin authoring\nexport { Plugin, toPlugin } from \"./plugin\";\nexport { server } from \"./server\";\n// Telemetry (for advanced custom telemetry)\nexport {\n type Counter,\n type Histogram,\n type ITelemetry,\n SeverityNumber,\n type Span,\n SpanStatusCode,\n type TelemetryConfig,\n} from \"./telemetry\";\n\n// Vite plugin and type generation\nexport { appKitTypesPlugin } from \"./type-generator/vite-plugin\";\nexport { getExecutionContext } from \"./context\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;aA6BkB;cAiB8B"}
|
|
@@ -5,9 +5,7 @@ import { SeverityNumber, logs } from "@opentelemetry/api-logs";
|
|
|
5
5
|
* Emits WideEvents to OpenTelemetry as structured logs
|
|
6
6
|
*/
|
|
7
7
|
var WideEventEmitter = class {
|
|
8
|
-
|
|
9
|
-
this.logger = logs.getLogger("appkit", "1.0.0");
|
|
10
|
-
}
|
|
8
|
+
logger = logs.getLogger("appkit", "1.0.0");
|
|
11
9
|
/**
|
|
12
10
|
* Emit a WideEvent to OpenTelemetry.
|
|
13
11
|
* Fails silently to avoid crashing the application due to observability issues.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wide-event-emitter.js","names":[],"sources":["../../src/logging/wide-event-emitter.ts"],"sourcesContent":["import { logs, SeverityNumber } from \"@opentelemetry/api-logs\";\nimport type { WideEventData } from \"./wide-event\";\n\n/**\n * Emits WideEvents to OpenTelemetry as structured logs\n */\nexport class WideEventEmitter {\n private logger = logs.getLogger(\"appkit\", \"1.0.0\");\n\n /**\n * Emit a WideEvent to OpenTelemetry.\n * Fails silently to avoid crashing the application due to observability issues.\n */\n emit(event: WideEventData): void {\n try {\n const logRecord = {\n timestamp: Date.parse(event.timestamp),\n severityNumber: this.getSeverityNumber(event),\n severityText: this.getSeverityText(event),\n body: this.createLogBody(event),\n attributes: this.createAttributes(event),\n };\n\n this.logger.emit(logRecord);\n } catch {\n // Silent fail - observability should never crash the application\n }\n }\n\n /**\n * Get OpenTelemetry severity number based on event data\n */\n private getSeverityNumber(event: WideEventData): SeverityNumber {\n // Error level\n if (event.error) {\n return SeverityNumber.ERROR;\n }\n\n // Status code based\n if (event.status_code) {\n if (event.status_code >= 500) {\n return SeverityNumber.ERROR;\n }\n if (event.status_code >= 400) {\n return SeverityNumber.WARN;\n }\n }\n\n // Check logs for errors/warnings\n if (event.logs) {\n const hasError = event.logs.some((log) => log.level === \"error\");\n if (hasError) {\n return SeverityNumber.ERROR;\n }\n\n const hasWarn = event.logs.some((log) => log.level === \"warn\");\n if (hasWarn) {\n return SeverityNumber.WARN;\n }\n }\n\n return SeverityNumber.INFO;\n }\n\n /**\n * Get severity text based on severity number\n */\n private getSeverityText(event: WideEventData): string {\n const severityNumber = this.getSeverityNumber(event);\n\n if (severityNumber >= SeverityNumber.ERROR) {\n return \"ERROR\";\n }\n if (severityNumber >= SeverityNumber.WARN) {\n return \"WARN\";\n }\n if (severityNumber >= SeverityNumber.INFO) {\n return \"INFO\";\n }\n return \"DEBUG\";\n }\n\n /**\n * Create log body from event data\n */\n private createLogBody(event: WideEventData): string {\n const parts: string[] = [];\n\n // HTTP request info\n if (event.method && event.path) {\n parts.push(`${event.method} ${event.path}`);\n }\n\n // Status code\n if (event.status_code) {\n parts.push(`→ ${event.status_code}`);\n }\n\n // Duration\n if (event.duration_ms) {\n parts.push(`(${event.duration_ms}ms)`);\n }\n\n // Component info\n if (event.component) {\n const componentStr = event.component.operation\n ? `${event.component.name}.${event.component.operation}`\n : event.component.name;\n parts.push(`[${componentStr}]`);\n }\n\n // Error message\n if (event.error) {\n parts.push(`ERROR: ${event.error.message}`);\n }\n\n return parts.join(\" \");\n }\n\n /**\n * Create OpenTelemetry attributes from event data\n */\n private createAttributes(\n event: WideEventData,\n ): Record<string, string | number | boolean | undefined> {\n const attributes: Record<string, string | number | boolean | undefined> = {\n // Request metadata\n request_id: event.request_id,\n trace_id: event.trace_id,\n\n // HTTP attributes (OpenTelemetry semantic conventions)\n \"http.method\": event.method,\n \"http.route\": event.path,\n \"http.status_code\": event.status_code,\n \"http.request.duration_ms\": event.duration_ms,\n\n // Service attributes\n \"service.name\": event.service?.name,\n \"service.version\": event.service?.version,\n \"service.region\": event.service?.region,\n \"service.deployment_id\": event.service?.deployment_id,\n \"service.node_env\": event.service?.node_env,\n\n // Component attributes\n \"component.name\": event.component?.name,\n \"component.operation\": event.component?.operation,\n\n // User attributes\n \"user.id\": event.user?.id,\n\n // Error attributes\n \"error.type\": event.error?.type,\n \"error.code\": event.error?.code,\n \"error.message\": event.error?.message,\n \"error.retriable\": event.error?.retriable,\n\n // Execution metadata\n \"execution.timeout_ms\": event.execution?.timeout_ms,\n \"execution.retry_attempts\": event.execution?.retry_attempts,\n \"execution.cache_hit\": event.execution?.cache_hit,\n \"execution.cache_key\": event.execution?.cache_key,\n \"execution.cache_deduplication\": event.execution?.cache_deduplication,\n\n // Stream metadata\n \"stream.id\": event.stream?.stream_id,\n \"stream.events_sent\": event.stream?.events_sent,\n\n // Log count\n log_count: event.logs?.length,\n };\n\n // Add custom context as attributes with scope prefix (no \"appkit\" prefix)\n if (event.context) {\n for (const [scope, scopeData] of Object.entries(event.context)) {\n for (const [key, value] of Object.entries(scopeData)) {\n // Only add primitive values\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n attributes[`${scope}.${key}`] = value;\n }\n }\n }\n }\n\n // Remove undefined values\n return Object.fromEntries(\n Object.entries(attributes).filter(([_, value]) => value !== undefined),\n );\n }\n}\n"],"mappings":";;;;;;AAMA,IAAa,mBAAb,MAA8B
|
|
1
|
+
{"version":3,"file":"wide-event-emitter.js","names":[],"sources":["../../src/logging/wide-event-emitter.ts"],"sourcesContent":["import { logs, SeverityNumber } from \"@opentelemetry/api-logs\";\nimport type { WideEventData } from \"./wide-event\";\n\n/**\n * Emits WideEvents to OpenTelemetry as structured logs\n */\nexport class WideEventEmitter {\n private logger = logs.getLogger(\"appkit\", \"1.0.0\");\n\n /**\n * Emit a WideEvent to OpenTelemetry.\n * Fails silently to avoid crashing the application due to observability issues.\n */\n emit(event: WideEventData): void {\n try {\n const logRecord = {\n timestamp: Date.parse(event.timestamp),\n severityNumber: this.getSeverityNumber(event),\n severityText: this.getSeverityText(event),\n body: this.createLogBody(event),\n attributes: this.createAttributes(event),\n };\n\n this.logger.emit(logRecord);\n } catch {\n // Silent fail - observability should never crash the application\n }\n }\n\n /**\n * Get OpenTelemetry severity number based on event data\n */\n private getSeverityNumber(event: WideEventData): SeverityNumber {\n // Error level\n if (event.error) {\n return SeverityNumber.ERROR;\n }\n\n // Status code based\n if (event.status_code) {\n if (event.status_code >= 500) {\n return SeverityNumber.ERROR;\n }\n if (event.status_code >= 400) {\n return SeverityNumber.WARN;\n }\n }\n\n // Check logs for errors/warnings\n if (event.logs) {\n const hasError = event.logs.some((log) => log.level === \"error\");\n if (hasError) {\n return SeverityNumber.ERROR;\n }\n\n const hasWarn = event.logs.some((log) => log.level === \"warn\");\n if (hasWarn) {\n return SeverityNumber.WARN;\n }\n }\n\n return SeverityNumber.INFO;\n }\n\n /**\n * Get severity text based on severity number\n */\n private getSeverityText(event: WideEventData): string {\n const severityNumber = this.getSeverityNumber(event);\n\n if (severityNumber >= SeverityNumber.ERROR) {\n return \"ERROR\";\n }\n if (severityNumber >= SeverityNumber.WARN) {\n return \"WARN\";\n }\n if (severityNumber >= SeverityNumber.INFO) {\n return \"INFO\";\n }\n return \"DEBUG\";\n }\n\n /**\n * Create log body from event data\n */\n private createLogBody(event: WideEventData): string {\n const parts: string[] = [];\n\n // HTTP request info\n if (event.method && event.path) {\n parts.push(`${event.method} ${event.path}`);\n }\n\n // Status code\n if (event.status_code) {\n parts.push(`→ ${event.status_code}`);\n }\n\n // Duration\n if (event.duration_ms) {\n parts.push(`(${event.duration_ms}ms)`);\n }\n\n // Component info\n if (event.component) {\n const componentStr = event.component.operation\n ? `${event.component.name}.${event.component.operation}`\n : event.component.name;\n parts.push(`[${componentStr}]`);\n }\n\n // Error message\n if (event.error) {\n parts.push(`ERROR: ${event.error.message}`);\n }\n\n return parts.join(\" \");\n }\n\n /**\n * Create OpenTelemetry attributes from event data\n */\n private createAttributes(\n event: WideEventData,\n ): Record<string, string | number | boolean | undefined> {\n const attributes: Record<string, string | number | boolean | undefined> = {\n // Request metadata\n request_id: event.request_id,\n trace_id: event.trace_id,\n\n // HTTP attributes (OpenTelemetry semantic conventions)\n \"http.method\": event.method,\n \"http.route\": event.path,\n \"http.status_code\": event.status_code,\n \"http.request.duration_ms\": event.duration_ms,\n\n // Service attributes\n \"service.name\": event.service?.name,\n \"service.version\": event.service?.version,\n \"service.region\": event.service?.region,\n \"service.deployment_id\": event.service?.deployment_id,\n \"service.node_env\": event.service?.node_env,\n\n // Component attributes\n \"component.name\": event.component?.name,\n \"component.operation\": event.component?.operation,\n\n // User attributes\n \"user.id\": event.user?.id,\n\n // Error attributes\n \"error.type\": event.error?.type,\n \"error.code\": event.error?.code,\n \"error.message\": event.error?.message,\n \"error.retriable\": event.error?.retriable,\n\n // Execution metadata\n \"execution.timeout_ms\": event.execution?.timeout_ms,\n \"execution.retry_attempts\": event.execution?.retry_attempts,\n \"execution.cache_hit\": event.execution?.cache_hit,\n \"execution.cache_key\": event.execution?.cache_key,\n \"execution.cache_deduplication\": event.execution?.cache_deduplication,\n\n // Stream metadata\n \"stream.id\": event.stream?.stream_id,\n \"stream.events_sent\": event.stream?.events_sent,\n\n // Log count\n log_count: event.logs?.length,\n };\n\n // Add custom context as attributes with scope prefix (no \"appkit\" prefix)\n if (event.context) {\n for (const [scope, scopeData] of Object.entries(event.context)) {\n for (const [key, value] of Object.entries(scopeData)) {\n // Only add primitive values\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n attributes[`${scope}.${key}`] = value;\n }\n }\n }\n }\n\n // Remove undefined values\n return Object.fromEntries(\n Object.entries(attributes).filter(([_, value]) => value !== undefined),\n );\n }\n}\n"],"mappings":";;;;;;AAMA,IAAa,mBAAb,MAA8B;CAC5B,AAAQ,SAAS,KAAK,UAAU,UAAU,QAAQ;;;;;CAMlD,KAAK,OAA4B;AAC/B,MAAI;GACF,MAAM,YAAY;IAChB,WAAW,KAAK,MAAM,MAAM,UAAU;IACtC,gBAAgB,KAAK,kBAAkB,MAAM;IAC7C,cAAc,KAAK,gBAAgB,MAAM;IACzC,MAAM,KAAK,cAAc,MAAM;IAC/B,YAAY,KAAK,iBAAiB,MAAM;IACzC;AAED,QAAK,OAAO,KAAK,UAAU;UACrB;;;;;CAQV,AAAQ,kBAAkB,OAAsC;AAE9D,MAAI,MAAM,MACR,QAAO,eAAe;AAIxB,MAAI,MAAM,aAAa;AACrB,OAAI,MAAM,eAAe,IACvB,QAAO,eAAe;AAExB,OAAI,MAAM,eAAe,IACvB,QAAO,eAAe;;AAK1B,MAAI,MAAM,MAAM;AAEd,OADiB,MAAM,KAAK,MAAM,QAAQ,IAAI,UAAU,QAAQ,CAE9D,QAAO,eAAe;AAIxB,OADgB,MA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B,MAAM,OAAO;GAC9B,mBAAmB,MAAM,OAAO;GAGhC,wBAAwB,MAAM,WAAW;GACzC,4BAA4B,MAAM,WAAW;GAC7C,uBAAuB,MAAM,WAAW;GACxC,uBAAuB,MAAM,WAAW;GACxC,iCAAiC,MAAM,WAAW;GAGlD,aAAa,MAAM,QAAQ;GAC3B,sBAAsB,MAAM,QAAQ;GAGpC,WAAW,MAAM,MAAM;GACxB;AAGD,MAAI,MAAM,SACR;QAAK,MAAM,CAAC,OAAO,cAAc,OAAO,QAAQ,MAAM,QAAQ,CAC5D,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,CAElD,KACE,OAAO,UAAU,YACjB,OAAO,UAAU,YACjB,OAAO,UAAU,UAEjB,YAAW,GAAG,MAAM,GAAG,SAAS;;AAOxC,SAAO,OAAO,YACZ,OAAO,QAAQ,WAAW,CAAC,QAAQ,CAAC,GAAG,WAAW,UAAU,OAAU,CACvE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wide-event.js","names":[],"sources":["../../src/logging/wide-event.ts"],"sourcesContent":["import type { LogLevel } from \"./types\";\n\n/**\n * WideEvent data interface\n * - Represents a single event for a request\n * - Fields are camelCase to match OpenTelemetry\n */\nexport interface WideEventData {\n // request metadata\n timestamp: string;\n request_id: string;\n trace_id?: string;\n method?: string;\n path?: string;\n status_code?: number;\n duration_ms?: number;\n\n // service metadata\n service?: {\n name: string;\n version: string;\n region?: string;\n deployment_id?: string;\n node_env?: string;\n };\n\n // component metadata (plugin, connector, or service)\n component?: {\n name: string;\n operation?: string;\n };\n\n // user metadata\n user?: {\n id?: string;\n [key: string]: unknown;\n };\n\n // execution metadata\n execution?: {\n cache_hit?: boolean;\n cache_key?: string;\n cache_deduplication?: boolean;\n retry_attempts?: number;\n timeout_ms?: number;\n [key: string]: unknown;\n };\n\n // stream metadata\n stream?: {\n stream_id?: string;\n events_sent?: number;\n buffer_size?: number;\n reconnections?: number;\n [key: string]: unknown;\n };\n\n // error metadata\n error?: {\n type: string;\n code: string;\n message: string;\n retriable?: boolean;\n cause?: string;\n };\n\n // log metadata\n logs?: Array<{\n level: LogLevel;\n message: string;\n timestamp: string;\n context?: Record<string, unknown>;\n }>;\n\n /**\n * Scoped context data\n * Each scope (plugin, connector, service) can add its own namespaced data here.\n * Example: { analytics: { query_key: \"...\"}, \"sql-warehouse\": { warehouse_id: \"...\"} }\n */\n context?: Record<string, Record<string, unknown>>;\n\n [key: string]: unknown;\n}\n\n/**\n * WideEvent\n * - Represents a single event for a request\n * - Fields are camelCase to match OpenTelemetry\n */\nexport class WideEvent {\n public data: WideEventData;\n private startTime: number;\n\n constructor(requestId: string) {\n this.startTime = Date.now();\n this.data = {\n timestamp: new Date().toISOString(),\n request_id: requestId,\n service: {\n name: \"appkit\",\n version: process.env.npm_package_version || \"unknown\",\n region: process.env.REGION,\n deployment_id: process.env.DEPLOYMENT_ID,\n node_env: process.env.NODE_ENV,\n },\n logs: [],\n context: {},\n };\n }\n\n /**\n * Set a value in the event\n * @param key - The key to set\n * @param value - The value to set\n * @returns The event\n */\n set<K extends keyof WideEventData>(key: K, value: WideEventData[K]): this {\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n // merge objects\n this.data[key] = {\n ...(this.data[key] as object),\n ...value,\n } as WideEventData[K];\n } else {\n this.data[key] = value;\n }\n return this;\n }\n\n /**\n * Set the component name and operation.\n * Component can be a plugin, connector, or service.\n * @param name - The name of the component (e.g., \"analytics\", \"sql-warehouse\", \"cache-manager\")\n * @param operation - The operation being performed (e.g., \"query\", \"getOrExecute\")\n * @returns The event\n */\n setComponent(name: string, operation?: string): this {\n this.data.component = { name, operation };\n return this;\n }\n\n /**\n * Set the user context\n * @param user - The user context\n * @returns The event\n */\n setUser(user: WideEventData[\"user\"]): this {\n this.data.user = { ...this.data.user, ...user };\n return this;\n }\n\n /**\n * Set the execution context\n * @param execution - The execution context\n * @returns The event\n */\n setExecution(execution: WideEventData[\"execution\"]): this {\n this.data.execution = { ...this.data.execution, ...execution };\n return this;\n }\n\n /**\n * Set the stream context\n * @param stream - The stream context\n * @returns The event\n */\n setStream(stream: WideEventData[\"stream\"]): this {\n this.data.stream = { ...this.data.stream, ...stream };\n return this;\n }\n\n /**\n * Set the error context\n * @param error - The error context\n * @returns The event\n */\n setError(error: Error): this {\n const isAppKitError = \"code\" in error && \"statusCode\" in error;\n const errorCause = (error as any).cause;\n\n this.data.error = {\n type: error.name,\n code: isAppKitError ? (error as any).code : \"UNKNOWN_ERROR\",\n message: error.message,\n retriable: isAppKitError ? (error as any).isRetryable : false,\n cause: errorCause ? String(errorCause) : undefined,\n };\n\n return this;\n }\n\n /**\n * Add scoped context to the event\n * @param scope - The scope name (plugin, connector, or service name)\n * @param ctx - Context data to merge\n * @example\n * event.setContext(\"analytics\", { query_key: \"apps_list\", rows_returned: 100 });\n * event.setContext(\"sql-warehouse\", { warehouse_id: \"1234567890\" });\n */\n setContext(scope: string, ctx: Record<string, unknown>): this {\n if (!this.data.context) {\n this.data.context = {};\n }\n\n this.data.context[scope] = {\n ...this.data.context[scope],\n ...ctx,\n };\n\n return this;\n }\n\n /**\n * Add a log to the event\n * @param level - The level of the log\n * @param message - The message of the log\n * @param context - The context of the log\n * @returns The event\n */\n addLog(\n level: LogLevel,\n message: string,\n context?: Record<string, unknown>,\n ): this {\n if (!this.data.logs) {\n this.data.logs = [];\n }\n\n this.data.logs.push({\n level,\n message,\n timestamp: new Date().toISOString(),\n context,\n });\n\n // Keep only last 50 logs to prevent unbounded growth\n if (this.data.logs.length > 50) {\n this.data.logs = this.data.logs.slice(-50);\n }\n\n return this;\n }\n\n /**\n * Finalize the event\n * @param statusCode - The status code of the response\n * @returns The event data\n */\n finalize(statusCode: number): WideEventData {\n this.data.status_code = statusCode;\n this.data.duration_ms = this.getDurationMs();\n return this.data;\n }\n\n /**\n * Get the duration of the event in milliseconds\n * @returns The duration of the event in milliseconds\n */\n getDurationMs(): number {\n return this.data.duration_ms || Date.now() - this.startTime;\n }\n\n /**\n * Convert the event to a JSON object\n * @returns The event data as a JSON object\n */\n toJSON(): WideEventData {\n return this.data;\n }\n}\n"],"mappings":";;;;;;AAyFA,IAAa,YAAb,MAAuB;
|
|
1
|
+
{"version":3,"file":"wide-event.js","names":[],"sources":["../../src/logging/wide-event.ts"],"sourcesContent":["import type { LogLevel } from \"./types\";\n\n/**\n * WideEvent data interface\n * - Represents a single event for a request\n * - Fields are camelCase to match OpenTelemetry\n */\nexport interface WideEventData {\n // request metadata\n timestamp: string;\n request_id: string;\n trace_id?: string;\n method?: string;\n path?: string;\n status_code?: number;\n duration_ms?: number;\n\n // service metadata\n service?: {\n name: string;\n version: string;\n region?: string;\n deployment_id?: string;\n node_env?: string;\n };\n\n // component metadata (plugin, connector, or service)\n component?: {\n name: string;\n operation?: string;\n };\n\n // user metadata\n user?: {\n id?: string;\n [key: string]: unknown;\n };\n\n // execution metadata\n execution?: {\n cache_hit?: boolean;\n cache_key?: string;\n cache_deduplication?: boolean;\n retry_attempts?: number;\n timeout_ms?: number;\n [key: string]: unknown;\n };\n\n // stream metadata\n stream?: {\n stream_id?: string;\n events_sent?: number;\n buffer_size?: number;\n reconnections?: number;\n [key: string]: unknown;\n };\n\n // error metadata\n error?: {\n type: string;\n code: string;\n message: string;\n retriable?: boolean;\n cause?: string;\n };\n\n // log metadata\n logs?: Array<{\n level: LogLevel;\n message: string;\n timestamp: string;\n context?: Record<string, unknown>;\n }>;\n\n /**\n * Scoped context data\n * Each scope (plugin, connector, service) can add its own namespaced data here.\n * Example: { analytics: { query_key: \"...\"}, \"sql-warehouse\": { warehouse_id: \"...\"} }\n */\n context?: Record<string, Record<string, unknown>>;\n\n [key: string]: unknown;\n}\n\n/**\n * WideEvent\n * - Represents a single event for a request\n * - Fields are camelCase to match OpenTelemetry\n */\nexport class WideEvent {\n public data: WideEventData;\n private startTime: number;\n\n constructor(requestId: string) {\n this.startTime = Date.now();\n this.data = {\n timestamp: new Date().toISOString(),\n request_id: requestId,\n service: {\n name: \"appkit\",\n version: process.env.npm_package_version || \"unknown\",\n region: process.env.REGION,\n deployment_id: process.env.DEPLOYMENT_ID,\n node_env: process.env.NODE_ENV,\n },\n logs: [],\n context: {},\n };\n }\n\n /**\n * Set a value in the event\n * @param key - The key to set\n * @param value - The value to set\n * @returns The event\n */\n set<K extends keyof WideEventData>(key: K, value: WideEventData[K]): this {\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n // merge objects\n this.data[key] = {\n ...(this.data[key] as object),\n ...value,\n } as WideEventData[K];\n } else {\n this.data[key] = value;\n }\n return this;\n }\n\n /**\n * Set the component name and operation.\n * Component can be a plugin, connector, or service.\n * @param name - The name of the component (e.g., \"analytics\", \"sql-warehouse\", \"cache-manager\")\n * @param operation - The operation being performed (e.g., \"query\", \"getOrExecute\")\n * @returns The event\n */\n setComponent(name: string, operation?: string): this {\n this.data.component = { name, operation };\n return this;\n }\n\n /**\n * Set the user context\n * @param user - The user context\n * @returns The event\n */\n setUser(user: WideEventData[\"user\"]): this {\n this.data.user = { ...this.data.user, ...user };\n return this;\n }\n\n /**\n * Set the execution context\n * @param execution - The execution context\n * @returns The event\n */\n setExecution(execution: WideEventData[\"execution\"]): this {\n this.data.execution = { ...this.data.execution, ...execution };\n return this;\n }\n\n /**\n * Set the stream context\n * @param stream - The stream context\n * @returns The event\n */\n setStream(stream: WideEventData[\"stream\"]): this {\n this.data.stream = { ...this.data.stream, ...stream };\n return this;\n }\n\n /**\n * Set the error context\n * @param error - The error context\n * @returns The event\n */\n setError(error: Error): this {\n const isAppKitError = \"code\" in error && \"statusCode\" in error;\n const errorCause = (error as any).cause;\n\n this.data.error = {\n type: error.name,\n code: isAppKitError ? (error as any).code : \"UNKNOWN_ERROR\",\n message: error.message,\n retriable: isAppKitError ? (error as any).isRetryable : false,\n cause: errorCause ? String(errorCause) : undefined,\n };\n\n return this;\n }\n\n /**\n * Add scoped context to the event\n * @param scope - The scope name (plugin, connector, or service name)\n * @param ctx - Context data to merge\n * @example\n * event.setContext(\"analytics\", { query_key: \"apps_list\", rows_returned: 100 });\n * event.setContext(\"sql-warehouse\", { warehouse_id: \"1234567890\" });\n */\n setContext(scope: string, ctx: Record<string, unknown>): this {\n if (!this.data.context) {\n this.data.context = {};\n }\n\n this.data.context[scope] = {\n ...this.data.context[scope],\n ...ctx,\n };\n\n return this;\n }\n\n /**\n * Add a log to the event\n * @param level - The level of the log\n * @param message - The message of the log\n * @param context - The context of the log\n * @returns The event\n */\n addLog(\n level: LogLevel,\n message: string,\n context?: Record<string, unknown>,\n ): this {\n if (!this.data.logs) {\n this.data.logs = [];\n }\n\n this.data.logs.push({\n level,\n message,\n timestamp: new Date().toISOString(),\n context,\n });\n\n // Keep only last 50 logs to prevent unbounded growth\n if (this.data.logs.length > 50) {\n this.data.logs = this.data.logs.slice(-50);\n }\n\n return this;\n }\n\n /**\n * Finalize the event\n * @param statusCode - The status code of the response\n * @returns The event data\n */\n finalize(statusCode: number): WideEventData {\n this.data.status_code = statusCode;\n this.data.duration_ms = this.getDurationMs();\n return this.data;\n }\n\n /**\n * Get the duration of the event in milliseconds\n * @returns The duration of the event in milliseconds\n */\n getDurationMs(): number {\n return this.data.duration_ms || Date.now() - this.startTime;\n }\n\n /**\n * Convert the event to a JSON object\n * @returns The event data as a JSON object\n */\n toJSON(): WideEventData {\n return this.data;\n }\n}\n"],"mappings":";;;;;;AAyFA,IAAa,YAAb,MAAuB;CACrB,AAAO;CACP,AAAQ;CAER,YAAY,WAAmB;AAC7B,OAAK,YAAY,KAAK,KAAK;AAC3B,OAAK,OAAO;GACV,4BAAW,IAAI,MAAM,EAAC,aAAa;GACnC,YAAY;GACZ,SAAS;IACP,MAAM;IACN,SAAS,QAAQ,IAAI,uBAAuB;IAC5C,QAAQ,QAAQ,IAAI;IACpB,eAAe,QAAQ,IAAI;IAC3B,UAAU,QAAQ,IAAI;IACvB;GACD,MAAM,EAAE;GACR,SAAS,EAAE;GACZ;;;;;;;;CASH,IAAmC,KAAQ,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AAC;AAGF,MAAI,KAAK,KAAK,KAAK,SAAS,GAC1B,MAAK,KAAK,OAAO,KAAK,KAAK,KAAK,MAAM,IAAI;AAG5C,SAAO;;;;;;;CAQT,SAAS,YAAmC;AAC1C,OAAK,KAAK,cAAc;AACxB,OAAK,KAAK,cAAc,KAAK,eAAe;AAC5C,SAAO,KAAK;;;;;;CAOd,gBAAwB;AACtB,SAAO,KAAK,KAAK,eAAe,KAAK,KAAK,GAAG,KAAK;;;;;;CAOpD,SAAwB;AACtB,SAAO,KAAK"}
|
|
@@ -12,12 +12,9 @@ const logger = createLogger("plugin:dev-reader");
|
|
|
12
12
|
* through the WebSocket tunnel.
|
|
13
13
|
*/
|
|
14
14
|
var DevFileReader = class DevFileReader {
|
|
15
|
-
static
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
constructor() {
|
|
19
|
-
this.getTunnelForRequest = null;
|
|
20
|
-
}
|
|
15
|
+
static instance = null;
|
|
16
|
+
getTunnelForRequest = null;
|
|
17
|
+
constructor() {}
|
|
21
18
|
static getInstance() {
|
|
22
19
|
if (!DevFileReader.instance) DevFileReader.instance = new Proxy(new DevFileReader(), {
|
|
23
20
|
get(target, prop, receiver) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev-reader.js","names":[],"sources":["../../src/plugin/dev-reader.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { TunnelConnection } from \"shared\";\nimport { isRemoteTunnelAllowedByEnv } from \"@/server/remote-tunnel/gate\";\nimport { TunnelError } from \"../errors\";\nimport { createLogger } from \"../logging/logger\";\n\nconst logger = createLogger(\"plugin:dev-reader\");\n\ntype TunnelConnectionGetter = (\n req: import(\"express\").Request,\n) => TunnelConnection | null;\n\n/**\n * This class is used to read files from the local filesystem in dev mode\n * through the WebSocket tunnel.\n */\nexport class DevFileReader {\n private static instance: DevFileReader | null = null;\n private getTunnelForRequest: TunnelConnectionGetter | null = null;\n\n private constructor() {}\n\n static getInstance(): DevFileReader {\n if (!DevFileReader.instance) {\n DevFileReader.instance = new Proxy(new DevFileReader(), {\n /**\n * We proxy the reader to return a noop function if the remote server is disabled.\n */\n get(target, prop, receiver) {\n if (isRemoteTunnelAllowedByEnv()) {\n return Reflect.get(target, prop, receiver);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n return function noop() {\n logger.debug(\"Noop: %s (remote server disabled)\", String(prop));\n return Promise.resolve(\"\");\n };\n }\n\n return value;\n },\n set(target, prop, value, receiver) {\n return Reflect.set(target, prop, value, receiver);\n },\n });\n }\n\n return DevFileReader.instance;\n }\n\n registerTunnelGetter(getter: TunnelConnectionGetter) {\n this.getTunnelForRequest = getter;\n }\n\n async readFile(\n filePath: string,\n req: import(\"express\").Request,\n ): Promise<string> {\n if (!this.getTunnelForRequest) {\n throw TunnelError.getterNotRegistered();\n }\n const tunnel = this.getTunnelForRequest(req);\n\n if (!tunnel) {\n throw TunnelError.noConnection();\n }\n\n const { ws, pendingFileReads } = tunnel;\n const requestId = randomUUID();\n\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n pendingFileReads.delete(requestId);\n reject(new Error(`File read timeout: ${filePath}`));\n }, 10000);\n\n pendingFileReads.set(requestId, { resolve, reject, timeout });\n\n ws.send(\n JSON.stringify({\n type: \"file:read\",\n requestId,\n path: filePath,\n }),\n );\n });\n }\n}\n"],"mappings":";;;;;;;aAGwC;AAGxC,MAAM,SAAS,aAAa,oBAAoB;;;;;AAUhD,IAAa,gBAAb,MAAa,cAAc
|
|
1
|
+
{"version":3,"file":"dev-reader.js","names":[],"sources":["../../src/plugin/dev-reader.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport type { TunnelConnection } from \"shared\";\nimport { isRemoteTunnelAllowedByEnv } from \"@/server/remote-tunnel/gate\";\nimport { TunnelError } from \"../errors\";\nimport { createLogger } from \"../logging/logger\";\n\nconst logger = createLogger(\"plugin:dev-reader\");\n\ntype TunnelConnectionGetter = (\n req: import(\"express\").Request,\n) => TunnelConnection | null;\n\n/**\n * This class is used to read files from the local filesystem in dev mode\n * through the WebSocket tunnel.\n */\nexport class DevFileReader {\n private static instance: DevFileReader | null = null;\n private getTunnelForRequest: TunnelConnectionGetter | null = null;\n\n private constructor() {}\n\n static getInstance(): DevFileReader {\n if (!DevFileReader.instance) {\n DevFileReader.instance = new Proxy(new DevFileReader(), {\n /**\n * We proxy the reader to return a noop function if the remote server is disabled.\n */\n get(target, prop, receiver) {\n if (isRemoteTunnelAllowedByEnv()) {\n return Reflect.get(target, prop, receiver);\n }\n\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value === \"function\") {\n return function noop() {\n logger.debug(\"Noop: %s (remote server disabled)\", String(prop));\n return Promise.resolve(\"\");\n };\n }\n\n return value;\n },\n set(target, prop, value, receiver) {\n return Reflect.set(target, prop, value, receiver);\n },\n });\n }\n\n return DevFileReader.instance;\n }\n\n registerTunnelGetter(getter: TunnelConnectionGetter) {\n this.getTunnelForRequest = getter;\n }\n\n async readFile(\n filePath: string,\n req: import(\"express\").Request,\n ): Promise<string> {\n if (!this.getTunnelForRequest) {\n throw TunnelError.getterNotRegistered();\n }\n const tunnel = this.getTunnelForRequest(req);\n\n if (!tunnel) {\n throw TunnelError.noConnection();\n }\n\n const { ws, pendingFileReads } = tunnel;\n const requestId = randomUUID();\n\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n pendingFileReads.delete(requestId);\n reject(new Error(`File read timeout: ${filePath}`));\n }, 10000);\n\n pendingFileReads.set(requestId, { resolve, reject, timeout });\n\n ws.send(\n JSON.stringify({\n type: \"file:read\",\n requestId,\n path: filePath,\n }),\n );\n });\n }\n}\n"],"mappings":";;;;;;;aAGwC;AAGxC,MAAM,SAAS,aAAa,oBAAoB;;;;;AAUhD,IAAa,gBAAb,MAAa,cAAc;CACzB,OAAe,WAAiC;CAChD,AAAQ,sBAAqD;CAE7D,AAAQ,cAAc;CAEtB,OAAO,cAA6B;AAClC,MAAI,CAAC,cAAc,SACjB,eAAc,WAAW,IAAI,MAAM,IAAI,eAAe,EAAE;GAItD,IAAI,QAAQ,MAAM,UAAU;AAC1B,QAAI,4BAA4B,CAC9B,QAAO,QAAQ,IAAI,QAAQ,MAAM,SAAS;IAG5C,MAAM,QAAQ,QAAQ,IAAI,QAAQ,MAAM,SAAS;AAEjD,QAAI,OAAO,UAAU,WACnB,QAAO,SAAS,OAAO;AACrB,YAAO,MAAM,qCAAqC,OAAO,KAAK,CAAC;AAC/D,YAAO,QAAQ,QAAQ,GAAG;;AAI9B,WAAO;;GAET,IAAI,QAAQ,MAAM,OAAO,UAAU;AACjC,WAAO,QAAQ,IAAI,QAAQ,MAAM,OAAO,SAAS;;GAEpD,CAAC;AAGJ,SAAO,cAAc;;CAGvB,qBAAqB,QAAgC;AACnD,OAAK,sBAAsB;;CAG7B,MAAM,SACJ,UACA,KACiB;AACjB,MAAI,CAAC,KAAK,oBACR,OAAM,YAAY,qBAAqB;EAEzC,MAAM,SAAS,KAAK,oBAAoB,IAAI;AAE5C,MAAI,CAAC,OACH,OAAM,YAAY,cAAc;EAGlC,MAAM,EAAE,IAAI,qBAAqB;EACjC,MAAM,YAAY,YAAY;AAE9B,SAAO,IAAI,SAAS,SAAS,WAAW;GACtC,MAAM,UAAU,iBAAiB;AAC/B,qBAAiB,OAAO,UAAU;AAClC,2BAAO,IAAI,MAAM,sBAAsB,WAAW,CAAC;MAClD,IAAM;AAET,oBAAiB,IAAI,WAAW;IAAE;IAAS;IAAQ;IAAS,CAAC;AAE7D,MAAG,KACD,KAAK,UAAU;IACb,MAAM;IACN;IACA,MAAM;IACP,CAAC,CACH;IACD"}
|
|
@@ -3,6 +3,9 @@ import { createLogger } from "../../logging/logger.js";
|
|
|
3
3
|
//#region src/plugin/interceptors/retry.ts
|
|
4
4
|
const logger = createLogger("interceptors:retry");
|
|
5
5
|
var RetryInterceptor = class {
|
|
6
|
+
attempts;
|
|
7
|
+
initialDelay;
|
|
8
|
+
maxDelay;
|
|
6
9
|
constructor(config) {
|
|
7
10
|
this.attempts = config.attempts ?? 3;
|
|
8
11
|
this.initialDelay = config.initialDelay ?? 1e3;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"retry.js","names":[],"sources":["../../../src/plugin/interceptors/retry.ts"],"sourcesContent":["import type { RetryConfig } from \"shared\";\nimport { createLogger } from \"../../logging/logger\";\nimport type { ExecutionInterceptor, InterceptorContext } from \"./types\";\n\nconst logger = createLogger(\"interceptors:retry\");\n\n// interceptor to handle retry logic\nexport class RetryInterceptor implements ExecutionInterceptor {\n private attempts: number;\n private initialDelay: number;\n private maxDelay: number;\n\n constructor(config: RetryConfig) {\n this.attempts = config.attempts ?? 3;\n this.initialDelay = config.initialDelay ?? 1000;\n this.maxDelay = config.maxDelay ?? 30000;\n }\n\n async intercept<T>(\n fn: () => Promise<T>,\n context: InterceptorContext,\n ): Promise<T> {\n let lastError: Error | unknown;\n\n for (let attempt = 1; attempt <= this.attempts; attempt++) {\n try {\n const result = await fn();\n\n if (attempt > 1) {\n logger.event()?.setExecution({\n retry_attempts: attempt - 1,\n });\n }\n\n return result;\n } catch (error) {\n lastError = error;\n\n // last attempt, rethrow the error\n if (attempt === this.attempts) {\n logger.event()?.setExecution({\n retry_attempts: attempt - 1,\n });\n throw error;\n }\n\n // don't retry if was already aborted\n if (context.signal?.aborted) {\n throw error;\n }\n\n const delay = this.calculateDelay(attempt);\n await this.sleep(delay);\n }\n }\n\n // type guard\n throw lastError;\n }\n\n private calculateDelay(attempt: number): number {\n // exponential backoff\n const delay = this.initialDelay * 2 ** (attempt - 1);\n\n // max delay cap\n return Math.min(delay, this.maxDelay);\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n"],"mappings":";;;AAIA,MAAM,SAAS,aAAa,qBAAqB;AAGjD,IAAa,mBAAb,MAA8D;
|
|
1
|
+
{"version":3,"file":"retry.js","names":[],"sources":["../../../src/plugin/interceptors/retry.ts"],"sourcesContent":["import type { RetryConfig } from \"shared\";\nimport { createLogger } from \"../../logging/logger\";\nimport type { ExecutionInterceptor, InterceptorContext } from \"./types\";\n\nconst logger = createLogger(\"interceptors:retry\");\n\n// interceptor to handle retry logic\nexport class RetryInterceptor implements ExecutionInterceptor {\n private attempts: number;\n private initialDelay: number;\n private maxDelay: number;\n\n constructor(config: RetryConfig) {\n this.attempts = config.attempts ?? 3;\n this.initialDelay = config.initialDelay ?? 1000;\n this.maxDelay = config.maxDelay ?? 30000;\n }\n\n async intercept<T>(\n fn: () => Promise<T>,\n context: InterceptorContext,\n ): Promise<T> {\n let lastError: Error | unknown;\n\n for (let attempt = 1; attempt <= this.attempts; attempt++) {\n try {\n const result = await fn();\n\n if (attempt > 1) {\n logger.event()?.setExecution({\n retry_attempts: attempt - 1,\n });\n }\n\n return result;\n } catch (error) {\n lastError = error;\n\n // last attempt, rethrow the error\n if (attempt === this.attempts) {\n logger.event()?.setExecution({\n retry_attempts: attempt - 1,\n });\n throw error;\n }\n\n // don't retry if was already aborted\n if (context.signal?.aborted) {\n throw error;\n }\n\n const delay = this.calculateDelay(attempt);\n await this.sleep(delay);\n }\n }\n\n // type guard\n throw lastError;\n }\n\n private calculateDelay(attempt: number): number {\n // exponential backoff\n const delay = this.initialDelay * 2 ** (attempt - 1);\n\n // max delay cap\n return Math.min(delay, this.maxDelay);\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n"],"mappings":";;;AAIA,MAAM,SAAS,aAAa,qBAAqB;AAGjD,IAAa,mBAAb,MAA8D;CAC5D,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YAAY,QAAqB;AAC/B,OAAK,WAAW,OAAO,YAAY;AACnC,OAAK,eAAe,OAAO,gBAAgB;AAC3C,OAAK,WAAW,OAAO,YAAY;;CAGrC,MAAM,UACJ,IACA,SACY;EACZ,IAAI;AAEJ,OAAK,IAAI,UAAU,GAAG,WAAW,KAAK,UAAU,UAC9C,KAAI;GACF,MAAM,SAAS,MAAM,IAAI;AAEzB,OAAI,UAAU,EACZ,QAAO,OAAO,EAAE,aAAa,EAC3B,gBAAgB,UAAU,GAC3B,CAAC;AAGJ,UAAO;WACA,OAAO;AACd,eAAY;AAGZ,OAAI,YAAY,KAAK,UAAU;AAC7B,WAAO,OAAO,EAAE,aAAa,EAC3B,gBAAgB,UAAU,GAC3B,CAAC;AACF,UAAM;;AAIR,OAAI,QAAQ,QAAQ,QAClB,OAAM;GAGR,MAAM,QAAQ,KAAK,eAAe,QAAQ;AAC1C,SAAM,KAAK,MAAM,MAAM;;AAK3B,QAAM;;CAGR,AAAQ,eAAe,SAAyB;EAE9C,MAAM,QAAQ,KAAK,eAAe,MAAM,UAAU;AAGlD,SAAO,KAAK,IAAI,OAAO,KAAK,SAAS;;CAGvC,AAAQ,MAAM,IAA2B;AACvC,SAAO,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC"}
|
package/dist/plugin/plugin.d.ts
CHANGED
|
@@ -28,34 +28,20 @@ declare abstract class Plugin<TConfig extends BasePluginConfig = BasePluginConfi
|
|
|
28
28
|
setup(): Promise<void>;
|
|
29
29
|
getEndpoints(): PluginEndpointMap;
|
|
30
30
|
abortActiveOperations(): void;
|
|
31
|
+
/**
|
|
32
|
+
* Returns the public exports for this plugin.
|
|
33
|
+
* Override this to define a custom public API.
|
|
34
|
+
* By default, returns an empty object.
|
|
35
|
+
*/
|
|
36
|
+
exports(): unknown;
|
|
31
37
|
/**
|
|
32
38
|
* Execute operations using the user's identity from the request.
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
* will execute with the user's Databricks credentials instead of
|
|
36
|
-
* the service principal.
|
|
39
|
+
* Returns a proxy of this plugin where all method calls execute
|
|
40
|
+
* with the user's Databricks credentials instead of the service principal.
|
|
37
41
|
*
|
|
38
42
|
* @param req - The Express request containing the user token in headers
|
|
39
|
-
* @returns A
|
|
43
|
+
* @returns A proxied plugin instance that executes as the user
|
|
40
44
|
* @throws Error if user token is not available in request headers
|
|
41
|
-
*
|
|
42
|
-
* @example
|
|
43
|
-
* ```typescript
|
|
44
|
-
* // In route handler - execute query as the requesting user
|
|
45
|
-
* router.post('/users/me/query/:key', async (req, res) => {
|
|
46
|
-
* const result = await this.asUser(req).query(req.params.key)
|
|
47
|
-
* res.json(result)
|
|
48
|
-
* })
|
|
49
|
-
*
|
|
50
|
-
* // Mixed execution in same handler
|
|
51
|
-
* router.post('/dashboard', async (req, res) => {
|
|
52
|
-
* const [systemData, userData] = await Promise.all([
|
|
53
|
-
* this.getSystemStats(), // Service principal
|
|
54
|
-
* this.asUser(req).getUserPreferences(), // User context
|
|
55
|
-
* ])
|
|
56
|
-
* res.json({ systemData, userData })
|
|
57
|
-
* })
|
|
58
|
-
* ```
|
|
59
45
|
*/
|
|
60
46
|
asUser(req: express.Request): this;
|
|
61
47
|
/**
|
|
@@ -63,7 +49,7 @@ declare abstract class Plugin<TConfig extends BasePluginConfig = BasePluginConfi
|
|
|
63
49
|
* This allows all plugin methods to automatically use the user's
|
|
64
50
|
* Databricks credentials.
|
|
65
51
|
*/
|
|
66
|
-
private
|
|
52
|
+
private _createUserContextProxy;
|
|
67
53
|
protected executeStream<T>(res: IAppResponse, fn: StreamExecuteHandler<T>, options: StreamExecutionSettings, userKey?: string): Promise<void>;
|
|
68
54
|
protected execute<T>(fn: (signal?: AbortSignal) => Promise<T>, options: PluginExecutionSettings, userKey?: string): Promise<T | undefined>;
|
|
69
55
|
protected registerEndpoint(name: string, path: string): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.d.ts","names":[],"sources":["../../src/plugin/plugin.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;uBA8DsB,uBACJ,mBAAmB,6BACxB;oBAgBmB;EAlBV,UAAM,OAAA,EAAA,OAAA;EAAA,UAAA,KAAA,EAKT,YALS;YACV,GAAA,EAKD,UALC;YAAmB,aAAA,EAMV,aANU;YAiBL,aAAA,EAVL,aAUK;YAbb,SAAA,EAII,UAJJ;qBACF,OAAA,EAAA,MAAA,EAAA;;UAEU,mBAAA;SACJ,KAAA,EAMP,WANO;MAMP,EAAA,MAAA;aAGgB,CAAA,MAAA,EAAA,OAAA;aAeN,CAAA,CAAA,EAAA,IAAA;cAIb,CAAA,CAAA,EAJK,OAAA,CAAQ,MAIb,CAAA,EAAA,IAAA;OAEK,CAAA,CAAA,EAFL,OAEK,CAAA,IAAA,CAAA;
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","names":[],"sources":["../../src/plugin/plugin.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;uBA8DsB,uBACJ,mBAAmB,6BACxB;oBAgBmB;EAlBV,UAAM,OAAA,EAAA,OAAA;EAAA,UAAA,KAAA,EAKT,YALS;YACV,GAAA,EAKD,UALC;YAAmB,aAAA,EAMV,aANU;YAiBL,aAAA,EAVL,aAUK;YAbb,SAAA,EAII,UAJJ;qBACF,OAAA,EAAA,MAAA,EAAA;;UAEU,mBAAA;SACJ,KAAA,EAMP,WANO;MAMP,EAAA,MAAA;aAGgB,CAAA,MAAA,EAAA,OAAA;aAeN,CAAA,CAAA,EAAA,IAAA;cAIb,CAAA,CAAA,EAJK,OAAA,CAAQ,MAIb,CAAA,EAAA,IAAA;OAEK,CAAA,CAAA,EAFL,OAEK,CAAA,IAAA,CAAA;cA0BI,CAAA,CAAA,EA1BJ,iBA0BI;uBA6Db,CAAA,CAAA,EAAA,IAAA;;;;;;SA8DiC,CAAA,CAAA,EAAA,OAAA;;;;;;;;;;cA3H5B,OAAA,CAAQ;;;;;;;kCA6Db,kBACD,qBAAqB,aAChB,4CACO;qCA2DF,gBAAgB,QAAQ,aAC7B,4CAER,QAAQ;;sCA0BD,OAAA,CAAQ,gBACR"}
|
package/dist/plugin/plugin.js
CHANGED
|
@@ -40,13 +40,18 @@ const EXCLUDED_FROM_PROXY = new Set([
|
|
|
40
40
|
]);
|
|
41
41
|
/** Base abstract class for creating AppKit plugins */
|
|
42
42
|
var Plugin = class {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
isReady = false;
|
|
44
|
+
cache;
|
|
45
|
+
app;
|
|
46
|
+
devFileReader;
|
|
47
|
+
streamManager;
|
|
48
|
+
telemetry;
|
|
49
|
+
/** Registered endpoints for this plugin */
|
|
50
|
+
registeredEndpoints = {};
|
|
51
|
+
static phase = "normal";
|
|
52
|
+
name;
|
|
46
53
|
constructor(config) {
|
|
47
54
|
this.config = config;
|
|
48
|
-
this.isReady = false;
|
|
49
|
-
this.registeredEndpoints = {};
|
|
50
55
|
this.name = config.name ?? "plugin";
|
|
51
56
|
this.telemetry = TelemetryManager.getProvider(this.name, config.telemetry);
|
|
52
57
|
this.streamManager = new StreamManager();
|
|
@@ -67,33 +72,21 @@ var Plugin = class {
|
|
|
67
72
|
this.streamManager.abortAll();
|
|
68
73
|
}
|
|
69
74
|
/**
|
|
75
|
+
* Returns the public exports for this plugin.
|
|
76
|
+
* Override this to define a custom public API.
|
|
77
|
+
* By default, returns an empty object.
|
|
78
|
+
*/
|
|
79
|
+
exports() {
|
|
80
|
+
return {};
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
70
83
|
* Execute operations using the user's identity from the request.
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
* will execute with the user's Databricks credentials instead of
|
|
74
|
-
* the service principal.
|
|
84
|
+
* Returns a proxy of this plugin where all method calls execute
|
|
85
|
+
* with the user's Databricks credentials instead of the service principal.
|
|
75
86
|
*
|
|
76
87
|
* @param req - The Express request containing the user token in headers
|
|
77
|
-
* @returns A
|
|
88
|
+
* @returns A proxied plugin instance that executes as the user
|
|
78
89
|
* @throws Error if user token is not available in request headers
|
|
79
|
-
*
|
|
80
|
-
* @example
|
|
81
|
-
* ```typescript
|
|
82
|
-
* // In route handler - execute query as the requesting user
|
|
83
|
-
* router.post('/users/me/query/:key', async (req, res) => {
|
|
84
|
-
* const result = await this.asUser(req).query(req.params.key)
|
|
85
|
-
* res.json(result)
|
|
86
|
-
* })
|
|
87
|
-
*
|
|
88
|
-
* // Mixed execution in same handler
|
|
89
|
-
* router.post('/dashboard', async (req, res) => {
|
|
90
|
-
* const [systemData, userData] = await Promise.all([
|
|
91
|
-
* this.getSystemStats(), // Service principal
|
|
92
|
-
* this.asUser(req).getUserPreferences(), // User context
|
|
93
|
-
* ])
|
|
94
|
-
* res.json({ systemData, userData })
|
|
95
|
-
* })
|
|
96
|
-
* ```
|
|
97
90
|
*/
|
|
98
91
|
asUser(req) {
|
|
99
92
|
const token = req.headers["x-forwarded-access-token"];
|
|
@@ -107,14 +100,14 @@ var Plugin = class {
|
|
|
107
100
|
if (!userId && !isDev) throw AuthenticationError.missingUserId();
|
|
108
101
|
const effectiveUserId = userId || "dev-user";
|
|
109
102
|
const userContext = ServiceContext.createUserContext(token, effectiveUserId);
|
|
110
|
-
return this.
|
|
103
|
+
return this._createUserContextProxy(userContext);
|
|
111
104
|
}
|
|
112
105
|
/**
|
|
113
106
|
* Creates a proxy that wraps method calls in a user context.
|
|
114
107
|
* This allows all plugin methods to automatically use the user's
|
|
115
108
|
* Databricks credentials.
|
|
116
109
|
*/
|
|
117
|
-
|
|
110
|
+
_createUserContextProxy(userContext) {
|
|
118
111
|
return new Proxy(this, { get: (target, prop, receiver) => {
|
|
119
112
|
const value = Reflect.get(target, prop, receiver);
|
|
120
113
|
if (typeof value !== "function") return value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","names":[],"sources":["../../src/plugin/plugin.ts"],"sourcesContent":["import type express from \"express\";\nimport type {\n BasePlugin,\n BasePluginConfig,\n IAppResponse,\n PluginEndpointMap,\n PluginExecuteConfig,\n PluginExecutionSettings,\n PluginPhase,\n RouteConfig,\n StreamExecuteHandler,\n StreamExecutionSettings,\n} from \"shared\";\nimport { AppManager } from \"../app\";\nimport { CacheManager } from \"../cache\";\nimport {\n getCurrentUserId,\n runInUserContext,\n ServiceContext,\n type UserContext,\n} from \"../context\";\nimport { AuthenticationError } from \"../errors\";\nimport { createLogger } from \"../logging/logger\";\nimport { StreamManager } from \"../stream\";\nimport {\n type ITelemetry,\n normalizeTelemetryOptions,\n TelemetryManager,\n} from \"../telemetry\";\nimport { deepMerge, validateEnv } from \"../utils\";\nimport { DevFileReader } from \"./dev-reader\";\nimport { CacheInterceptor } from \"./interceptors/cache\";\nimport { RetryInterceptor } from \"./interceptors/retry\";\nimport { TelemetryInterceptor } from \"./interceptors/telemetry\";\nimport { TimeoutInterceptor } from \"./interceptors/timeout\";\nimport type {\n ExecutionInterceptor,\n InterceptorContext,\n} from \"./interceptors/types\";\n\nconst logger = createLogger(\"plugin\");\n\n/**\n * Methods that should not be proxied by asUser().\n * These are lifecycle/internal methods that don't make sense\n * to execute in a user context.\n */\nconst EXCLUDED_FROM_PROXY = new Set([\n // Lifecycle methods\n \"setup\",\n \"shutdown\",\n \"validateEnv\",\n \"injectRoutes\",\n \"getEndpoints\",\n \"abortActiveOperations\",\n // asUser itself - prevent chaining like .asUser().asUser()\n \"asUser\",\n // Internal methods\n \"constructor\",\n]);\n\n/** Base abstract class for creating AppKit plugins */\nexport abstract class Plugin<\n TConfig extends BasePluginConfig = BasePluginConfig,\n> implements BasePlugin\n{\n protected isReady = false;\n protected cache: CacheManager;\n protected app: AppManager;\n protected devFileReader: DevFileReader;\n protected streamManager: StreamManager;\n protected telemetry: ITelemetry;\n protected abstract envVars: string[];\n\n /** Registered endpoints for this plugin */\n private registeredEndpoints: PluginEndpointMap = {};\n\n static phase: PluginPhase = \"normal\";\n name: string;\n\n constructor(protected config: TConfig) {\n this.name = config.name ?? \"plugin\";\n this.telemetry = TelemetryManager.getProvider(this.name, config.telemetry);\n this.streamManager = new StreamManager();\n this.cache = CacheManager.getInstanceSync();\n this.app = new AppManager();\n this.devFileReader = DevFileReader.getInstance();\n\n this.isReady = true;\n }\n\n validateEnv() {\n validateEnv(this.envVars);\n }\n\n injectRoutes(_: express.Router) {\n return;\n }\n\n async setup() {}\n\n getEndpoints(): PluginEndpointMap {\n return this.registeredEndpoints;\n }\n\n abortActiveOperations(): void {\n this.streamManager.abortAll();\n }\n\n /**\n * Execute operations using the user's identity from the request.\n *\n * Returns a scoped instance of this plugin where all method calls\n * will execute with the user's Databricks credentials instead of\n * the service principal.\n *\n * @param req - The Express request containing the user token in headers\n * @returns A scoped plugin instance that executes as the user\n * @throws Error if user token is not available in request headers\n *\n * @example\n * ```typescript\n * // In route handler - execute query as the requesting user\n * router.post('/users/me/query/:key', async (req, res) => {\n * const result = await this.asUser(req).query(req.params.key)\n * res.json(result)\n * })\n *\n * // Mixed execution in same handler\n * router.post('/dashboard', async (req, res) => {\n * const [systemData, userData] = await Promise.all([\n * this.getSystemStats(), // Service principal\n * this.asUser(req).getUserPreferences(), // User context\n * ])\n * res.json({ systemData, userData })\n * })\n * ```\n */\n asUser(req: express.Request): this {\n const token = req.headers[\"x-forwarded-access-token\"] as string;\n const userId = req.headers[\"x-forwarded-user\"] as string;\n const isDev = process.env.NODE_ENV === \"development\";\n\n // In local development, fall back to service principal\n // since there's no user token available\n if (!token && isDev) {\n logger.warn(\n \"asUser() called without user token in development mode. Using service principal.\",\n );\n\n return this;\n }\n\n if (!token) {\n throw AuthenticationError.missingToken(\"user token\");\n }\n\n if (!userId && !isDev) {\n throw AuthenticationError.missingUserId();\n }\n\n const effectiveUserId = userId || \"dev-user\";\n\n const userContext = ServiceContext.createUserContext(\n token,\n effectiveUserId,\n );\n\n // Return a proxy that wraps method calls in user context\n return this.createUserContextProxy(userContext);\n }\n\n /**\n * Creates a proxy that wraps method calls in a user context.\n * This allows all plugin methods to automatically use the user's\n * Databricks credentials.\n */\n private createUserContextProxy(userContext: UserContext): this {\n return new Proxy(this, {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== \"function\") {\n return value;\n }\n\n if (typeof prop === \"string\" && EXCLUDED_FROM_PROXY.has(prop)) {\n return value;\n }\n\n return (...args: unknown[]) => {\n return runInUserContext(userContext, () => value.apply(target, args));\n };\n },\n }) as this;\n }\n\n // streaming execution with interceptors\n protected async executeStream<T>(\n res: IAppResponse,\n fn: StreamExecuteHandler<T>,\n options: StreamExecutionSettings,\n userKey?: string,\n ) {\n // destructure options\n const {\n stream: streamConfig,\n default: defaultConfig,\n user: userConfig,\n } = options;\n\n // build execution options\n const executeConfig = this._buildExecutionConfig({\n default: defaultConfig,\n user: userConfig,\n });\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentUserId();\n\n const self = this;\n\n // wrapper function to ensure it returns a generator\n const asyncWrapperFn = async function* (streamSignal?: AbortSignal) {\n // build execution context\n const context: InterceptorContext = {\n signal: streamSignal,\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n // build interceptors\n const interceptors = self._buildInterceptors(executeConfig);\n\n // wrap the function to ensure it returns a promise\n const wrappedFn = async () => {\n const result = await fn(context.signal);\n return result;\n };\n\n // execute the function with interceptors\n const result = await self._executeWithInterceptors(\n wrappedFn as (signal?: AbortSignal) => Promise<T>,\n interceptors,\n context,\n );\n\n // check if result is a generator\n if (self._checkIfGenerator(result)) {\n yield* result;\n } else {\n yield result;\n }\n };\n\n // stream the result to the client\n await this.streamManager.stream(res, asyncWrapperFn, streamConfig);\n }\n\n // single sync execution with interceptors\n protected async execute<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n options: PluginExecutionSettings,\n userKey?: string,\n ): Promise<T | undefined> {\n const executeConfig = this._buildExecutionConfig(options);\n\n const interceptors = this._buildInterceptors(executeConfig);\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentUserId();\n\n const context: InterceptorContext = {\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n try {\n return await this._executeWithInterceptors(fn, interceptors, context);\n } catch (_error) {\n // production-safe, don't crash sdk\n return undefined;\n }\n }\n\n protected registerEndpoint(name: string, path: string): void {\n this.registeredEndpoints[name] = path;\n }\n\n protected route<_TResponse>(\n router: express.Router,\n config: RouteConfig,\n ): void {\n const { name, method, path, handler } = config;\n\n router[method](path, handler);\n\n this.registerEndpoint(name, `/api/${this.name}${path}`);\n }\n\n // build execution options by merging defaults, plugin config, and user overrides\n private _buildExecutionConfig(\n options: PluginExecutionSettings,\n ): PluginExecuteConfig {\n const { default: methodDefaults, user: userOverride } = options;\n\n // Merge: method defaults <- plugin config <- user override (highest priority)\n return deepMerge(\n deepMerge(methodDefaults, this.config),\n userOverride ?? {},\n ) as PluginExecuteConfig;\n }\n\n // build interceptors based on execute options\n private _buildInterceptors(\n options: PluginExecuteConfig,\n ): ExecutionInterceptor[] {\n const interceptors: ExecutionInterceptor[] = [];\n\n // order matters: telemetry → timeout → retry → cache (innermost to outermost)\n\n const telemetryConfig = normalizeTelemetryOptions(this.config.telemetry);\n if (\n telemetryConfig.traces &&\n (options.telemetryInterceptor?.enabled ?? true)\n ) {\n interceptors.push(\n new TelemetryInterceptor(this.telemetry, options.telemetryInterceptor),\n );\n }\n\n if (options.timeout && options.timeout > 0) {\n interceptors.push(new TimeoutInterceptor(options.timeout));\n }\n\n if (\n options.retry?.enabled &&\n options.retry.attempts &&\n options.retry.attempts > 1\n ) {\n interceptors.push(new RetryInterceptor(options.retry));\n }\n\n if (options.cache?.enabled && options.cache.cacheKey?.length) {\n interceptors.push(new CacheInterceptor(this.cache, options.cache));\n }\n\n return interceptors;\n }\n\n // execute method wrapped with interceptors\n private async _executeWithInterceptors<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n interceptors: ExecutionInterceptor[],\n context: InterceptorContext,\n ): Promise<T> {\n // no interceptors, execute directly\n if (interceptors.length === 0) {\n return fn(context.signal);\n }\n // build nested execution chain from interceptors\n let wrappedFn = () => fn(context.signal);\n\n // wrap each interceptor around the previous function\n for (const interceptor of interceptors) {\n const previousFn = wrappedFn;\n wrappedFn = () => interceptor.intercept(previousFn, context);\n }\n\n return wrappedFn();\n }\n\n private _checkIfGenerator(\n result: any,\n ): result is AsyncGenerator<any, void, unknown> {\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express from \"express\";\nimport type {\n BasePlugin,\n BasePluginConfig,\n IAppResponse,\n PluginEndpointMap,\n PluginExecuteConfig,\n PluginExecutionSettings,\n PluginPhase,\n RouteConfig,\n StreamExecuteHandler,\n StreamExecutionSettings,\n} from \"shared\";\nimport { AppManager } from \"../app\";\nimport { CacheManager } from \"../cache\";\nimport {\n getCurrentUserId,\n runInUserContext,\n ServiceContext,\n type UserContext,\n} from \"../context\";\nimport { AuthenticationError } from \"../errors\";\nimport { createLogger } from \"../logging/logger\";\nimport { StreamManager } from \"../stream\";\nimport {\n type ITelemetry,\n normalizeTelemetryOptions,\n TelemetryManager,\n} from \"../telemetry\";\nimport { deepMerge, validateEnv } from \"../utils\";\nimport { DevFileReader } from \"./dev-reader\";\nimport { CacheInterceptor } from \"./interceptors/cache\";\nimport { RetryInterceptor } from \"./interceptors/retry\";\nimport { TelemetryInterceptor } from \"./interceptors/telemetry\";\nimport { TimeoutInterceptor } from \"./interceptors/timeout\";\nimport type {\n ExecutionInterceptor,\n InterceptorContext,\n} from \"./interceptors/types\";\n\nconst logger = createLogger(\"plugin\");\n\n/**\n * Methods that should not be proxied by asUser().\n * These are lifecycle/internal methods that don't make sense\n * to execute in a user context.\n */\nconst EXCLUDED_FROM_PROXY = new Set([\n // Lifecycle methods\n \"setup\",\n \"shutdown\",\n \"validateEnv\",\n \"injectRoutes\",\n \"getEndpoints\",\n \"abortActiveOperations\",\n // asUser itself - prevent chaining like .asUser().asUser()\n \"asUser\",\n // Internal methods\n \"constructor\",\n]);\n\n/** Base abstract class for creating AppKit plugins */\nexport abstract class Plugin<\n TConfig extends BasePluginConfig = BasePluginConfig,\n> implements BasePlugin\n{\n protected isReady = false;\n protected cache: CacheManager;\n protected app: AppManager;\n protected devFileReader: DevFileReader;\n protected streamManager: StreamManager;\n protected telemetry: ITelemetry;\n protected abstract envVars: string[];\n\n /** Registered endpoints for this plugin */\n private registeredEndpoints: PluginEndpointMap = {};\n\n static phase: PluginPhase = \"normal\";\n name: string;\n\n constructor(protected config: TConfig) {\n this.name = config.name ?? \"plugin\";\n this.telemetry = TelemetryManager.getProvider(this.name, config.telemetry);\n this.streamManager = new StreamManager();\n this.cache = CacheManager.getInstanceSync();\n this.app = new AppManager();\n this.devFileReader = DevFileReader.getInstance();\n\n this.isReady = true;\n }\n\n validateEnv() {\n validateEnv(this.envVars);\n }\n\n injectRoutes(_: express.Router) {\n return;\n }\n\n async setup() {}\n\n getEndpoints(): PluginEndpointMap {\n return this.registeredEndpoints;\n }\n\n abortActiveOperations(): void {\n this.streamManager.abortAll();\n }\n\n /**\n * Returns the public exports for this plugin.\n * Override this to define a custom public API.\n * By default, returns an empty object.\n */\n exports(): unknown {\n return {};\n }\n\n /**\n * Execute operations using the user's identity from the request.\n * Returns a proxy of this plugin where all method calls execute\n * with the user's Databricks credentials instead of the service principal.\n *\n * @param req - The Express request containing the user token in headers\n * @returns A proxied plugin instance that executes as the user\n * @throws Error if user token is not available in request headers\n */\n asUser(req: express.Request): this {\n const token = req.headers[\"x-forwarded-access-token\"] as string;\n const userId = req.headers[\"x-forwarded-user\"] as string;\n const isDev = process.env.NODE_ENV === \"development\";\n\n // In local development, fall back to service principal\n // since there's no user token available\n if (!token && isDev) {\n logger.warn(\n \"asUser() called without user token in development mode. Using service principal.\",\n );\n\n return this;\n }\n\n if (!token) {\n throw AuthenticationError.missingToken(\"user token\");\n }\n\n if (!userId && !isDev) {\n throw AuthenticationError.missingUserId();\n }\n\n const effectiveUserId = userId || \"dev-user\";\n\n const userContext = ServiceContext.createUserContext(\n token,\n effectiveUserId,\n );\n\n // Return a proxy that wraps method calls in user context\n return this._createUserContextProxy(userContext);\n }\n\n /**\n * Creates a proxy that wraps method calls in a user context.\n * This allows all plugin methods to automatically use the user's\n * Databricks credentials.\n */\n private _createUserContextProxy(userContext: UserContext): this {\n return new Proxy(this, {\n get: (target, prop, receiver) => {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof value !== \"function\") {\n return value;\n }\n\n if (typeof prop === \"string\" && EXCLUDED_FROM_PROXY.has(prop)) {\n return value;\n }\n\n return (...args: unknown[]) => {\n return runInUserContext(userContext, () => value.apply(target, args));\n };\n },\n }) as this;\n }\n\n // streaming execution with interceptors\n protected async executeStream<T>(\n res: IAppResponse,\n fn: StreamExecuteHandler<T>,\n options: StreamExecutionSettings,\n userKey?: string,\n ) {\n // destructure options\n const {\n stream: streamConfig,\n default: defaultConfig,\n user: userConfig,\n } = options;\n\n // build execution options\n const executeConfig = this._buildExecutionConfig({\n default: defaultConfig,\n user: userConfig,\n });\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentUserId();\n\n const self = this;\n\n // wrapper function to ensure it returns a generator\n const asyncWrapperFn = async function* (streamSignal?: AbortSignal) {\n // build execution context\n const context: InterceptorContext = {\n signal: streamSignal,\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n // build interceptors\n const interceptors = self._buildInterceptors(executeConfig);\n\n // wrap the function to ensure it returns a promise\n const wrappedFn = async () => {\n const result = await fn(context.signal);\n return result;\n };\n\n // execute the function with interceptors\n const result = await self._executeWithInterceptors(\n wrappedFn as (signal?: AbortSignal) => Promise<T>,\n interceptors,\n context,\n );\n\n // check if result is a generator\n if (self._checkIfGenerator(result)) {\n yield* result;\n } else {\n yield result;\n }\n };\n\n // stream the result to the client\n await this.streamManager.stream(res, asyncWrapperFn, streamConfig);\n }\n\n // single sync execution with interceptors\n protected async execute<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n options: PluginExecutionSettings,\n userKey?: string,\n ): Promise<T | undefined> {\n const executeConfig = this._buildExecutionConfig(options);\n\n const interceptors = this._buildInterceptors(executeConfig);\n\n // get user key from context if not provided\n const effectiveUserKey = userKey ?? getCurrentUserId();\n\n const context: InterceptorContext = {\n metadata: new Map(),\n userKey: effectiveUserKey,\n };\n\n try {\n return await this._executeWithInterceptors(fn, interceptors, context);\n } catch (_error) {\n // production-safe, don't crash sdk\n return undefined;\n }\n }\n\n protected registerEndpoint(name: string, path: string): void {\n this.registeredEndpoints[name] = path;\n }\n\n protected route<_TResponse>(\n router: express.Router,\n config: RouteConfig,\n ): void {\n const { name, method, path, handler } = config;\n\n router[method](path, handler);\n\n this.registerEndpoint(name, `/api/${this.name}${path}`);\n }\n\n // build execution options by merging defaults, plugin config, and user overrides\n private _buildExecutionConfig(\n options: PluginExecutionSettings,\n ): PluginExecuteConfig {\n const { default: methodDefaults, user: userOverride } = options;\n\n // Merge: method defaults <- plugin config <- user override (highest priority)\n return deepMerge(\n deepMerge(methodDefaults, this.config),\n userOverride ?? {},\n ) as PluginExecuteConfig;\n }\n\n // build interceptors based on execute options\n private _buildInterceptors(\n options: PluginExecuteConfig,\n ): ExecutionInterceptor[] {\n const interceptors: ExecutionInterceptor[] = [];\n\n // order matters: telemetry → timeout → retry → cache (innermost to outermost)\n\n const telemetryConfig = normalizeTelemetryOptions(this.config.telemetry);\n if (\n telemetryConfig.traces &&\n (options.telemetryInterceptor?.enabled ?? true)\n ) {\n interceptors.push(\n new TelemetryInterceptor(this.telemetry, options.telemetryInterceptor),\n );\n }\n\n if (options.timeout && options.timeout > 0) {\n interceptors.push(new TimeoutInterceptor(options.timeout));\n }\n\n if (\n options.retry?.enabled &&\n options.retry.attempts &&\n options.retry.attempts > 1\n ) {\n interceptors.push(new RetryInterceptor(options.retry));\n }\n\n if (options.cache?.enabled && options.cache.cacheKey?.length) {\n interceptors.push(new CacheInterceptor(this.cache, options.cache));\n }\n\n return interceptors;\n }\n\n // execute method wrapped with interceptors\n private async _executeWithInterceptors<T>(\n fn: (signal?: AbortSignal) => Promise<T>,\n interceptors: ExecutionInterceptor[],\n context: InterceptorContext,\n ): Promise<T> {\n // no interceptors, execute directly\n if (interceptors.length === 0) {\n return fn(context.signal);\n }\n // build nested execution chain from interceptors\n let wrappedFn = () => fn(context.signal);\n\n // wrap each interceptor around the previous function\n for (const interceptor of interceptors) {\n const previousFn = wrappedFn;\n wrappedFn = () => interceptor.intercept(previousFn, context);\n }\n\n return wrappedFn();\n }\n\n private _checkIfGenerator(\n result: any,\n ): result is AsyncGenerator<any, void, unknown> {\n return (\n result && typeof result === \"object\" && Symbol.asyncIterator in result\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;cAoBoB;aAC4B;AAmBhD,MAAM,SAAS,aAAa,SAAS;;;;;;AAOrC,MAAM,sBAAsB,IAAI,IAAI;CAElC;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACD,CAAC;;AAGF,IAAsB,SAAtB,MAGA;CACE,AAAU,UAAU;CACpB,AAAU;CACV,AAAU;CACV,AAAU;CACV,AAAU;CACV,AAAU;;CAIV,AAAQ,sBAAyC,EAAE;CAEnD,OAAO,QAAqB;CAC5B;CAEA,YAAY,AAAU,QAAiB;EAAjB;AACpB,OAAK,OAAO,OAAO,QAAQ;AAC3B,OAAK,YAAY,iBAAiB,YAAY,KAAK,MAAM,OAAO,UAAU;AAC1E,OAAK,gBAAgB,IAAI,eAAe;AACxC,OAAK,QAAQ,aAAa,iBAAiB;AAC3C,OAAK,MAAM,IAAI,YAAY;AAC3B,OAAK,gBAAgB,cAAc,aAAa;AAEhD,OAAK,UAAU;;CAGjB,cAAc;AACZ,cAAY,KAAK,QAAQ;;CAG3B,aAAa,GAAmB;CAIhC,MAAM,QAAQ;CAEd,eAAkC;AAChC,SAAO,KAAK;;CAGd,wBAA8B;AAC5B,OAAK,cAAc,UAAU;;;;;;;CAQ/B,UAAmB;AACjB,SAAO,EAAE;;;;;;;;;;;CAYX,OAAO,KAA4B;EACjC,MAAM,QAAQ,IAAI,QAAQ;EAC1B,MAAM,SAAS,IAAI,QAAQ;EAC3B,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAIvC,MAAI,CAAC,SAAS,OAAO;AACnB,UAAO,KACL,mFACD;AAED,UAAO;;AAGT,MAAI,CAAC,MACH,OAAM,oBAAoB,aAAa,aAAa;AAGtD,MAAI,CAAC,UAAU,CAAC,MACd,OAAM,oBAAoB,eAAe;EAG3C,MA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G9D,SAAO,WAAW;;CAGpB,AAAQ,kBACN,QAC8C;AAC9C,SACE,UAAU,OAAO,WAAW,YAAY,OAAO,iBAAiB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-server.js","names":[],"sources":["../../src/server/base-server.ts"],"sourcesContent":["import type express from \"express\";\nimport { type PluginEndpoints, getConfigScript } from \"./utils\";\n\n/**\n * Base server for the AppKit.\n *\n * Abstract base class that provides common functionality for serving\n * frontend applications. Subclasses implement specific serving strategies\n * (Vite dev server, static file server, etc.).\n */\nexport abstract class BaseServer {\n protected app: express.Application;\n protected endpoints: PluginEndpoints;\n\n constructor(app: express.Application, endpoints: PluginEndpoints = {}) {\n this.app = app;\n this.endpoints = endpoints;\n }\n\n abstract setup(): void | Promise<void>;\n\n async close(): Promise<void> {}\n\n protected getConfigScript(): string {\n return getConfigScript(this.endpoints);\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAsB,aAAtB,MAAiC;
|
|
1
|
+
{"version":3,"file":"base-server.js","names":[],"sources":["../../src/server/base-server.ts"],"sourcesContent":["import type express from \"express\";\nimport { type PluginEndpoints, getConfigScript } from \"./utils\";\n\n/**\n * Base server for the AppKit.\n *\n * Abstract base class that provides common functionality for serving\n * frontend applications. Subclasses implement specific serving strategies\n * (Vite dev server, static file server, etc.).\n */\nexport abstract class BaseServer {\n protected app: express.Application;\n protected endpoints: PluginEndpoints;\n\n constructor(app: express.Application, endpoints: PluginEndpoints = {}) {\n this.app = app;\n this.endpoints = endpoints;\n }\n\n abstract setup(): void | Promise<void>;\n\n async close(): Promise<void> {}\n\n protected getConfigScript(): string {\n return getConfigScript(this.endpoints);\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAsB,aAAtB,MAAiC;CAC/B,AAAU;CACV,AAAU;CAEV,YAAY,KAA0B,YAA6B,EAAE,EAAE;AACrE,OAAK,MAAM;AACX,OAAK,YAAY;;CAKnB,MAAM,QAAuB;CAE7B,AAAU,kBAA0B;AAClC,SAAO,gBAAgB,KAAK,UAAU"}
|
package/dist/server/index.d.ts
CHANGED
|
@@ -27,7 +27,7 @@ declare class ServerPlugin extends Plugin {
|
|
|
27
27
|
port: number;
|
|
28
28
|
};
|
|
29
29
|
name: "server";
|
|
30
|
-
envVars: string[];
|
|
30
|
+
protected envVars: string[];
|
|
31
31
|
private serverApplication;
|
|
32
32
|
private server;
|
|
33
33
|
private viteDevServer?;
|
|
@@ -93,6 +93,28 @@ declare class ServerPlugin extends Plugin {
|
|
|
93
93
|
private static findStaticPath;
|
|
94
94
|
private logStartupInfo;
|
|
95
95
|
private _gracefulShutdown;
|
|
96
|
+
/**
|
|
97
|
+
* Returns the public exports for the server plugin.
|
|
98
|
+
* Exposes server management methods.
|
|
99
|
+
*/
|
|
100
|
+
exports(): {
|
|
101
|
+
/** Start the server */
|
|
102
|
+
start: () => Promise<express.Application>;
|
|
103
|
+
/** Extend the server with custom routes or middleware */
|
|
104
|
+
extend(fn: (app: express.Application) => void): /*elided*/any;
|
|
105
|
+
/** Get the underlying HTTP server instance */
|
|
106
|
+
getServer: () => Server;
|
|
107
|
+
/** Get the server configuration */
|
|
108
|
+
getConfig: () => {
|
|
109
|
+
[key: string]: unknown;
|
|
110
|
+
port?: number;
|
|
111
|
+
staticPath?: string;
|
|
112
|
+
autoStart?: boolean;
|
|
113
|
+
host?: string;
|
|
114
|
+
name?: string;
|
|
115
|
+
telemetry?: TelemetryOptions;
|
|
116
|
+
};
|
|
117
|
+
};
|
|
96
118
|
}
|
|
97
119
|
/**
|
|
98
120
|
* @internal
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/server/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;AAkCA;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/server/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;AAkCA;;;;;;;;;;;;AAwDiB,cAxDJ,YAAA,SAAqB,MAAA,CAwDjB;SAsPM,cAAQ,EAAA;IAxMhB,SAAA,EAAA,OAAA;IAAU,IAAA,EAAA,MAAA;IAtGS,IAAA,EAAA,MAAA;EAAM,CAAA;EA+T3B,IAAA,EAAA,QAGZ;EAAA,UAAA,OAAA,EAAA,MAAA,EAAA;UAHkB,iBAAA;UAAA,MAAA;UAAA,aAAA;EAAA,QAAA,sBAAA;oBAlTS;;gBAEZ;sBAEM;;WAaT;;;;;;;;;gBAAA;;;;;;;;;;;;WA0BI,QAAQ,OAAA,CAAQ;;;;;;;;;eA8ClB;;;;;;;;mBAmBI,OAAA,CAAQ;;;;;;;;;;;;;;;;;;;;;;;;iBAjEV,QAAQ,OAAA,CAAQ;;qBAsPV,OAAA,CAAQ;;qBAxMhB;;;;;;;;;kBAAU;;;;;;;cAyNZ,QAAM,gBAAA,cAAA"}
|