@databricks/appkit 0.45.0 → 0.46.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/agents/databricks.d.ts +25 -1
- package/dist/agents/databricks.d.ts.map +1 -1
- package/dist/agents/databricks.js +20 -1
- package/dist/agents/databricks.js.map +1 -1
- package/dist/appkit/package.js +1 -1
- package/dist/beta.d.ts +2 -2
- package/dist/core/agent/load-agents.d.ts.map +1 -1
- package/dist/core/agent/load-agents.js +52 -0
- package/dist/core/agent/load-agents.js.map +1 -1
- package/dist/core/agent/types.d.ts +11 -0
- package/dist/core/agent/types.d.ts.map +1 -1
- package/dist/core/agent/types.js.map +1 -1
- package/dist/core/appkit.d.ts.map +1 -1
- package/dist/core/appkit.js +2 -0
- package/dist/core/appkit.js.map +1 -1
- package/dist/core/lifecycle-manager.js +183 -0
- package/dist/core/lifecycle-manager.js.map +1 -0
- package/dist/core/plugin-context.d.ts +19 -1
- package/dist/core/plugin-context.d.ts.map +1 -1
- package/dist/core/plugin-context.js +9 -3
- package/dist/core/plugin-context.js.map +1 -1
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/plugin/plugin.js +2 -1
- package/dist/plugin/plugin.js.map +1 -1
- package/dist/plugins/agents/agents.d.ts.map +1 -1
- package/dist/plugins/agents/agents.js +3 -3
- package/dist/plugins/agents/agents.js.map +1 -1
- package/dist/plugins/lakebase/lakebase.d.ts +10 -2
- package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
- package/dist/plugins/lakebase/lakebase.js +18 -7
- package/dist/plugins/lakebase/lakebase.js.map +1 -1
- package/dist/plugins/server/index.d.ts +51 -1
- package/dist/plugins/server/index.d.ts.map +1 -1
- package/dist/plugins/server/index.js +110 -23
- package/dist/plugins/server/index.js.map +1 -1
- package/dist/registry/resource-registry.d.ts +9 -1
- package/dist/registry/resource-registry.d.ts.map +1 -1
- package/dist/registry/resource-registry.js +22 -5
- package/dist/registry/resource-registry.js.map +1 -1
- package/dist/shared/src/execute.d.ts +1 -3
- package/dist/shared/src/execute.d.ts.map +1 -1
- package/dist/shared/src/plugin.d.ts +16 -0
- package/dist/shared/src/plugin.d.ts.map +1 -1
- package/dist/stream/buffers.js +1 -1
- package/dist/stream/buffers.js.map +1 -1
- package/dist/stream/defaults.js +0 -2
- package/dist/stream/defaults.js.map +1 -1
- package/dist/stream/stream-manager.d.ts +2 -2
- package/dist/stream/stream-manager.d.ts.map +1 -1
- package/dist/stream/stream-manager.js +26 -24
- package/dist/stream/stream-manager.js.map +1 -1
- package/dist/stream/stream-registry.js +30 -23
- package/dist/stream/stream-registry.js.map +1 -1
- package/dist/stream/timers.js +17 -0
- package/dist/stream/timers.js.map +1 -0
- package/dist/stream/types.js.map +1 -1
- package/dist/telemetry/telemetry-manager.js +19 -13
- package/dist/telemetry/telemetry-manager.js.map +1 -1
- package/dist/utils/safe-handler.js +28 -0
- package/dist/utils/safe-handler.js.map +1 -0
- package/docs/api/appkit/Class.Plugin.md +2 -0
- package/docs/api/appkit/Class.ResourceRegistry.md +1 -1
- package/docs/api/appkit/Interface.AgentDefinition.md +11 -0
- package/docs/api/appkit/Interface.GenerationParams.md +58 -0
- package/docs/api/appkit/Interface.RegisteredAgent.md +11 -0
- package/docs/api/appkit.md +1 -0
- package/llms.txt +1 -0
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -93,9 +93,17 @@ declare class LakebasePlugin extends Plugin implements ToolProvider {
|
|
|
93
93
|
private runReadOnlyStatement;
|
|
94
94
|
/**
|
|
95
95
|
* Gracefully drains and closes all connection pools (SP + OBO).
|
|
96
|
-
*
|
|
96
|
+
*
|
|
97
|
+
* Runs as the plugin's `shutdown()` hook (phase 3 of the core lifecycle
|
|
98
|
+
* manager's graceful shutdown), NOT in `abortActiveOperations()` (phase 2):
|
|
99
|
+
* other plugins' `shutdown()` hooks may still need database connections to
|
|
100
|
+
* drain state,
|
|
101
|
+
* so the pools must outlive the abort phase. `pg.Pool#end()` waits for
|
|
102
|
+
* checked-out clients to be released, so hooks running concurrently with
|
|
103
|
+
* this one can still finish their in-flight queries. Errors are caught
|
|
104
|
+
* and logged; this hook never throws.
|
|
97
105
|
*/
|
|
98
|
-
|
|
106
|
+
shutdown(): Promise<void>;
|
|
99
107
|
/**
|
|
100
108
|
* Agent tool registry. Empty by default — the Lakebase plugin does NOT
|
|
101
109
|
* expose its SQL connection to LLM agents unless the developer explicitly
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lakebase.d.ts","names":[],"sources":["../../../src/plugins/lakebase/lakebase.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA;;;;;;;;;;;;;;;;cAAa,cAAA,SAAuB,MAAA,YAAkB,YAAA;
|
|
1
|
+
{"version":3,"file":"lakebase.d.ts","names":[],"sources":["../../../src/plugins/lakebase/lakebase.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA;;;;;;;;;;;;;;;;cAAa,cAAA,SAAuB,MAAA,YAAkB,YAAA;EA6NU;EAAA,OA3NvD,QAAA,EAAuB,cAAA;EAAA,UAEZ,MAAA,EAAQ,eAAA;EAAA,QAClB,IAAA;EAAA,QACA,cAAA;EAmEL;;;;;;;;EAzDG,KAAA,CAAA,GAAK,OAAA;EAhBqD;;;;;;;;;;;;;;;;;;EAsE1D,KAAA,WAAgB,cAAA,OAAA,CACpB,IAAA,UACA,MAAA,eACC,OAAA,CAAQ,WAAA,CAAY,CAAA;EAAA;;;;;;;;;;;;;;EAAA,QAmBT,oBAAA;EA4HZ;;;;;;;;;;;;EA7FI,QAAA,CAAA,GAAY,OAAA;EArDI;;;;;EAAA,QAkFd,KAAA;cAEI,MAAA,EAAQ,eAAA;EAAA,QAYZ,cAAA;EA2CR,aAAA,CAAA,GAAiB,mBAAA;EAIX,gBAAA,CACJ,IAAA,UACA,IAAA,WACA,MAAA,GAAS,WAAA,GACR,OAAA;EAIH,OAAA,CAAQ,IAAA,GAJE,cAAA,GAIoD,MAAA,SAAA,YAAA;;;;;UAQtD,gBAAA;EAtPA;;;;;;;;;;;;EA2QR,OAAA,CAAA;UAGwB,YAAA;sBAvLF,cAAA,QAAc,IAAA,UACtB,MAAA,iBAEX,OAAA,CAAQ,WAAA,CAAY,CAAA;;;;;;;;;;iBA1Ff,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAyRG,QAAA,EAAQ,QAAA,QAAA,cAAA,EAAA,eAAA"}
|
|
@@ -141,22 +141,33 @@ var LakebasePlugin = class extends Plugin {
|
|
|
141
141
|
}
|
|
142
142
|
/**
|
|
143
143
|
* Gracefully drains and closes all connection pools (SP + OBO).
|
|
144
|
-
*
|
|
144
|
+
*
|
|
145
|
+
* Runs as the plugin's `shutdown()` hook (phase 3 of the core lifecycle
|
|
146
|
+
* manager's graceful shutdown), NOT in `abortActiveOperations()` (phase 2):
|
|
147
|
+
* other plugins' `shutdown()` hooks may still need database connections to
|
|
148
|
+
* drain state,
|
|
149
|
+
* so the pools must outlive the abort phase. `pg.Pool#end()` waits for
|
|
150
|
+
* checked-out clients to be released, so hooks running concurrently with
|
|
151
|
+
* this one can still finish their in-flight queries. Errors are caught
|
|
152
|
+
* and logged; this hook never throws.
|
|
145
153
|
*/
|
|
146
|
-
|
|
147
|
-
super.abortActiveOperations();
|
|
154
|
+
async shutdown() {
|
|
148
155
|
if (this.pool) {
|
|
149
156
|
logger.info("Closing Lakebase SP pool");
|
|
150
|
-
|
|
157
|
+
try {
|
|
158
|
+
await this.pool.end();
|
|
159
|
+
} catch (err) {
|
|
151
160
|
logger.error("Error closing Lakebase SP pool: %O", err);
|
|
152
|
-
}
|
|
161
|
+
}
|
|
153
162
|
this.pool = null;
|
|
154
163
|
}
|
|
155
164
|
if (this.oboPoolManager) {
|
|
156
165
|
logger.info("Closing all Lakebase OBO pools (%d)", this.oboPoolManager.size);
|
|
157
|
-
|
|
166
|
+
try {
|
|
167
|
+
await this.oboPoolManager.closeAll();
|
|
168
|
+
} catch (err) {
|
|
158
169
|
logger.error("Error closing Lakebase OBO pools: %O", err);
|
|
159
|
-
}
|
|
170
|
+
}
|
|
160
171
|
this.oboPoolManager = null;
|
|
161
172
|
}
|
|
162
173
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lakebase.js","names":["manifest"],"sources":["../../../src/plugins/lakebase/lakebase.ts"],"sourcesContent":["import { WorkspaceClient } from \"@databricks/sdk-experimental\";\nimport type { QueryResult, QueryResultRow } from \"pg\";\nimport type { AgentToolDefinition, ToolProvider } from \"shared\";\nimport { z } from \"zod\";\nimport {\n createLakebasePool,\n createLakebasePoolManager,\n getLakebaseOrmConfig,\n getLakebasePgConfig,\n getUsernameWithApiLookup,\n type LakebasePool,\n type LakebasePoolManager,\n RoutingPool,\n} from \"../../connectors/lakebase\";\nimport { getClientOptions } from \"../../context/client-options\";\nimport { getUserContext } from \"../../context/execution-context\";\nimport { buildToolkitEntries } from \"../../core/agent/build-toolkit\";\nimport {\n defineTool,\n executeFromRegistry,\n toolsFromRegistry,\n} from \"../../core/agent/tools/define-tool\";\nimport { assertReadOnlySql } from \"../../core/agent/tools/sql-policy\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport type { PluginManifest } from \"../../registry\";\nimport manifest from \"./manifest.json\";\nimport type { ILakebaseConfig } from \"./types\";\n\nconst logger = createLogger(\"lakebase\");\n\n/** Default pool settings for per-user OBO pools. */\nconst OBO_POOL_DEFAULTS = {\n max: 3,\n allowExitOnIdle: true,\n idleTimeoutMillis: 30_000,\n};\n\n/**\n * AppKit plugin for Databricks Lakebase Autoscaling.\n *\n * Wraps `@databricks/lakebase` to provide a standard `pg.Pool` with automatic\n * OAuth token refresh, integrated with AppKit's logger and OpenTelemetry setup.\n *\n * Supports On-Behalf-Of (OBO) via `asUser(req)` — each user gets a separate\n * `pg.Pool` authenticated with their Databricks identity, enabling features\n * like Row-Level Security (RLS). Routing is handled transparently by\n * {@link RoutingPool}, which reads the execution context set by the base\n * class `asUser()`.\n *\n * @example\n * ```ts\n * import { createApp, lakebase, server } from \"@databricks/appkit\";\n *\n * const AppKit = await createApp({\n * plugins: [server(), lakebase()],\n * });\n *\n * // Service principal query\n * const result = await AppKit.lakebase.query(\"SELECT * FROM users WHERE id = $1\", [userId]);\n *\n * // User-scoped query (per-user pool, RLS enforced)\n * const mine = await AppKit.lakebase.asUser(req).query(\"SELECT * FROM my_data\");\n * ```\n */\nexport class LakebasePlugin extends Plugin implements ToolProvider {\n /** Plugin manifest declaring metadata and resource requirements */\n static manifest = manifest as PluginManifest<\"lakebase\">;\n\n protected declare config: ILakebaseConfig;\n private pool: RoutingPool | null = null;\n private oboPoolManager: LakebasePoolManager | null = null;\n\n /**\n * Initializes the Lakebase connection pool and OBO pool manager.\n * Called automatically by AppKit during the plugin setup phase.\n *\n * Creates a {@link RoutingPool} that automatically routes queries to either\n * the service-principal pool or a per-user pool based on the execution\n * context (set by `Plugin.asUser(req)` via AsyncLocalStorage).\n */\n async setup() {\n const poolConfig = {\n ...this.config.pool,\n workspaceClient:\n this.config.pool?.workspaceClient ??\n new WorkspaceClient({}, getClientOptions()),\n };\n const user = await getUsernameWithApiLookup(poolConfig);\n\n const spPool = createLakebasePool({ ...poolConfig, user });\n logger.info(\"Lakebase SP pool initialized\");\n\n this.oboPoolManager = createLakebasePoolManager({\n ...poolConfig,\n ...OBO_POOL_DEFAULTS,\n });\n logger.info(\"Lakebase OBO pool manager initialized\");\n\n const oboManager = this.oboPoolManager;\n this.pool = new RoutingPool(spPool, (ctx) => {\n if (!oboManager) throw new Error(\"OBO pool manager not initialized\");\n // Lakebase OAuth roles use email as the postgres role when available\n const userKey = ctx.userEmail ?? ctx.userId;\n const isNew = !oboManager.hasPool(userKey);\n const pool = oboManager.getPool(\n userKey,\n { workspaceClient: ctx.client, user: userKey },\n ctx.tokenFingerprint,\n );\n if (isNew) {\n logger.debug(\"Created OBO pool for user (total: %d)\", oboManager.size);\n }\n return pool;\n });\n }\n\n /**\n * Executes a parameterized SQL query against the Lakebase pool.\n *\n * When called inside `asUser(req)`, the query automatically routes to\n * the per-user pool via {@link RoutingPool}.\n *\n * @param text - SQL query string, using `$1`, `$2`, ... placeholders\n * @param values - Parameter values corresponding to placeholders\n * @returns Query result with typed rows\n *\n * @example\n * ```ts\n * const result = await AppKit.lakebase.query<{ id: number; name: string }>(\n * \"SELECT id, name FROM users WHERE active = $1\",\n * [true],\n * );\n * ```\n */\n async query<T extends QueryResultRow = any>(\n text: string,\n values?: unknown[],\n ): Promise<QueryResult<T>> {\n // biome-ignore lint/style/noNonNullAssertion: pool is guaranteed non-null after setup(), which AppKit always awaits before exposing the plugin API\n return this.pool!.query<T>(text, values);\n }\n\n /**\n * Execute a single statement inside a `BEGIN READ ONLY … ROLLBACK`\n * transaction on a dedicated client.\n *\n * The three commands MUST share a connection — a naive\n * `pool.query(\"BEGIN READ ONLY; <stmt>; ROLLBACK\")` batch cannot accept\n * parameter values (PostgreSQL's Extended Query protocol rejects multi-\n * statement prepared queries), which would silently break every\n * parameterized query the agent tool issues.\n *\n * Returns the raw `rows` array for the user's statement. Side effects the\n * statement may attempt (writes, writable-function side effects) are\n * rejected by PostgreSQL under the read-only transaction posture.\n */\n private async runReadOnlyStatement(\n text: string,\n values?: unknown[],\n ): Promise<unknown[]> {\n // biome-ignore lint/style/noNonNullAssertion: pool is guaranteed non-null after setup()\n const client = await this.pool!.connect();\n try {\n await client.query(\"BEGIN READ ONLY\");\n const result = await client.query(text, values);\n return result.rows;\n } finally {\n try {\n await client.query(\"ROLLBACK\");\n } finally {\n client.release();\n }\n }\n }\n\n /**\n * Gracefully drains and closes all connection pools (SP + OBO).\n * Called automatically by AppKit during shutdown.\n */\n abortActiveOperations(): void {\n super.abortActiveOperations();\n if (this.pool) {\n logger.info(\"Closing Lakebase SP pool\");\n this.pool.end().catch((err) => {\n logger.error(\"Error closing Lakebase SP pool: %O\", err);\n });\n this.pool = null;\n }\n if (this.oboPoolManager) {\n logger.info(\n \"Closing all Lakebase OBO pools (%d)\",\n this.oboPoolManager.size,\n );\n this.oboPoolManager.closeAll().catch((err) => {\n logger.error(\"Error closing Lakebase OBO pools: %O\", err);\n });\n this.oboPoolManager = null;\n }\n }\n\n /**\n * Agent tool registry. Empty by default — the Lakebase plugin does NOT\n * expose its SQL connection to LLM agents unless the developer explicitly\n * opts in via `config.exposeAsAgentTool`. See {@link buildQueryTool}.\n */\n private tools: Record<string, ReturnType<typeof this.buildQueryTool>> = {};\n\n constructor(config: ILakebaseConfig) {\n super(config);\n this.config = config;\n if (config.exposeAsAgentTool) {\n this.tools = { query: this.buildQueryTool(config.exposeAsAgentTool) };\n logger.warn(\n \"Lakebase agent tool is enabled (readOnly=%s). Every agent with access to this plugin can execute SQL against the Lakebase database as the requesting user's identity.\",\n config.exposeAsAgentTool.readOnly !== false,\n );\n }\n }\n\n private buildQueryTool(\n opt: NonNullable<ILakebaseConfig[\"exposeAsAgentTool\"]>,\n ) {\n const readOnly = opt.readOnly !== false;\n return defineTool({\n description: readOnly\n ? \"Execute a read-only SQL query against the Lakebase PostgreSQL database. Only SELECT, WITH, SHOW, EXPLAIN, and DESCRIBE statements are accepted. Use $1, $2, etc. as placeholders and pass values separately.\"\n : \"Execute a parameterized SQL statement against the Lakebase PostgreSQL database. Use $1, $2, etc. as placeholders and pass values separately. This tool can modify data; every invocation requires explicit human approval.\",\n schema: z.object({\n text: z\n .string()\n .describe(\n \"SQL statement with $1, $2, ... placeholders for parameters\",\n ),\n values: z\n .array(z.unknown())\n .optional()\n .describe(\"Parameter values corresponding to placeholders\"),\n }),\n annotations: {\n effect: readOnly ? \"read\" : \"destructive\",\n idempotent: false,\n requiresUserContext: true,\n },\n execute: async (args, signal) => {\n // Matches the files plugin pattern: the pg connection API\n // doesn't accept AbortSignal in its current shape, so deeper\n // mid-call cancellation needs a separate plumbing pass on the\n // connector. This entry check still catches the common case —\n // a tool dispatched after the user already cancelled the\n // stream — and unwinds cleanly instead of running to\n // completion against the SQL warehouse.\n signal?.throwIfAborted();\n if (readOnly) {\n assertReadOnlySql(args.text);\n return this.runReadOnlyStatement(args.text, args.values);\n }\n const result = await this.query(args.text, args.values);\n return result.rows;\n },\n });\n }\n\n getAgentTools(): AgentToolDefinition[] {\n return toolsFromRegistry(this.tools);\n }\n\n async executeAgentTool(\n name: string,\n args: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> {\n return executeFromRegistry(this.tools, name, args, signal);\n }\n\n toolkit(opts?: import(\"../../core/agent/types\").ToolkitOptions) {\n return buildToolkitEntries(this.name, this.tools, opts);\n }\n\n /**\n * Returns the pool config for the current execution context.\n * Inside `asUser(req)`, returns user-scoped config; otherwise SP config.\n */\n private activePoolConfig() {\n const ctx = getUserContext();\n if (ctx) {\n const user = ctx.userEmail ?? ctx.userId;\n return { ...this.config.pool, workspaceClient: ctx.client, user };\n }\n return this.config.pool;\n }\n\n /**\n * Returns the plugin's public API, accessible via `AppKit.lakebase`.\n *\n * - `pool` — The connection pool (routes to per-user pool when inside `asUser(req)`)\n * - `query` — Convenience method for executing parameterized SQL queries\n * - `getOrmConfig()` — Returns a config object compatible with Drizzle, TypeORM, Sequelize, etc.\n * Inside `asUser(req)`, returns user-scoped config.\n * - `getPgConfig()` — Returns a `pg.PoolConfig` object for manual pool construction.\n * Inside `asUser(req)`, returns user-scoped config.\n *\n * Use `AppKit.lakebase.asUser(req)` to get the same API backed by a per-user pool.\n */\n exports() {\n return {\n // biome-ignore lint/style/noNonNullAssertion: pool is guaranteed non-null after setup(), which AppKit always awaits before exposing the plugin API\n pool: this.pool! as LakebasePool,\n query: this.query.bind(this),\n getOrmConfig: () => getLakebaseOrmConfig(this.activePoolConfig()),\n getPgConfig: () => getLakebasePgConfig(this.activePoolConfig()),\n };\n }\n}\n\n/**\n * @internal\n */\nexport const lakebase = toPlugin(LakebasePlugin);\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAM,SAAS,aAA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AAK,MAAM;;CAGtC,MAAM,iBACJ,MACA,MACA,QACkB;AAClB,SAAO,oBAAoB,KAAK,OAAO,MAAM,MAAM,OAAO;;CAG5D,QAAQ,MAAwD;AAC9D,SAAO,oBAAoB,KAAK,MAAM,KAAK,OAAO,KAAK;;;;;;CAOzD,AAAQ,mBAAmB;EACzB,MAAM,MAAM,gBAAgB;AAC5B,MAAI,KAAK;GACP,MAAM,OAAO,IAAI,aAAa,IAAI;AAClC,UAAO;IAAE,GAAG,KAAK,OAAO;IAAM,iBAAiB,IAAI;IAAQ;IAAM;;AAEnE,SAAO,KAAK,OAAO;;;;;;;;;;;;;;CAerB,UAAU;AACR,SAAO;GAEL,MAAM,KAAK;GACX,OAAO,KAAK,MAAM,KAAK,KAAK;GAC5B,oBAAoB,qBAAqB,KAAK,kBAAkB,CAAC;GACjE,mBAAmB,oBAAoB,KAAK,kBAAkB,CAAC;GAChE;;;;;;AAOL,MAAa,WAAW,SAAS,eAAe"}
|
|
1
|
+
{"version":3,"file":"lakebase.js","names":["manifest"],"sources":["../../../src/plugins/lakebase/lakebase.ts"],"sourcesContent":["import { WorkspaceClient } from \"@databricks/sdk-experimental\";\nimport type { QueryResult, QueryResultRow } from \"pg\";\nimport type { AgentToolDefinition, ToolProvider } from \"shared\";\nimport { z } from \"zod\";\nimport {\n createLakebasePool,\n createLakebasePoolManager,\n getLakebaseOrmConfig,\n getLakebasePgConfig,\n getUsernameWithApiLookup,\n type LakebasePool,\n type LakebasePoolManager,\n RoutingPool,\n} from \"../../connectors/lakebase\";\nimport { getClientOptions } from \"../../context/client-options\";\nimport { getUserContext } from \"../../context/execution-context\";\nimport { buildToolkitEntries } from \"../../core/agent/build-toolkit\";\nimport {\n defineTool,\n executeFromRegistry,\n toolsFromRegistry,\n} from \"../../core/agent/tools/define-tool\";\nimport { assertReadOnlySql } from \"../../core/agent/tools/sql-policy\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport type { PluginManifest } from \"../../registry\";\nimport manifest from \"./manifest.json\";\nimport type { ILakebaseConfig } from \"./types\";\n\nconst logger = createLogger(\"lakebase\");\n\n/** Default pool settings for per-user OBO pools. */\nconst OBO_POOL_DEFAULTS = {\n max: 3,\n allowExitOnIdle: true,\n idleTimeoutMillis: 30_000,\n};\n\n/**\n * AppKit plugin for Databricks Lakebase Autoscaling.\n *\n * Wraps `@databricks/lakebase` to provide a standard `pg.Pool` with automatic\n * OAuth token refresh, integrated with AppKit's logger and OpenTelemetry setup.\n *\n * Supports On-Behalf-Of (OBO) via `asUser(req)` — each user gets a separate\n * `pg.Pool` authenticated with their Databricks identity, enabling features\n * like Row-Level Security (RLS). Routing is handled transparently by\n * {@link RoutingPool}, which reads the execution context set by the base\n * class `asUser()`.\n *\n * @example\n * ```ts\n * import { createApp, lakebase, server } from \"@databricks/appkit\";\n *\n * const AppKit = await createApp({\n * plugins: [server(), lakebase()],\n * });\n *\n * // Service principal query\n * const result = await AppKit.lakebase.query(\"SELECT * FROM users WHERE id = $1\", [userId]);\n *\n * // User-scoped query (per-user pool, RLS enforced)\n * const mine = await AppKit.lakebase.asUser(req).query(\"SELECT * FROM my_data\");\n * ```\n */\nexport class LakebasePlugin extends Plugin implements ToolProvider {\n /** Plugin manifest declaring metadata and resource requirements */\n static manifest = manifest as PluginManifest<\"lakebase\">;\n\n protected declare config: ILakebaseConfig;\n private pool: RoutingPool | null = null;\n private oboPoolManager: LakebasePoolManager | null = null;\n\n /**\n * Initializes the Lakebase connection pool and OBO pool manager.\n * Called automatically by AppKit during the plugin setup phase.\n *\n * Creates a {@link RoutingPool} that automatically routes queries to either\n * the service-principal pool or a per-user pool based on the execution\n * context (set by `Plugin.asUser(req)` via AsyncLocalStorage).\n */\n async setup() {\n const poolConfig = {\n ...this.config.pool,\n workspaceClient:\n this.config.pool?.workspaceClient ??\n new WorkspaceClient({}, getClientOptions()),\n };\n const user = await getUsernameWithApiLookup(poolConfig);\n\n const spPool = createLakebasePool({ ...poolConfig, user });\n logger.info(\"Lakebase SP pool initialized\");\n\n this.oboPoolManager = createLakebasePoolManager({\n ...poolConfig,\n ...OBO_POOL_DEFAULTS,\n });\n logger.info(\"Lakebase OBO pool manager initialized\");\n\n const oboManager = this.oboPoolManager;\n this.pool = new RoutingPool(spPool, (ctx) => {\n if (!oboManager) throw new Error(\"OBO pool manager not initialized\");\n // Lakebase OAuth roles use email as the postgres role when available\n const userKey = ctx.userEmail ?? ctx.userId;\n const isNew = !oboManager.hasPool(userKey);\n const pool = oboManager.getPool(\n userKey,\n { workspaceClient: ctx.client, user: userKey },\n ctx.tokenFingerprint,\n );\n if (isNew) {\n logger.debug(\"Created OBO pool for user (total: %d)\", oboManager.size);\n }\n return pool;\n });\n }\n\n /**\n * Executes a parameterized SQL query against the Lakebase pool.\n *\n * When called inside `asUser(req)`, the query automatically routes to\n * the per-user pool via {@link RoutingPool}.\n *\n * @param text - SQL query string, using `$1`, `$2`, ... placeholders\n * @param values - Parameter values corresponding to placeholders\n * @returns Query result with typed rows\n *\n * @example\n * ```ts\n * const result = await AppKit.lakebase.query<{ id: number; name: string }>(\n * \"SELECT id, name FROM users WHERE active = $1\",\n * [true],\n * );\n * ```\n */\n async query<T extends QueryResultRow = any>(\n text: string,\n values?: unknown[],\n ): Promise<QueryResult<T>> {\n // biome-ignore lint/style/noNonNullAssertion: pool is guaranteed non-null after setup(), which AppKit always awaits before exposing the plugin API\n return this.pool!.query<T>(text, values);\n }\n\n /**\n * Execute a single statement inside a `BEGIN READ ONLY … ROLLBACK`\n * transaction on a dedicated client.\n *\n * The three commands MUST share a connection — a naive\n * `pool.query(\"BEGIN READ ONLY; <stmt>; ROLLBACK\")` batch cannot accept\n * parameter values (PostgreSQL's Extended Query protocol rejects multi-\n * statement prepared queries), which would silently break every\n * parameterized query the agent tool issues.\n *\n * Returns the raw `rows` array for the user's statement. Side effects the\n * statement may attempt (writes, writable-function side effects) are\n * rejected by PostgreSQL under the read-only transaction posture.\n */\n private async runReadOnlyStatement(\n text: string,\n values?: unknown[],\n ): Promise<unknown[]> {\n // biome-ignore lint/style/noNonNullAssertion: pool is guaranteed non-null after setup()\n const client = await this.pool!.connect();\n try {\n await client.query(\"BEGIN READ ONLY\");\n const result = await client.query(text, values);\n return result.rows;\n } finally {\n try {\n await client.query(\"ROLLBACK\");\n } finally {\n client.release();\n }\n }\n }\n\n /**\n * Gracefully drains and closes all connection pools (SP + OBO).\n *\n * Runs as the plugin's `shutdown()` hook (phase 3 of the core lifecycle\n * manager's graceful shutdown), NOT in `abortActiveOperations()` (phase 2):\n * other plugins' `shutdown()` hooks may still need database connections to\n * drain state,\n * so the pools must outlive the abort phase. `pg.Pool#end()` waits for\n * checked-out clients to be released, so hooks running concurrently with\n * this one can still finish their in-flight queries. Errors are caught\n * and logged; this hook never throws.\n */\n async shutdown(): Promise<void> {\n if (this.pool) {\n logger.info(\"Closing Lakebase SP pool\");\n try {\n await this.pool.end();\n } catch (err) {\n logger.error(\"Error closing Lakebase SP pool: %O\", err);\n }\n this.pool = null;\n }\n if (this.oboPoolManager) {\n logger.info(\n \"Closing all Lakebase OBO pools (%d)\",\n this.oboPoolManager.size,\n );\n try {\n await this.oboPoolManager.closeAll();\n } catch (err) {\n logger.error(\"Error closing Lakebase OBO pools: %O\", err);\n }\n this.oboPoolManager = null;\n }\n }\n\n /**\n * Agent tool registry. Empty by default — the Lakebase plugin does NOT\n * expose its SQL connection to LLM agents unless the developer explicitly\n * opts in via `config.exposeAsAgentTool`. See {@link buildQueryTool}.\n */\n private tools: Record<string, ReturnType<typeof this.buildQueryTool>> = {};\n\n constructor(config: ILakebaseConfig) {\n super(config);\n this.config = config;\n if (config.exposeAsAgentTool) {\n this.tools = { query: this.buildQueryTool(config.exposeAsAgentTool) };\n logger.warn(\n \"Lakebase agent tool is enabled (readOnly=%s). Every agent with access to this plugin can execute SQL against the Lakebase database as the requesting user's identity.\",\n config.exposeAsAgentTool.readOnly !== false,\n );\n }\n }\n\n private buildQueryTool(\n opt: NonNullable<ILakebaseConfig[\"exposeAsAgentTool\"]>,\n ) {\n const readOnly = opt.readOnly !== false;\n return defineTool({\n description: readOnly\n ? \"Execute a read-only SQL query against the Lakebase PostgreSQL database. Only SELECT, WITH, SHOW, EXPLAIN, and DESCRIBE statements are accepted. Use $1, $2, etc. as placeholders and pass values separately.\"\n : \"Execute a parameterized SQL statement against the Lakebase PostgreSQL database. Use $1, $2, etc. as placeholders and pass values separately. This tool can modify data; every invocation requires explicit human approval.\",\n schema: z.object({\n text: z\n .string()\n .describe(\n \"SQL statement with $1, $2, ... placeholders for parameters\",\n ),\n values: z\n .array(z.unknown())\n .optional()\n .describe(\"Parameter values corresponding to placeholders\"),\n }),\n annotations: {\n effect: readOnly ? \"read\" : \"destructive\",\n idempotent: false,\n requiresUserContext: true,\n },\n execute: async (args, signal) => {\n // Matches the files plugin pattern: the pg connection API\n // doesn't accept AbortSignal in its current shape, so deeper\n // mid-call cancellation needs a separate plumbing pass on the\n // connector. This entry check still catches the common case —\n // a tool dispatched after the user already cancelled the\n // stream — and unwinds cleanly instead of running to\n // completion against the SQL warehouse.\n signal?.throwIfAborted();\n if (readOnly) {\n assertReadOnlySql(args.text);\n return this.runReadOnlyStatement(args.text, args.values);\n }\n const result = await this.query(args.text, args.values);\n return result.rows;\n },\n });\n }\n\n getAgentTools(): AgentToolDefinition[] {\n return toolsFromRegistry(this.tools);\n }\n\n async executeAgentTool(\n name: string,\n args: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> {\n return executeFromRegistry(this.tools, name, args, signal);\n }\n\n toolkit(opts?: import(\"../../core/agent/types\").ToolkitOptions) {\n return buildToolkitEntries(this.name, this.tools, opts);\n }\n\n /**\n * Returns the pool config for the current execution context.\n * Inside `asUser(req)`, returns user-scoped config; otherwise SP config.\n */\n private activePoolConfig() {\n const ctx = getUserContext();\n if (ctx) {\n const user = ctx.userEmail ?? ctx.userId;\n return { ...this.config.pool, workspaceClient: ctx.client, user };\n }\n return this.config.pool;\n }\n\n /**\n * Returns the plugin's public API, accessible via `AppKit.lakebase`.\n *\n * - `pool` — The connection pool (routes to per-user pool when inside `asUser(req)`)\n * - `query` — Convenience method for executing parameterized SQL queries\n * - `getOrmConfig()` — Returns a config object compatible with Drizzle, TypeORM, Sequelize, etc.\n * Inside `asUser(req)`, returns user-scoped config.\n * - `getPgConfig()` — Returns a `pg.PoolConfig` object for manual pool construction.\n * Inside `asUser(req)`, returns user-scoped config.\n *\n * Use `AppKit.lakebase.asUser(req)` to get the same API backed by a per-user pool.\n */\n exports() {\n return {\n // biome-ignore lint/style/noNonNullAssertion: pool is guaranteed non-null after setup(), which AppKit always awaits before exposing the plugin API\n pool: this.pool! as LakebasePool,\n query: this.query.bind(this),\n getOrmConfig: () => getLakebaseOrmConfig(this.activePoolConfig()),\n getPgConfig: () => getLakebasePgConfig(this.activePoolConfig()),\n };\n }\n}\n\n/**\n * @internal\n */\nexport const lakebase = toPlugin(LakebasePlugin);\n"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAM,SAAS,aAAa,WAAW;;AAGvC,MAAM,oBAAoB;CACxB,KAAK;CACL,iBAAiB;CACjB,mBAAmB;CACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BD,IAAa,iBAAb,cAAoC,OAA+B;;CAEjE,OAAO,WAAWA;CAGlB,AAAQ,OAA2B;CACnC,AAAQ,iBAA6C;;;;;;;;;CAUrD,MAAM,QAAQ;EACZ,MAAM,aAAa;GACjB,GAAG,KAAK,OAAO;GACf,iBACE,KAAK,OAAO,MAAM,mBAClB,IAAI,gBAAgB,EAAE,EAAE,kBAAkB,CAAC;GAC9C;EACD,MAAM,OAAO,MAAM,yBAAyB,WAAW;EAEvD,MAAM,SAAS,mBAAmB;GAAE,GAAG;GAAY;GAAM,CAAC;AAC1D,SAAO,KAAK,+BAA+B;AAE3C,OAAK,iBAAiB,0BAA0B;GAC9C,GAAG;GACH,GAAG;GACJ,CAAC;AACF,SAAO,KAAK,wCAAwC;EAEpD,MAAM,aAA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AAS,eAAe"}
|
|
@@ -36,6 +36,13 @@ declare class ServerPlugin extends Plugin {
|
|
|
36
36
|
host: string;
|
|
37
37
|
port: number;
|
|
38
38
|
};
|
|
39
|
+
/**
|
|
40
|
+
* Budget for awaiting `server.close()` during shutdown. Bounded because
|
|
41
|
+
* `closeAllConnections()` runs immediately before the await, so the close
|
|
42
|
+
* is expected to resolve promptly; the core lifecycle manager's overall
|
|
43
|
+
* force-exit timer is the ultimate backstop if it does not.
|
|
44
|
+
*/
|
|
45
|
+
private static readonly SERVER_CLOSE_TIMEOUT_MS;
|
|
39
46
|
/** Plugin manifest declaring metadata and resource requirements */
|
|
40
47
|
static manifest: PluginManifest<"server">;
|
|
41
48
|
private serverApplication;
|
|
@@ -47,6 +54,12 @@ declare class ServerPlugin extends Plugin {
|
|
|
47
54
|
protected config: ServerConfig;
|
|
48
55
|
private serverExtensions;
|
|
49
56
|
private rawBodyPaths;
|
|
57
|
+
/**
|
|
58
|
+
* Resolves when `server.close()` completes. Created in
|
|
59
|
+
* {@link abortActiveOperations} (which initiates the close) and awaited in
|
|
60
|
+
* {@link closeRemainingConnections} after other plugins have drained.
|
|
61
|
+
*/
|
|
62
|
+
private serverClosed?;
|
|
50
63
|
static phase: PluginPhase;
|
|
51
64
|
constructor(config: ServerConfig);
|
|
52
65
|
attachContext(deps?: Parameters<Plugin["attachContext"]>[0]): void;
|
|
@@ -86,6 +99,11 @@ declare class ServerPlugin extends Plugin {
|
|
|
86
99
|
* Call this inside the `onPluginsReady` callback of `createApp` to register
|
|
87
100
|
* custom Express routes or middleware before the server starts listening.
|
|
88
101
|
*
|
|
102
|
+
* Note: async handlers registered directly on the app must handle their own
|
|
103
|
+
* rejections — Express 4 does not forward rejected promises to the error
|
|
104
|
+
* middleware. Errors passed explicitly to `next(err)` are formatted by the
|
|
105
|
+
* terminal error middleware.
|
|
106
|
+
*
|
|
89
107
|
* @param fn - A function that receives the express application.
|
|
90
108
|
* @returns The server plugin instance for chaining.
|
|
91
109
|
*/
|
|
@@ -120,7 +138,39 @@ declare class ServerPlugin extends Plugin {
|
|
|
120
138
|
*/
|
|
121
139
|
private resolveListenPort;
|
|
122
140
|
private logStartupInfo;
|
|
123
|
-
|
|
141
|
+
/**
|
|
142
|
+
* Cancel in-flight work and begin closing the HTTP server.
|
|
143
|
+
*
|
|
144
|
+
* Runs in the first phase of the core LifecycleManager's graceful shutdown,
|
|
145
|
+
* before any plugin `shutdown()` hook. In addition to the base behavior
|
|
146
|
+
* (aborting SSE streams), it stops the server accepting new connections and
|
|
147
|
+
* drops idle keep-alive sockets — without `closeIdleConnections()`, a
|
|
148
|
+
* connected browser would pin `server.close()` open until the force-exit
|
|
149
|
+
* timer fires. The close is only *initiated* here; the returned promise is
|
|
150
|
+
* awaited later in {@link closeRemainingConnections} so peer plugins can
|
|
151
|
+
* still drain in-flight requests through the server first.
|
|
152
|
+
*/
|
|
153
|
+
abortActiveOperations(): void;
|
|
154
|
+
/**
|
|
155
|
+
* Drain the dev-only servers as this plugin's `shutdown()` hook.
|
|
156
|
+
*
|
|
157
|
+
* Runs concurrently with the other plugins' hooks during graceful shutdown.
|
|
158
|
+
* These are no-ops in production (neither is created), so this hook is
|
|
159
|
+
* effectively dev-only.
|
|
160
|
+
*/
|
|
161
|
+
shutdown(): Promise<void>;
|
|
162
|
+
/**
|
|
163
|
+
* Force-close whatever sockets remain and await the server close.
|
|
164
|
+
*
|
|
165
|
+
* Registered on the `"shutdown"` lifecycle event in {@link start}, so it
|
|
166
|
+
* fires after every plugin's `shutdown()` hook has run — meaning any
|
|
167
|
+
* in-flight request a peer plugin was draining has already completed.
|
|
168
|
+
* `closeAllConnections()` destroys the leftover sockets (aborted SSE
|
|
169
|
+
* responses, keep-alive connections) synchronously so the pending
|
|
170
|
+
* `server.close()` can complete; the await is bounded because the close is
|
|
171
|
+
* expected to resolve promptly once the sockets are gone.
|
|
172
|
+
*/
|
|
173
|
+
private closeRemainingConnections;
|
|
124
174
|
/**
|
|
125
175
|
* Returns the public exports for the server plugin.
|
|
126
176
|
* Exposes server management methods.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/plugins/server/index.ts"],"mappings":";;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;cAAa,YAAA,SAAqB,MAAA;EAAA,OAClB,cAAA;;;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/plugins/server/index.ts"],"mappings":";;;;;;;;;;;;;;;;AAkDA;;;;;;;;;;;;;;;;;cAAa,YAAA,SAAqB,MAAA;EAAA,OAClB,cAAA;;;;EADwB;;;;;;EAAA,wBAYd,uBAAA;EAGM;EAAA,OAAvB,QAAA,EAAuB,cAAA;EAAA,QACtB,iBAAA;EAAA,QACA,MAAA;EAAA,QACA,aAAA;EAAA,QACA,sBAAA;EAGU;EAAA,QADV,kBAAA;EAAA,UACU,MAAA,EAAQ,YAAA;EAAA,QAClB,gBAAA;EAAA,QACA,YAAA;EAOD;;;;;EAAA,QADC,YAAA;EAAA,OACD,KAAA,EAAO,WAAA;cAEF,MAAA,EAAQ,YAAA;EAepB,aAAA,CAAc,IAAA,GAAM,UAAA,CAAW,MAAA;EAUzB;EAAA,KAAA,CAAA,GAAK,OAAA;EAGX;EAAA,SAAA,CAAA;IAAA;;;;;;gBAHW,gBAAA;EAAA;EAiBI;;;;;;;;EAAT,KAAA,CAAA,GAAS,OAAA,CAAQ,OAAA,CAAQ,WAAA;EAwGxB;;;;;;;;EAtBP,SAAA,CAAA,GAAa,MAAA;EA6KC;;;;;;;;;;;;;;EAvJd,MAAA,CAAO,EAAA,GAAK,GAAA,EAAK,OAAA,CAAQ,WAAA;;;;;;;EAWzB,YAAA,CAAa,EAAA,GAAK,GAAA,EAAK,OAAA,CAAQ,WAAA;;;;;AA8YjC;;;UAnYgB,YAAA;EAmYG;;;;;;EAAA,QAhUH,aAAA;EAAA,eA4CC,cAAA;EAoRE;;;;;EAAA,QAlQH,iBAAA;EAAA,QAqBN,cAAA;;;;;;;;;;;;;EA2CR,qBAAA,CAAA;;;;;;;;EAmBM,QAAA,CAAA,GAAY,OAAA;;;;;;;;;;;;UAoBJ,yBAAA;;;;;EAoBd,OAAA,CAAA;yEAIgB,GAAA,EAAK,OAAA,CAAQ,WAAA;qBA5ShB,MAAA;;;;;;;;kBAAU,gBAAA;IAAA;;;;;;;cA+aZ,MAAA,EAAM,QAAA,QAAA,YAAA,EAAA,YAAA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createLogger } from "../../logging/logger.js";
|
|
2
|
+
import { AppKitError } from "../../errors/base.js";
|
|
2
3
|
import { ServerError } from "../../errors/server.js";
|
|
3
4
|
import "../../errors/index.js";
|
|
4
5
|
import { instrumentations } from "../../telemetry/instrumentations.js";
|
|
@@ -52,6 +53,13 @@ var ServerPlugin = class ServerPlugin extends Plugin {
|
|
|
52
53
|
host: process.env.FLASK_RUN_HOST || "0.0.0.0",
|
|
53
54
|
port: Number(process.env.DATABRICKS_APP_PORT) || 8e3
|
|
54
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* Budget for awaiting `server.close()` during shutdown. Bounded because
|
|
58
|
+
* `closeAllConnections()` runs immediately before the await, so the close
|
|
59
|
+
* is expected to resolve promptly; the core lifecycle manager's overall
|
|
60
|
+
* force-exit timer is the ultimate backstop if it does not.
|
|
61
|
+
*/
|
|
62
|
+
static SERVER_CLOSE_TIMEOUT_MS = 2e3;
|
|
55
63
|
/** Plugin manifest declaring metadata and resource requirements */
|
|
56
64
|
static manifest = manifest_default;
|
|
57
65
|
serverApplication;
|
|
@@ -62,6 +70,12 @@ var ServerPlugin = class ServerPlugin extends Plugin {
|
|
|
62
70
|
resolvedListenPort;
|
|
63
71
|
serverExtensions = [];
|
|
64
72
|
rawBodyPaths = /* @__PURE__ */ new Set();
|
|
73
|
+
/**
|
|
74
|
+
* Resolves when `server.close()` completes. Created in
|
|
75
|
+
* {@link abortActiveOperations} (which initiates the close) and awaited in
|
|
76
|
+
* {@link closeRemainingConnections} after other plugins have drained.
|
|
77
|
+
*/
|
|
78
|
+
serverClosed;
|
|
65
79
|
static phase = "deferred";
|
|
66
80
|
constructor(config) {
|
|
67
81
|
super(config);
|
|
@@ -106,12 +120,12 @@ var ServerPlugin = class ServerPlugin extends Plugin {
|
|
|
106
120
|
this.remoteTunnelController = new RemoteTunnelController(this.devFileReader);
|
|
107
121
|
this.serverApplication.use(this.remoteTunnelController.middleware);
|
|
108
122
|
await this.setupFrontend(endpoints, pluginConfigs);
|
|
123
|
+
this.serverApplication.use(errorHandlerMiddleware);
|
|
109
124
|
const listenPort = await this.resolveListenPort();
|
|
110
125
|
const server = this.serverApplication.listen(listenPort, this.config.host ?? ServerPlugin.DEFAULT_CONFIG.host, () => this.logStartupInfo());
|
|
111
126
|
this.server = server;
|
|
112
127
|
this.remoteTunnelController.setServer(server);
|
|
113
|
-
|
|
114
|
-
process.on("SIGINT", () => this._gracefulShutdown());
|
|
128
|
+
this.context?.onLifecycle("shutdown", () => this.closeRemainingConnections());
|
|
115
129
|
if (process.env.NODE_ENV === "development") printRoutes(getRoutes(this.serverApplication._router.stack));
|
|
116
130
|
return this.serverApplication;
|
|
117
131
|
}
|
|
@@ -133,6 +147,11 @@ var ServerPlugin = class ServerPlugin extends Plugin {
|
|
|
133
147
|
* Call this inside the `onPluginsReady` callback of `createApp` to register
|
|
134
148
|
* custom Express routes or middleware before the server starts listening.
|
|
135
149
|
*
|
|
150
|
+
* Note: async handlers registered directly on the app must handle their own
|
|
151
|
+
* rejections — Express 4 does not forward rejected promises to the error
|
|
152
|
+
* middleware. Errors passed explicitly to `next(err)` are formatted by the
|
|
153
|
+
* terminal error middleware.
|
|
154
|
+
*
|
|
136
155
|
* @param fn - A function that receives the express application.
|
|
137
156
|
* @returns The server plugin instance for chaining.
|
|
138
157
|
*/
|
|
@@ -262,29 +281,57 @@ var ServerPlugin = class ServerPlugin extends Plugin {
|
|
|
262
281
|
if (!remoteServerController) logger.debug("Remote tunnel: disabled (controller not initialized)");
|
|
263
282
|
else logger.debug("Remote tunnel: %s; %s", remoteServerController.isAllowedByEnv() ? "allowed" : "blocked", remoteServerController.isActive() ? "active" : "inactive");
|
|
264
283
|
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
284
|
+
/**
|
|
285
|
+
* Cancel in-flight work and begin closing the HTTP server.
|
|
286
|
+
*
|
|
287
|
+
* Runs in the first phase of the core LifecycleManager's graceful shutdown,
|
|
288
|
+
* before any plugin `shutdown()` hook. In addition to the base behavior
|
|
289
|
+
* (aborting SSE streams), it stops the server accepting new connections and
|
|
290
|
+
* drops idle keep-alive sockets — without `closeIdleConnections()`, a
|
|
291
|
+
* connected browser would pin `server.close()` open until the force-exit
|
|
292
|
+
* timer fires. The close is only *initiated* here; the returned promise is
|
|
293
|
+
* awaited later in {@link closeRemainingConnections} so peer plugins can
|
|
294
|
+
* still drain in-flight requests through the server first.
|
|
295
|
+
*/
|
|
296
|
+
abortActiveOperations() {
|
|
297
|
+
super.abortActiveOperations();
|
|
278
298
|
if (this.server) {
|
|
279
|
-
this.server
|
|
280
|
-
|
|
281
|
-
|
|
299
|
+
const server = this.server;
|
|
300
|
+
this.serverClosed = new Promise((resolve) => {
|
|
301
|
+
server.close(() => resolve());
|
|
282
302
|
});
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
303
|
+
server.closeIdleConnections();
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Drain the dev-only servers as this plugin's `shutdown()` hook.
|
|
308
|
+
*
|
|
309
|
+
* Runs concurrently with the other plugins' hooks during graceful shutdown.
|
|
310
|
+
* These are no-ops in production (neither is created), so this hook is
|
|
311
|
+
* effectively dev-only.
|
|
312
|
+
*/
|
|
313
|
+
async shutdown() {
|
|
314
|
+
if (this.viteDevServer) await this.viteDevServer.close();
|
|
315
|
+
if (this.remoteTunnelController) this.remoteTunnelController.cleanup();
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Force-close whatever sockets remain and await the server close.
|
|
319
|
+
*
|
|
320
|
+
* Registered on the `"shutdown"` lifecycle event in {@link start}, so it
|
|
321
|
+
* fires after every plugin's `shutdown()` hook has run — meaning any
|
|
322
|
+
* in-flight request a peer plugin was draining has already completed.
|
|
323
|
+
* `closeAllConnections()` destroys the leftover sockets (aborted SSE
|
|
324
|
+
* responses, keep-alive connections) synchronously so the pending
|
|
325
|
+
* `server.close()` can complete; the await is bounded because the close is
|
|
326
|
+
* expected to resolve promptly once the sockets are gone.
|
|
327
|
+
*/
|
|
328
|
+
async closeRemainingConnections() {
|
|
329
|
+
if (this.server) this.server.closeAllConnections();
|
|
330
|
+
if (!this.serverClosed) return;
|
|
331
|
+
await Promise.race([this.serverClosed, new Promise((resolve) => {
|
|
332
|
+
setTimeout(resolve, ServerPlugin.SERVER_CLOSE_TIMEOUT_MS).unref();
|
|
333
|
+
})]);
|
|
334
|
+
logger.debug("Server closed gracefully");
|
|
288
335
|
}
|
|
289
336
|
/**
|
|
290
337
|
* Returns the public exports for the server plugin.
|
|
@@ -320,6 +367,46 @@ function requestMetricsMiddleware(req, res, next) {
|
|
|
320
367
|
next();
|
|
321
368
|
}
|
|
322
369
|
/**
|
|
370
|
+
* Narrow an unknown thrown value to an Error that carries a numeric
|
|
371
|
+
* `statusCode` property in the HTTP error range (e.g. `ApiError` from
|
|
372
|
+
* `@databricks/sdk-experimental`).
|
|
373
|
+
*/
|
|
374
|
+
function hasHttpStatusCode(error) {
|
|
375
|
+
if (!(error instanceof Error) || !("statusCode" in error)) return false;
|
|
376
|
+
const statusCode = error.statusCode;
|
|
377
|
+
return typeof statusCode === "number" && Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599;
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Terminal Express error-handling middleware.
|
|
381
|
+
*
|
|
382
|
+
* Converts errors forwarded via `next(err)` (including async handler
|
|
383
|
+
* rejections forwarded by `Plugin.route()`) into JSON error responses,
|
|
384
|
+
* following the same status/message conventions as `Plugin.execute()`:
|
|
385
|
+
* - errors carrying an HTTP `statusCode` (including `AppKitError`) → that
|
|
386
|
+
* status; 5xx messages are masked in production to avoid leaking internals
|
|
387
|
+
* - anything else → 500 with a generic message in production
|
|
388
|
+
*
|
|
389
|
+
* 4xx errors are expected client errors (e.g. missing auth headers) and are
|
|
390
|
+
* logged at `warn` with just the message; 5xx/unknown errors are logged at
|
|
391
|
+
* `error` with the full error.
|
|
392
|
+
*
|
|
393
|
+
* @internal Exported for unit tests.
|
|
394
|
+
*/
|
|
395
|
+
function errorHandlerMiddleware(err, req, res, next) {
|
|
396
|
+
const httpError = err instanceof AppKitError || hasHttpStatusCode(err) ? err : null;
|
|
397
|
+
const statusCode = httpError ? httpError.statusCode : 500;
|
|
398
|
+
const isClientError = statusCode < 500;
|
|
399
|
+
if (isClientError) logger.warn("Request failed for %s %s with status %d: %s", req.method, req.originalUrl, statusCode, err instanceof Error ? err.message : String(err));
|
|
400
|
+
else logger.error("Unhandled error for %s %s: %O", req.method, req.originalUrl, err instanceof AppKitError ? err.toJSON() : err);
|
|
401
|
+
if (res.headersSent) {
|
|
402
|
+
next(err);
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const isDev = process.env.NODE_ENV !== "production";
|
|
406
|
+
const message = err instanceof Error ? err.message : "Server error";
|
|
407
|
+
res.status(statusCode).json({ error: isDev || isClientError ? message : "Server error" });
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
323
410
|
* @internal
|
|
324
411
|
*/
|
|
325
412
|
const server = toPlugin(ServerPlugin);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["manifest"],"sources":["../../../src/plugins/server/index.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { Server as HTTPServer } from \"node:http\";\nimport path from \"node:path\";\nimport dotenv from \"dotenv\";\nimport express from \"express\";\nimport getPort, { portNumbers } from \"get-port\";\nimport type { PluginClientConfigs, PluginPhase } from \"shared\";\nimport { ServerError } from \"../../errors\";\nimport { TelemetryReporter } from \"../../internal-telemetry\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport type { PluginManifest } from \"../../registry\";\nimport { instrumentations } from \"../../telemetry\";\nimport { sanitizeClientConfig } from \"./client-config-sanitizer\";\nimport manifest from \"./manifest.json\";\nimport { RemoteTunnelController } from \"./remote-tunnel/remote-tunnel-controller\";\nimport { StaticServer } from \"./static-server\";\nimport type { ServerConfig } from \"./types\";\nimport { getRoutes, type PluginEndpoints, printRoutes } from \"./utils\";\nimport { ViteDevServer } from \"./vite-dev-server\";\n\ndotenv.config({ path: path.resolve(process.cwd(), \"./.env\") });\n\nconst logger = createLogger(\"server\");\n\n/** Dev-only: try `requested` then consecutive ports (see `get-port` `portNumbers`). */\nconst devListenPortSpan = 100;\n\n/**\n * Server plugin for the AppKit.\n *\n * This plugin is responsible for starting the server and serving the static files.\n * It also handles the remote tunneling for development purposes.\n *\n * The server is started automatically by `createApp` after all plugins are set up\n * and the optional `onPluginsReady` callback has run.\n *\n * @example\n * ```ts\n * createApp({\n * plugins: [server(), analytics({})],\n * onPluginsReady(appkit) {\n * appkit.server.extend((app) => {\n * app.get(\"/custom\", (_req, res) => res.json({ ok: true }));\n * });\n * },\n * });\n * ```\n *\n */\nexport class ServerPlugin extends Plugin {\n public static DEFAULT_CONFIG = {\n host: process.env.FLASK_RUN_HOST || \"0.0.0.0\",\n port: Number(process.env.DATABRICKS_APP_PORT) || 8000,\n };\n\n /** Plugin manifest declaring metadata and resource requirements */\n static manifest = manifest as PluginManifest<\"server\">;\n private serverApplication: express.Application;\n private server: HTTPServer | null;\n private viteDevServer?: ViteDevServer;\n private remoteTunnelController?: RemoteTunnelController;\n /** Bound listen port after optional dev-time resolution. */\n private resolvedListenPort?: number;\n protected declare config: ServerConfig;\n private serverExtensions: ((app: express.Application) => void)[] = [];\n private rawBodyPaths: Set<string> = new Set();\n static phase: PluginPhase = \"deferred\";\n\n constructor(config: ServerConfig) {\n super(config);\n if (\"autoStart\" in config) {\n throw new ServerError(\n \"server({ autoStart }) has been removed. \" +\n \"The server is now started automatically by createApp.\\n\\n\" +\n \"Run `npx appkit codemod on-plugins-ready --write` to auto-migrate.\",\n );\n }\n this.config = config;\n this.serverApplication = express();\n this.server = null;\n this.serverExtensions = [];\n }\n\n attachContext(deps: Parameters<Plugin[\"attachContext\"]>[0] = {}): void {\n super.attachContext(deps);\n this.telemetry.registerInstrumentations([\n instrumentations.http,\n instrumentations.express,\n ]);\n this.context?.registerAsRouteTarget(this);\n }\n\n /** Setup the server plugin. */\n async setup() {}\n\n /** Get the server configuration. */\n getConfig() {\n const { plugins: _plugins, ...config } = this.config;\n\n return config;\n }\n\n /**\n * Start the server.\n *\n * This method starts the server and sets up the frontend.\n * It also sets up the remote tunneling if enabled.\n *\n * @returns The express application.\n */\n async start(): Promise<express.Application> {\n this.serverApplication.use(requestMetricsMiddleware);\n this.serverApplication.use(\n express.json({\n // Express's stock 100kb default is too tight for modern apps —\n // agent chat payloads and any base64-encoded upload (e.g. the\n // dev playground's smart-dashboard \"save view\" screenshot at\n // ~105KB) blow past it instantly. Raise to 1mb by default and\n // let consumers tune via `server({ bodyLimit })` if they need\n // more headroom.\n limit: this.config.bodyLimit ?? \"1mb\",\n type: (req) => {\n // Skip JSON parsing for routes that declared skipBodyParsing\n // (e.g. file uploads where the raw body must flow through).\n // rawBodyPaths is populated by extendRoutes() below; the type\n // callback runs per-request so the set is already filled.\n const urlPath = req.url?.split(\"?\")[0];\n if (urlPath && this.rawBodyPaths.has(urlPath)) return false;\n const ct = req.headers[\"content-type\"] ?? \"\";\n return ct.includes(\"json\");\n },\n }),\n );\n\n const { endpoints, pluginConfigs } = await this.extendRoutes();\n\n for (const extension of this.serverExtensions) {\n extension(this.serverApplication);\n }\n\n // register remote tunnel controller (before static/vite)\n this.remoteTunnelController = new RemoteTunnelController(\n this.devFileReader,\n );\n this.serverApplication.use(this.remoteTunnelController.middleware);\n\n await this.setupFrontend(endpoints, pluginConfigs);\n\n const listenPort = await this.resolveListenPort();\n\n const server = this.serverApplication.listen(\n listenPort,\n this.config.host ?? ServerPlugin.DEFAULT_CONFIG.host,\n () => this.logStartupInfo(),\n );\n\n this.server = server;\n\n // attach server to remote tunnel controller\n this.remoteTunnelController.setServer(server);\n\n process.on(\"SIGTERM\", () => this._gracefulShutdown());\n process.on(\"SIGINT\", () => this._gracefulShutdown());\n\n if (process.env.NODE_ENV === \"development\") {\n const allRoutes = getRoutes(this.serverApplication._router.stack);\n printRoutes(allRoutes);\n }\n return this.serverApplication;\n }\n\n /**\n * Get the low level node.js http server instance.\n *\n * Only use this method if you need to access the server instance for advanced usage like a custom websocket server, etc.\n *\n * @throws {Error} If the server has not started yet.\n * @returns {HTTPServer} The server instance.\n */\n getServer(): HTTPServer {\n if (!this.server) {\n throw ServerError.notStarted();\n }\n\n return this.server;\n }\n\n /**\n * Extend the server with custom routes or middleware.\n *\n * Call this inside the `onPluginsReady` callback of `createApp` to register\n * custom Express routes or middleware before the server starts listening.\n *\n * @param fn - A function that receives the express application.\n * @returns The server plugin instance for chaining.\n */\n extend(fn: (app: express.Application) => void) {\n this.serverExtensions.push(fn);\n return this;\n }\n\n /**\n * Register a server extension from another plugin during setup.\n * Unlike extend(), this is designed for internal plugin-to-plugin\n * coordination where extensions are registered before the server starts\n * listening — typically called by PluginContext when flushing buffered routes.\n */\n addExtension(fn: (app: express.Application) => void) {\n this.serverExtensions.push(fn);\n }\n\n /**\n * Setup the routes with the plugins.\n *\n * This method goes through all the plugins and injects the routes into the server application.\n * Returns a map of plugin names to their registered named endpoints,\n * and a map of plugin names to their client-exposed configs.\n */\n private async extendRoutes(): Promise<{\n endpoints: PluginEndpoints;\n pluginConfigs: PluginClientConfigs;\n }> {\n const endpoints: PluginEndpoints = {};\n const pluginConfigs: PluginClientConfigs = {};\n\n const plugins = this.context?.getPlugins();\n if (!plugins || plugins.size === 0) return { endpoints, pluginConfigs };\n\n this.serverApplication.get(\"/health\", (_, res) => {\n res.status(200).json({ status: \"ok\" });\n });\n this.registerEndpoint(\"health\", \"/health\");\n\n for (const plugin of plugins.values()) {\n if (EXCLUDED_PLUGINS.includes(plugin.name)) continue;\n\n if (plugin?.injectRoutes && typeof plugin.injectRoutes === \"function\") {\n const router = express.Router();\n\n plugin.injectRoutes(router);\n\n const basePath = `/api/${plugin.name}`;\n this.serverApplication.use(basePath, router);\n\n endpoints[plugin.name] = plugin.getEndpoints();\n\n // Collect paths that should skip body parsing\n if (\n plugin.getSkipBodyParsingPaths &&\n typeof plugin.getSkipBodyParsingPaths === \"function\"\n ) {\n for (const p of plugin.getSkipBodyParsingPaths()) {\n this.rawBodyPaths.add(p);\n }\n }\n }\n\n if (typeof plugin.clientConfig === \"function\") {\n try {\n const raw = plugin.clientConfig();\n if (raw != null) {\n const sanitized = sanitizeClientConfig(plugin.name, raw);\n if (Object.keys(sanitized).length > 0) {\n pluginConfigs[plugin.name] = sanitized;\n }\n }\n } catch (error) {\n logger.error(\n \"Plugin '%s' clientConfig() failed, skipping its config: %O\",\n plugin.name,\n error,\n );\n }\n }\n }\n\n return { endpoints, pluginConfigs };\n }\n\n /**\n * Setup frontend serving based on environment:\n * - If staticPath is explicitly provided: use static server\n * - Dev mode (no staticPath): Vite for HMR\n * - Production (no staticPath): Static files auto-detected\n */\n private async setupFrontend(\n endpoints: PluginEndpoints,\n pluginConfigs: PluginClientConfigs,\n ) {\n const isDev = process.env.NODE_ENV === \"development\";\n const hasExplicitStaticPath = this.config.staticPath !== undefined;\n\n // explict static path provided\n if (hasExplicitStaticPath) {\n const staticServer = new StaticServer(\n this.serverApplication,\n this.config.staticPath as string,\n endpoints,\n pluginConfigs,\n );\n staticServer.setup();\n return;\n }\n\n // auto-detection based on environment\n if (isDev) {\n this.viteDevServer = new ViteDevServer(\n this.serverApplication,\n endpoints,\n pluginConfigs,\n );\n await this.viteDevServer.setup();\n return;\n }\n\n // auto-detection based on static path\n const staticPath = ServerPlugin.findStaticPath();\n if (staticPath) {\n const staticServer = new StaticServer(\n this.serverApplication,\n staticPath,\n endpoints,\n pluginConfigs,\n );\n\n staticServer.setup();\n }\n }\n\n private static findStaticPath() {\n const staticPaths = [\"dist\", \"client/dist\", \"build\", \"public\", \"out\"];\n const cwd = process.cwd();\n for (const p of staticPaths) {\n const fullPath = path.resolve(cwd, p);\n if (fs.existsSync(path.resolve(fullPath, \"index.html\"))) {\n logger.debug(\"Static files: serving from %s\", fullPath);\n return fullPath;\n }\n }\n return undefined;\n }\n\n /**\n * In development, prefers {@link ServerConfig.port} / env / default (8000), then\n * scans upward using `get-port`'s `portNumbers()` on the listen host until one binds.\n * In non-development, uses config / env / default only (no fallback).\n */\n private async resolveListenPort(): Promise<number> {\n const requested = this.config.port ?? ServerPlugin.DEFAULT_CONFIG.port;\n\n if (process.env.NODE_ENV !== \"development\") {\n this.resolvedListenPort = requested;\n return requested;\n }\n\n const host = this.config.host ?? ServerPlugin.DEFAULT_CONFIG.host;\n const upper = Math.min(requested + devListenPortSpan - 1, 65_535);\n const port = await getPort({\n host,\n port: portNumbers(requested, upper),\n });\n this.resolvedListenPort = port;\n if (port !== requested) {\n logger.info(\"Port %d was busy, picking %d\", requested, port);\n }\n return port;\n }\n\n private logStartupInfo() {\n const isDev = process.env.NODE_ENV === \"development\";\n const hasExplicitStaticPath = this.config.staticPath !== undefined;\n const port =\n this.resolvedListenPort ??\n this.config.port ??\n ServerPlugin.DEFAULT_CONFIG.port;\n const host = this.config.host ?? ServerPlugin.DEFAULT_CONFIG.host;\n\n logger.info(\"Server running on http://%s:%d\", host, port);\n\n if (hasExplicitStaticPath) {\n logger.info(\"Mode: static (%s)\", this.config.staticPath);\n } else if (isDev) {\n logger.info(\"Mode: development (Vite HMR)\");\n } else {\n logger.info(\"Mode: production (static)\");\n }\n\n const remoteServerController = this.remoteTunnelController;\n if (!remoteServerController) {\n logger.debug(\"Remote tunnel: disabled (controller not initialized)\");\n } else {\n logger.debug(\n \"Remote tunnel: %s; %s\",\n remoteServerController.isAllowedByEnv() ? \"allowed\" : \"blocked\",\n remoteServerController.isActive() ? \"active\" : \"inactive\",\n );\n }\n }\n\n private async _gracefulShutdown() {\n logger.info(\"Starting graceful shutdown...\");\n\n if (this.viteDevServer) {\n await this.viteDevServer.close();\n }\n\n if (this.remoteTunnelController) {\n this.remoteTunnelController.cleanup();\n }\n\n TelemetryReporter.getInstance()?.stop();\n\n // 1. abort active operations from plugins\n const shutdownPlugins = this.context?.getPlugins();\n if (shutdownPlugins) {\n for (const plugin of shutdownPlugins.values()) {\n if (plugin.abortActiveOperations) {\n try {\n plugin.abortActiveOperations();\n } catch (err) {\n logger.error(\n \"Error aborting operations for plugin %s: %O\",\n plugin.name,\n err,\n );\n }\n }\n }\n }\n\n // 2. close the server\n if (this.server) {\n this.server.close(() => {\n logger.debug(\"Server closed gracefully\");\n process.exit(0);\n });\n\n // 3. timeout to force shutdown after 15 seconds\n setTimeout(() => {\n logger.debug(\"Force shutdown after timeout\");\n process.exit(1);\n }, 15000);\n } else {\n process.exit(0);\n }\n }\n\n /**\n * Returns the public exports for the server plugin.\n * Exposes server management methods.\n */\n exports() {\n const self = this;\n return {\n /** Extend the server with custom routes or middleware */\n extend(fn: (app: express.Application) => void) {\n self.extend(fn);\n return this;\n },\n /** Get the underlying HTTP server instance */\n getServer: this.getServer,\n /** Get the server configuration */\n getConfig: this.getConfig,\n /** @deprecated Server is now started automatically by createApp. */\n start() {\n throw new ServerError(\n \"server.start() has been removed. Use the onPluginsReady callback instead:\\n\\n\" +\n \" createApp({\\n\" +\n \" plugins: [server(), ...],\\n\" +\n \" onPluginsReady(appkit) {\\n\" +\n \" appkit.server.extend(...);\\n\" +\n \" },\\n\" +\n \" });\\n\\n\" +\n \"Run `npx appkit codemod on-plugins-ready --write` to auto-migrate.\",\n );\n },\n };\n }\n}\n\nconst EXCLUDED_PLUGINS: string[] = [ServerPlugin.manifest.name];\n\n/** @internal Exported for unit tests. */\nexport function requestMetricsMiddleware(\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n) {\n const startMs = Date.now();\n res.on(\"finish\", () => {\n const reporter = TelemetryReporter.getInstance();\n if (!reporter) return;\n const routePath = (req.route as { path?: string } | undefined)?.path;\n if (!routePath) return;\n const baseUrl = req.baseUrl ?? \"\";\n const template = `${baseUrl}${routePath}`;\n reporter.recordRequest(\n req.method,\n template,\n res.statusCode,\n Date.now() - startMs,\n );\n });\n next();\n}\n\n/**\n * @internal\n */\nexport const server = toPlugin(ServerPlugin);\n// Export manifest and types\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAqBA,OAAO,OAAO,EAAE,MAAM,KAAK,QAAQ,QAAQ,KAAK,EAAE,SAAS,EAAE,CAAC;AAE9D,MAAM,SAAS,aAAa,SAAS;;AAGrC,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;AAwB1B,IAAa,eAAb,MAAa,qBAAqB,OAAO;CACvC,OAAc,iBAAiB;EAC7B,MAAM,QAAQ,IAAI,kBAAkB;EACpC,MAAM,OAAO,QAAQ,IAAI,oBAAoB,IAAI;EAClD;;CAGD,OAAO,WAAWA;CAClB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;;CAER,AAAQ;CAER,AAAQ,mBAA2D,EAAE;CACrE,AAAQ,+BAA4B,IAAI,KAAK;CAC7C,OAAO,QAAqB;CAE5B,YAAY,QAAsB;AAChC,QAAM,OAAO;AACb,MAAI,eAAe,OACjB,OAAM,IAAI,YACR,sKAGD;AAEH,OAAK,SAAS;AACd,OAAK,oBAAoB,SAAS;AAClC,OAAK,SAAS;AACd,OAAK,mBAAmB,EAAE;;CAG5B,cAAc,OAA+C,EAAE,EAAQ;AACrE,QAAM,cAA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A;CACA,MAAM,UAAU,KAAK,KAAK;AAC1B,KAAI,GAAG,gBAAgB;EACrB,MAAM,WAAW,kBAAkB,aAAa;AAChD,MAAI,CAAC,SAAU;EACf,MAAM,YAAa,IAAI,OAAyC;AAChE,MAAI,CAAC,UAAW;EAEhB,MAAM,WAAW,GADD,IAAI,WAAW,KACD;AAC9B,WAAS,cACP,IAAI,QACJ,UACA,IAAI,YACJ,KAAK,KAAK,GAAG,QACd;GACD;AACF,OAAM;;;;;AAMR,MAAa,SAAS,SAAS,aAAa"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["manifest"],"sources":["../../../src/plugins/server/index.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport type { Server as HTTPServer } from \"node:http\";\nimport path from \"node:path\";\nimport dotenv from \"dotenv\";\nimport express from \"express\";\nimport getPort, { portNumbers } from \"get-port\";\nimport type { PluginClientConfigs, PluginPhase } from \"shared\";\nimport { AppKitError, ServerError } from \"../../errors\";\nimport { TelemetryReporter } from \"../../internal-telemetry\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport type { PluginManifest } from \"../../registry\";\nimport { instrumentations } from \"../../telemetry\";\nimport { sanitizeClientConfig } from \"./client-config-sanitizer\";\nimport manifest from \"./manifest.json\";\nimport { RemoteTunnelController } from \"./remote-tunnel/remote-tunnel-controller\";\nimport { StaticServer } from \"./static-server\";\nimport type { ServerConfig } from \"./types\";\nimport { getRoutes, type PluginEndpoints, printRoutes } from \"./utils\";\nimport { ViteDevServer } from \"./vite-dev-server\";\n\ndotenv.config({ path: path.resolve(process.cwd(), \"./.env\") });\n\nconst logger = createLogger(\"server\");\n\n/** Dev-only: try `requested` then consecutive ports (see `get-port` `portNumbers`). */\nconst devListenPortSpan = 100;\n\n/**\n * Server plugin for the AppKit.\n *\n * This plugin is responsible for starting the server and serving the static files.\n * It also handles the remote tunneling for development purposes.\n *\n * The server is started automatically by `createApp` after all plugins are set up\n * and the optional `onPluginsReady` callback has run.\n *\n * @example\n * ```ts\n * createApp({\n * plugins: [server(), analytics({})],\n * onPluginsReady(appkit) {\n * appkit.server.extend((app) => {\n * app.get(\"/custom\", (_req, res) => res.json({ ok: true }));\n * });\n * },\n * });\n * ```\n *\n */\nexport class ServerPlugin extends Plugin {\n public static DEFAULT_CONFIG = {\n host: process.env.FLASK_RUN_HOST || \"0.0.0.0\",\n port: Number(process.env.DATABRICKS_APP_PORT) || 8000,\n };\n\n /**\n * Budget for awaiting `server.close()` during shutdown. Bounded because\n * `closeAllConnections()` runs immediately before the await, so the close\n * is expected to resolve promptly; the core lifecycle manager's overall\n * force-exit timer is the ultimate backstop if it does not.\n */\n private static readonly SERVER_CLOSE_TIMEOUT_MS = 2_000;\n\n /** Plugin manifest declaring metadata and resource requirements */\n static manifest = manifest as PluginManifest<\"server\">;\n private serverApplication: express.Application;\n private server: HTTPServer | null;\n private viteDevServer?: ViteDevServer;\n private remoteTunnelController?: RemoteTunnelController;\n /** Bound listen port after optional dev-time resolution. */\n private resolvedListenPort?: number;\n protected declare config: ServerConfig;\n private serverExtensions: ((app: express.Application) => void)[] = [];\n private rawBodyPaths: Set<string> = new Set();\n /**\n * Resolves when `server.close()` completes. Created in\n * {@link abortActiveOperations} (which initiates the close) and awaited in\n * {@link closeRemainingConnections} after other plugins have drained.\n */\n private serverClosed?: Promise<void>;\n static phase: PluginPhase = \"deferred\";\n\n constructor(config: ServerConfig) {\n super(config);\n if (\"autoStart\" in config) {\n throw new ServerError(\n \"server({ autoStart }) has been removed. \" +\n \"The server is now started automatically by createApp.\\n\\n\" +\n \"Run `npx appkit codemod on-plugins-ready --write` to auto-migrate.\",\n );\n }\n this.config = config;\n this.serverApplication = express();\n this.server = null;\n this.serverExtensions = [];\n }\n\n attachContext(deps: Parameters<Plugin[\"attachContext\"]>[0] = {}): void {\n super.attachContext(deps);\n this.telemetry.registerInstrumentations([\n instrumentations.http,\n instrumentations.express,\n ]);\n this.context?.registerAsRouteTarget(this);\n }\n\n /** Setup the server plugin. */\n async setup() {}\n\n /** Get the server configuration. */\n getConfig() {\n const { plugins: _plugins, ...config } = this.config;\n\n return config;\n }\n\n /**\n * Start the server.\n *\n * This method starts the server and sets up the frontend.\n * It also sets up the remote tunneling if enabled.\n *\n * @returns The express application.\n */\n async start(): Promise<express.Application> {\n this.serverApplication.use(requestMetricsMiddleware);\n this.serverApplication.use(\n express.json({\n // Express's stock 100kb default is too tight for modern apps —\n // agent chat payloads and any base64-encoded upload (e.g. the\n // dev playground's smart-dashboard \"save view\" screenshot at\n // ~105KB) blow past it instantly. Raise to 1mb by default and\n // let consumers tune via `server({ bodyLimit })` if they need\n // more headroom.\n limit: this.config.bodyLimit ?? \"1mb\",\n type: (req) => {\n // Skip JSON parsing for routes that declared skipBodyParsing\n // (e.g. file uploads where the raw body must flow through).\n // rawBodyPaths is populated by extendRoutes() below; the type\n // callback runs per-request so the set is already filled.\n const urlPath = req.url?.split(\"?\")[0];\n if (urlPath && this.rawBodyPaths.has(urlPath)) return false;\n const ct = req.headers[\"content-type\"] ?? \"\";\n return ct.includes(\"json\");\n },\n }),\n );\n\n const { endpoints, pluginConfigs } = await this.extendRoutes();\n\n for (const extension of this.serverExtensions) {\n extension(this.serverApplication);\n }\n\n // register remote tunnel controller (before static/vite)\n this.remoteTunnelController = new RemoteTunnelController(\n this.devFileReader,\n );\n this.serverApplication.use(this.remoteTunnelController.middleware);\n\n await this.setupFrontend(endpoints, pluginConfigs);\n\n // Terminal error handler — registered after all routes, extensions, and\n // frontend middleware so that errors forwarded via next(err) from any of\n // them (e.g. async handler rejections forwarded by Plugin.route()) are\n // turned into JSON error responses instead of hanging the request.\n this.serverApplication.use(errorHandlerMiddleware);\n\n const listenPort = await this.resolveListenPort();\n\n const server = this.serverApplication.listen(\n listenPort,\n this.config.host ?? ServerPlugin.DEFAULT_CONFIG.host,\n () => this.logStartupInfo(),\n );\n\n this.server = server;\n\n // attach server to remote tunnel controller\n this.remoteTunnelController.setServer(server);\n\n // Graceful shutdown is orchestrated by the core LifecycleManager, which\n // owns the process signal handlers. This plugin only contributes its\n // HTTP concerns: it aborts/initiates the socket close in\n // abortActiveOperations(), drains dev servers in shutdown(), and force-\n // closes remaining sockets in the \"shutdown\" lifecycle hook below (which\n // fires after every plugin's shutdown() has run).\n this.context?.onLifecycle(\"shutdown\", () =>\n this.closeRemainingConnections(),\n );\n\n if (process.env.NODE_ENV === \"development\") {\n const allRoutes = getRoutes(this.serverApplication._router.stack);\n printRoutes(allRoutes);\n }\n return this.serverApplication;\n }\n\n /**\n * Get the low level node.js http server instance.\n *\n * Only use this method if you need to access the server instance for advanced usage like a custom websocket server, etc.\n *\n * @throws {Error} If the server has not started yet.\n * @returns {HTTPServer} The server instance.\n */\n getServer(): HTTPServer {\n if (!this.server) {\n throw ServerError.notStarted();\n }\n\n return this.server;\n }\n\n /**\n * Extend the server with custom routes or middleware.\n *\n * Call this inside the `onPluginsReady` callback of `createApp` to register\n * custom Express routes or middleware before the server starts listening.\n *\n * Note: async handlers registered directly on the app must handle their own\n * rejections — Express 4 does not forward rejected promises to the error\n * middleware. Errors passed explicitly to `next(err)` are formatted by the\n * terminal error middleware.\n *\n * @param fn - A function that receives the express application.\n * @returns The server plugin instance for chaining.\n */\n extend(fn: (app: express.Application) => void) {\n this.serverExtensions.push(fn);\n return this;\n }\n\n /**\n * Register a server extension from another plugin during setup.\n * Unlike extend(), this is designed for internal plugin-to-plugin\n * coordination where extensions are registered before the server starts\n * listening — typically called by PluginContext when flushing buffered routes.\n */\n addExtension(fn: (app: express.Application) => void) {\n this.serverExtensions.push(fn);\n }\n\n /**\n * Setup the routes with the plugins.\n *\n * This method goes through all the plugins and injects the routes into the server application.\n * Returns a map of plugin names to their registered named endpoints,\n * and a map of plugin names to their client-exposed configs.\n */\n private async extendRoutes(): Promise<{\n endpoints: PluginEndpoints;\n pluginConfigs: PluginClientConfigs;\n }> {\n const endpoints: PluginEndpoints = {};\n const pluginConfigs: PluginClientConfigs = {};\n\n const plugins = this.context?.getPlugins();\n if (!plugins || plugins.size === 0) return { endpoints, pluginConfigs };\n\n this.serverApplication.get(\"/health\", (_, res) => {\n res.status(200).json({ status: \"ok\" });\n });\n this.registerEndpoint(\"health\", \"/health\");\n\n for (const plugin of plugins.values()) {\n if (EXCLUDED_PLUGINS.includes(plugin.name)) continue;\n\n if (plugin?.injectRoutes && typeof plugin.injectRoutes === \"function\") {\n const router = express.Router();\n\n plugin.injectRoutes(router);\n\n const basePath = `/api/${plugin.name}`;\n this.serverApplication.use(basePath, router);\n\n endpoints[plugin.name] = plugin.getEndpoints();\n\n // Collect paths that should skip body parsing\n if (\n plugin.getSkipBodyParsingPaths &&\n typeof plugin.getSkipBodyParsingPaths === \"function\"\n ) {\n for (const p of plugin.getSkipBodyParsingPaths()) {\n this.rawBodyPaths.add(p);\n }\n }\n }\n\n if (typeof plugin.clientConfig === \"function\") {\n try {\n const raw = plugin.clientConfig();\n if (raw != null) {\n const sanitized = sanitizeClientConfig(plugin.name, raw);\n if (Object.keys(sanitized).length > 0) {\n pluginConfigs[plugin.name] = sanitized;\n }\n }\n } catch (error) {\n logger.error(\n \"Plugin '%s' clientConfig() failed, skipping its config: %O\",\n plugin.name,\n error,\n );\n }\n }\n }\n\n return { endpoints, pluginConfigs };\n }\n\n /**\n * Setup frontend serving based on environment:\n * - If staticPath is explicitly provided: use static server\n * - Dev mode (no staticPath): Vite for HMR\n * - Production (no staticPath): Static files auto-detected\n */\n private async setupFrontend(\n endpoints: PluginEndpoints,\n pluginConfigs: PluginClientConfigs,\n ) {\n const isDev = process.env.NODE_ENV === \"development\";\n const hasExplicitStaticPath = this.config.staticPath !== undefined;\n\n // explict static path provided\n if (hasExplicitStaticPath) {\n const staticServer = new StaticServer(\n this.serverApplication,\n this.config.staticPath as string,\n endpoints,\n pluginConfigs,\n );\n staticServer.setup();\n return;\n }\n\n // auto-detection based on environment\n if (isDev) {\n this.viteDevServer = new ViteDevServer(\n this.serverApplication,\n endpoints,\n pluginConfigs,\n );\n await this.viteDevServer.setup();\n return;\n }\n\n // auto-detection based on static path\n const staticPath = ServerPlugin.findStaticPath();\n if (staticPath) {\n const staticServer = new StaticServer(\n this.serverApplication,\n staticPath,\n endpoints,\n pluginConfigs,\n );\n\n staticServer.setup();\n }\n }\n\n private static findStaticPath() {\n const staticPaths = [\"dist\", \"client/dist\", \"build\", \"public\", \"out\"];\n const cwd = process.cwd();\n for (const p of staticPaths) {\n const fullPath = path.resolve(cwd, p);\n if (fs.existsSync(path.resolve(fullPath, \"index.html\"))) {\n logger.debug(\"Static files: serving from %s\", fullPath);\n return fullPath;\n }\n }\n return undefined;\n }\n\n /**\n * In development, prefers {@link ServerConfig.port} / env / default (8000), then\n * scans upward using `get-port`'s `portNumbers()` on the listen host until one binds.\n * In non-development, uses config / env / default only (no fallback).\n */\n private async resolveListenPort(): Promise<number> {\n const requested = this.config.port ?? ServerPlugin.DEFAULT_CONFIG.port;\n\n if (process.env.NODE_ENV !== \"development\") {\n this.resolvedListenPort = requested;\n return requested;\n }\n\n const host = this.config.host ?? ServerPlugin.DEFAULT_CONFIG.host;\n const upper = Math.min(requested + devListenPortSpan - 1, 65_535);\n const port = await getPort({\n host,\n port: portNumbers(requested, upper),\n });\n this.resolvedListenPort = port;\n if (port !== requested) {\n logger.info(\"Port %d was busy, picking %d\", requested, port);\n }\n return port;\n }\n\n private logStartupInfo() {\n const isDev = process.env.NODE_ENV === \"development\";\n const hasExplicitStaticPath = this.config.staticPath !== undefined;\n const port =\n this.resolvedListenPort ??\n this.config.port ??\n ServerPlugin.DEFAULT_CONFIG.port;\n const host = this.config.host ?? ServerPlugin.DEFAULT_CONFIG.host;\n\n logger.info(\"Server running on http://%s:%d\", host, port);\n\n if (hasExplicitStaticPath) {\n logger.info(\"Mode: static (%s)\", this.config.staticPath);\n } else if (isDev) {\n logger.info(\"Mode: development (Vite HMR)\");\n } else {\n logger.info(\"Mode: production (static)\");\n }\n\n const remoteServerController = this.remoteTunnelController;\n if (!remoteServerController) {\n logger.debug(\"Remote tunnel: disabled (controller not initialized)\");\n } else {\n logger.debug(\n \"Remote tunnel: %s; %s\",\n remoteServerController.isAllowedByEnv() ? \"allowed\" : \"blocked\",\n remoteServerController.isActive() ? \"active\" : \"inactive\",\n );\n }\n }\n\n /**\n * Cancel in-flight work and begin closing the HTTP server.\n *\n * Runs in the first phase of the core LifecycleManager's graceful shutdown,\n * before any plugin `shutdown()` hook. In addition to the base behavior\n * (aborting SSE streams), it stops the server accepting new connections and\n * drops idle keep-alive sockets — without `closeIdleConnections()`, a\n * connected browser would pin `server.close()` open until the force-exit\n * timer fires. The close is only *initiated* here; the returned promise is\n * awaited later in {@link closeRemainingConnections} so peer plugins can\n * still drain in-flight requests through the server first.\n */\n abortActiveOperations(): void {\n super.abortActiveOperations();\n\n if (this.server) {\n const server = this.server;\n this.serverClosed = new Promise((resolve) => {\n server.close(() => resolve());\n });\n server.closeIdleConnections();\n }\n }\n\n /**\n * Drain the dev-only servers as this plugin's `shutdown()` hook.\n *\n * Runs concurrently with the other plugins' hooks during graceful shutdown.\n * These are no-ops in production (neither is created), so this hook is\n * effectively dev-only.\n */\n async shutdown(): Promise<void> {\n if (this.viteDevServer) {\n await this.viteDevServer.close();\n }\n if (this.remoteTunnelController) {\n this.remoteTunnelController.cleanup();\n }\n }\n\n /**\n * Force-close whatever sockets remain and await the server close.\n *\n * Registered on the `\"shutdown\"` lifecycle event in {@link start}, so it\n * fires after every plugin's `shutdown()` hook has run — meaning any\n * in-flight request a peer plugin was draining has already completed.\n * `closeAllConnections()` destroys the leftover sockets (aborted SSE\n * responses, keep-alive connections) synchronously so the pending\n * `server.close()` can complete; the await is bounded because the close is\n * expected to resolve promptly once the sockets are gone.\n */\n private async closeRemainingConnections(): Promise<void> {\n if (this.server) {\n this.server.closeAllConnections();\n }\n if (!this.serverClosed) return;\n\n await Promise.race([\n this.serverClosed,\n new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, ServerPlugin.SERVER_CLOSE_TIMEOUT_MS);\n timer.unref();\n }),\n ]);\n logger.debug(\"Server closed gracefully\");\n }\n\n /**\n * Returns the public exports for the server plugin.\n * Exposes server management methods.\n */\n exports() {\n const self = this;\n return {\n /** Extend the server with custom routes or middleware */\n extend(fn: (app: express.Application) => void) {\n self.extend(fn);\n return this;\n },\n /** Get the underlying HTTP server instance */\n getServer: this.getServer,\n /** Get the server configuration */\n getConfig: this.getConfig,\n /** @deprecated Server is now started automatically by createApp. */\n start() {\n throw new ServerError(\n \"server.start() has been removed. Use the onPluginsReady callback instead:\\n\\n\" +\n \" createApp({\\n\" +\n \" plugins: [server(), ...],\\n\" +\n \" onPluginsReady(appkit) {\\n\" +\n \" appkit.server.extend(...);\\n\" +\n \" },\\n\" +\n \" });\\n\\n\" +\n \"Run `npx appkit codemod on-plugins-ready --write` to auto-migrate.\",\n );\n },\n };\n }\n}\n\nconst EXCLUDED_PLUGINS: string[] = [ServerPlugin.manifest.name];\n\n/** @internal Exported for unit tests. */\nexport function requestMetricsMiddleware(\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n) {\n const startMs = Date.now();\n res.on(\"finish\", () => {\n const reporter = TelemetryReporter.getInstance();\n if (!reporter) return;\n const routePath = (req.route as { path?: string } | undefined)?.path;\n if (!routePath) return;\n const baseUrl = req.baseUrl ?? \"\";\n const template = `${baseUrl}${routePath}`;\n reporter.recordRequest(\n req.method,\n template,\n res.statusCode,\n Date.now() - startMs,\n );\n });\n next();\n}\n\n/**\n * Narrow an unknown thrown value to an Error that carries a numeric\n * `statusCode` property in the HTTP error range (e.g. `ApiError` from\n * `@databricks/sdk-experimental`).\n */\nfunction hasHttpStatusCode(\n error: unknown,\n): error is Error & { statusCode: number } {\n if (!(error instanceof Error) || !(\"statusCode\" in error)) return false;\n const statusCode = error.statusCode;\n return (\n typeof statusCode === \"number\" &&\n Number.isInteger(statusCode) &&\n statusCode >= 400 &&\n statusCode <= 599\n );\n}\n\n/**\n * Terminal Express error-handling middleware.\n *\n * Converts errors forwarded via `next(err)` (including async handler\n * rejections forwarded by `Plugin.route()`) into JSON error responses,\n * following the same status/message conventions as `Plugin.execute()`:\n * - errors carrying an HTTP `statusCode` (including `AppKitError`) → that\n * status; 5xx messages are masked in production to avoid leaking internals\n * - anything else → 500 with a generic message in production\n *\n * 4xx errors are expected client errors (e.g. missing auth headers) and are\n * logged at `warn` with just the message; 5xx/unknown errors are logged at\n * `error` with the full error.\n *\n * @internal Exported for unit tests.\n */\nexport function errorHandlerMiddleware(\n err: unknown,\n req: express.Request,\n res: express.Response,\n next: express.NextFunction,\n) {\n const httpError =\n err instanceof AppKitError || hasHttpStatusCode(err) ? err : null;\n const statusCode = httpError ? httpError.statusCode : 500;\n const isClientError = statusCode < 500;\n\n if (isClientError) {\n logger.warn(\n \"Request failed for %s %s with status %d: %s\",\n req.method,\n req.originalUrl,\n statusCode,\n err instanceof Error ? err.message : String(err),\n );\n } else {\n logger.error(\n \"Unhandled error for %s %s: %O\",\n req.method,\n req.originalUrl,\n // toJSON() redacts sensitive context fields; %O on a raw AppKitError\n // would enumerate them unredacted.\n err instanceof AppKitError ? err.toJSON() : err,\n );\n }\n\n if (res.headersSent) {\n next(err);\n return;\n }\n\n const isDev = process.env.NODE_ENV !== \"production\";\n const message = err instanceof Error ? err.message : \"Server error\";\n\n res.status(statusCode).json({\n error: isDev || isClientError ? message : \"Server error\",\n });\n}\n\n/**\n * @internal\n */\nexport const server = toPlugin(ServerPlugin);\n// Export manifest and types\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,OAAO,OAAO,EAAE,MAAM,KAAK,QAAQ,QAAQ,KAAK,EAAE,SAAS,EAAE,CAAC;AAE9D,MAAM,SAAS,aAAa,SAAS;;AAGrC,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;AAwB1B,IAAa,eAAb,MAAa,qBAAqB,OAAO;CACvC,OAAc,iBAAiB;EAC7B,MAAM,QAAQ,IAAI,kBAAkB;EACpC,MAAM,OAAO,QAAQ,IAAI,oBAAoB,I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,iCACA,IAAI,QACJ,IAAI,aAGJ,eAAe,cAAc,IAAI,QAAQ,GAAG,IAC7C;AAGH,KAAI,IAAI,aAAa;AACnB,OAAK,IAAI;AACT;;CAGF,MAAM,QAAQ,QAAQ,IAAI,aAAa;CACvC,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AAErD,KAAI,OAAO,WAAW,CAAC,KAAK,EAC1B,OAAO,SAAS,gBAAgB,UAAU,gBAC3C,CAAC;;;;;AAMJ,MAAa,SAAS,SAAS,aAAa"}
|
|
@@ -95,7 +95,7 @@ declare class ResourceRegistry {
|
|
|
95
95
|
* const result = registry.validate();
|
|
96
96
|
*
|
|
97
97
|
* if (!result.valid) {
|
|
98
|
-
* console.error(
|
|
98
|
+
* console.error(ResourceRegistry.formatMissingResources(result.missing));
|
|
99
99
|
* }
|
|
100
100
|
* ```
|
|
101
101
|
*/
|
|
@@ -112,6 +112,14 @@ declare class ResourceRegistry {
|
|
|
112
112
|
* @throws {ConfigurationError} In production when required resources are missing, or in dev when APPKIT_STRICT_VALIDATION=true
|
|
113
113
|
*/
|
|
114
114
|
enforceValidation(): ValidationResult;
|
|
115
|
+
/**
|
|
116
|
+
* Env var names for an entry's fields that are actually unset (undefined or
|
|
117
|
+
* empty), skipping fields that declare no env var (e.g. discovery-only
|
|
118
|
+
* fields resolved at deploy time). Mirrors the resolution check in
|
|
119
|
+
* {@link validate} so error output lists exactly what the caller must set —
|
|
120
|
+
* not every field on the resource.
|
|
121
|
+
*/
|
|
122
|
+
private static unsetEnvVars;
|
|
115
123
|
/**
|
|
116
124
|
* Formats missing resources into a human-readable error message.
|
|
117
125
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-registry.d.ts","names":[],"sources":["../../src/registry/resource-registry.ts"],"mappings":";;;;;;;;;cAqDa,gBAAA;EAAA,QACH,SAAA;
|
|
1
|
+
{"version":3,"file":"resource-registry.d.ts","names":[],"sources":["../../src/registry/resource-registry.ts"],"mappings":";;;;;;;;;cAqDa,gBAAA;EAAA,QACH,SAAA;EAoZsC;;;;;;;;;;;;EAtYvC,QAAA,CAAS,MAAA,UAAgB,QAAA,EAAU,mBAAA;EAiKnC;;;;;;;EAtIA,gBAAA,CACL,UAAA,EAAY,UAAA,CAAW,iBAAA;EAyKlB;;;;EAAA,QAjIC,cAAA;EAqJD;;;;;;EAxDA,MAAA,CAAA,GAAU,aAAA;EAgNH;;;;;;;EArMP,GAAA,CAAI,IAAA,UAAc,WAAA,WAAsB,aAAA;;;;;EAQxC,KAAA,CAAA;;;;EAOA,IAAA,CAAA;;;;;;;EAUA,WAAA,CAAY,UAAA,WAAqB,aAAA;;;;;;EAWjC,WAAA,CAAA,GAAe,aAAA;;;;;;EASf,WAAA,CAAA,GAAe,aAAA;;;;;;;;;;;;;;;;;;;;;;EAyBf,QAAA,CAAA,GAAY,gBAAA;;;;;;;;;;;;EA+DZ,iBAAA,CAAA,GAAqB,gBAAA;;;;;;;;iBA8Cb,YAAA;;;;;;;SAkBD,sBAAA,CAAuB,OAAA,EAAS,aAAA;;;;;;;;SAqBhC,sBAAA,CAAuB,OAAA,EAAS,aAAA;AAAA"}
|