@databricks/appkit-ui 0.95.0 → 0.97.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 +16 -7
- package/dist/cli/commands/generate-types.js +36 -7
- package/dist/cli/commands/generate-types.js.map +1 -1
- package/dist/cli/commands/spawn-lock.js +18 -5
- package/dist/cli/commands/spawn-lock.js.map +1 -1
- package/dist/js/database/client.d.ts +2 -2
- package/dist/js/database/client.js +1 -1
- package/dist/js/database/client.js.map +1 -1
- package/dist/react/beta.d.ts +2 -2
- package/dist/react/beta.js +1 -2
- package/dist/react/hooks/use-database-list.d.ts +4 -4
- package/dist/react/hooks/use-database-list.d.ts.map +1 -1
- package/dist/react/hooks/use-database-list.js +1 -2
- package/dist/react/hooks/use-database-list.js.map +1 -1
- package/dist/react/hooks/use-database-read.d.ts +4 -41
- package/dist/react/hooks/use-database-read.d.ts.map +1 -1
- package/dist/react/hooks/use-database-read.js +7 -68
- package/dist/react/hooks/use-database-read.js.map +1 -1
- package/dist/react/hooks/use-database-record.d.ts +3 -3
- package/dist/react/hooks/use-database-record.d.ts.map +1 -1
- package/dist/react/hooks/use-database-record.js +2 -3
- package/dist/react/hooks/use-database-record.js.map +1 -1
- package/dist/react/hooks/use-database-write.d.ts +3 -3
- package/dist/react/hooks/use-database-write.js.map +1 -1
- package/dist/react/ui/button.d.ts +1 -1
- package/dist/shared/src/database/api-types.d.ts +1 -4
- package/dist/shared/src/database/api-types.d.ts.map +1 -1
- package/dist/shared/src/database/index.d.ts +3 -0
- package/dist/shared/src/database/operations.d.ts +11 -0
- package/dist/shared/src/database/operations.d.ts.map +1 -0
- package/dist/shared/src/index.d.ts +1 -0
- package/docs/api/appkit/Class.DatabaseValidationError.md +1 -1
- package/docs/api/appkit/Function.defineOperation.md +61 -0
- package/docs/api/appkit/Function.definePolicy.md +52 -0
- package/docs/api/appkit/Function.defineSchema.md +1 -1
- package/docs/api/appkit/Interface.Actor.md +21 -0
- package/docs/api/appkit/Interface.DatabaseOperationContract.md +30 -0
- package/docs/api/appkit/Interface.DatabaseRoutes.md +30 -0
- package/docs/api/appkit/Interface.OperationContext.md +75 -0
- package/docs/api/appkit/Interface.OperationDefinition.md +77 -0
- package/docs/api/appkit/Interface.PolicyContext.md +49 -0
- package/docs/api/appkit/Interface.PolicyDenial.md +21 -0
- package/docs/api/appkit/TypeAlias.DatabricksAppKitDatabaseOperations.md +8 -0
- package/docs/api/appkit/TypeAlias.IDatabaseConfig.md +0 -10
- package/docs/api/appkit/TypeAlias.OperationMethod.md +8 -0
- package/docs/api/appkit/TypeAlias.OperationWireInput.md +14 -0
- package/docs/api/appkit/TypeAlias.OperationWireOutput.md +14 -0
- package/docs/api/appkit/TypeAlias.Policy.md +15 -0
- package/docs/api/appkit/TypeAlias.PolicyDecision.md +8 -0
- package/docs/api/appkit.md +60 -51
- package/docs/development/type-generation.md +20 -1
- package/docs/plugins/database.md +17 -70
- package/llms.txt +16 -7
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
- package/docs/api/appkit/Interface.EntityMutationHooks.md +0 -173
- package/docs/api/appkit/Interface.HookApp.md +0 -12
- package/docs/api/appkit/Interface.HookContext.md +0 -21
- package/docs/api/appkit/Interface.ReadSerializerContext.md +0 -21
- package/docs/api/appkit/TypeAlias.EntityHooks.md +0 -25
- package/docs/api/appkit/TypeAlias.ReadSerializer.md +0 -19
package/CLAUDE.md
CHANGED
|
@@ -72,7 +72,7 @@ npx @databricks/appkit docs <query>
|
|
|
72
72
|
- [Class: AuthenticationError](./docs/api/appkit/Class.AuthenticationError.md): Error thrown when authentication fails.
|
|
73
73
|
- [Class: ConfigurationError](./docs/api/appkit/Class.ConfigurationError.md): Error thrown when configuration is missing or invalid.
|
|
74
74
|
- [Class: ConnectionError](./docs/api/appkit/Class.ConnectionError.md): Error thrown when a connection or network operation fails.
|
|
75
|
-
- [Class: DatabaseValidationError](./docs/api/appkit/Class.DatabaseValidationError.md): Deliberate validation failure
|
|
75
|
+
- [Class: DatabaseValidationError](./docs/api/appkit/Class.DatabaseValidationError.md): Deliberate validation failure. An explicit transaction callback can throw it,
|
|
76
76
|
- [Class: DatabricksAdapter](./docs/api/appkit/Class.DatabricksAdapter.md): Adapter that talks directly to Databricks Model Serving /invocations endpoint.
|
|
77
77
|
- [Class: ExecutionError](./docs/api/appkit/Class.ExecutionError.md): Error thrown when an operation execution fails.
|
|
78
78
|
- [Class: IdentityExpiredError](./docs/api/appkit/Class.IdentityExpiredError.md): The downstream service rejected the active caller's credentials.
|
|
@@ -106,6 +106,8 @@ npx @databricks/appkit docs <query>
|
|
|
106
106
|
- [Function: defineEval()](./docs/api/appkit/Function.defineEval.md): Define an agent eval. Default-export the result from a
|
|
107
107
|
- [Function: defineEvalConfig()](./docs/api/appkit/Function.defineEvalConfig.md): Define per-directory eval config. Default-export from evals.config.ts.
|
|
108
108
|
- [Function: defineManifest()](./docs/api/appkit/Function.defineManifest.md): Validates a raw manifest (typically a manifest.json import) against the
|
|
109
|
+
- [Function: defineOperation()](./docs/api/appkit/Function.defineOperation.md): Call Signature
|
|
110
|
+
- [Function: definePolicy()](./docs/api/appkit/Function.definePolicy.md): Call Signature
|
|
109
111
|
- [Function: defineSchema()](./docs/api/appkit/Function.defineSchema.md): Compile one declared schema. The returned type keeps the table names the
|
|
110
112
|
- [Function: defineTool()](./docs/api/appkit/Function.defineTool.md): Defines a single tool entry for a plugin's internal registry.
|
|
111
113
|
- [Function: discoverEvalConfigs()](./docs/api/appkit/Function.discoverEvalConfigs.md): Discover the per-agent evals.config.ts (from defineEvalConfig) at
|
|
@@ -178,6 +180,7 @@ npx @databricks/appkit docs <query>
|
|
|
178
180
|
- [Function: userTurns()](./docs/api/appkit/Function.userTurns.md): Extract every user-message content, in order, from an MLflow
|
|
179
181
|
- [Function: uuid()](./docs/api/appkit/Function.uuid.md): Returns
|
|
180
182
|
- [Function: varchar()](./docs/api/appkit/Function.varchar.md): Parameters
|
|
183
|
+
- [Interface: Actor](./docs/api/appkit/Interface.Actor.md): The authenticated caller. The HTTP boundary resolves it before any policy runs.
|
|
181
184
|
- [Interface: AgentAdapter](./docs/api/appkit/Interface.AgentAdapter.md): Properties
|
|
182
185
|
- [Interface: AgentDefinition](./docs/api/appkit/Interface.AgentDefinition.md): Properties
|
|
183
186
|
- [Interface: AgentInput](./docs/api/appkit/Interface.AgentInput.md): Properties
|
|
@@ -193,7 +196,9 @@ npx @databricks/appkit docs <query>
|
|
|
193
196
|
- [Interface: CallerContext](./docs/api/appkit/Interface.CallerContext.md): Caller identity and workspace for one immutable execution scope.
|
|
194
197
|
- [Interface: CustomJudgeSpec](./docs/api/appkit/Interface.CustomJudgeSpec.md): A custom LLM-judge definition: a prompt template and choice→score mapping.
|
|
195
198
|
- [Interface: DatabaseCredential](./docs/api/appkit/Interface.DatabaseCredential.md): Database credentials with OAuth token for Postgres connection
|
|
199
|
+
- [Interface: DatabaseOperationContract](./docs/api/appkit/Interface.DatabaseOperationContract.md): The browser-safe contract of one generated operation. input and output
|
|
196
200
|
- [Interface: DatabaseRegistry](./docs/api/appkit/Interface.DatabaseRegistry.md): CANONICAL augmentation target. Empty by default; the generated database.d.ts
|
|
201
|
+
- [Interface: DatabaseRoutes](./docs/api/appkit/Interface.DatabaseRoutes.md): The generated route entry. schema and each module stay lazy, so importing
|
|
197
202
|
- [Interface: DatabaseValidationIssue](./docs/api/appkit/Interface.DatabaseValidationIssue.md): One rejected field; path names public columns, never their values.
|
|
198
203
|
- [Interface: DatabricksAuth](./docs/api/appkit/Interface.DatabricksAuth.md): Resolved Databricks host + bearer token for the eval runner's REST calls.
|
|
199
204
|
- [Interface: DatasetRow](./docs/api/appkit/Interface.DatasetRow.md): One row of a managed evaluation dataset. inputs are the kwargs passed to the
|
|
@@ -203,7 +208,6 @@ npx @databricks/appkit docs <query>
|
|
|
203
208
|
- [Interface: DownloadResponse](./docs/api/appkit/Interface.DownloadResponse.md): Response object for file downloads containing a readable stream.
|
|
204
209
|
- [Interface: DriveResult](./docs/api/appkit/Interface.DriveResult.md): What a driver returns for a single t.send.
|
|
205
210
|
- [Interface: EndpointConfig](./docs/api/appkit/Interface.EndpointConfig.md): Properties
|
|
206
|
-
- [Interface: EntityMutationHooks<TTable>](./docs/api/appkit/Interface.EntityMutationHooks.md): Mutation lifecycle for one entity. A before hook may return a replacement
|
|
207
211
|
- [Interface: EvalDefinition](./docs/api/appkit/Interface.EvalDefinition.md): A single eval, default-exported from a *.eval.ts file.
|
|
208
212
|
- [Interface: EvalDriver](./docs/api/appkit/Interface.EvalDriver.md): Abstraction over how the agent is driven. The HTTP driver posts to a running
|
|
209
213
|
- [Interface: EvalResult](./docs/api/appkit/Interface.EvalResult.md): The outcome of running one eval.
|
|
@@ -215,8 +219,6 @@ npx @databricks/appkit docs <query>
|
|
|
215
219
|
- [Interface: FunctionTool](./docs/api/appkit/Interface.FunctionTool.md): Properties
|
|
216
220
|
- [Interface: GenerateDatabaseCredentialRequest](./docs/api/appkit/Interface.GenerateDatabaseCredentialRequest.md): Request parameters for generating database OAuth credentials
|
|
217
221
|
- [Interface: GenerationParams](./docs/api/appkit/Interface.GenerationParams.md): Optional generation parameters forwarded to the OpenAI-compatible serving
|
|
218
|
-
- [Interface: HookApp](./docs/api/appkit/Interface.HookApp.md): The only capability a hook receives: entities bound to its transaction.
|
|
219
|
-
- [Interface: HookContext](./docs/api/appkit/Interface.HookContext.md): Which entity is being mutated, and the surface a hook may write through.
|
|
220
222
|
- [Interface: HostedSupervisorTool](./docs/api/appkit/Interface.HostedSupervisorTool.md): Tagged record returned by every supervisorTools factory. The
|
|
221
223
|
- [Interface: HttpDriverOptions](./docs/api/appkit/Interface.HttpDriverOptions.md): Properties
|
|
222
224
|
- [Interface: IAiSearchConfig](./docs/api/appkit/Interface.IAiSearchConfig.md): Base configuration interface for AppKit plugins
|
|
@@ -234,12 +236,15 @@ npx @databricks/appkit docs <query>
|
|
|
234
236
|
- [Interface: MatchResult](./docs/api/appkit/Interface.MatchResult.md): Result of a deterministic matcher run against a value.
|
|
235
237
|
- [Interface: McpConnectAllResult](./docs/api/appkit/Interface.McpConnectAllResult.md): Per-endpoint outcome of AppKitMcpClient.connectAll. Callers (the
|
|
236
238
|
- [Interface: Message](./docs/api/appkit/Interface.Message.md): Properties
|
|
239
|
+
- [Interface: OperationContext<In, R>](./docs/api/appkit/Interface.OperationContext.md): What allow and execute receive: the policy context and the loaded resource.
|
|
240
|
+
- [Interface: OperationDefinition<M, I, O, R, Name>](./docs/api/appkit/Interface.OperationDefinition.md): One immutable operation descriptor. Nothing in it runs until a request does.
|
|
237
241
|
- [Interface: PluginManifest<TName>](./docs/api/appkit/Interface.PluginManifest.md): Plugin manifest that declares metadata and resource requirements.
|
|
238
242
|
- [Interface: PluginToolkitProvider](./docs/api/appkit/Interface.PluginToolkitProvider.md): Minimum shape every entry in the Plugins map must expose. Core
|
|
243
|
+
- [Interface: PolicyContext<In>](./docs/api/appkit/Interface.PolicyContext.md): What every authorization callback receives, the resource lookup included.
|
|
244
|
+
- [Interface: PolicyDenial](./docs/api/appkit/Interface.PolicyDenial.md): An explicit refusal. reason stays on the server; HTTP and logs do not receive it.
|
|
239
245
|
- [Interface: PostResult](./docs/api/appkit/Interface.PostResult.md): Structured result for a best-effort POST that must not throw.
|
|
240
246
|
- [Interface: PromptContext](./docs/api/appkit/Interface.PromptContext.md): Context passed to baseSystemPrompt callbacks.
|
|
241
247
|
- [Interface: ReadEvalDatasetOptions](./docs/api/appkit/Interface.ReadEvalDatasetOptions.md): Properties
|
|
242
|
-
- [Interface: ReadSerializerContext](./docs/api/appkit/Interface.ReadSerializerContext.md): Which entity and generated operation produced the row being shaped.
|
|
243
248
|
- [Interface: RegisteredAgent](./docs/api/appkit/Interface.RegisteredAgent.md): Properties
|
|
244
249
|
- [Interface: ReportOutcome](./docs/api/appkit/Interface.ReportOutcome.md): Properties
|
|
245
250
|
- [Interface: RequestedClaims](./docs/api/appkit/Interface.RequestedClaims.md): Optional claims for fine-grained Unity Catalog table permissions
|
|
@@ -287,7 +292,7 @@ npx @databricks/appkit docs <query>
|
|
|
287
292
|
- [Type Alias: DatabaseApiWriteOperation](./docs/api/appkit/TypeAlias.DatabaseApiWriteOperation.md): Generated HTTP write operations.
|
|
288
293
|
- [Type Alias: DatabaseApiWritesConfig<TSchema>](./docs/api/appkit/TypeAlias.DatabaseApiWritesConfig.md): All writes by default; false keeps reads only, and an object narrows writes.
|
|
289
294
|
- [Type Alias: DatabaseExports](./docs/api/appkit/TypeAlias.DatabaseExports.md): Typed database API published by the plugin.
|
|
290
|
-
- [Type Alias:
|
|
295
|
+
- [Type Alias: DatabricksAppKitDatabaseOperations](./docs/api/appkit/TypeAlias.DatabricksAppKitDatabaseOperations.md): The same global registry, available as a module type for package exports.
|
|
291
296
|
- [Type Alias: EvalProgress](./docs/api/appkit/TypeAlias.EvalProgress.md)
|
|
292
297
|
- [Type Alias: ExecutionContext](./docs/api/appkit/TypeAlias.ExecutionContext.md)
|
|
293
298
|
- [Type Alias: ExecutionResult<T>](./docs/api/appkit/TypeAlias.ExecutionResult.md): Discriminated union for plugin execution results.
|
|
@@ -300,9 +305,13 @@ npx @databricks/appkit docs <query>
|
|
|
300
305
|
- [Type Alias: IDatabaseConfig<TSchema>](./docs/api/appkit/TypeAlias.IDatabaseConfig.md): Configuration for one schema-bound DatabasePlugin instance.
|
|
301
306
|
- [Type Alias: JobsExport()](./docs/api/appkit/TypeAlias.JobsExport.md): Public API shape of the jobs plugin.
|
|
302
307
|
- [Type Alias: Matcher()](./docs/api/appkit/TypeAlias.Matcher.md): A deterministic matcher: inspects a string value and returns a result.
|
|
308
|
+
- [Type Alias: OperationMethod](./docs/api/appkit/TypeAlias.OperationMethod.md): HTTP methods an operation can answer; the browser client reads the same union.
|
|
309
|
+
- [Type Alias: OperationWireInput<Operation>](./docs/api/appkit/TypeAlias.OperationWireInput.md): The JSON a caller sends to an operation; a bigint travels as a string or safe integer.
|
|
310
|
+
- [Type Alias: OperationWireOutput<Operation>](./docs/api/appkit/TypeAlias.OperationWireOutput.md): The JSON a successful call answers with; without an output schema there is none.
|
|
303
311
|
- [Type Alias: PluginData<T, U, N>](./docs/api/appkit/TypeAlias.PluginData.md): Tuple of plugin class, config, and name. Created by toPlugin() and passed to createApp().
|
|
304
312
|
- [Type Alias: Plugins](./docs/api/appkit/TypeAlias.Plugins.md): Plugin map passed to the function form of AgentDefinition.tools.
|
|
305
|
-
- [Type Alias:
|
|
313
|
+
- [Type Alias: Policy<In, R>](./docs/api/appkit/TypeAlias.Policy.md): A reusable authorization rule, with or without a resource lookup.
|
|
314
|
+
- [Type Alias: PolicyDecision](./docs/api/appkit/TypeAlias.PolicyDecision.md): Only literal true admits. False and an explicit denial refuse.
|
|
306
315
|
- [Type Alias: ResolvedToolEntry](./docs/api/appkit/TypeAlias.ResolvedToolEntry.md): Internal tool-index entry after a tool record has been resolved to a dispatchable form.
|
|
307
316
|
- [Type Alias: ResourceFieldEntry](./docs/api/appkit/TypeAlias.ResourceFieldEntry.md)
|
|
308
317
|
- [Type Alias: ResourcePermission](./docs/api/appkit/TypeAlias.ResourcePermission.md): Union of all possible permission levels across all resource types.
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import { METRIC_CONFIG_FILE } from "../../schemas/metric-fqn.js";
|
|
2
|
-
import { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock } from "./spawn-lock.js";
|
|
2
|
+
import { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock, spawnLockStaleMsFor } from "./spawn-lock.js";
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
4
|
import fs from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import { Command, Option } from "commander";
|
|
6
|
+
import { Command, InvalidArgumentError, Option } from "commander";
|
|
7
7
|
|
|
8
8
|
//#region src/cli/commands/generate-types.ts
|
|
9
9
|
/**
|
|
10
|
+
* Env var for the warehouse wait limit, in seconds. Read by the type generator;
|
|
11
|
+
* the CLI only reads it to size the background worker's lock.
|
|
12
|
+
*/
|
|
13
|
+
const WAIT_TIMEOUT_ENV = "APPKIT_TYPEGEN_WAIT_TIMEOUT";
|
|
14
|
+
/**
|
|
10
15
|
* Resolve the typegen pre-flight mode for the CLI. Defaults to "non-blocking" —
|
|
11
16
|
* a one-shot CLI can't describe in the background, so by default it never
|
|
12
17
|
* describes at all: it skips the warehouse probe AND every DESCRIBE, emits
|
|
@@ -20,6 +25,26 @@ function resolveTypegenMode(options) {
|
|
|
20
25
|
return options?.wait ? "blocking" : "non-blocking";
|
|
21
26
|
}
|
|
22
27
|
/**
|
|
28
|
+
* Parse `--wait-timeout <seconds>`: a non-negative number of seconds. `0` means
|
|
29
|
+
* "check the warehouse once, don't wait".
|
|
30
|
+
*/
|
|
31
|
+
function parseWaitTimeoutSeconds(value) {
|
|
32
|
+
const seconds = Number(value);
|
|
33
|
+
if (value.trim() === "" || !Number.isFinite(seconds) || seconds < 0) throw new InvalidArgumentError("Expected a number of seconds (0 or more).");
|
|
34
|
+
return seconds;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The wait limit the background worker will use, in milliseconds, when one is
|
|
38
|
+
* configured (flag first, then env). `undefined` means the generator default.
|
|
39
|
+
*/
|
|
40
|
+
function configuredWaitTimeoutMs(flagSeconds) {
|
|
41
|
+
if (flagSeconds !== void 0) return flagSeconds * 1e3;
|
|
42
|
+
const raw = process.env[WAIT_TIMEOUT_ENV]?.trim();
|
|
43
|
+
if (!raw) return void 0;
|
|
44
|
+
const seconds = Number(raw);
|
|
45
|
+
return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1e3 : void 0;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
23
48
|
* Generate types command implementation. Runs the library generate (which, in
|
|
24
49
|
* non-blocking mode, writes degraded types and returns immediately). This is the
|
|
25
50
|
* SAME work the worker performs in blocking mode in the background.
|
|
@@ -44,7 +69,8 @@ async function runGenerateTypes(rootDir, outFile, warehouseId, options) {
|
|
|
44
69
|
outFile: resolvedOutFile,
|
|
45
70
|
warehouseId: resolvedWarehouseId,
|
|
46
71
|
noCache,
|
|
47
|
-
mode
|
|
72
|
+
mode,
|
|
73
|
+
waitTimeoutMs: options?.waitTimeout === void 0 ? void 0 : options.waitTimeout * 1e3
|
|
48
74
|
});
|
|
49
75
|
if (hasQueries) console.log(`Generated query types: ${resolvedOutFile}`);
|
|
50
76
|
const metricConfig = path.join(metricViewsFolder, METRIC_CONFIG_FILE);
|
|
@@ -121,6 +147,7 @@ function spawnTypegenWorker(lockPath, targets) {
|
|
|
121
147
|
"--wait",
|
|
122
148
|
"--worker-lock",
|
|
123
149
|
lockPath,
|
|
150
|
+
...targets.waitTimeout === void 0 ? [] : ["--wait-timeout", String(targets.waitTimeout)],
|
|
124
151
|
...positionals
|
|
125
152
|
];
|
|
126
153
|
try {
|
|
@@ -159,21 +186,23 @@ async function generateTypesAction(rootDir, outFile, warehouseId, options) {
|
|
|
159
186
|
}
|
|
160
187
|
if (!isWorker && resolveTypegenMode(options) === "non-blocking") {
|
|
161
188
|
const lockPath = getSpawnLockPath(rootDir || process.cwd());
|
|
162
|
-
if (acquireSpawnLock(lockPath)) spawnTypegenWorker(lockPath, {
|
|
189
|
+
if (acquireSpawnLock(lockPath, spawnLockStaleMsFor(configuredWaitTimeoutMs(options.waitTimeout)))) spawnTypegenWorker(lockPath, {
|
|
163
190
|
rootDir,
|
|
164
191
|
outFile,
|
|
165
|
-
warehouseId
|
|
192
|
+
warehouseId,
|
|
193
|
+
waitTimeout: options.waitTimeout
|
|
166
194
|
});
|
|
167
195
|
else console.log("Type refresh already in progress, skipping.");
|
|
168
196
|
}
|
|
169
197
|
}
|
|
170
|
-
const generateTypesCommand = new Command("generate-types").description("Generate TypeScript types from AppKit configuration").argument("[rootDir]", "Root directory of the project", process.cwd()).argument("[outFile]", "Output file path", path.join(process.cwd(), "shared/appkit-types/analytics.d.ts")).argument("[warehouseId]", "Databricks warehouse ID").option("--no-cache", "Disable caching for type generation").option("--wait", "Wait for warehouse readiness instead of degrading (use for CI)").addOption(new Option("--worker-lock <path>", "Internal: detached worker lock path").hideHelp()).addHelpText("after", `
|
|
198
|
+
const generateTypesCommand = new Command("generate-types").description("Generate TypeScript types from AppKit configuration").argument("[rootDir]", "Root directory of the project", process.cwd()).argument("[outFile]", "Output file path", path.join(process.cwd(), "shared/appkit-types/analytics.d.ts")).argument("[warehouseId]", "Databricks warehouse ID").option("--no-cache", "Disable caching for type generation").option("--wait", "Wait for warehouse readiness instead of degrading (use for CI)").option("--wait-timeout <seconds>", "With --wait: give up waiting for the warehouse after this many seconds, then keep committed types or fail (default: $APPKIT_TYPEGEN_WAIT_TIMEOUT, else 300)", parseWaitTimeoutSeconds).addOption(new Option("--worker-lock <path>", "Internal: detached worker lock path").hideHelp()).addHelpText("after", `
|
|
171
199
|
Examples:
|
|
172
200
|
$ appkit generate-types
|
|
173
201
|
$ appkit generate-types . shared/appkit-types/analytics.d.ts
|
|
174
202
|
$ appkit generate-types . shared/appkit-types/analytics.d.ts my-warehouse-id
|
|
175
203
|
$ appkit generate-types --no-cache
|
|
176
|
-
$ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one
|
|
204
|
+
$ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one
|
|
205
|
+
$ appkit generate-types --wait --wait-timeout 120 # give up on the warehouse after 2 minutes`).action(generateTypesAction);
|
|
177
206
|
|
|
178
207
|
//#endregion
|
|
179
208
|
export { generateTypesCommand };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-types.js","names":[],"sources":["../../../src/cli/commands/generate-types.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Command, Option } from \"commander\";\n\nimport { METRIC_CONFIG_FILE } from \"../../schemas/metric-fqn\";\nimport {\n acquireSpawnLock,\n getSpawnLockPath,\n releaseSpawnLock,\n} from \"./spawn-lock.js\";\n\n/**\n * Resolve the typegen pre-flight mode for the CLI. Defaults to \"non-blocking\" —\n * a one-shot CLI can't describe in the background, so by default it never\n * describes at all: it skips the warehouse probe AND every DESCRIBE, emits\n * best-available types (cache where the SQL hash matches, else `result: unknown`)\n * and returns immediately, never blocking on — or failing because of — a\n * warehouse, even a RUNNING one. Pass `--wait` (commander sets `wait: true`)\n * for a deliberate/CI invocation that should wait for a starting warehouse and\n * fail fast on a stopped one.\n */\nexport function resolveTypegenMode(options?: {\n wait?: boolean;\n}): \"non-blocking\" | \"blocking\" {\n return options?.wait ? \"blocking\" : \"non-blocking\";\n}\n\n/** Options parsed by commander for the generate-types command. */\ninterface GenerateTypesOptions {\n noCache?: boolean;\n wait?: boolean;\n /**\n * Internal: present only on the detached worker invocation. Carries the path\n * of the single-flight lock this worker must release when it finishes. Its\n * presence is what marks an invocation as \"the worker\" — workers always run\n * with `--wait`, so they never spawn another worker (only non-blocking runs\n * spawn), which terminates the recursion.\n */\n workerLock?: string;\n}\n\n/**\n * Generate types command implementation. Runs the library generate (which, in\n * non-blocking mode, writes degraded types and returns immediately). This is the\n * SAME work the worker performs in blocking mode in the background.\n */\nasync function runGenerateTypes(\n rootDir?: string,\n outFile?: string,\n warehouseId?: string,\n options?: GenerateTypesOptions,\n) {\n try {\n const resolvedRootDir = rootDir || process.cwd();\n const noCache = options?.noCache || false;\n const mode = resolveTypegenMode(options);\n\n const typeGen = await import(\"@databricks/appkit/type-generator\");\n const resolvedOutFile =\n outFile || path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\");\n\n // Generate analytics query types (requires warehouse ID)\n const resolvedWarehouseId =\n warehouseId || process.env.DATABRICKS_WAREHOUSE_ID;\n\n if (resolvedWarehouseId) {\n const queryFolder = path.join(resolvedRootDir, \"config/queries\");\n const metricViewsFolder = path.join(\n resolvedRootDir,\n \"config/metric-views\",\n );\n const hasQueries = fs.existsSync(queryFolder);\n const hasMetricViews = fs.existsSync(metricViewsFolder);\n\n // Generate when either config surface exists. Metric-view types are\n // independent of `.sql` queries — an app can declare metric views in\n // `config/metric-views/` without a `config/queries/` folder.\n if (hasQueries || hasMetricViews) {\n await typeGen.generateFromEntryPoint({\n queryFolder: hasQueries ? queryFolder : undefined,\n metricViewsFolder: hasMetricViews ? metricViewsFolder : undefined,\n outFile: resolvedOutFile,\n warehouseId: resolvedWarehouseId,\n noCache,\n mode,\n });\n\n if (hasQueries) {\n console.log(`Generated query types: ${resolvedOutFile}`);\n }\n\n const metricConfig = path.join(metricViewsFolder, METRIC_CONFIG_FILE);\n if (fs.existsSync(metricConfig)) {\n const typesDir = path.dirname(resolvedOutFile);\n console.log(\n `Generated metric types: ${path.join(typesDir, \"metric-views.ts\")}`,\n );\n }\n }\n } else {\n console.error(\n \"Skipping query type generation: no warehouse ID. Set DATABRICKS_WAREHOUSE_ID or pass as argument.\",\n );\n }\n\n // Generate serving endpoint types (no warehouse required)\n const servingOutFile = path.join(\n process.cwd(),\n \"shared/appkit-types/serving.d.ts\",\n );\n await typeGen.generateServingTypes({\n outFile: servingOutFile,\n noCache,\n });\n console.log(`Generated serving types: ${servingOutFile}`);\n\n // Generate database declarations.\n const databaseSchemaFile = path.join(\n resolvedRootDir,\n \"config/database/schema.ts\",\n );\n const databaseOutFile = path.join(\n path.dirname(resolvedOutFile),\n typeGen.DATABASE_TYPES_FILE,\n );\n if (fs.existsSync(databaseSchemaFile) || fs.existsSync(databaseOutFile)) {\n await typeGen.generateDatabaseTypes({\n schemaFile: databaseSchemaFile,\n outFile: databaseOutFile,\n });\n console.log(`Generated database types: ${databaseOutFile}`);\n }\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"Cannot find module\")\n ) {\n console.error(\n \"Error: The 'generate-types' command is only available in @databricks/appkit.\",\n );\n console.error(\"Please install @databricks/appkit to use this command.\");\n process.exit(1);\n }\n // TypegenSyntaxError / TypegenFatalError carry a complete, actionable\n // message (which queries failed and how to debug them). The stack trace\n // points into appkit internals and is noise for app developers, so print\n // only the message and exit non-zero instead of letting it bubble up.\n if (\n error instanceof Error &&\n (error.name === \"TypegenSyntaxError\" ||\n error.name === \"TypegenFatalError\" ||\n error.name === \"DatabaseTypegenError\")\n ) {\n console.error(error.message);\n process.exit(1);\n }\n throw error;\n }\n}\n\n/**\n * Spawn the detached blocking worker that refreshes real types in the background\n * after the foreground non-blocking generate has already written degraded types.\n *\n * Re-invokes THIS CLI (`process.execPath` + `process.argv[1]` — the bin entry\n * that launched us) with `generate-types --wait --worker-lock <lockPath>` plus\n * the same positional target options the foreground used, so the worker writes\n * to the same out file / reads the same query folder. The worker is:\n * - `detached: true` + `.unref()` so it outlives this process (install/dev-setup\n * can finish and exit while the worker keeps warming the warehouse).\n * - `stdio: \"ignore\"` so it never holds the parent's pipes open or interleaves\n * output into the install/dev log.\n *\n * Spawning is wrapped so any failure is non-fatal: the caller still has degraded\n * types and exits 0.\n *\n * @param lockPath - the acquired single-flight lock; passed to the worker so it\n * releases the SAME lock when it finishes.\n * @param targets - the foreground's positional args, forwarded verbatim.\n * @returns true if the worker was spawned, false if spawning threw.\n */\nexport function spawnTypegenWorker(\n lockPath: string,\n targets: { rootDir?: string; outFile?: string; warehouseId?: string },\n): boolean {\n // The script the runtime launched us with (the `appkit` bin shim). Re-running\n // it under the same node binary reproduces this exact CLI in the worker.\n const cliEntry = process.argv[1];\n\n // Forward the positionals in declaration order (rootDir, outFile,\n // warehouseId). Stop at the first undefined so we never pass a literal\n // \"undefined\" — commander would treat it as a positional value. (rootDir is\n // effectively always set by commander's default, but guard anyway.)\n const positionals: string[] = [];\n for (const value of [targets.rootDir, targets.outFile, targets.warehouseId]) {\n if (value === undefined) break;\n positionals.push(value);\n }\n\n const args = [\n // Forward the parent's node/loader flags so the worker runs under the same\n // runtime. Critically this carries tsx's `--require`/`--import` when the CLI\n // is run from source (`tsx index.ts …`); without them the worker would be\n // `node index.ts …`, which can't parse TypeScript and dies silently — the\n // degraded types would then never refresh. Empty for the built bin (plain\n // `node bin/appkit.js`), so production behaviour is unchanged.\n ...process.execArgv,\n cliEntry,\n \"generate-types\",\n \"--wait\",\n \"--worker-lock\",\n lockPath,\n ...positionals,\n ];\n\n try {\n const child = spawn(process.execPath, args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n return true;\n } catch (error) {\n // Non-fatal: the foreground already wrote degraded types. Log and move on.\n console.error(\n `Could not start background type refresh: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n}\n\n/**\n * The command action. Orchestrates the non-blocking foreground contract:\n * 1. Run the library generate (writes degraded types immediately in non-blocking\n * mode; does the full blocking lifecycle when this is the worker).\n * 2. If this is a non-blocking, non-worker invocation, try to spawn the detached\n * blocking worker behind the single-flight lock. If the lock is already held\n * by a live worker, skip (single-flight) with a one-line note. Either way the\n * foreground returns normally (exit 0).\n * 3. If this IS the worker (`--worker-lock` present), it ran blocking above and\n * releases the lock here (and via a process-exit guard, so a hard failure /\n * process.exit still frees it).\n */\nasync function generateTypesAction(\n rootDir: string | undefined,\n outFile: string | undefined,\n warehouseId: string | undefined,\n options: GenerateTypesOptions,\n) {\n const isWorker = typeof options.workerLock === \"string\";\n\n // A worker must always free its lock, even if the blocking generate throws or\n // calls process.exit (TypegenFatalError → exit 1). The exit handler covers the\n // process.exit / uncaught paths; the finally covers the normal return.\n if (isWorker && options.workerLock) {\n const lockPath = options.workerLock;\n process.once(\"exit\", () => releaseSpawnLock(lockPath));\n }\n\n try {\n await runGenerateTypes(rootDir, outFile, warehouseId, options);\n } finally {\n if (isWorker && options.workerLock) {\n releaseSpawnLock(options.workerLock);\n }\n }\n\n // Only a non-blocking, non-worker invocation spawns. A worker is always\n // --wait (so resolveTypegenMode → \"blocking\"), which both prevents recursion\n // and means we never get here for a worker.\n if (!isWorker && resolveTypegenMode(options) === \"non-blocking\") {\n const resolvedRootDir = rootDir || process.cwd();\n const lockPath = getSpawnLockPath(resolvedRootDir);\n\n if (acquireSpawnLock(lockPath)) {\n spawnTypegenWorker(lockPath, { rootDir, outFile, warehouseId });\n } else {\n console.log(\"Type refresh already in progress, skipping.\");\n }\n }\n}\n\nexport const generateTypesCommand = new Command(\"generate-types\")\n .description(\"Generate TypeScript types from AppKit configuration\")\n .argument(\"[rootDir]\", \"Root directory of the project\", process.cwd())\n .argument(\n \"[outFile]\",\n \"Output file path\",\n path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\"),\n )\n .argument(\"[warehouseId]\", \"Databricks warehouse ID\")\n .option(\"--no-cache\", \"Disable caching for type generation\")\n .option(\n \"--wait\",\n \"Wait for warehouse readiness instead of degrading (use for CI)\",\n )\n // Internal: marks the detached background worker and carries the lock it must\n // release. Hidden from --help; users should never pass it.\n .addOption(\n new Option(\n \"--worker-lock <path>\",\n \"Internal: detached worker lock path\",\n ).hideHelp(),\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ appkit generate-types\n $ appkit generate-types . shared/appkit-types/analytics.d.ts\n $ appkit generate-types . shared/appkit-types/analytics.d.ts my-warehouse-id\n $ appkit generate-types --no-cache\n $ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one`,\n )\n .action(generateTypesAction);\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,SAAgB,mBAAmB,SAEH;AAC9B,QAAO,SAAS,OAAO,aAAa;;;;;;;AAsBtC,eAAe,iBACb,SACA,SACA,aACA,SACA;AACA,KAAI;EACF,MAAM,kBAAkB,WAAW,QAAQ,KAAK;EAChD,MAAM,UAAU,SAAS,WAAW;EACpC,MAAM,OAAO,mBAAmB,QAAQ;EAExC,MAAM,UAAU,MAAM,OAAO;EAC7B,MAAM,kBACJ,WAAW,KAAK,KAAK,QAAQ,KAAK,EAAE,qCAAqC;EAG3E,MAAM,sBACJ,eAAe,QAAQ,IAAI;AAE7B,MAAI,qBAAqB;GACvB,MAAM,cAAc,KAAK,KAAK,iBAAiB,iBAAiB;GAChE,MAAM,oBAAoB,KAAK,KAC7B,iBACA,sBACD;GACD,MAAM,aAAa,GAAG,WAAW,YAAY;GAC7C,MAAM,iBAAiB,GAAG,WAAW,kBAAkB;AAKvD,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ACA,sCACD,CAAC,UAAU,CACb,CACA,YACC,SACA;;;;;;wFAOD,CACA,OAAO,oBAAoB"}
|
|
1
|
+
{"version":3,"file":"generate-types.js","names":[],"sources":["../../../src/cli/commands/generate-types.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Command, InvalidArgumentError, Option } from \"commander\";\n\nimport { METRIC_CONFIG_FILE } from \"../../schemas/metric-fqn\";\nimport {\n acquireSpawnLock,\n getSpawnLockPath,\n releaseSpawnLock,\n spawnLockStaleMsFor,\n} from \"./spawn-lock.js\";\n\n/**\n * Env var for the warehouse wait limit, in seconds. Read by the type generator;\n * the CLI only reads it to size the background worker's lock.\n */\nconst WAIT_TIMEOUT_ENV = \"APPKIT_TYPEGEN_WAIT_TIMEOUT\";\n\n/**\n * Resolve the typegen pre-flight mode for the CLI. Defaults to \"non-blocking\" —\n * a one-shot CLI can't describe in the background, so by default it never\n * describes at all: it skips the warehouse probe AND every DESCRIBE, emits\n * best-available types (cache where the SQL hash matches, else `result: unknown`)\n * and returns immediately, never blocking on — or failing because of — a\n * warehouse, even a RUNNING one. Pass `--wait` (commander sets `wait: true`)\n * for a deliberate/CI invocation that should wait for a starting warehouse and\n * fail fast on a stopped one.\n */\nexport function resolveTypegenMode(options?: {\n wait?: boolean;\n}): \"non-blocking\" | \"blocking\" {\n return options?.wait ? \"blocking\" : \"non-blocking\";\n}\n\n/**\n * Parse `--wait-timeout <seconds>`: a non-negative number of seconds. `0` means\n * \"check the warehouse once, don't wait\".\n */\nexport function parseWaitTimeoutSeconds(value: string): number {\n const seconds = Number(value);\n if (value.trim() === \"\" || !Number.isFinite(seconds) || seconds < 0) {\n throw new InvalidArgumentError(\"Expected a number of seconds (0 or more).\");\n }\n return seconds;\n}\n\n/**\n * The wait limit the background worker will use, in milliseconds, when one is\n * configured (flag first, then env). `undefined` means the generator default.\n */\nfunction configuredWaitTimeoutMs(flagSeconds?: number): number | undefined {\n if (flagSeconds !== undefined) return flagSeconds * 1000;\n const raw = process.env[WAIT_TIMEOUT_ENV]?.trim();\n if (!raw) return undefined;\n const seconds = Number(raw);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : undefined;\n}\n\n/** Options parsed by commander for the generate-types command. */\ninterface GenerateTypesOptions {\n noCache?: boolean;\n wait?: boolean;\n /**\n * `--wait-timeout <seconds>`: limit on waiting for the warehouse to reach\n * RUNNING under `--wait`. Unset → `APPKIT_TYPEGEN_WAIT_TIMEOUT`, else 5 min\n * (resolved by the type generator).\n */\n waitTimeout?: number;\n /**\n * Internal: present only on the detached worker invocation. Carries the path\n * of the single-flight lock this worker must release when it finishes. Its\n * presence is what marks an invocation as \"the worker\" — workers always run\n * with `--wait`, so they never spawn another worker (only non-blocking runs\n * spawn), which terminates the recursion.\n */\n workerLock?: string;\n}\n\n/**\n * Generate types command implementation. Runs the library generate (which, in\n * non-blocking mode, writes degraded types and returns immediately). This is the\n * SAME work the worker performs in blocking mode in the background.\n */\nasync function runGenerateTypes(\n rootDir?: string,\n outFile?: string,\n warehouseId?: string,\n options?: GenerateTypesOptions,\n) {\n try {\n const resolvedRootDir = rootDir || process.cwd();\n const noCache = options?.noCache || false;\n const mode = resolveTypegenMode(options);\n\n const typeGen = await import(\"@databricks/appkit/type-generator\");\n const resolvedOutFile =\n outFile || path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\");\n\n // Generate analytics query types (requires warehouse ID)\n const resolvedWarehouseId =\n warehouseId || process.env.DATABRICKS_WAREHOUSE_ID;\n\n if (resolvedWarehouseId) {\n const queryFolder = path.join(resolvedRootDir, \"config/queries\");\n const metricViewsFolder = path.join(\n resolvedRootDir,\n \"config/metric-views\",\n );\n const hasQueries = fs.existsSync(queryFolder);\n const hasMetricViews = fs.existsSync(metricViewsFolder);\n\n // Generate when either config surface exists. Metric-view types are\n // independent of `.sql` queries — an app can declare metric views in\n // `config/metric-views/` without a `config/queries/` folder.\n if (hasQueries || hasMetricViews) {\n await typeGen.generateFromEntryPoint({\n queryFolder: hasQueries ? queryFolder : undefined,\n metricViewsFolder: hasMetricViews ? metricViewsFolder : undefined,\n outFile: resolvedOutFile,\n warehouseId: resolvedWarehouseId,\n noCache,\n mode,\n waitTimeoutMs:\n options?.waitTimeout === undefined\n ? undefined\n : options.waitTimeout * 1000,\n });\n\n if (hasQueries) {\n console.log(`Generated query types: ${resolvedOutFile}`);\n }\n\n const metricConfig = path.join(metricViewsFolder, METRIC_CONFIG_FILE);\n if (fs.existsSync(metricConfig)) {\n const typesDir = path.dirname(resolvedOutFile);\n console.log(\n `Generated metric types: ${path.join(typesDir, \"metric-views.ts\")}`,\n );\n }\n }\n } else {\n console.error(\n \"Skipping query type generation: no warehouse ID. Set DATABRICKS_WAREHOUSE_ID or pass as argument.\",\n );\n }\n\n // Generate serving endpoint types (no warehouse required)\n const servingOutFile = path.join(\n process.cwd(),\n \"shared/appkit-types/serving.d.ts\",\n );\n await typeGen.generateServingTypes({\n outFile: servingOutFile,\n noCache,\n });\n console.log(`Generated serving types: ${servingOutFile}`);\n\n // Generate database declarations.\n const databaseSchemaFile = path.join(\n resolvedRootDir,\n \"config/database/schema.ts\",\n );\n const databaseOutFile = path.join(\n path.dirname(resolvedOutFile),\n typeGen.DATABASE_TYPES_FILE,\n );\n if (fs.existsSync(databaseSchemaFile) || fs.existsSync(databaseOutFile)) {\n await typeGen.generateDatabaseTypes({\n schemaFile: databaseSchemaFile,\n outFile: databaseOutFile,\n });\n console.log(`Generated database types: ${databaseOutFile}`);\n }\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(\"Cannot find module\")\n ) {\n console.error(\n \"Error: The 'generate-types' command is only available in @databricks/appkit.\",\n );\n console.error(\"Please install @databricks/appkit to use this command.\");\n process.exit(1);\n }\n // TypegenSyntaxError / TypegenFatalError carry a complete, actionable\n // message (which queries failed and how to debug them). The stack trace\n // points into appkit internals and is noise for app developers, so print\n // only the message and exit non-zero instead of letting it bubble up.\n if (\n error instanceof Error &&\n (error.name === \"TypegenSyntaxError\" ||\n error.name === \"TypegenFatalError\" ||\n error.name === \"DatabaseTypegenError\")\n ) {\n console.error(error.message);\n process.exit(1);\n }\n throw error;\n }\n}\n\n/**\n * Spawn the detached blocking worker that refreshes real types in the background\n * after the foreground non-blocking generate has already written degraded types.\n *\n * Re-invokes THIS CLI (`process.execPath` + `process.argv[1]` — the bin entry\n * that launched us) with `generate-types --wait --worker-lock <lockPath>` plus\n * the same positional target options the foreground used, so the worker writes\n * to the same out file / reads the same query folder. The worker is:\n * - `detached: true` + `.unref()` so it outlives this process (install/dev-setup\n * can finish and exit while the worker keeps warming the warehouse).\n * - `stdio: \"ignore\"` so it never holds the parent's pipes open or interleaves\n * output into the install/dev log.\n *\n * Spawning is wrapped so any failure is non-fatal: the caller still has degraded\n * types and exits 0.\n *\n * @param lockPath - the acquired single-flight lock; passed to the worker so it\n * releases the SAME lock when it finishes.\n * @param targets - the foreground's positional args, forwarded verbatim.\n * @returns true if the worker was spawned, false if spawning threw.\n */\nexport function spawnTypegenWorker(\n lockPath: string,\n targets: {\n rootDir?: string;\n outFile?: string;\n warehouseId?: string;\n waitTimeout?: number;\n },\n): boolean {\n // The script the runtime launched us with (the `appkit` bin shim). Re-running\n // it under the same node binary reproduces this exact CLI in the worker.\n const cliEntry = process.argv[1];\n\n // Forward the positionals in declaration order (rootDir, outFile,\n // warehouseId). Stop at the first undefined so we never pass a literal\n // \"undefined\" — commander would treat it as a positional value. (rootDir is\n // effectively always set by commander's default, but guard anyway.)\n const positionals: string[] = [];\n for (const value of [targets.rootDir, targets.outFile, targets.warehouseId]) {\n if (value === undefined) break;\n positionals.push(value);\n }\n\n const args = [\n // Forward the parent's node/loader flags so the worker runs under the same\n // runtime. Critically this carries tsx's `--require`/`--import` when the CLI\n // is run from source (`tsx index.ts …`); without them the worker would be\n // `node index.ts …`, which can't parse TypeScript and dies silently — the\n // degraded types would then never refresh. Empty for the built bin (plain\n // `node bin/appkit.js`), so production behaviour is unchanged.\n ...process.execArgv,\n cliEntry,\n \"generate-types\",\n \"--wait\",\n \"--worker-lock\",\n lockPath,\n ...(targets.waitTimeout === undefined\n ? []\n : [\"--wait-timeout\", String(targets.waitTimeout)]),\n ...positionals,\n ];\n\n try {\n const child = spawn(process.execPath, args, {\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n return true;\n } catch (error) {\n // Non-fatal: the foreground already wrote degraded types. Log and move on.\n console.error(\n `Could not start background type refresh: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n return false;\n }\n}\n\n/**\n * The command action. Orchestrates the non-blocking foreground contract:\n * 1. Run the library generate (writes degraded types immediately in non-blocking\n * mode; does the full blocking lifecycle when this is the worker).\n * 2. If this is a non-blocking, non-worker invocation, try to spawn the detached\n * blocking worker behind the single-flight lock. If the lock is already held\n * by a live worker, skip (single-flight) with a one-line note. Either way the\n * foreground returns normally (exit 0).\n * 3. If this IS the worker (`--worker-lock` present), it ran blocking above and\n * releases the lock here (and via a process-exit guard, so a hard failure /\n * process.exit still frees it).\n */\nasync function generateTypesAction(\n rootDir: string | undefined,\n outFile: string | undefined,\n warehouseId: string | undefined,\n options: GenerateTypesOptions,\n) {\n const isWorker = typeof options.workerLock === \"string\";\n\n // A worker must always free its lock, even if the blocking generate throws or\n // calls process.exit (TypegenFatalError → exit 1). The exit handler covers the\n // process.exit / uncaught paths; the finally covers the normal return.\n if (isWorker && options.workerLock) {\n const lockPath = options.workerLock;\n process.once(\"exit\", () => releaseSpawnLock(lockPath));\n }\n\n try {\n await runGenerateTypes(rootDir, outFile, warehouseId, options);\n } finally {\n if (isWorker && options.workerLock) {\n releaseSpawnLock(options.workerLock);\n }\n }\n\n // Only a non-blocking, non-worker invocation spawns. A worker is always\n // --wait (so resolveTypegenMode → \"blocking\"), which both prevents recursion\n // and means we never get here for a worker.\n if (!isWorker && resolveTypegenMode(options) === \"non-blocking\") {\n const resolvedRootDir = rootDir || process.cwd();\n const lockPath = getSpawnLockPath(resolvedRootDir);\n\n const staleMs = spawnLockStaleMsFor(\n configuredWaitTimeoutMs(options.waitTimeout),\n );\n if (acquireSpawnLock(lockPath, staleMs)) {\n spawnTypegenWorker(lockPath, {\n rootDir,\n outFile,\n warehouseId,\n waitTimeout: options.waitTimeout,\n });\n } else {\n console.log(\"Type refresh already in progress, skipping.\");\n }\n }\n}\n\nexport const generateTypesCommand = new Command(\"generate-types\")\n .description(\"Generate TypeScript types from AppKit configuration\")\n .argument(\"[rootDir]\", \"Root directory of the project\", process.cwd())\n .argument(\n \"[outFile]\",\n \"Output file path\",\n path.join(process.cwd(), \"shared/appkit-types/analytics.d.ts\"),\n )\n .argument(\"[warehouseId]\", \"Databricks warehouse ID\")\n .option(\"--no-cache\", \"Disable caching for type generation\")\n .option(\n \"--wait\",\n \"Wait for warehouse readiness instead of degrading (use for CI)\",\n )\n .option(\n \"--wait-timeout <seconds>\",\n \"With --wait: give up waiting for the warehouse after this many seconds, then keep committed types or fail (default: $APPKIT_TYPEGEN_WAIT_TIMEOUT, else 300)\",\n parseWaitTimeoutSeconds,\n )\n // Internal: marks the detached background worker and carries the lock it must\n // release. Hidden from --help; users should never pass it.\n .addOption(\n new Option(\n \"--worker-lock <path>\",\n \"Internal: detached worker lock path\",\n ).hideHelp(),\n )\n .addHelpText(\n \"after\",\n `\nExamples:\n $ appkit generate-types\n $ appkit generate-types . shared/appkit-types/analytics.d.ts\n $ appkit generate-types . shared/appkit-types/analytics.d.ts my-warehouse-id\n $ appkit generate-types --no-cache\n $ appkit generate-types --wait # CI: wait for the warehouse and fail on a cold one\n $ appkit generate-types --wait --wait-timeout 120 # give up on the warehouse after 2 minutes`,\n )\n .action(generateTypesAction);\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAM,mBAAmB;;;;;;;;;;;AAYzB,SAAgB,mBAAmB,SAEH;AAC9B,QAAO,SAAS,OAAO,aAAa;;;;;;AAOtC,SAAgB,wBAAwB,OAAuB;CAC7D,MAAM,UAAU,OAAO,MAAM;AAC7B,KAAI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MAAM,QAAQ,UAAU,MAAM;GAC1C,UAAU;GACV,OAAO;GACR,CAAC,CACI,OAAO;AACb,SAAO;UACA,OAAO;AAEd,UAAQ,MACN,4CACE,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAEzD;AACD,SAAO;;;;;;;;;;;;;;;AAgBX,eAAe,oBACb,SACA,SACA,aACA,SACA;CACA,MAAM,WAAW,OAAO,QAAQ,eAAe;AAK/C,KAAI,YAAY,QAAQ,YAAY;EAClC,MAAM,WAAW,QAAQ;AACzB,UAAQ,KAAK,cAAc,iBAAiB,SAAS,CAAC;;AAGxD,KAAI;AACF,QAAM,iBAAiB,SAAS,SAAS,aAAa,QAAQ;WACtD;AACR,MAAI,YAAY,QAAQ,WACtB,kBAAiB,QAAQ,WAAW;;AAOxC,KAAI,CAAC,YAAY,mBAAmB,QAAQ,KAAK,gBAAgB;EAE/D,MAAM,WAAW,iBADO,WAAW,QAAQ,KAAK,CACE;AAKlD,MAAI,iBAAiB,UAHL,oBACd,wBAAwB,QAAQ,YAAY,CAC7C,CACsC,CACrC,oBAAmB,UAAU;GAC3B;GACA;GACA;GACA,aAAa,QAAQ;GACtB,CAAC;MAEF,SAAQ,IAAI,8CAA8C;;;AAKhE,MAAa,uBAAuB,IAAI,QAAQ,iBAAiB,CAC9D,YAAY,sDAAsD,CAClE,SAAS,aAAa,iCAAiC,QAAQ,KAAK,CAAC,CACrE,SACC,aACA,oBACA,KAAK,KAAK,QAAQ,KAAK,EAAE,qCAAqC,CAC/D,CACA,SAAS,iBAAiB,0BAA0B,CACpD,OAAO,cAAc,sCAAsC,CAC3D,OACC,UACA,iEACD,CACA,OACC,4BACA,+JACA,wBACD,CAGA,UACC,IAAI,OACF,wBACA,sCACD,CAAC,UAAU,CACb,CACA,YACC,SACA;;;;;;;kGAQD,CACA,OAAO,oBAAoB"}
|
|
@@ -8,12 +8,25 @@ import path from "node:path";
|
|
|
8
8
|
* older than this the lock is presumed orphaned (the worker crashed/was killed
|
|
9
9
|
* before it could release) and is stolen.
|
|
10
10
|
*
|
|
11
|
-
* Must comfortably exceed the worker's worst-case runtime: the
|
|
12
|
-
* wait
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Must comfortably exceed the worker's worst-case runtime: the default warehouse
|
|
12
|
+
* wait limit (5 min in the type-generator) plus a DESCRIBE budget. Six minutes
|
|
13
|
+
* leaves ~1 min of headroom over a worker that waits the full limit and then
|
|
14
|
+
* describes. A longer configured limit stretches it — see
|
|
15
|
+
* {@link spawnLockStaleMsFor}.
|
|
15
16
|
*/
|
|
16
17
|
const SPAWN_LOCK_STALE_MS = 360 * 1e3;
|
|
18
|
+
/** Headroom over the wait limit for the worker's DESCRIBE work. */
|
|
19
|
+
const DESCRIBE_HEADROOM_MS = 60 * 1e3;
|
|
20
|
+
/**
|
|
21
|
+
* Staleness threshold for a worker that may wait up to `waitTimeoutMs` for the
|
|
22
|
+
* warehouse: never shorter than {@link SPAWN_LOCK_STALE_MS}, and always at
|
|
23
|
+
* least the limit plus describe headroom, so a live worker on a long limit
|
|
24
|
+
* isn't mistaken for an orphan.
|
|
25
|
+
*/
|
|
26
|
+
function spawnLockStaleMsFor(waitTimeoutMs) {
|
|
27
|
+
if (waitTimeoutMs === void 0 || !Number.isFinite(waitTimeoutMs)) return SPAWN_LOCK_STALE_MS;
|
|
28
|
+
return Math.max(SPAWN_LOCK_STALE_MS, waitTimeoutMs + DESCRIBE_HEADROOM_MS);
|
|
29
|
+
}
|
|
17
30
|
/**
|
|
18
31
|
* Resolve the on-disk path of the single-flight spawn lock for a project.
|
|
19
32
|
*
|
|
@@ -112,5 +125,5 @@ function isErrnoException(error) {
|
|
|
112
125
|
}
|
|
113
126
|
|
|
114
127
|
//#endregion
|
|
115
|
-
export { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock };
|
|
128
|
+
export { acquireSpawnLock, getSpawnLockPath, releaseSpawnLock, spawnLockStaleMsFor };
|
|
116
129
|
//# sourceMappingURL=spawn-lock.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spawn-lock.js","names":[],"sources":["../../../src/cli/commands/spawn-lock.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * How long a spawn lock is considered fresh. A held lock newer than this means a\n * background worker is genuinely in flight, so the foreground skips spawning;\n * older than this the lock is presumed orphaned (the worker crashed/was killed\n * before it could release) and is stolen.\n *\n * Must comfortably exceed the worker's worst-case runtime: the
|
|
1
|
+
{"version":3,"file":"spawn-lock.js","names":[],"sources":["../../../src/cli/commands/spawn-lock.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * How long a spawn lock is considered fresh. A held lock newer than this means a\n * background worker is genuinely in flight, so the foreground skips spawning;\n * older than this the lock is presumed orphaned (the worker crashed/was killed\n * before it could release) and is stolen.\n *\n * Must comfortably exceed the worker's worst-case runtime: the default warehouse\n * wait limit (5 min in the type-generator) plus a DESCRIBE budget. Six minutes\n * leaves ~1 min of headroom over a worker that waits the full limit and then\n * describes. A longer configured limit stretches it — see\n * {@link spawnLockStaleMsFor}.\n */\nexport const SPAWN_LOCK_STALE_MS = 6 * 60 * 1000;\n\n/** Headroom over the wait limit for the worker's DESCRIBE work. */\nconst DESCRIBE_HEADROOM_MS = 60 * 1000;\n\n/**\n * Staleness threshold for a worker that may wait up to `waitTimeoutMs` for the\n * warehouse: never shorter than {@link SPAWN_LOCK_STALE_MS}, and always at\n * least the limit plus describe headroom, so a live worker on a long limit\n * isn't mistaken for an orphan.\n */\nexport function spawnLockStaleMsFor(waitTimeoutMs?: number): number {\n if (waitTimeoutMs === undefined || !Number.isFinite(waitTimeoutMs)) {\n return SPAWN_LOCK_STALE_MS;\n }\n return Math.max(SPAWN_LOCK_STALE_MS, waitTimeoutMs + DESCRIBE_HEADROOM_MS);\n}\n\n/**\n * Resolve the on-disk path of the single-flight spawn lock for a project.\n *\n * Lives alongside the type-generator cache (`node_modules/.databricks/appkit/`)\n * so it shares the same already-creatable, gitignored, per-project location and\n * doesn't introduce a new directory. The lock is keyed only by project root, so\n * concurrent `generate-types` invocations for the same project (postinstall +\n * predev, say) contend for one lock and only one wins the spawn.\n *\n * @param rootDir - project root (the resolved first CLI argument / cwd).\n * @returns absolute path to the lock file.\n */\nexport function getSpawnLockPath(rootDir: string): string {\n return path.join(\n rootDir,\n \"node_modules\",\n \".databricks\",\n \"appkit\",\n \".appkit-typegen-worker.lock\",\n );\n}\n\n/**\n * Try to acquire the single-flight spawn lock.\n *\n * Atomic create via `fs.writeFileSync(lockPath, ..., { flag: \"wx\" })` — `wx`\n * fails (EEXIST) if the file already exists, so the create itself is the\n * mutual-exclusion primitive (no check-then-create race between two foreground\n * processes). The lock body records pid + timestamp purely for debugging.\n *\n * On EEXIST we stat the existing lock:\n * - fresh (mtime within {@link staleMs}) → a worker is in flight, return false.\n * - stale (mtime older than staleMs) → presumed orphaned; unlink and recreate.\n * The recreate also uses `wx`, so if a competing process steals it first we\n * lose the race cleanly and return false.\n *\n * Any unexpected error (permission, ENOENT on a missing parent dir we couldn't\n * create, …) is swallowed and reported as \"not acquired\": failing to take the\n * lock must never break the foreground — at worst we skip the background refresh.\n *\n * @param lockPath - path returned by {@link getSpawnLockPath}.\n * @param staleMs - age beyond which a held lock is stolen. Defaults to\n * {@link SPAWN_LOCK_STALE_MS}.\n * @returns true if this caller now owns the lock (and must release it), false if\n * another live worker holds it or the lock couldn't be taken.\n */\nexport function acquireSpawnLock(\n lockPath: string,\n staleMs: number = SPAWN_LOCK_STALE_MS,\n): boolean {\n const body = `${process.pid} ${Date.now()}\\n`;\n\n try {\n fs.mkdirSync(path.dirname(lockPath), { recursive: true });\n } catch {\n // Parent dir creation is best-effort; the create below will surface any real\n // problem and we'll treat it as \"not acquired\".\n }\n\n try {\n fs.writeFileSync(lockPath, body, { flag: \"wx\" });\n return true;\n } catch (error) {\n if (!isErrnoException(error) || error.code !== \"EEXIST\") {\n // Unexpected failure — don't let lock IO break the foreground.\n return false;\n }\n }\n\n // Lock exists — decide fresh vs stale.\n let mtimeMs: number;\n try {\n mtimeMs = fs.statSync(lockPath).mtimeMs;\n } catch {\n // It vanished between the failed create and the stat (released by the\n // worker). Try once more to take it.\n return tryCreate(lockPath, body);\n }\n\n if (Date.now() - mtimeMs < staleMs) {\n // A worker is genuinely in flight.\n return false;\n }\n\n // Stale: steal it. Unlink (ignore ENOENT — someone else may have cleaned up)\n // then re-create with `wx` so we still lose cleanly to a racing stealer.\n try {\n fs.unlinkSync(lockPath);\n } catch (error) {\n if (isErrnoException(error) && error.code !== \"ENOENT\") {\n return false;\n }\n }\n return tryCreate(lockPath, body);\n}\n\n/**\n * Release the spawn lock. Unlink, ignoring ENOENT (already gone — e.g. it was\n * stolen as stale by another process, or never existed). Any other error is\n * swallowed: a failed release at worst leaves a stale lock that the next caller\n * will steal after {@link SPAWN_LOCK_STALE_MS}.\n *\n * @param lockPath - path returned by {@link getSpawnLockPath}.\n */\nexport function releaseSpawnLock(lockPath: string): void {\n try {\n fs.unlinkSync(lockPath);\n } catch {\n // ENOENT or any other error — releasing is best-effort.\n }\n}\n\n/**\n * Attempt an atomic `wx` create, returning whether it succeeded. EEXIST (a\n * racing creator beat us) and any other error map to false.\n */\nfunction tryCreate(lockPath: string, body: string): boolean {\n try {\n fs.writeFileSync(lockPath, body, { flag: \"wx\" });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Narrow an unknown caught value to a Node errno exception so `.code` is safe to\n * read.\n */\nfunction isErrnoException(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeA,MAAa,sBAAsB,MAAS;;AAG5C,MAAM,uBAAuB,KAAK;;;;;;;AAQlC,SAAgB,oBAAoB,eAAgC;AAClE,KAAI,kBAAkB,UAAa,CAAC,OAAO,SAAS,cAAc,CAChE,QAAO;AAET,QAAO,KAAK,IAAI,qBAAqB,gBAAgB,qBAAqB;;;;;;;;;;;;;;AAe5E,SAAgB,iBAAiB,SAAyB;AACxD,QAAO,KAAK,KACV,SACA,gBACA,eACA,UACA,8BACD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BH,SAAgB,iBACd,UACA,UAAkB,qBACT;CACT,MAAM,OAAO,GAAG,QAAQ,IAAI,GAAG,KAAK,KAAK,CAAC;AAE1C,KAAI;AACF,KAAG,UAAU,KAAK,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;SACnD;AAKR,KAAI;AACF,KAAG,cAAc,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAChD,SAAO;UACA,OAAO;AACd,MAAI,CAAC,iBAAiB,MAAM,IAAI,MAAM,SAAS,SAE7C,QAAO;;CAKX,IAAI;AACJ,KAAI;AACF,YAAU,GAAG,SAAS,SAAS,CAAC;SAC1B;AAGN,SAAO,UAAU,UAAU,KAAK;;AAGlC,KAAI,KAAK,KAAK,GAAG,UAAU,QAEzB,QAAO;AAKT,KAAI;AACF,KAAG,WAAW,SAAS;UAChB,OAAO;AACd,MAAI,iBAAiB,MAAM,IAAI,MAAM,SAAS,SAC5C,QAAO;;AAGX,QAAO,UAAU,UAAU,KAAK;;;;;;;;;;AAWlC,SAAgB,iBAAiB,UAAwB;AACvD,KAAI;AACF,KAAG,WAAW,SAAS;SACjB;;;;;;AASV,SAAS,UAAU,UAAkB,MAAuB;AAC1D,KAAI;AACF,KAAG,cAAc,UAAU,MAAM,EAAE,MAAM,MAAM,CAAC;AAChD,SAAO;SACD;AACN,SAAO;;;;;;;AAQX,SAAS,iBAAiB,OAAgD;AACxE,QAAO,iBAAiB,SAAS,UAAU"}
|
|
@@ -45,8 +45,8 @@ interface DatabaseApi {
|
|
|
45
45
|
get<K extends DatabaseKeyedEntity, const P extends DatabaseRecordParams<K> = Record<never, never>>(entity: K, id: DatabaseId<K>, params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>, init?: DatabaseRequestOptions): Promise<DatabaseRecordRow<K, P>>;
|
|
46
46
|
/**
|
|
47
47
|
* Create one row with `POST /api/database/<entity>` and return it as the
|
|
48
|
-
* database holds it
|
|
49
|
-
*
|
|
48
|
+
* database holds it. Private, generated, and undeclared fields are compile
|
|
49
|
+
* errors, as the server refuses them.
|
|
50
50
|
*
|
|
51
51
|
* @example
|
|
52
52
|
* ```typescript
|
|
@@ -91,7 +91,7 @@ function isDatabaseListPage(body) {
|
|
|
91
91
|
return isRecord(body) && Array.isArray(body.items) && typeof body.limit === "number" && typeof body.offset === "number";
|
|
92
92
|
}
|
|
93
93
|
/**
|
|
94
|
-
* A detail route answers one bare row
|
|
94
|
+
* A detail route answers one bare row.
|
|
95
95
|
* @internal Shared with the React hooks; not part of the public surface.
|
|
96
96
|
*/
|
|
97
97
|
function isDatabaseRow(body) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../../src/js/database/client.ts"],"sourcesContent":["import {\n type DatabaseErrorDetail,\n type DatabaseListPage,\n type DatabaseListQuery,\n databaseErrorCategoryForStatus,\n encodeDatabaseListQuery,\n encodeDatabaseRecordQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { getClientConfig } from \"../config\";\nimport {\n DatabaseApiError,\n invalidDatabaseQuery,\n invalidDatabaseWrite,\n} from \"./errors\";\nimport type {\n DatabaseEntity,\n DatabaseId,\n DatabaseInsert,\n DatabaseKeyedEntity,\n DatabaseListParams,\n DatabaseListRow,\n DatabaseRecordParams,\n DatabaseRecordRow,\n DatabaseRow,\n DatabaseUpdate,\n} from \"./types\";\n\n/**\n * Suffix of the endpoint names `DatabasePlugin` publishes for each table.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport type DatabaseOperation =\n | \"list\"\n | \"detail\"\n | \"create\"\n | \"update\"\n | \"delete\";\n\n/**\n * An id as a keyed route addresses it in its path.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport type IdLike = string | number | bigint;\n\n/** Per-call options for a database request. */\nexport interface DatabaseRequestOptions {\n /**\n * Cancels the request; the promise then rejects with the abort reason.\n * Cancelling a write does not undo it once the server has committed.\n */\n readonly signal?: AbortSignal;\n}\n\n/** Typed calls to the routes `DatabasePlugin` generates under `/api/database`. */\nexport interface DatabaseApi {\n /**\n * Read one page from `GET /api/database/<entity>`. Rows are public rows as\n * JSON carries them, narrowed by `select` and widened by `include`.\n *\n * @example\n * ```typescript\n * const page = await databaseApi.list(\"notes\", {\n * where: { board_id: 7 },\n * order: { created_at: \"desc\" },\n * limit: 5,\n * });\n * page.items[0]?.body;\n * ```\n */\n list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K>>>;\n list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\n\n /**\n * Read one row from `GET /api/database/<entity>/:id`. Only entities with a\n * public primary key have this route; a missing row rejects with\n * `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * const board = await databaseApi.get(\"boards\", 7, {\n * include: { notes: { limit: 20 } },\n * });\n * board.notes.length;\n * ```\n */\n get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n >(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRecordRow<K, P>>;\n\n /**\n * Create one row with `POST /api/database/<entity>` and return it as the\n * database holds it after any `beforeCreate` hook. Private, generated, and\n * undeclared fields are compile errors, as the server refuses them.\n *\n * @example\n * ```typescript\n * const note = await databaseApi.create(\"notes\", {\n * board_id: 7,\n * author: \"ada\",\n * body: \"Ship it\",\n * });\n * note.id;\n * ```\n */\n create<K extends DatabaseEntity, const V extends DatabaseInsert<K>>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Change some fields of one row with `PATCH /api/database/<entity>/:id` and\n * return the updated row. A missing row rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.update(\"notes\", 7, { body: \"Shipped\" });\n * ```\n */\n update<K extends DatabaseKeyedEntity, const V extends DatabaseUpdate<K>>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Delete one row with `DELETE /api/database/<entity>/:id`. A missing row\n * rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.remove(\"notes\", 7);\n * ```\n */\n remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init?: DatabaseRequestOptions,\n ): Promise<void>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * An id that URL resolution would not keep as one path segment: `\"\"` and\n * `\".\"` collapse onto the list route and `\"..\"` climbs above the table, so a\n * keyed request would silently reach another route.\n */\nfunction isUnaddressableId(segment: string): boolean {\n return segment === \"\" || segment === \".\" || segment === \"..\";\n}\n\n/**\n * Find the route the server published for one operation. The plugin publishes\n * only what its `api` configuration exposes, so a missing entry is refused\n * here with `NOT_EXPOSED` and no request is sent. An id that is not one path\n * segment is refused with `INVALID_REQUEST`, also without a request.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function resolveDatabaseUrl(\n entity: string,\n operation: DatabaseOperation,\n id?: IdLike,\n query?: string,\n): string {\n const name = `${entity}.${operation}`;\n const endpoints = getClientConfig().endpoints.database;\n const path =\n isRecord(endpoints) && Object.hasOwn(endpoints, name)\n ? endpoints[name]\n : undefined;\n if (typeof path !== \"string\") {\n throw new DatabaseApiError(\n \"NOT_EXPOSED\",\n null,\n `Database operation \"${name}\" is not exposed`,\n );\n }\n let url = path;\n if (id !== undefined) {\n const segment = String(id);\n if (isUnaddressableId(segment)) {\n // The id may be user input from a route param; do not echo it.\n throw new DatabaseApiError(\n \"INVALID_REQUEST\",\n null,\n \"Database id must be a non-empty path segment\",\n );\n }\n url = path.replace(\":id\", encodeURIComponent(segment));\n }\n return query ? `${url}?${query}` : url;\n}\n\n/** Keep only details shaped like the server's; they name public fields only. */\nfunction publicDetails(value: unknown): DatabaseErrorDetail[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((detail): DatabaseErrorDetail[] =>\n isRecord(detail) &&\n typeof detail.message === \"string\" &&\n Array.isArray(detail.path) &&\n detail.path.every((segment) => typeof segment === \"string\")\n ? [{ path: [...detail.path], message: detail.message }]\n : [],\n );\n}\n\n/** Decode a failure envelope; a non-JSON body still keeps its category. */\nasync function failure(response: Response): Promise<DatabaseApiError> {\n const body: unknown = await response.json().catch(() => undefined);\n const envelope = isRecord(body) ? body : {};\n return new DatabaseApiError(\n databaseErrorCategoryForStatus(response.status),\n response.status,\n typeof envelope.error === \"string\"\n ? envelope.error\n : `Database request failed with status ${response.status}`,\n publicDetails(envelope.details),\n );\n}\n\n/**\n * Send one request and decode its JSON body, throwing `DatabaseApiError` for\n * anything but the shape `accept` expects. A `204` has no body, so `accept`\n * sees `undefined`. An abort rejects with the signal's own reason, so a\n * caller can tell cancellation from failure.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport async function requestDatabase<T>(\n url: string,\n init: RequestInit,\n accept: (body: unknown) => body is T,\n): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"application/json\");\n const write = init.method !== \"GET\";\n let response: Response;\n try {\n response = await fetch(url, { ...init, headers });\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"TRANSIENT\",\n null,\n write\n ? \"Database write may have completed; check its result before retrying\"\n : \"Database read failed before receiving a response\",\n [],\n { cause: error },\n );\n }\n if (!response.ok) throw await failure(response);\n\n let body: unknown;\n try {\n body = response.status === 204 ? undefined : await response.json();\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response is not JSON\"\n : \"Database response is not JSON\",\n [],\n { cause: error },\n );\n }\n if (!accept(body)) {\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response has an unexpected shape\"\n : \"Database response has an unexpected shape\",\n );\n }\n return body;\n}\n\n/**\n * The `{ items, limit, offset }` envelope a list route answers with.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function isDatabaseListPage(\n body: unknown,\n): body is DatabaseListPage<unknown> {\n return (\n isRecord(body) &&\n Array.isArray(body.items) &&\n typeof body.limit === \"number\" &&\n typeof body.offset === \"number\"\n );\n}\n\n/**\n * A detail route answers one bare row; a serializer returns an object too.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function isDatabaseRow(body: unknown): body is Record<string, unknown> {\n return isRecord(body);\n}\n\n/** A delete answers `204` with nothing to decode. */\nfunction isNoContent(body: unknown): body is undefined {\n return body === undefined;\n}\n\n/** A write must not lose a non-finite number to JSON's implicit null coercion. */\nfunction jsonWriteValue(_key: string, value: unknown): unknown {\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw invalidDatabaseWrite(\n \"Database write numbers must be finite; use null explicitly to clear a value\",\n );\n }\n return typeof value === \"bigint\" ? value.toString() : value;\n}\n\n/** A write sends its values as a JSON body, the only type its route parses. */\nfunction jsonWrite(\n method: \"POST\" | \"PATCH\",\n values: object,\n signal: AbortSignal | undefined,\n): RequestInit {\n try {\n return {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(values, jsonWriteValue),\n signal,\n };\n } catch (error) {\n if (error instanceof DatabaseApiError) throw error;\n throw invalidDatabaseWrite();\n }\n}\n\n/**\n * Untyped create behind `databaseApi.create` and `useDatabaseCreate`; their\n * signatures carry the checks, while the entity is still a literal.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport async function createDatabaseRow(\n entity: string,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"create\");\n return requestDatabase(\n url,\n jsonWrite(\"POST\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/**\n * Untyped update, shared by the typed client and the write hooks.\n * @internal Not part of the public surface.\n */\nexport async function updateDatabaseRow(\n entity: string,\n id: IdLike,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"update\", id);\n return requestDatabase(\n url,\n jsonWrite(\"PATCH\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/**\n * Untyped delete, shared by the typed client and the write hooks.\n * @internal Not part of the public surface.\n */\nexport async function deleteDatabaseRow(\n entity: string,\n id: IdLike,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n const url = resolveDatabaseUrl(entity, \"delete\", id);\n await requestDatabase(\n url,\n { method: \"DELETE\", signal: init.signal },\n isNoContent,\n );\n}\n\nfunction list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K>>>;\nfunction list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\nasync function list(\n entity: string,\n params?: DatabaseListQuery,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseListPage<unknown>> {\n let query: string;\n try {\n query = encodeDatabaseListQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"list\", undefined, query);\n const page = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseListPage,\n );\n return page;\n}\n\nasync function get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n>(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRecordRow<K, P>> {\n let query: string;\n try {\n query = encodeDatabaseRecordQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"detail\", id, query);\n const row = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseRow,\n );\n return row as DatabaseRecordRow<K, P>;\n}\n\nasync function create<\n K extends DatabaseEntity,\n const V extends DatabaseInsert<K>,\n>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n // `values` is an insert object; a still-generic `K` only widens its type.\n const row = await createDatabaseRow(entity, values as object, init);\n // The server projected the row it holds; the types describe that wire.\n return row as DatabaseRow<K>;\n}\n\nasync function update<\n K extends DatabaseKeyedEntity,\n const V extends DatabaseUpdate<K>,\n>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n const row = await updateDatabaseRow(entity, id, values as object, init);\n return row as DatabaseRow<K>;\n}\n\nfunction remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n return deleteDatabaseRow(entity, id, init);\n}\n\n/**\n * Typed browser client for the routes `DatabasePlugin` generates. Entity names,\n * params, and rows come from the generated `database.d.ts`; routes come from\n * the endpoints the server published in the boot payload.\n */\nexport const databaseApi: DatabaseApi = { list, get, create, update, remove };\n"],"mappings":";;;;;;AA8JA,SAAS,SAAS,OAAkD;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H,eAAe,OAIb,QACA,QACA,OAA+B,EAAE,EACR;AAIzB,QAFY,MAAM,kBAAkB,QAAQ,QAAkB,KAAK;;AAKrE,eAAe,OAIb,QACA,IACA,QACA,OAA+B,EAAE,EACR;AAEzB,QADY,MAAM,kBAAkB,QAAQ,IAAI,QAAkB,KAAK;;AAIzE,SAAS,OACP,QACA,IACA,OAA+B,EAAE,EAClB;AACf,QAAO,kBAAkB,QAAQ,IAAI,KAAK;;;;;;;AAQ5C,MAAa,cAA2B;CAAE;CAAM;CAAK;CAAQ;CAAQ;CAAQ"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../../src/js/database/client.ts"],"sourcesContent":["import {\n type DatabaseErrorDetail,\n type DatabaseListPage,\n type DatabaseListQuery,\n databaseErrorCategoryForStatus,\n encodeDatabaseListQuery,\n encodeDatabaseRecordQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { getClientConfig } from \"../config\";\nimport {\n DatabaseApiError,\n invalidDatabaseQuery,\n invalidDatabaseWrite,\n} from \"./errors\";\nimport type {\n DatabaseEntity,\n DatabaseId,\n DatabaseInsert,\n DatabaseKeyedEntity,\n DatabaseListParams,\n DatabaseListRow,\n DatabaseRecordParams,\n DatabaseRecordRow,\n DatabaseRow,\n DatabaseUpdate,\n} from \"./types\";\n\n/**\n * Suffix of the endpoint names `DatabasePlugin` publishes for each table.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport type DatabaseOperation =\n | \"list\"\n | \"detail\"\n | \"create\"\n | \"update\"\n | \"delete\";\n\n/**\n * An id as a keyed route addresses it in its path.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport type IdLike = string | number | bigint;\n\n/** Per-call options for a database request. */\nexport interface DatabaseRequestOptions {\n /**\n * Cancels the request; the promise then rejects with the abort reason.\n * Cancelling a write does not undo it once the server has committed.\n */\n readonly signal?: AbortSignal;\n}\n\n/** Typed calls to the routes `DatabasePlugin` generates under `/api/database`. */\nexport interface DatabaseApi {\n /**\n * Read one page from `GET /api/database/<entity>`. Rows are public rows as\n * JSON carries them, narrowed by `select` and widened by `include`.\n *\n * @example\n * ```typescript\n * const page = await databaseApi.list(\"notes\", {\n * where: { board_id: 7 },\n * order: { created_at: \"desc\" },\n * limit: 5,\n * });\n * page.items[0]?.body;\n * ```\n */\n list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K>>>;\n list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\n\n /**\n * Read one row from `GET /api/database/<entity>/:id`. Only entities with a\n * public primary key have this route; a missing row rejects with\n * `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * const board = await databaseApi.get(\"boards\", 7, {\n * include: { notes: { limit: 20 } },\n * });\n * board.notes.length;\n * ```\n */\n get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n >(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRecordRow<K, P>>;\n\n /**\n * Create one row with `POST /api/database/<entity>` and return it as the\n * database holds it. Private, generated, and undeclared fields are compile\n * errors, as the server refuses them.\n *\n * @example\n * ```typescript\n * const note = await databaseApi.create(\"notes\", {\n * board_id: 7,\n * author: \"ada\",\n * body: \"Ship it\",\n * });\n * note.id;\n * ```\n */\n create<K extends DatabaseEntity, const V extends DatabaseInsert<K>>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Change some fields of one row with `PATCH /api/database/<entity>/:id` and\n * return the updated row. A missing row rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.update(\"notes\", 7, { body: \"Shipped\" });\n * ```\n */\n update<K extends DatabaseKeyedEntity, const V extends DatabaseUpdate<K>>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Delete one row with `DELETE /api/database/<entity>/:id`. A missing row\n * rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.remove(\"notes\", 7);\n * ```\n */\n remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init?: DatabaseRequestOptions,\n ): Promise<void>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * An id that URL resolution would not keep as one path segment: `\"\"` and\n * `\".\"` collapse onto the list route and `\"..\"` climbs above the table, so a\n * keyed request would silently reach another route.\n */\nfunction isUnaddressableId(segment: string): boolean {\n return segment === \"\" || segment === \".\" || segment === \"..\";\n}\n\n/**\n * Find the route the server published for one operation. The plugin publishes\n * only what its `api` configuration exposes, so a missing entry is refused\n * here with `NOT_EXPOSED` and no request is sent. An id that is not one path\n * segment is refused with `INVALID_REQUEST`, also without a request.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function resolveDatabaseUrl(\n entity: string,\n operation: DatabaseOperation,\n id?: IdLike,\n query?: string,\n): string {\n const name = `${entity}.${operation}`;\n const endpoints = getClientConfig().endpoints.database;\n const path =\n isRecord(endpoints) && Object.hasOwn(endpoints, name)\n ? endpoints[name]\n : undefined;\n if (typeof path !== \"string\") {\n throw new DatabaseApiError(\n \"NOT_EXPOSED\",\n null,\n `Database operation \"${name}\" is not exposed`,\n );\n }\n let url = path;\n if (id !== undefined) {\n const segment = String(id);\n if (isUnaddressableId(segment)) {\n // The id may be user input from a route param; do not echo it.\n throw new DatabaseApiError(\n \"INVALID_REQUEST\",\n null,\n \"Database id must be a non-empty path segment\",\n );\n }\n url = path.replace(\":id\", encodeURIComponent(segment));\n }\n return query ? `${url}?${query}` : url;\n}\n\n/** Keep only details shaped like the server's; they name public fields only. */\nfunction publicDetails(value: unknown): DatabaseErrorDetail[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((detail): DatabaseErrorDetail[] =>\n isRecord(detail) &&\n typeof detail.message === \"string\" &&\n Array.isArray(detail.path) &&\n detail.path.every((segment) => typeof segment === \"string\")\n ? [{ path: [...detail.path], message: detail.message }]\n : [],\n );\n}\n\n/** Decode a failure envelope; a non-JSON body still keeps its category. */\nasync function failure(response: Response): Promise<DatabaseApiError> {\n const body: unknown = await response.json().catch(() => undefined);\n const envelope = isRecord(body) ? body : {};\n return new DatabaseApiError(\n databaseErrorCategoryForStatus(response.status),\n response.status,\n typeof envelope.error === \"string\"\n ? envelope.error\n : `Database request failed with status ${response.status}`,\n publicDetails(envelope.details),\n );\n}\n\n/**\n * Send one request and decode its JSON body, throwing `DatabaseApiError` for\n * anything but the shape `accept` expects. A `204` has no body, so `accept`\n * sees `undefined`. An abort rejects with the signal's own reason, so a\n * caller can tell cancellation from failure.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport async function requestDatabase<T>(\n url: string,\n init: RequestInit,\n accept: (body: unknown) => body is T,\n): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"application/json\");\n const write = init.method !== \"GET\";\n let response: Response;\n try {\n response = await fetch(url, { ...init, headers });\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"TRANSIENT\",\n null,\n write\n ? \"Database write may have completed; check its result before retrying\"\n : \"Database read failed before receiving a response\",\n [],\n { cause: error },\n );\n }\n if (!response.ok) throw await failure(response);\n\n let body: unknown;\n try {\n body = response.status === 204 ? undefined : await response.json();\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response is not JSON\"\n : \"Database response is not JSON\",\n [],\n { cause: error },\n );\n }\n if (!accept(body)) {\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response has an unexpected shape\"\n : \"Database response has an unexpected shape\",\n );\n }\n return body;\n}\n\n/**\n * The `{ items, limit, offset }` envelope a list route answers with.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function isDatabaseListPage(\n body: unknown,\n): body is DatabaseListPage<unknown> {\n return (\n isRecord(body) &&\n Array.isArray(body.items) &&\n typeof body.limit === \"number\" &&\n typeof body.offset === \"number\"\n );\n}\n\n/**\n * A detail route answers one bare row.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function isDatabaseRow(body: unknown): body is Record<string, unknown> {\n return isRecord(body);\n}\n\n/** A delete answers `204` with nothing to decode. */\nfunction isNoContent(body: unknown): body is undefined {\n return body === undefined;\n}\n\n/** A write must not lose a non-finite number to JSON's implicit null coercion. */\nfunction jsonWriteValue(_key: string, value: unknown): unknown {\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw invalidDatabaseWrite(\n \"Database write numbers must be finite; use null explicitly to clear a value\",\n );\n }\n return typeof value === \"bigint\" ? value.toString() : value;\n}\n\n/** A write sends its values as a JSON body, the only type its route parses. */\nfunction jsonWrite(\n method: \"POST\" | \"PATCH\",\n values: object,\n signal: AbortSignal | undefined,\n): RequestInit {\n try {\n return {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(values, jsonWriteValue),\n signal,\n };\n } catch (error) {\n if (error instanceof DatabaseApiError) throw error;\n throw invalidDatabaseWrite();\n }\n}\n\n/**\n * Untyped create behind `databaseApi.create` and `useDatabaseCreate`; their\n * signatures carry the checks, while the entity is still a literal.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport async function createDatabaseRow(\n entity: string,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"create\");\n return requestDatabase(\n url,\n jsonWrite(\"POST\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/**\n * Untyped update, shared by the typed client and the write hooks.\n * @internal Not part of the public surface.\n */\nexport async function updateDatabaseRow(\n entity: string,\n id: IdLike,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"update\", id);\n return requestDatabase(\n url,\n jsonWrite(\"PATCH\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/**\n * Untyped delete, shared by the typed client and the write hooks.\n * @internal Not part of the public surface.\n */\nexport async function deleteDatabaseRow(\n entity: string,\n id: IdLike,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n const url = resolveDatabaseUrl(entity, \"delete\", id);\n await requestDatabase(\n url,\n { method: \"DELETE\", signal: init.signal },\n isNoContent,\n );\n}\n\nfunction list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K>>>;\nfunction list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\nasync function list(\n entity: string,\n params?: DatabaseListQuery,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseListPage<unknown>> {\n let query: string;\n try {\n query = encodeDatabaseListQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"list\", undefined, query);\n const page = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseListPage,\n );\n return page;\n}\n\nasync function get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n>(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRecordRow<K, P>> {\n let query: string;\n try {\n query = encodeDatabaseRecordQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"detail\", id, query);\n const row = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseRow,\n );\n return row as DatabaseRecordRow<K, P>;\n}\n\nasync function create<\n K extends DatabaseEntity,\n const V extends DatabaseInsert<K>,\n>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n // `values` is an insert object; a still-generic `K` only widens its type.\n const row = await createDatabaseRow(entity, values as object, init);\n // The server projected the row it holds; the types describe that wire.\n return row as DatabaseRow<K>;\n}\n\nasync function update<\n K extends DatabaseKeyedEntity,\n const V extends DatabaseUpdate<K>,\n>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n const row = await updateDatabaseRow(entity, id, values as object, init);\n return row as DatabaseRow<K>;\n}\n\nfunction remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n return deleteDatabaseRow(entity, id, init);\n}\n\n/**\n * Typed browser client for the routes `DatabasePlugin` generates. Entity names,\n * params, and rows come from the generated `database.d.ts`; routes come from\n * the endpoints the server published in the boot payload.\n */\nexport const databaseApi: DatabaseApi = { list, get, create, update, remove };\n"],"mappings":";;;;;;AA8JA,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;;;;;;AAQ7E,SAAS,kBAAkB,SAA0B;AACnD,QAAO,YAAY,MAAM,YAAY,OAAO,YAAY;;;;;;;;;;AAW1D,SAAgB,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Q,IAAI,QAAkB,KAAK;;AAIzE,SAAS,OACP,QACA,IACA,OAA+B,EAAE,EAClB;AACf,QAAO,kBAAkB,QAAQ,IAAI,KAAK;;;;;;;AAQ5C,MAAa,cAA2B;CAAE;CAAM;CAAK;CAAQ;CAAQ;CAAQ"}
|
package/dist/react/beta.d.ts
CHANGED
|
@@ -9,10 +9,10 @@ import { DatabaseInvalidation, invalidateDatabaseReads } from "./hooks/database-
|
|
|
9
9
|
import { UseDatabaseWriteOptions, UseDatabaseWriteState } from "./hooks/use-database-write.js";
|
|
10
10
|
import { UseDatabaseCreateOptions, UseDatabaseCreateResult, useDatabaseCreate } from "./hooks/use-database-create.js";
|
|
11
11
|
import { UseDatabaseDeleteOptions, UseDatabaseDeleteResult, useDatabaseDelete } from "./hooks/use-database-delete.js";
|
|
12
|
-
import {
|
|
12
|
+
import { UseDatabaseReadOptions, UseDatabaseReadResult } from "./hooks/use-database-read.js";
|
|
13
13
|
import { UseDatabaseListOptions, UseDatabaseListResult, useDatabaseList } from "./hooks/use-database-list.js";
|
|
14
14
|
import { UseDatabaseRecordOptions, UseDatabaseRecordResult, useDatabaseRecord } from "./hooks/use-database-record.js";
|
|
15
15
|
import { UseDatabaseUpdateOptions, UseDatabaseUpdateResult, useDatabaseUpdate } from "./hooks/use-database-update.js";
|
|
16
16
|
import { useDesignReady } from "./hooks/use-design-ready.js";
|
|
17
17
|
import { DesignPage, DesignPageProps, DraftPlaceholder, DraftPlaceholderKind } from "./design-page.js";
|
|
18
|
-
export { type AiSearchClientConfig, type AiSearchIndexSummary, type AiSearchQueryType, type AiSearchRequest, type AiSearchResponse, type AiSearchResult, DatabaseApiError, type DatabaseApiErrorCode, type DatabaseEntity, type DatabaseErrorDetail, type DatabaseId, type DatabaseInsert, type DatabaseInvalidation, type DatabaseKeyedEntity, type DatabaseListPage, type DatabaseListParams, type DatabaseListRow, type DatabaseRecordParams, type DatabaseRecordRow, type DatabaseRow, type
|
|
18
|
+
export { type AiSearchClientConfig, type AiSearchIndexSummary, type AiSearchQueryType, type AiSearchRequest, type AiSearchResponse, type AiSearchResult, DatabaseApiError, type DatabaseApiErrorCode, type DatabaseEntity, type DatabaseErrorDetail, type DatabaseId, type DatabaseInsert, type DatabaseInvalidation, type DatabaseKeyedEntity, type DatabaseListPage, type DatabaseListParams, type DatabaseListRow, type DatabaseRecordParams, type DatabaseRecordRow, type DatabaseRow, type DatabaseUpdate, DesignPage, type DesignPageProps, DraftPlaceholder, type DraftPlaceholderKind, type UseAiSearchQueryOptions, type UseAiSearchQueryResult, type UseDatabaseCreateOptions, type UseDatabaseCreateResult, type UseDatabaseDeleteOptions, type UseDatabaseDeleteResult, type UseDatabaseListOptions, type UseDatabaseListResult, type UseDatabaseReadOptions, type UseDatabaseReadResult, type UseDatabaseRecordOptions, type UseDatabaseRecordResult, type UseDatabaseUpdateOptions, type UseDatabaseUpdateResult, type UseDatabaseWriteOptions, type UseDatabaseWriteState, invalidateDatabaseReads, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate, useDesignReady };
|
package/dist/react/beta.js
CHANGED
|
@@ -3,11 +3,10 @@ import { useAiSearchQuery } from "./hooks/use-ai-search-query.js";
|
|
|
3
3
|
import { invalidateDatabaseReads } from "./hooks/database-request-store.js";
|
|
4
4
|
import { useDatabaseCreate } from "./hooks/use-database-create.js";
|
|
5
5
|
import { useDatabaseDelete } from "./hooks/use-database-delete.js";
|
|
6
|
-
import { serialized } from "./hooks/use-database-read.js";
|
|
7
6
|
import { useDatabaseList } from "./hooks/use-database-list.js";
|
|
8
7
|
import { useDatabaseRecord } from "./hooks/use-database-record.js";
|
|
9
8
|
import { useDatabaseUpdate } from "./hooks/use-database-update.js";
|
|
10
9
|
import { useDesignReady } from "./hooks/use-design-ready.js";
|
|
11
10
|
import { DesignPage, DraftPlaceholder } from "./design-page.js";
|
|
12
11
|
|
|
13
|
-
export { DatabaseApiError, DesignPage, DraftPlaceholder, invalidateDatabaseReads,
|
|
12
|
+
export { DatabaseApiError, DesignPage, DraftPlaceholder, invalidateDatabaseReads, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate, useDesignReady };
|
|
@@ -5,7 +5,7 @@ import { UseDatabaseReadOptions, UseDatabaseReadResult } from "./use-database-re
|
|
|
5
5
|
|
|
6
6
|
//#region src/react/hooks/use-database-list.d.ts
|
|
7
7
|
/** Options for {@link useDatabaseList}. */
|
|
8
|
-
type UseDatabaseListOptions
|
|
8
|
+
type UseDatabaseListOptions = UseDatabaseReadOptions;
|
|
9
9
|
/** What {@link useDatabaseList} returns: one page of rows and its state. */
|
|
10
10
|
type UseDatabaseListResult<Row> = UseDatabaseReadResult<DatabaseListPage<Row>>;
|
|
11
11
|
/**
|
|
@@ -20,7 +20,7 @@ type UseDatabaseListResult<Row> = UseDatabaseReadResult<DatabaseListPage<Row>>;
|
|
|
20
20
|
* @param entity - A table the generated registry exposes
|
|
21
21
|
* @param params - `where`, `order`, `select`, `include`, `limit`, `offset`;
|
|
22
22
|
* `null` holds the hook idle, for params that depend on another read
|
|
23
|
-
* @param options - `enabled
|
|
23
|
+
* @param options - `enabled` and `keepPreviousData`
|
|
24
24
|
* @returns The page, loading and error state, and `refetch`
|
|
25
25
|
*
|
|
26
26
|
* @example
|
|
@@ -33,8 +33,8 @@ type UseDatabaseListResult<Row> = UseDatabaseReadResult<DatabaseListPage<Row>>;
|
|
|
33
33
|
* notes.data?.items.map((note) => note.body);
|
|
34
34
|
* ```
|
|
35
35
|
*/
|
|
36
|
-
declare function useDatabaseList<K extends DatabaseKeyedEntity
|
|
37
|
-
declare function useDatabaseList<K extends DatabaseEntity, const P extends DatabaseListParams<K
|
|
36
|
+
declare function useDatabaseList<K extends DatabaseKeyedEntity>(entity: K, params?: undefined, options?: UseDatabaseListOptions): UseDatabaseListResult<DatabaseListRow<K>>;
|
|
37
|
+
declare function useDatabaseList<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(entity: K, params: (P & ExactDatabaseParams<P, DatabaseListParams<K>>) | null, options?: UseDatabaseListOptions): UseDatabaseListResult<DatabaseListRow<K, P>>;
|
|
38
38
|
//#endregion
|
|
39
39
|
export { UseDatabaseListOptions, UseDatabaseListResult, useDatabaseList };
|
|
40
40
|
//# sourceMappingURL=use-database-list.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-database-list.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-list.ts"],"mappings":";;;;;;;KAwBY,sBAAA,
|
|
1
|
+
{"version":3,"file":"use-database-list.d.ts","names":[],"sources":["../../../src/react/hooks/use-database-list.ts"],"mappings":";;;;;;;KAwBY,sBAAA,GAAyB,sBAAA;;KAGzB,qBAAA,QAA6B,qBAAA,CACvC,gBAAA,CAAiB,GAAA;;;;;AADnB;;;;;;;;;;;;;;AA6BA;;;;;;;iBAAgB,eAAA,WAA0B,mBAAA,CAAA,CACxC,MAAA,EAAQ,CAAA,EACR,MAAA,cACA,OAAA,GAAU,sBAAA,GACT,qBAAA,CAAsB,eAAA,CAAgB,CAAA;AAAA,iBACzB,eAAA,WACJ,cAAA,kBACM,kBAAA,CAAmB,CAAA,EAAA,CAEnC,MAAA,EAAQ,CAAA,EACR,MAAA,GAAS,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,kBAAA,CAAmB,CAAA,YACvD,OAAA,GAAU,sBAAA,GACT,qBAAA,CAAsB,eAAA,CAAgB,CAAA,EAAG,CAAA"}
|
|
@@ -19,8 +19,7 @@ function useDatabaseList(entity, params, options = {}) {
|
|
|
19
19
|
include: params?.include,
|
|
20
20
|
enabled,
|
|
21
21
|
accept: isDatabaseListPage,
|
|
22
|
-
keepPreviousData: options.keepPreviousData ?? false
|
|
23
|
-
shape: options.shape
|
|
22
|
+
keepPreviousData: options.keepPreviousData ?? false
|
|
24
23
|
});
|
|
25
24
|
}
|
|
26
25
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-database-list.js","names":[],"sources":["../../../src/react/hooks/use-database-list.ts"],"sourcesContent":["import {\n type DatabaseListPage,\n type DatabaseListQuery,\n DatabaseQueryEncodingError,\n encodeDatabaseListQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { isDatabaseListPage } from \"@/js/database/client\";\nimport type {\n DatabaseEntity,\n DatabaseKeyedEntity,\n DatabaseListParams,\n DatabaseListRow,\n} from \"@/js/database/types\";\n\nimport {\n type DatabaseReadRequest,\n type UseDatabaseReadOptions,\n type UseDatabaseReadResult,\n useDatabaseRead,\n} from \"./use-database-read\";\n\n/** Options for {@link useDatabaseList}. */\nexport type UseDatabaseListOptions
|
|
1
|
+
{"version":3,"file":"use-database-list.js","names":[],"sources":["../../../src/react/hooks/use-database-list.ts"],"sourcesContent":["import {\n type DatabaseListPage,\n type DatabaseListQuery,\n DatabaseQueryEncodingError,\n encodeDatabaseListQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { isDatabaseListPage } from \"@/js/database/client\";\nimport type {\n DatabaseEntity,\n DatabaseKeyedEntity,\n DatabaseListParams,\n DatabaseListRow,\n} from \"@/js/database/types\";\n\nimport {\n type DatabaseReadRequest,\n type UseDatabaseReadOptions,\n type UseDatabaseReadResult,\n useDatabaseRead,\n} from \"./use-database-read\";\n\n/** Options for {@link useDatabaseList}. */\nexport type UseDatabaseListOptions = UseDatabaseReadOptions;\n\n/** What {@link useDatabaseList} returns: one page of rows and its state. */\nexport type UseDatabaseListResult<Row> = UseDatabaseReadResult<\n DatabaseListPage<Row>\n>;\n\n/**\n * Subscribe to one page of `GET /api/database/<entity>`. Entity, params, and\n * rows are typed from the generated `database.d.ts`; the route comes from the\n * endpoints the server published.\n *\n * Mounted hooks whose params encode to the same query share one request, so\n * an inline params literal does not refetch on every render. The request is\n * aborted once its last subscriber unmounts.\n *\n * @param entity - A table the generated registry exposes\n * @param params - `where`, `order`, `select`, `include`, `limit`, `offset`;\n * `null` holds the hook idle, for params that depend on another read\n * @param options - `enabled` and `keepPreviousData`\n * @returns The page, loading and error state, and `refetch`\n *\n * @example\n * ```tsx\n * const notes = useDatabaseList(\n * \"notes\",\n * board ? { where: { board_id: board.id }, limit: 20, offset } : null,\n * { keepPreviousData: true },\n * );\n * notes.data?.items.map((note) => note.body);\n * ```\n */\nexport function useDatabaseList<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n options?: UseDatabaseListOptions,\n): UseDatabaseListResult<DatabaseListRow<K>>;\nexport function useDatabaseList<\n K extends DatabaseEntity,\n const P extends DatabaseListParams<K>,\n>(\n entity: K,\n params: (P & ExactDatabaseParams<P, DatabaseListParams<K>>) | null,\n options?: UseDatabaseListOptions,\n): UseDatabaseListResult<DatabaseListRow<K, P>>;\nexport function useDatabaseList(\n entity: string,\n params?: DatabaseListQuery | null,\n options: UseDatabaseListOptions = {},\n): UseDatabaseListResult<unknown> {\n const enabled = (options.enabled ?? true) && params !== null;\n // Encode only an enabled read: a held read's params may still be incomplete.\n let query: DatabaseReadRequest[\"query\"] = \"\";\n if (enabled) {\n try {\n query = encodeDatabaseListQuery(params ?? {});\n } catch (error) {\n query = error instanceof DatabaseQueryEncodingError ? error : null;\n }\n }\n const read = useDatabaseRead({\n entity,\n operation: \"list\",\n id: undefined,\n query,\n include: params?.include,\n enabled,\n accept: isDatabaseListPage,\n keepPreviousData: options.keepPreviousData ?? false,\n });\n return read as UseDatabaseListResult<unknown>;\n}\n"],"mappings":";;;;;AAqEA,SAAgB,gBACd,QACA,QACA,UAAkC,EAAE,EACJ;CAChC,MAAM,WAAW,QAAQ,WAAW,SAAS,WAAW;CAExD,IAAI,QAAsC;AAC1C,KAAI,QACF,KAAI;AACF,UAAQ,wBAAwB,UAAU,EAAE,CAAC;UACtC,OAAO;AACd,UAAQ,iBAAiB,6BAA6B,QAAQ;;AAalE,QAVa,gBAAgB;EAC3B;EACA,WAAW;EACX,IAAI;EACJ;EACA,SAAS,QAAQ;EACjB;EACA,QAAQ;EACR,kBAAkB,QAAQ,oBAAoB;EAC/C,CAAC"}
|