@databricks/appkit 0.72.0 → 0.74.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 +24 -0
- package/NOTICE.md +1 -0
- package/dist/appkit/package.js +1 -1
- package/dist/beta.d.ts +11 -8
- package/dist/beta.js +7 -6
- package/dist/cli/commands/agent/eval.js +85 -16
- package/dist/cli/commands/agent/eval.js.map +1 -1
- package/dist/connectors/index.js +1 -1
- package/dist/connectors/mlflow/auth.d.ts +11 -1
- package/dist/connectors/mlflow/auth.d.ts.map +1 -1
- package/dist/connectors/mlflow/auth.js +22 -2
- package/dist/connectors/mlflow/auth.js.map +1 -1
- package/dist/connectors/mlflow/index.d.ts +2 -0
- package/dist/database/errors.js +15 -5
- package/dist/database/errors.js.map +1 -1
- package/dist/database/runtime/data-path.d.ts +7 -0
- package/dist/database/runtime/data-path.d.ts.map +1 -0
- package/dist/database/runtime/data-path.js.map +1 -1
- package/dist/database/runtime/engine/drizzle-data-path.js +7 -5
- package/dist/database/runtime/engine/drizzle-data-path.js.map +1 -1
- package/dist/database/schema-builder/define-schema.d.ts +1 -1
- package/dist/database/schema-builder/define-schema.js +1 -1
- package/dist/database/schema-builder/define-schema.js.map +1 -1
- package/dist/errors/database-validation.d.ts +23 -0
- package/dist/errors/database-validation.d.ts.map +1 -0
- package/dist/errors/database-validation.js +24 -0
- package/dist/errors/database-validation.js.map +1 -0
- package/dist/errors/index.js +1 -0
- package/dist/evals/dataset.d.ts +49 -0
- package/dist/evals/dataset.d.ts.map +1 -0
- package/dist/evals/dataset.js +51 -0
- package/dist/evals/dataset.js.map +1 -0
- package/dist/evals/define-eval.d.ts +4 -2
- package/dist/evals/define-eval.d.ts.map +1 -1
- package/dist/evals/define-eval.js +5 -1
- package/dist/evals/define-eval.js.map +1 -1
- package/dist/evals/discover.d.ts +15 -1
- package/dist/evals/discover.d.ts.map +1 -1
- package/dist/evals/discover.js +26 -2
- package/dist/evals/discover.js.map +1 -1
- package/dist/evals/http-driver.d.ts.map +1 -1
- package/dist/evals/http-driver.js +82 -55
- package/dist/evals/http-driver.js.map +1 -1
- package/dist/evals/index.d.ts +14 -0
- package/dist/evals/index.js +6 -5
- package/dist/evals/judge.d.ts +1 -0
- package/dist/evals/judge.d.ts.map +1 -1
- package/dist/evals/mlflow-report.d.ts +1 -0
- package/dist/evals/mlflow-report.d.ts.map +1 -1
- package/dist/evals/mlflow-run.d.ts +2 -0
- package/dist/evals/mlflow-run.d.ts.map +1 -1
- package/dist/evals/report.d.ts +16 -1
- package/dist/evals/report.d.ts.map +1 -1
- package/dist/evals/report.js +64 -2
- package/dist/evals/report.js.map +1 -1
- package/dist/evals/run-eval.d.ts +8 -0
- package/dist/evals/run-eval.d.ts.map +1 -1
- package/dist/evals/run-eval.js +54 -5
- package/dist/evals/run-eval.js.map +1 -1
- package/dist/evals/run-evals.d.ts +41 -3
- package/dist/evals/run-evals.d.ts.map +1 -1
- package/dist/evals/run-evals.js +215 -34
- package/dist/evals/run-evals.js.map +1 -1
- package/dist/evals/types.d.ts +80 -6
- package/dist/evals/types.d.ts.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/plugin/plugin.js +1 -1
- package/dist/plugin/plugin.js.map +1 -1
- package/dist/plugins/database/crud/contract.js +17 -8
- package/dist/plugins/database/crud/contract.js.map +1 -1
- package/dist/plugins/database/crud/exposure.js +63 -22
- package/dist/plugins/database/crud/exposure.js.map +1 -1
- package/dist/plugins/database/crud/request.js +50 -0
- package/dist/plugins/database/crud/request.js.map +1 -0
- package/dist/plugins/database/crud/response.js +77 -0
- package/dist/plugins/database/crud/response.js.map +1 -0
- package/dist/plugins/database/crud/routes.js +71 -52
- package/dist/plugins/database/crud/routes.js.map +1 -1
- package/dist/plugins/database/database.d.ts +6 -4
- package/dist/plugins/database/database.d.ts.map +1 -1
- package/dist/plugins/database/database.js +46 -16
- package/dist/plugins/database/database.js.map +1 -1
- package/dist/plugins/database/defaults.js +5 -1
- package/dist/plugins/database/defaults.js.map +1 -1
- package/dist/plugins/database/entity-client.js +143 -10
- package/dist/plugins/database/entity-client.js.map +1 -1
- package/dist/plugins/database/entity-types.d.ts +1 -1
- package/dist/plugins/database/hooks.d.ts +38 -0
- package/dist/plugins/database/hooks.d.ts.map +1 -0
- package/dist/plugins/database/index.d.ts +3 -2
- package/dist/plugins/database/lifecycle.js +67 -28
- package/dist/plugins/database/lifecycle.js.map +1 -1
- package/dist/plugins/database/scope.js +58 -0
- package/dist/plugins/database/scope.js.map +1 -0
- package/dist/plugins/database/types.d.ts +40 -12
- package/dist/plugins/database/types.d.ts.map +1 -1
- package/dist/plugins/server/index.js +2 -2
- package/dist/plugins/server/index.js.map +1 -1
- package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js +3 -3
- package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js.map +1 -1
- package/dist/plugins/server/static-server.js +3 -3
- package/dist/plugins/server/static-server.js.map +1 -1
- package/dist/plugins/server/utils.js +3 -3
- package/dist/plugins/server/utils.js.map +1 -1
- package/dist/plugins/server/vite-dev-server.js +4 -4
- package/dist/plugins/server/vite-dev-server.js.map +1 -1
- package/dist/shared/src/schemas/manifest.d.ts +87 -87
- package/dist/type-generator/database/generate.js +3 -3
- package/dist/type-generator/database/generate.js.map +1 -1
- package/dist/type-generator/migration.js +2 -2
- package/dist/type-generator/migration.js.map +1 -1
- package/dist/type-generator/serving/server-file-extractor.js +3 -3
- package/dist/type-generator/serving/server-file-extractor.js.map +1 -1
- package/docs/api/appkit/Class.AppKitError.md +1 -0
- package/docs/api/appkit/Class.DatabaseValidationError.md +191 -0
- package/docs/api/appkit/Function.defineEvalConfig.md +18 -0
- package/docs/api/appkit/Function.defineSchema.md +1 -1
- package/docs/api/appkit/Function.discoverEvalConfigs.md +18 -0
- package/docs/api/appkit/Function.formatResultsJUnit.md +18 -0
- package/docs/api/appkit/Function.formatResultsJson.md +18 -0
- package/docs/api/appkit/Function.readEvalDataset.md +21 -0
- package/docs/api/appkit/Function.resolveWorkspaceClient.md +18 -0
- package/docs/api/appkit/Function.runWithRetries.md +28 -0
- package/docs/api/appkit/Function.userTurns.md +20 -0
- package/docs/api/appkit/Interface.AssertionHandle.md +1 -1
- package/docs/api/appkit/Interface.DatabaseValidationIssue.md +21 -0
- package/docs/api/appkit/Interface.DatasetRow.md +21 -0
- package/docs/api/appkit/Interface.DiscoveredEvalConfig.md +25 -0
- package/docs/api/appkit/Interface.DriveResult.md +28 -0
- package/docs/api/appkit/Interface.EntityMutationHooks.md +173 -0
- package/docs/api/appkit/Interface.EvalDefinition.md +50 -0
- package/docs/api/appkit/Interface.EvalDriver.md +26 -5
- package/docs/api/appkit/Interface.EvalResult.md +11 -0
- package/docs/api/appkit/Interface.EvalSummary.md +11 -0
- package/docs/api/appkit/Interface.HookApp.md +12 -0
- package/docs/api/appkit/Interface.HookContext.md +21 -0
- package/docs/api/appkit/Interface.ReadEvalDatasetOptions.md +34 -0
- package/docs/api/appkit/Interface.ReadSerializerContext.md +21 -0
- package/docs/api/appkit/Interface.RunEvalOptions.md +22 -0
- package/docs/api/appkit/Interface.RunEvalsOptions.md +45 -1
- package/docs/api/appkit/Interface.TestContext.md +67 -8
- package/docs/api/appkit/TypeAlias.DatabaseApiConfig.md +53 -0
- package/docs/api/appkit/TypeAlias.DatabaseApiWriteOperation.md +8 -0
- package/docs/api/appkit/TypeAlias.DatabaseApiWritesConfig.md +49 -0
- package/docs/api/appkit/TypeAlias.DatabaseExports.md +3 -3
- package/docs/api/appkit/TypeAlias.EntityHooks.md +25 -0
- package/docs/api/appkit/TypeAlias.IDatabaseConfig.md +16 -5
- package/docs/api/appkit/TypeAlias.ReadSerializer.md +19 -0
- package/docs/api/appkit/TypeAlias.TransactionClient.md +19 -0
- package/docs/api/appkit.md +142 -119
- package/docs/plugins/database.md +144 -0
- package/llms.txt +24 -0
- package/package.json +2 -2
- package/sbom.cdx.json +1 -1
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { createLogger } from "../../logging/logger.js";
|
|
2
|
+
import { DatabaseValidationError } from "../../errors/database-validation.js";
|
|
3
|
+
import "../../errors/index.js";
|
|
2
4
|
import { createLakebasePool } from "../../connectors/lakebase/index.js";
|
|
3
5
|
import { assertFinalizedSchema } from "../../database/schema-builder/define-schema.js";
|
|
4
6
|
import { DatabasePluginError, classifyDatabaseError } from "../../database/errors.js";
|
|
5
|
-
import { STATEMENT_TIMEOUT_MS } from "./defaults.js";
|
|
7
|
+
import { IDLE_IN_TRANSACTION_TIMEOUT_MS, STATEMENT_TIMEOUT_MS, TRANSACTION_TIMEOUT_MS } from "./defaults.js";
|
|
6
8
|
import { createDrizzleDataPath, createDrizzleDb } from "../../database/runtime/engine/drizzle-data-path.js";
|
|
7
9
|
import { EntityClient } from "./entity-client.js";
|
|
10
|
+
import { createMutationScope } from "./scope.js";
|
|
8
11
|
|
|
9
12
|
//#region src/plugins/database/lifecycle.ts
|
|
10
13
|
const logger = createLogger("database");
|
|
@@ -13,6 +16,7 @@ function buildSql(context) {
|
|
|
13
16
|
return async (strings, ...values) => {
|
|
14
17
|
try {
|
|
15
18
|
context.assertActive();
|
|
19
|
+
if (context.transactionBound) context.scope.consumeTransactionOperation();
|
|
16
20
|
return await context.getDataPath().raw(strings, ...values);
|
|
17
21
|
} catch (error) {
|
|
18
22
|
throw classifyDatabaseError(error, "read");
|
|
@@ -26,47 +30,76 @@ function buildTransactionClient(context) {
|
|
|
26
30
|
table,
|
|
27
31
|
getDataPath: context.getDataPath,
|
|
28
32
|
execute: context.execute,
|
|
29
|
-
assertActive: context.assertActive
|
|
33
|
+
assertActive: context.assertActive,
|
|
34
|
+
scope: context.scope,
|
|
35
|
+
hooks: context.hooks?.[name],
|
|
36
|
+
transactionBound: context.transactionBound,
|
|
37
|
+
runInTransaction: (run) => runTransaction(context, (tx) => run(entityOf(tx, name)))
|
|
30
38
|
});
|
|
31
39
|
result.sql = buildSql(context);
|
|
32
40
|
return result;
|
|
33
41
|
}
|
|
42
|
+
/** Typegen owns the entity keys, so reaching one by table name stays dynamic. */
|
|
43
|
+
function entityOf(tx, name) {
|
|
44
|
+
return tx[name];
|
|
45
|
+
}
|
|
46
|
+
/** Reject from inside the driver callback so the driver rolls back on expiry. */
|
|
47
|
+
function runWithTransactionDeadline(run) {
|
|
48
|
+
let timer;
|
|
49
|
+
const deadline = new Promise((_, reject) => {
|
|
50
|
+
timer = setTimeout(() => reject(new DatabasePluginError("TRANSIENT", "transaction")), TRANSACTION_TIMEOUT_MS);
|
|
51
|
+
timer.unref?.();
|
|
52
|
+
});
|
|
53
|
+
return Promise.race([Promise.resolve().then(run), deadline]).finally(() => clearTimeout(timer));
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Run inside one transaction, joining the active one rather than nesting:
|
|
57
|
+
* PostgreSQL has no nested transaction, and a savepoint would let part of a
|
|
58
|
+
* hooked mutation survive a rollback.
|
|
59
|
+
*/
|
|
60
|
+
function runTransaction(context, callback) {
|
|
61
|
+
context.assertActive();
|
|
62
|
+
const active = context.scope.activeTransaction();
|
|
63
|
+
if (active) return callback(active);
|
|
64
|
+
return context.getDataPath().transaction(async (txDataPath) => {
|
|
65
|
+
let open = true;
|
|
66
|
+
const assertTransactionActive = () => {
|
|
67
|
+
context.assertActive();
|
|
68
|
+
if (!open) throw new DatabasePluginError("INTERNAL", "transaction");
|
|
69
|
+
};
|
|
70
|
+
const directExecute = async (operation) => ({
|
|
71
|
+
ok: true,
|
|
72
|
+
data: await operation()
|
|
73
|
+
});
|
|
74
|
+
const tx = buildTransactionClient({
|
|
75
|
+
...context,
|
|
76
|
+
getDataPath: () => txDataPath,
|
|
77
|
+
execute: directExecute,
|
|
78
|
+
assertActive: assertTransactionActive,
|
|
79
|
+
transactionBound: true
|
|
80
|
+
});
|
|
81
|
+
try {
|
|
82
|
+
return await runWithTransactionDeadline(() => context.scope.runWithTransaction(tx, () => callback(tx)));
|
|
83
|
+
} finally {
|
|
84
|
+
open = false;
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
}
|
|
34
88
|
/** Add the transaction entry point to the root database surface. */
|
|
35
89
|
function buildDatabaseExports(context) {
|
|
36
90
|
const result = buildTransactionClient(context);
|
|
37
91
|
result.transaction = async (callback) => {
|
|
38
92
|
try {
|
|
39
|
-
context
|
|
40
|
-
return await context.getDataPath().transaction(async (txDataPath) => {
|
|
41
|
-
let active = true;
|
|
42
|
-
const assertTransactionActive = () => {
|
|
43
|
-
context.assertActive();
|
|
44
|
-
if (!active) throw new DatabasePluginError("INTERNAL", "transaction");
|
|
45
|
-
};
|
|
46
|
-
const directExecute = async (operation) => ({
|
|
47
|
-
ok: true,
|
|
48
|
-
data: await operation()
|
|
49
|
-
});
|
|
50
|
-
const tx = buildTransactionClient({
|
|
51
|
-
...context,
|
|
52
|
-
getDataPath: () => txDataPath,
|
|
53
|
-
execute: directExecute,
|
|
54
|
-
assertActive: assertTransactionActive
|
|
55
|
-
});
|
|
56
|
-
try {
|
|
57
|
-
return await callback(tx);
|
|
58
|
-
} finally {
|
|
59
|
-
active = false;
|
|
60
|
-
}
|
|
61
|
-
});
|
|
93
|
+
return await runTransaction(context, callback);
|
|
62
94
|
} catch (error) {
|
|
95
|
+
if (error instanceof DatabaseValidationError) throw error;
|
|
63
96
|
throw classifyDatabaseError(error, "transaction");
|
|
64
97
|
}
|
|
65
98
|
};
|
|
66
99
|
return result;
|
|
67
100
|
}
|
|
68
101
|
/** Validate the schema, create one pool-backed API, and verify connectivity. */
|
|
69
|
-
async function createDatabaseState(schema, execute) {
|
|
102
|
+
async function createDatabaseState(schema, execute, hooks) {
|
|
70
103
|
try {
|
|
71
104
|
assertFinalizedSchema(schema);
|
|
72
105
|
} catch (error) {
|
|
@@ -79,13 +112,19 @@ async function createDatabaseState(schema, execute) {
|
|
|
79
112
|
if (!active) throw new DatabasePluginError("INTERNAL", "runtime");
|
|
80
113
|
};
|
|
81
114
|
try {
|
|
82
|
-
pool = createLakebasePool({
|
|
115
|
+
pool = createLakebasePool({
|
|
116
|
+
statement_timeout: STATEMENT_TIMEOUT_MS,
|
|
117
|
+
idle_in_transaction_session_timeout: IDLE_IN_TRANSACTION_TIMEOUT_MS
|
|
118
|
+
});
|
|
83
119
|
const dataPath = createDrizzleDataPath(createDrizzleDb(pool, schema), schema, { columnAccess: "trusted" });
|
|
84
120
|
const exports = buildDatabaseExports({
|
|
85
121
|
schema,
|
|
86
122
|
getDataPath: () => dataPath,
|
|
87
123
|
execute,
|
|
88
|
-
assertActive
|
|
124
|
+
assertActive,
|
|
125
|
+
scope: createMutationScope(),
|
|
126
|
+
hooks,
|
|
127
|
+
transactionBound: false
|
|
89
128
|
});
|
|
90
129
|
await dataPath.raw`select 1`;
|
|
91
130
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifecycle.js","names":[],"sources":["../../../src/plugins/database/lifecycle.ts"],"sourcesContent":["import { createLakebasePool } from \"../../connectors/lakebase\";\nimport {\n classifyDatabaseError,\n DatabasePluginError,\n} from \"../../database/errors\";\nimport type { DataPath } from \"../../database/runtime\";\nimport {\n createDrizzleDataPath,\n createDrizzleDb,\n} from \"../../database/runtime/engine/drizzle-data-path\";\nimport type { Schema } from \"../../database/schema-builder\";\nimport { assertFinalizedSchema } from \"../../database/schema-builder/define-schema\";\nimport { createLogger } from \"../../logging/logger\";\nimport {
|
|
1
|
+
{"version":3,"file":"lifecycle.js","names":[],"sources":["../../../src/plugins/database/lifecycle.ts"],"sourcesContent":["import { createLakebasePool } from \"../../connectors/lakebase\";\nimport {\n classifyDatabaseError,\n DatabasePluginError,\n} from \"../../database/errors\";\nimport type { DataPath } from \"../../database/runtime\";\nimport {\n createDrizzleDataPath,\n createDrizzleDb,\n} from \"../../database/runtime/engine/drizzle-data-path\";\nimport type { Schema } from \"../../database/schema-builder\";\nimport { assertFinalizedSchema } from \"../../database/schema-builder/define-schema\";\nimport { DatabaseValidationError } from \"../../errors\";\nimport { createLogger } from \"../../logging/logger\";\nimport {\n IDLE_IN_TRANSACTION_TIMEOUT_MS,\n STATEMENT_TIMEOUT_MS,\n TRANSACTION_TIMEOUT_MS,\n} from \"./defaults\";\nimport { EntityClient, type EntityExecute } from \"./entity-client\";\nimport type {\n DatabaseExports,\n SqlTag,\n TransactionClient,\n} from \"./entity-types\";\nimport { createMutationScope, type MutationScope } from \"./scope\";\nimport type { DatabaseHooks } from \"./types\";\n\nconst logger = createLogger(\"database\");\n\n/** Resources owned by one successfully initialized plugin instance. */\nexport interface DatabaseState {\n readonly pool: ReturnType<typeof createLakebasePool>;\n readonly exports: DatabaseExports;\n readonly deactivate: () => void;\n}\n\ninterface ExportContext {\n readonly schema: Schema;\n readonly getDataPath: () => DataPath;\n readonly execute: EntityExecute;\n readonly assertActive: () => void;\n readonly scope: MutationScope;\n readonly hooks?: DatabaseHooks;\n readonly transactionBound: boolean;\n}\n\n/** Execute value-only SQL on the bound DataPath without per-statement retries. */\nfunction buildSql(context: ExportContext): SqlTag {\n return async <T = Record<string, unknown>>(\n strings: TemplateStringsArray,\n ...values: unknown[]\n ) => {\n try {\n context.assertActive();\n if (context.transactionBound) {\n context.scope.consumeTransactionOperation();\n }\n // DataPath accepts value interpolation only and keeps Drizzle private.\n return await context.getDataPath().raw<T>(strings, ...values);\n } catch (error) {\n throw classifyDatabaseError(error, \"read\");\n }\n };\n}\n\n/** Build entities and SQL bound to either the root pool or one transaction. */\nfunction buildTransactionClient(context: ExportContext): TransactionClient {\n const result: Record<string, unknown> = Object.create(null);\n for (const [name, table] of Object.entries(context.schema.$tables)) {\n result[name] = new EntityClient({\n table,\n getDataPath: context.getDataPath,\n execute: context.execute,\n assertActive: context.assertActive,\n scope: context.scope,\n hooks: context.hooks?.[name],\n transactionBound: context.transactionBound,\n runInTransaction: (run) =>\n runTransaction(context, (tx) => run(entityOf(tx, name))),\n });\n }\n result.sql = buildSql(context);\n return result as TransactionClient;\n}\n\n/** Typegen owns the entity keys, so reaching one by table name stays dynamic. */\nfunction entityOf(tx: TransactionClient, name: string): EntityClient {\n return (tx as unknown as Record<string, EntityClient>)[name];\n}\n\n/** Reject from inside the driver callback so the driver rolls back on expiry. */\nfunction runWithTransactionDeadline<T>(run: () => Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout>;\n const deadline = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new DatabasePluginError(\"TRANSIENT\", \"transaction\")),\n TRANSACTION_TIMEOUT_MS,\n );\n timer.unref?.();\n });\n return Promise.race([Promise.resolve().then(run), deadline]).finally(() =>\n clearTimeout(timer),\n );\n}\n\n/**\n * Run inside one transaction, joining the active one rather than nesting:\n * PostgreSQL has no nested transaction, and a savepoint would let part of a\n * hooked mutation survive a rollback.\n */\nfunction runTransaction<T>(\n context: ExportContext,\n callback: (tx: TransactionClient) => Promise<T>,\n): Promise<T> {\n context.assertActive();\n const active = context.scope.activeTransaction();\n if (active) return callback(active);\n return context.getDataPath().transaction(async (txDataPath) => {\n let open = true;\n const assertTransactionActive = () => {\n context.assertActive();\n if (!open) throw new DatabasePluginError(\"INTERNAL\", \"transaction\");\n };\n // The outer transaction owns execution; inner clients use its connection.\n const directExecute: EntityExecute = async (operation) => ({\n ok: true,\n data: await operation(),\n });\n const tx = buildTransactionClient({\n ...context,\n getDataPath: () => txDataPath,\n execute: directExecute,\n assertActive: assertTransactionActive,\n transactionBound: true,\n });\n try {\n return await runWithTransactionDeadline(() =>\n context.scope.runWithTransaction(tx, () => callback(tx)),\n );\n } finally {\n // Captured clients must not outlive the transaction callback.\n open = false;\n }\n });\n}\n\n/** Add the transaction entry point to the root database surface. */\nfunction buildDatabaseExports(context: ExportContext): DatabaseExports {\n const result = buildTransactionClient(context) as DatabaseExports;\n result.transaction = async <T>(\n callback: (tx: TransactionClient) => Promise<T>,\n ) => {\n try {\n return await runTransaction(context, callback);\n } catch (error) {\n if (error instanceof DatabaseValidationError) throw error;\n throw classifyDatabaseError(error, \"transaction\");\n }\n };\n return result;\n}\n\n/** Validate the schema, create one pool-backed API, and verify connectivity. */\nexport async function createDatabaseState<TSchema extends Schema>(\n schema: TSchema,\n execute: EntityExecute,\n hooks?: DatabaseHooks,\n): Promise<DatabaseState> {\n try {\n assertFinalizedSchema(schema);\n } catch (error) {\n logger.error(\"Database schema failed validation: %O\", error);\n throw new DatabasePluginError(\"SETUP_FAILED\", \"setup\");\n }\n\n let active = true;\n let pool: ReturnType<typeof createLakebasePool> | undefined;\n const assertActive = () => {\n if (!active) throw new DatabasePluginError(\"INTERNAL\", \"runtime\");\n };\n try {\n pool = createLakebasePool({\n statement_timeout: STATEMENT_TIMEOUT_MS,\n idle_in_transaction_session_timeout: IDLE_IN_TRANSACTION_TIMEOUT_MS,\n });\n const db = createDrizzleDb(pool, schema);\n const dataPath = createDrizzleDataPath(db, schema, {\n columnAccess: \"trusted\",\n });\n const exports = buildDatabaseExports({\n schema,\n getDataPath: () => dataPath,\n execute,\n assertActive,\n // One scope per state keeps concurrent instances from sharing a transaction.\n scope: createMutationScope(),\n hooks,\n transactionBound: false,\n });\n // Do not publish exports until an authenticated statement succeeds.\n await dataPath.raw`select 1`;\n return {\n pool,\n exports,\n deactivate: () => {\n active = false;\n },\n };\n } catch (error) {\n logger.error(\"Database setup failed: %O\", error);\n active = false;\n await pool?.end().catch(() => undefined);\n throw new DatabasePluginError(\"SETUP_FAILED\", \"setup\");\n }\n}\n"],"mappings":";;;;;;;;;;;;AA4BA,MAAM,SAAS,aAAa,WAAW;;AAoBvC,SAAS,SAAS,SAAgC;AAChD,QAAO,OACL,SACA,GAAG,WACA;AACH,MAAI;AACF,WAAQ,cAAc;AACtB,OAAI,QAAQ,iBACV,SAAQ,MAAM,6BAA6B;AAG7C,UAAO,MAAM,QAAQ,aAAa,CAAC,IAAO,SAAS,GAAG,OAAO;WACtD,OAAO;AACd,SAAM,sBAAsB,OAAO,OAAO;;;;;AAMhD,SAAS,uBAAuB,SAA2C;CACzE,MAAM,SAAkC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,QAAQ,MAAM,mBAAmB,UAAU,SAAS,GAAG,CAAC,CACzD;YACO;AAER,UAAO;;GAET;;;AAIJ,SAAS,qBAAqB,SAAyC;CACrE,MAAM,SAAS,uBAAuB,QAAQ;AAC9C,QAAO,cAAc,OACnB,aACG;AACH,MAAI;AACF,UAAO,MAAM,eAAe,SAAS,SAAS;WACvC,OAAO;AACd,OAAI,iBAAiB,wBAAyB,OAAM;AACpD,SAAM,sBAAsB,OAAO,cAAc;;;AAGrD,QAAO;;;AAIT,eAAsB,oBACpB,QACA,SACA,OACwB;AACxB,KAAI;AACF,wBAAsB,OAAO;UACtB,OAAO;AACd,SAAO,MAAM,yCAAyC,MAAM;AAC5D,QAAM,IAAI,oBAAoB,gBAAgB,QAAQ;;CAGxD,IAAI,SAAS;CACb,IAAI;CACJ,MAAM,qBAAqB;AACzB,MAAI,CAAC,OAAQ,OAAM,IAAI,oBAAoB,YAAY,UAAU;;AAEnE,KAAI;AACF,SAAO,mBAAmB;GACxB,mBAAmB;GACnB,qCAAqC;GACtC,CAAC;EAEF,MAAM,WAAW,sBADN,gBAAgB,MAAM,OAAO,EACG,QAAQ,EACjD,cAAc,WACf,CAAC;EACF,MAAM,UAAU,qBAAqB;GACnC;GACA,mBAAmB;GACnB;GACA;GAEA,OAAO,qBAAqB;GAC5B;GACA,kBAAkB;GACnB,CAAC;AAEF,QAAM,SAAS,GAAG;AAClB,SAAO;GACL;GACA;GACA,kBAAkB;AAChB,aAAS;;GAEZ;UACM,OAAO;AACd,SAAO,MAAM,6BAA6B,MAAM;AAChD,WAAS;AACT,QAAM,MAAM,KAAK,CAAC,YAAY,OAAU;AACxC,QAAM,IAAI,oBAAoB,gBAAgB,QAAQ"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { DatabasePluginError } from "../../database/errors.js";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
|
|
4
|
+
//#region src/plugins/database/scope.ts
|
|
5
|
+
/** How deep hook-issued mutations may nest before the guard rejects. */
|
|
6
|
+
const MAX_MUTATION_DEPTH = 8;
|
|
7
|
+
/** Max database operations admitted by one transaction. */
|
|
8
|
+
const MAX_TRANSACTION_OPERATIONS = 100;
|
|
9
|
+
/** Charge one operation to a transaction-owned shared budget. */
|
|
10
|
+
function consumeBudget(state, phase) {
|
|
11
|
+
const budget = state?.budget ?? { used: 0 };
|
|
12
|
+
if (budget.used >= MAX_TRANSACTION_OPERATIONS) throw new DatabasePluginError("INTERNAL", phase);
|
|
13
|
+
budget.used += 1;
|
|
14
|
+
return budget;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Async context owned by one plugin instance. It carries the transaction,
|
|
18
|
+
* mutation budget, and frames that bound recursion, so neither two instances
|
|
19
|
+
* nor two concurrent calls can observe each other.
|
|
20
|
+
*/
|
|
21
|
+
function createMutationScope() {
|
|
22
|
+
const storage = new AsyncLocalStorage();
|
|
23
|
+
return {
|
|
24
|
+
activeTransaction() {
|
|
25
|
+
return storage.getStore()?.transaction;
|
|
26
|
+
},
|
|
27
|
+
runWithTransaction(transaction, run) {
|
|
28
|
+
const current = storage.getStore();
|
|
29
|
+
return storage.run({
|
|
30
|
+
transaction,
|
|
31
|
+
frames: current?.frames ?? [],
|
|
32
|
+
budget: current?.budget ?? { used: 0 }
|
|
33
|
+
}, run);
|
|
34
|
+
},
|
|
35
|
+
consumeTransactionOperation() {
|
|
36
|
+
const state = storage.getStore();
|
|
37
|
+
if (state?.transaction) consumeBudget(state, "transaction");
|
|
38
|
+
},
|
|
39
|
+
async runMutation(entity, operation, run) {
|
|
40
|
+
const state = storage.getStore();
|
|
41
|
+
const frames = state?.frames ?? [];
|
|
42
|
+
if (frames.some((frame) => frame.entity === entity && frame.operation === operation) || frames.length >= MAX_MUTATION_DEPTH) throw new DatabasePluginError("INTERNAL", "write");
|
|
43
|
+
const budget = consumeBudget(state, "write");
|
|
44
|
+
return storage.run({
|
|
45
|
+
transaction: state?.transaction,
|
|
46
|
+
frames: [...frames, {
|
|
47
|
+
entity,
|
|
48
|
+
operation
|
|
49
|
+
}],
|
|
50
|
+
budget
|
|
51
|
+
}, run);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
export { createMutationScope };
|
|
58
|
+
//# sourceMappingURL=scope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope.js","names":[],"sources":["../../../src/plugins/database/scope.ts"],"sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { DatabasePluginError } from \"../../database/errors\";\nimport type { TransactionClient } from \"./entity-types\";\nimport type { MutationOperation } from \"./hooks\";\n\n/** How deep hook-issued mutations may nest before the guard rejects. */\nconst MAX_MUTATION_DEPTH = 8;\n/** Max database operations admitted by one transaction. */\nexport const MAX_TRANSACTION_OPERATIONS = 100;\n\ninterface MutationFrame {\n readonly entity: string;\n readonly operation: MutationOperation;\n}\n\ninterface MutationBudget {\n used: number;\n}\n\ninterface ScopeState {\n readonly transaction?: TransactionClient;\n readonly frames: readonly MutationFrame[];\n readonly budget: MutationBudget;\n}\n\n/** Charge one operation to a transaction-owned shared budget. */\nfunction consumeBudget(\n state: ScopeState | undefined,\n phase: \"transaction\" | \"write\",\n): MutationBudget {\n const budget = state?.budget ?? { used: 0 };\n if (budget.used >= MAX_TRANSACTION_OPERATIONS) {\n throw new DatabasePluginError(\"INTERNAL\", phase);\n }\n budget.used += 1;\n return budget;\n}\n\n/** Instance-owned async context created by `createMutationScope()`. */\nexport type MutationScope = ReturnType<typeof createMutationScope>;\n\n/**\n * Async context owned by one plugin instance. It carries the transaction,\n * mutation budget, and frames that bound recursion, so neither two instances\n * nor two concurrent calls can observe each other.\n */\nexport function createMutationScope() {\n const storage = new AsyncLocalStorage<ScopeState>();\n\n return {\n /** The transaction a hook must join, or `undefined` outside one. */\n activeTransaction(): TransactionClient | undefined {\n return storage.getStore()?.transaction;\n },\n\n /** Publish one transaction to everything the callback awaits. */\n runWithTransaction<T>(\n transaction: TransactionClient,\n run: () => Promise<T>,\n ): Promise<T> {\n const current = storage.getStore();\n return storage.run(\n {\n transaction,\n frames: current?.frames ?? [],\n budget: current?.budget ?? { used: 0 },\n },\n run,\n );\n },\n\n /** Charge SQL and other direct work bound to the active transaction. */\n consumeTransactionOperation(): void {\n const state = storage.getStore();\n if (state?.transaction) consumeBudget(state, \"transaction\");\n },\n\n /** Open one frame, refusing a repeated entity/operation pair or deep nesting. */\n async runMutation<T>(\n entity: string,\n operation: MutationOperation,\n run: () => Promise<T>,\n ): Promise<T> {\n const state = storage.getStore();\n const frames = state?.frames ?? [];\n const repeated = frames.some(\n (frame) => frame.entity === entity && frame.operation === operation,\n );\n if (repeated || frames.length >= MAX_MUTATION_DEPTH) {\n throw new DatabasePluginError(\"INTERNAL\", \"write\");\n }\n const budget = consumeBudget(state, \"write\");\n return storage.run(\n {\n transaction: state?.transaction,\n frames: [...frames, { entity, operation }],\n budget,\n },\n run,\n );\n },\n };\n}\n"],"mappings":";;;;;AAOA,MAAM,qBAAqB;;AAE3B,MAAa,6BAA6B;;AAkB1C,SAAS,cACP,OACA,OACgB;CAChB,MAAM,SAAS,OAAO,UAAU,EAAE,MAAM,GAAG;AAC3C,KAAI,OAAO,QAAQ,2BACjB,OAAM,IAAI,oBAAoB,YAAY,MAAM;AAElD,QAAO,QAAQ;AACf,QAAO;;;;;;;AAWT,SAAgB,sBAAsB;CACpC,MAAM,UAAU,IAAI,mBAA+B;AAEnD,QAAO;EAEL,oBAAmD;AACjD,UAAO,QAAQ,UAAU,EAAE;;EAI7B,mBACE,aACA,KACY;GACZ,MAAM,UAAU,QAAQ,UAAU;AAClC,UAAO,QAAQ,IACb;IACE;IACA,QAAQ,SAAS,UAAU,EAAE;IAC7B,QAAQ,SAAS,UAAU,EAAE,MAAM,GAAG;IACvC,EACD,IACD;;EAIH,8BAAoC;GAClC,MAAM,QAAQ,QAAQ,UAAU;AAChC,OAAI,OAAO,YAAa,eAAc,OAAO,cAAc;;EAI7D,MAAM,YACJ,QACA,WACA,KACY;GACZ,MAAM,QAAQ,QAAQ,UAAU;GAChC,MAAM,SAAS,OAAO,UAAU,EAAE;AAIlC,OAHiB,OAAO,MACrB,UAAU,MAAM,WAAW,UAAU,MAAM,cAAc,UAC3D,IACe,OAAO,UAAU,mBAC/B,OAAM,IAAI,oBAAoB,YAAY,QAAQ;GAEpD,MAAM,SAAS,cAAc,OAAO,QAAQ;AAC5C,UAAO,QAAQ,IACb;IACE,aAAa,OAAO;IACpB,QAAQ,CAAC,GAAG,QAAQ;KAAE;KAAQ;KAAW,CAAC;IAC1C;IACD,EACD,IACD;;EAEJ"}
|
|
@@ -1,22 +1,36 @@
|
|
|
1
1
|
import { Schema } from "../../database/schema-builder/types.js";
|
|
2
|
+
import { EntityMutationHooks } from "./hooks.js";
|
|
2
3
|
|
|
3
4
|
//#region src/plugins/database/types.d.ts
|
|
4
5
|
/** Table names declared by one finalized schema. */
|
|
5
6
|
type SchemaTableName<TSchema extends Schema> = Extract<keyof TSchema["$tables"], string>;
|
|
7
|
+
/** Generated HTTP write operations. */
|
|
8
|
+
type DatabaseApiWriteOperation = "create" | "update" | "delete";
|
|
9
|
+
/** All writes by default; false keeps reads only, and an object narrows writes. */
|
|
10
|
+
type DatabaseApiWritesConfig<TSchema extends Schema> = boolean | {
|
|
11
|
+
/** Tables that remain writable. Defaults to every exposed table. */readonly tables?: readonly SchemaTableName<TSchema>[]; /** Operations that remain enabled. Defaults to create, update, and delete. */
|
|
12
|
+
readonly operations?: readonly DatabaseApiWriteOperation[];
|
|
13
|
+
};
|
|
6
14
|
/**
|
|
7
|
-
*
|
|
15
|
+
* Full generated CRUD for every declared table by default. Set false to disable
|
|
16
|
+
* all generated routes, or use an object to restrict tables and writes.
|
|
17
|
+
* Keyed routes require a public primary key; upsert stays programmatic.
|
|
18
|
+
* Route names must start with a letter, contain only letters, digits, `_`, or
|
|
19
|
+
* `-`, be at most 64 characters, and be unique ignoring case. Invalid names
|
|
20
|
+
* fail setup; exclude internal tables with `api.tables` or use `api: false`.
|
|
8
21
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* cannot be included
|
|
22
|
+
* Routes run as the app's service principal and apply no per-user filter, so
|
|
23
|
+
* anyone the app admits receives every enabled operation. An exposed table
|
|
24
|
+
* also becomes includable from its neighbours; a relation whose target
|
|
25
|
+
* stays off cannot be included.
|
|
13
26
|
*
|
|
14
27
|
* Text filters accept caller-supplied `like`/`ilike` patterns; a server-side
|
|
15
28
|
* `statement_timeout` cancels a pattern that would otherwise hold its pooled
|
|
16
29
|
* connection to completion.
|
|
17
30
|
*/
|
|
18
|
-
type
|
|
19
|
-
readonly tables
|
|
31
|
+
type DatabaseApiConfig<TSchema extends Schema> = boolean | {
|
|
32
|
+
/** Tables that remain exposed. Defaults to every declared table. */readonly tables?: readonly SchemaTableName<TSchema>[]; /** All writes by default. Set false for read-only routes. */
|
|
33
|
+
readonly writes?: DatabaseApiWritesConfig<TSchema>;
|
|
20
34
|
};
|
|
21
35
|
/** Which entity and generated operation produced the row being shaped. */
|
|
22
36
|
interface ReadSerializerContext {
|
|
@@ -29,14 +43,28 @@ interface ReadSerializerContext {
|
|
|
29
43
|
* serializers run inside the response path and must not add latency there.
|
|
30
44
|
*/
|
|
31
45
|
type ReadSerializer = (row: Record<string, unknown>, context: ReadSerializerContext) => Record<string, unknown>;
|
|
46
|
+
/** Response shaping and mutation lifecycle declared for one table. */
|
|
47
|
+
type EntityHooks<TTable extends string = string> = EntityMutationHooks<TTable> & {
|
|
48
|
+
readonly serialize?: ReadSerializer;
|
|
49
|
+
};
|
|
32
50
|
/** Configuration for one schema-bound DatabasePlugin instance. */
|
|
33
51
|
type IDatabaseConfig<TSchema extends Schema> = {
|
|
34
52
|
readonly schema: TSchema;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
53
|
+
/**
|
|
54
|
+
* Generated HTTP CRUD is enabled for all tables by default, using the app's
|
|
55
|
+
* service principal. Every admitted caller receives the enabled operations;
|
|
56
|
+
* no per-user or per-row authorization is applied. This plugin does not
|
|
57
|
+
* support OBO. Use custom routes for application-specific authorization.
|
|
58
|
+
*
|
|
59
|
+
* Set `false` to disable routes, `{ writes: false }` for reads only, or
|
|
60
|
+
* `{ tables: ["notes"] }` to expose only selected tables. To disable delete,
|
|
61
|
+
* use `{ writes: { operations: ["create", "update"] } }`.
|
|
62
|
+
*
|
|
63
|
+
* @defaultValue true
|
|
64
|
+
*/
|
|
65
|
+
readonly api?: DatabaseApiConfig<TSchema>;
|
|
66
|
+
readonly hooks?: { readonly [TTable in SchemaTableName<TSchema>]?: EntityHooks<TTable> };
|
|
39
67
|
};
|
|
40
68
|
//#endregion
|
|
41
|
-
export { IDatabaseConfig };
|
|
69
|
+
export { DatabaseApiConfig, DatabaseApiWriteOperation, DatabaseApiWritesConfig, EntityHooks, IDatabaseConfig, ReadSerializer, ReadSerializerContext };
|
|
42
70
|
//# sourceMappingURL=types.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/plugins/database/types.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/plugins/database/types.ts"],"mappings":";;;;;KAIY,eAAA,iBAAgC,MAAA,IAAU,OAAA,OAC9C,OAAA;AADR;AAAA,KAMY,yBAAA;;KAGA,uBAAA,iBAAwC,MAAA;EAR5C,6EAYO,MAAA,YAAkB,eAAA,CAAgB,OAAA,KAbY;EAAA,SAe9C,UAAA,YAAsB,yBAAA;AAAA;;;;;;AATrC;;;;;AAGA;;;;;;;KA0BY,iBAAA,iBAAkC,MAAA;EApBgB,6EAwB/C,MAAA,YAAkB,eAAA,CAAgB,OAAA,KA9BG;EAAA,SAgCrC,MAAA,GAAS,uBAAA,CAAwB,OAAA;AAAA;;UAI/B,qBAAA;EAAA,SACN,MAAA;EAAA,SACA,SAAA;AAAA;AAZX;;;;;AAAA,KAoBY,cAAA,IACV,GAAA,EAAK,MAAA,mBACL,OAAA,EAAS,qBAAA,KACN,MAAA;;KAGO,WAAA,mCACV,mBAAA,CAAoB,MAAA;EAAA,SACT,SAAA,GAAY,cAAA;AAAA;;KAOb,eAAA,iBAAgC,MAAA;EAAA,SACjC,MAAA,EAAQ,OAAA;EA9BJ;;;;;AAIf;;;;;AAUA;;EAde,SA2CJ,GAAA,GAAM,iBAAA,CAAkB,OAAA;EAAA,SACxB,KAAA,yBACa,eAAA,CAAgB,OAAA,KAAY,WAAA,CAAY,MAAA;AAAA"}
|
|
@@ -19,7 +19,7 @@ import { getRoutes, printRoutes } from "./utils.js";
|
|
|
19
19
|
import { StaticServer } from "./static-server.js";
|
|
20
20
|
import { ViteDevServer } from "./vite-dev-server.js";
|
|
21
21
|
import path from "node:path";
|
|
22
|
-
import
|
|
22
|
+
import fsSync from "node:fs";
|
|
23
23
|
import dotenv from "dotenv";
|
|
24
24
|
import express from "express";
|
|
25
25
|
import getPort, { portNumbers } from "get-port";
|
|
@@ -246,7 +246,7 @@ var ServerPlugin = class ServerPlugin extends Plugin {
|
|
|
246
246
|
const cwd = process.cwd();
|
|
247
247
|
for (const p of staticPaths) {
|
|
248
248
|
const fullPath = path.resolve(cwd, p);
|
|
249
|
-
if (
|
|
249
|
+
if (fsSync.existsSync(path.resolve(fullPath, "index.html"))) {
|
|
250
250
|
logger.debug("Static files: serving from %s", fullPath);
|
|
251
251
|
return fullPath;
|
|
252
252
|
}
|
|
@@ -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\";\n\nimport dotenv from \"dotenv\";\nimport express from \"express\";\nimport getPort, { portNumbers } from \"get-port\";\nimport type { PluginClientConfigs, PluginPhase } from \"shared\";\nimport { camelToKebab } from \"shared\";\n\nimport { AppKitError, ServerError } from \"../../errors\";\nimport { TelemetryReporter } from \"../../internal-telemetry\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport { defineManifest } 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 = defineManifest<\"server\">(manifest);\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 declare protected 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/${camelToKebab(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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,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;;;;;;;CAQD,OAAwB,0BAA0B;;CAGlD,OAAO,WAAW,eAAyBA,iBAAS;CACpD,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;;CAER,AAAQ;CAER,AAAQ,mBAA2D,EAAE;CACrE,AAAQ,+BAA4B,IAAI,KAAK;;;;;;CAM7C,AAAQ;CACR,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,cAAc,KAAK;AACzB,OAAK,UAAU,yBAAyB,CACtC,iBAAiB,MACjB,iBAAiB,QAClB,CAAC;AACF,OAAK,SA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W,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;;;;;;;AAQR,SAAS,kBACP,OACyC;AACzC,KAAI,EAAE,iBAAiB,UAAU,EAAE,gBAAgB,OAAQ,QAAO;CAClE,MAAM,aAAa,MAAM;AACzB,QACE,OAAO,eAAe,YACtB,OAAO,UAAU,WAAW,IAC5B,cAAc,OACd,cAAc;;;;;;;;;;;;;;;;;;AAoBlB,SAAgB,uBACd,KACA,KACA,KACA,MACA;CACA,MAAM,YACJ,eAAe,eAAe,kBAAkB,IAAI,GAAG,MAAM;CAC/D,MAAM,aAAa,YAAY,UAAU,aAAa;CACtD,MAAM,gBAAgB,aAAa;AAEnC,KAAI,cACF,QAAO,KACL,+CACA,IAAI,QACJ,IAAI,aACJ,YACA,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,CACjD;KAED,QAAO,MACL,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"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["manifest","fs"],"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\";\n\nimport dotenv from \"dotenv\";\nimport express from \"express\";\nimport getPort, { portNumbers } from \"get-port\";\nimport type { PluginClientConfigs, PluginPhase } from \"shared\";\nimport { camelToKebab } from \"shared\";\n\nimport { AppKitError, ServerError } from \"../../errors\";\nimport { TelemetryReporter } from \"../../internal-telemetry\";\nimport { createLogger } from \"../../logging/logger\";\nimport { Plugin, toPlugin } from \"../../plugin\";\nimport { defineManifest } 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 = defineManifest<\"server\">(manifest);\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 declare protected 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/${camelToKebab(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":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,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;;;;;;;CAQD,OAAwB,0BAA0B;;CAGlD,OAAO,WAAW,eAAyBA,iBAAS;CACpD,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;;CAER,AAAQ;CAER,AAAQ,mBAA2D,EAAE;CACrE,AAAQ,+BAA4B,IAAI,KAAK;;;;;;CAM7C,AAAQ;CACR,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,cAAc,KAAK;AACzB,OAAK,UAAU,yBAA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import { randomUUID } from "node:crypto";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import
|
|
6
|
+
import fsSync from "node:fs";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { WebSocketServer } from "ws";
|
|
9
9
|
|
|
@@ -118,7 +118,7 @@ var RemoteTunnelManager = class {
|
|
|
118
118
|
sameSite: "lax"
|
|
119
119
|
});
|
|
120
120
|
const indexPath = path.join(__dirname, "index.html");
|
|
121
|
-
let html =
|
|
121
|
+
let html = fsSync.readFileSync(indexPath, "utf-8");
|
|
122
122
|
html = html.replace("<body>", `<body>${getConfigScript()}`);
|
|
123
123
|
res.send(html);
|
|
124
124
|
};
|
|
@@ -133,7 +133,7 @@ var RemoteTunnelManager = class {
|
|
|
133
133
|
}
|
|
134
134
|
loadHtmlTemplate(filename, replacements) {
|
|
135
135
|
const filePath = path.join(__dirname, filename);
|
|
136
|
-
let content =
|
|
136
|
+
let content = fsSync.readFileSync(filePath, "utf-8");
|
|
137
137
|
for (const [key, value] of Object.entries(replacements)) content = content.replaceAll(`{{${key}}}`, value);
|
|
138
138
|
return content;
|
|
139
139
|
}
|