@dbx-tools/appkit 0.6.89 → 0.6.91

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/src/bundle.ts CHANGED
@@ -1,422 +1,32 @@
1
1
  /**
2
- * DATABRICKS-APP configuration resolution: the bundle and `app.yaml` vocabulary.
2
+ * Compatibility exports for Databricks bundle/app configuration.
3
3
  *
4
- * node-core's `config` module owns the generic lookup - environment, `.env`,
5
- * `databricks bundle validate` - and knows nothing about what a bundle resource
6
- * IS. That last part is this module: `sql_warehouse`, `genie_space`, and
7
- * `postgres` are Databricks-App concepts, and an `app.yaml` / bundle
8
- * `value_from` entry is a REFERENCE to one of them whose real value is the
9
- * warehouse id or Genie space id sitting on the named resource. So this module
10
- * extends node-core's resource schema, adds `app.yaml` (which the bundle CLI
11
- * never sees), and resolves those references.
12
- *
13
- * Default sources: `explicit`, then `env`, then Databricks App `config.env`
14
- * (from {@link bundle}) and hard-coded `app.yaml` env entries (from
15
- * {@link appYaml}). Opt in to `cli` when a dev command wants flag overrides.
16
- *
17
- * Server-only, and Databricks-app specific, so it lives in node-appkit rather
18
- * than node-core.
4
+ * Configuration sources, file loading, flattening, resource references, and
5
+ * name normalization live in `@dbx-tools/core`'s `config` module.
19
6
  *
20
7
  * @module
21
8
  */
22
9
 
23
- import { readFile } from "node:fs/promises";
24
- import { resolve } from "node:path";
25
- import { ValidationError } from "@databricks/appkit";
26
- import { config as coreConfig, file, project } from "@dbx-tools/core";
27
- import { context, object, log, string } from "@dbx-tools/shared-core";
28
- import { parse as yamlParse } from "yaml";
29
- import { z } from "zod";
30
-
31
- const logger = log.logger("config");
10
+ import { config as coreConfig } from "@dbx-tools/core";
32
11
 
33
- /** Parsed payload from `databricks bundle validate --output json`. */
34
12
  export type BundleValidateJson = Record<string, unknown>;
13
+ export type ConfigFile = coreConfig.ConfigFile;
14
+ export type ConfigMapValue = coreConfig.ConfigMapValue;
15
+ export type ConfigSource = coreConfig.ConfigSource;
16
+ export type ResolveConfigValueOptions = coreConfig.ConfigOptions;
35
17
 
36
- /** A config file discovered on disk with its parsed contents. */
37
- export interface ConfigFile {
38
- path: string;
39
- data: Record<string, unknown>;
40
- }
41
-
42
- /** Supported configuration sources, consulted in array order. */
43
- export type ConfigSource = "explicit" | "cli" | "env" | "bundle";
44
-
45
- const defaultConfigSources: ConfigSource[] = ["explicit", "env", "bundle"];
46
-
47
- const APP_YAML_NAMES = ["app.yaml", "app.yml"] as const;
48
-
49
- export const bundleAppResourceSchema = coreConfig.bundleResourceSchema.extend({
50
- sql_warehouse: z.object({ id: coreConfig.valueSchema.optional() }).optional(),
51
- genie_space: z.object({ space_id: coreConfig.valueSchema.optional() }).optional(),
52
- postgres: z
53
- .object({
54
- database: coreConfig.valueSchema.optional(),
55
- branch: coreConfig.valueSchema.optional(),
56
- endpoint: coreConfig.valueSchema.optional(),
57
- })
58
- .optional(),
59
- });
60
-
61
- const bundleAppSchema = coreConfig.bundleAppSchema.extend({
62
- resources: z.array(bundleAppResourceSchema).optional(),
63
- });
64
-
65
- const bundleValidateAppsSchema = z.object({
66
- resources: z.object({ apps: z.record(z.string(), bundleAppSchema).optional() }).optional(),
67
- });
68
-
69
- const appYamlEnvEntrySchema = coreConfig.bundleEnvEntrySchema.omit({ value_from: true }).extend({
70
- name: coreConfig.valueSchema,
71
- valueFrom: coreConfig.valueSchema.optional(),
72
- });
73
-
74
- const appYamlResourceSchema = coreConfig.bundleResourceSchema
75
- .extend({
76
- name: coreConfig.valueSchema,
77
- sql_warehouse: z.object({ id: coreConfig.valueSchema.optional() }).optional(),
78
- genie_space: z.object({ space_id: coreConfig.valueSchema.optional() }).optional(),
79
- postgres: z
80
- .object({
81
- database: coreConfig.valueSchema.optional(),
82
- branch: coreConfig.valueSchema.optional(),
83
- endpoint: coreConfig.valueSchema.optional(),
84
- })
85
- .optional(),
86
- })
87
- .passthrough();
88
-
89
- const appYamlSchema = z.object({
90
- env: z.array(appYamlEnvEntrySchema).optional(),
91
- resources: z.array(appYamlResourceSchema).optional(),
92
- });
93
-
94
- type BundleApp = z.infer<typeof bundleAppSchema>;
95
-
96
- /** Single config map entry (string or repeated values, like headers). */
97
- export type ConfigMapValue = string | string[] | undefined;
98
-
99
- export interface ResolveConfigValueOptions {
100
- /** Bundle validate JSON. Defaults to {@link bundle} (skipped inside a Databricks App). */
101
- bundleData?: ConfigFile;
102
- /** Parsed `app.yaml` contents. Defaults to {@link appYaml} (skipped inside a Databricks App). */
103
- appData?: ConfigFile;
104
- /**
105
- * Sources to consult, first truthy string wins. Defaults to `explicit`, then
106
- * `env`, then `bundle`.
107
- */
108
- sources?: ConfigSource[];
109
- /** Programmatic overrides. When set, `explicit` is prepended to `sources` unless already listed. */
110
- explicit?: Record<string, ConfigMapValue>;
111
- /** CLI flag values (when `cli` is listed in `sources`). */
112
- cli?: Record<string, ConfigMapValue>;
113
- }
114
-
115
- function envKeysForName(name: string): object.Sequence<string> {
116
- const trimmed = name.trim();
117
- if (!trimmed) {
118
- return object.sequence();
119
- }
120
- const keys = (function* () {
121
- const modifiers: (((value: string) => string) | null)[] = [
122
- null,
123
- () => trimmed.toUpperCase(),
124
- () => Array.from(string.tokenize(trimmed)).join("_").toUpperCase(),
125
- ];
126
- for (const modifier of modifiers) {
127
- yield modifier ? modifier(trimmed) : trimmed;
128
- }
129
- })();
130
- return object.sequence(keys).cache().filter(Boolean).distinct();
131
- }
132
-
133
- function readEnv(keys: Iterable<string>): string | undefined {
134
- for (const key of keys) {
135
- const value = process.env[key]?.trim();
136
- if (value) return value;
137
- }
138
- return undefined;
139
- }
140
-
141
- function readConfigMapValue(value: ConfigMapValue): string | undefined {
142
- if (value == null) return undefined;
143
- if (Array.isArray(value)) {
144
- for (const item of value) {
145
- const trimmed = item?.trim();
146
- if (trimmed) return trimmed;
147
- }
148
- return undefined;
149
- }
150
- const trimmed = value.trim();
151
- return trimmed || undefined;
152
- }
153
-
154
- function readMap(
155
- keys: Iterable<string>,
156
- map: Record<string, ConfigMapValue> | undefined,
157
- ): string | undefined {
158
- if (!map) return undefined;
159
- for (const key of keys) {
160
- const value = readConfigMapValue(map[key]);
161
- if (value) return value;
162
- }
163
- return undefined;
164
- }
165
-
166
- function readAppEnv(keys: Iterable<string>, envMap: Record<string, string>): string | undefined {
167
- for (const key of keys) {
168
- const value = envMap[key]?.trim();
169
- if (value) return value;
170
- }
171
- return undefined;
172
- }
173
-
174
- function parseYaml(text: string): unknown {
175
- return yamlParse(text);
176
- }
177
-
178
- function pickAppResourceId(apps: Record<string, BundleApp>): string | undefined {
179
- const keys = Object.keys(apps);
180
- return keys.length === 1 ? keys[0] : undefined;
181
- }
182
-
183
- /**
184
- * Resolve the effective value a `value_from`/`valueFrom` entry points at:
185
- * the first present of the warehouse id, Genie space id, or Postgres
186
- * endpoint/database/branch on the named resource. Shared by both the
187
- * `app.yaml` and `bundle validate` flatteners, whose resource shapes match.
188
- */
189
- function resolveResourceValue(
190
- resource: z.infer<typeof bundleAppResourceSchema> | undefined,
191
- ): string | undefined {
192
- return (
193
- resource?.sql_warehouse?.id ??
194
- resource?.genie_space?.space_id ??
195
- resource?.postgres?.endpoint ??
196
- resource?.postgres?.database ??
197
- resource?.postgres?.branch
198
- );
199
- }
200
-
201
- /**
202
- * Flatten `env` entries from parsed `app.yaml` content. Literal `value` entries
203
- * are returned as-is; `valueFrom` entries resolve against the sibling
204
- * `resources` array when possible.
205
- */
206
- export function flattenAppYamlEnv(data: unknown): Record<string, string> {
207
- const parsed = appYamlSchema.safeParse(data);
208
- if (!parsed.success || !parsed.data.env?.length) {
209
- return {};
210
- }
211
-
212
- const resourceByName = new Map(
213
- (parsed.data.resources ?? []).map((resource) => [resource.name, resource]),
214
- );
18
+ export const bundleAppResourceSchema = coreConfig.bundleResourceSchema;
19
+ export const flattenAppYamlEnv = coreConfig.flattenAppEnv;
20
+ export const flattenAppEnv = coreConfig.flattenBundleEnv;
21
+ export const getBundlePath = coreConfig.getBundlePath;
215
22
 
216
- const out: Record<string, string> = {};
217
- for (const entry of parsed.data.env) {
218
- const value = coreConfig.valueSchema.safeParse(entry.value);
219
- if (value.success) {
220
- out[entry.name] = value.data;
221
- continue;
222
- }
223
- if (!entry.valueFrom) continue;
224
- const resolved = resolveResourceValue(resourceByName.get(entry.valueFrom));
225
- if (resolved) out[entry.name] = resolved;
226
- }
227
- return out;
228
- }
229
-
230
- /**
231
- * Flatten `resources.apps.<key>.config.env` into a `name -> value` map.
232
- * Auto-picks the app only when the bundle defines exactly one.
233
- */
234
- export function flattenAppEnv(data: unknown): Record<string, string> {
235
- const parsed = bundleValidateAppsSchema.safeParse(data);
236
- if (!parsed.success) return {};
237
-
238
- const apps = parsed.data.resources?.apps;
239
- if (!apps || Object.keys(apps).length === 0) return {};
240
-
241
- const key = pickAppResourceId(apps);
242
- if (!key) return {};
243
-
244
- const app = apps[key];
245
- if (!app?.config?.env?.length) return {};
246
-
247
- const resourceByName = new Map(
248
- (app.resources ?? [])
249
- .filter((resource) => resource.name)
250
- .map((resource) => [resource.name!, resource]),
251
- );
252
-
253
- const out: Record<string, string> = {};
254
- for (const entry of app.config.env) {
255
- if (!entry.name) continue;
256
- const value = coreConfig.valueSchema.safeParse(entry.value);
257
- if (value.success) {
258
- out[entry.name] = value.data;
259
- continue;
260
- }
261
- if (!entry.value_from) continue;
262
- const resolved = resolveResourceValue(resourceByName.get(entry.value_from));
263
- if (resolved) out[entry.name] = resolved;
264
- }
265
- return out;
266
- }
267
-
268
- async function loadAppYaml(cwd: string): Promise<ConfigFile | undefined> {
269
- for (const fileName of APP_YAML_NAMES) {
270
- const configFile = resolveConfigFile(cwd, fileName);
271
- if (!configFile) continue;
272
- try {
273
- const text = await readFile(configFile, "utf8");
274
- const data = parseYaml(text);
275
- if (!object.isRecord(data)) {
276
- return undefined;
277
- }
278
- return { path: configFile, data };
279
- } catch {
280
- logger.warn("failed to parse app yaml", { path: configFile });
281
- }
282
- }
283
- return undefined;
284
- }
285
-
286
- function resolveConfigFile(cwd: string, configFile: string): string | undefined {
287
- if (coreConfig.isDatabricksAppEnv()) return undefined;
288
- for (const rootDir of project.resolveProjectRoots(cwd)) {
289
- const bundlePath = resolve(rootDir, configFile);
290
- if (file.statSync(bundlePath)?.isFile()) return bundlePath;
291
- }
292
- return undefined;
293
- }
294
-
295
- /**
296
- * The validated bundle for `cwd` - {@link coreConfig.bundleFile}, which caches it
297
- * per working directory. Returns `undefined` inside a Databricks App, where the
298
- * platform has already turned `config.env` into real environment variables and
299
- * there is no bundle to validate.
300
- */
301
23
  export function bundle(cwd?: string): Promise<ConfigFile | undefined> {
302
- return Promise.resolve(coreConfig.isDatabricksAppEnv() ? undefined : coreConfig.bundleFile(cwd));
24
+ return Promise.resolve(coreConfig.bundleFile(cwd));
303
25
  }
304
26
 
305
- /**
306
- * Locate and parse `app.yaml` / `app.yml` from the bundle or project root.
307
- * Cached per working directory through {@link context.cached}, so a `cwd` change
308
- * re-reads instead of returning another project's file. Returns `undefined`
309
- * inside a Databricks App.
310
- */
311
- export function appYaml(cwd?: string): Promise<ConfigFile | undefined> {
312
- if (coreConfig.isDatabricksAppEnv()) return Promise.resolve(undefined);
313
- return context.cached(["appkit", "appYaml"], (resolved) => loadAppYaml(resolved ?? "."), cwd);
314
- }
315
-
316
- /**
317
- * Walk a dot-separated path through bundle validate JSON. When the terminal
318
- * node is a bundle variable object (`{ value: "..." }`), the `value` field is
319
- * returned.
320
- */
321
- export function getBundlePath(data: BundleValidateJson, path: string): string | undefined {
322
- const parts = path.split(".").filter(Boolean);
323
- if (parts.length === 0) return undefined;
324
-
325
- let current: unknown = data;
326
- for (let i = 0; i < parts.length; i++) {
327
- if (!object.isRecord(current)) return undefined;
328
- const part = parts[i]!;
329
- const next = current[part];
330
- if (i === parts.length - 1) {
331
- if (typeof next === "string" && next) return next;
332
- if (object.isRecord(next)) {
333
- const value = next.value;
334
- return typeof value === "string" && value ? value : undefined;
335
- }
336
- return undefined;
337
- }
338
- current = next;
339
- }
340
- return undefined;
341
- }
342
-
343
- async function resolveAppEnvMap(
344
- options: ResolveConfigValueOptions,
345
- ): Promise<Record<string, string>> {
346
- const appData = options.appData ?? (await appYaml());
347
- const bundleData = options.bundleData ?? (await bundle());
348
- const fromYaml = appData ? flattenAppYamlEnv(appData.data) : {};
349
- const fromBundle = bundleData ? flattenAppEnv(bundleData.data) : {};
350
- return { ...fromYaml, ...fromBundle };
351
- }
352
-
353
- function resolveSources(options: ResolveConfigValueOptions): ConfigSource[] {
354
- const sources = [...(options.sources ?? defaultConfigSources)];
355
- if (options.explicit !== undefined && !sources.includes("explicit")) {
356
- sources.unshift("explicit");
357
- }
358
- return sources;
359
- }
360
-
361
- /**
362
- * Resolve a configuration string from the configured sources. Returns the first
363
- * non-empty value, or `undefined` when nothing matches.
364
- *
365
- * Precedence follows AppKit's: explicit config, then environment variable, then
366
- * whatever the Databricks App / bundle definition supplies.
367
- *
368
- * @example
369
- * import { bundle } from "@dbx-tools/appkit";
370
- *
371
- * const warehouseId = await bundle.resolveConfigValue("DATABRICKS_WAREHOUSE_ID", {
372
- * cli: { DATABRICKS_WAREHOUSE_ID: flags.warehouse },
373
- * sources: bundle.withCliSources(),
374
- * });
375
- */
376
- export async function resolveConfigValue(
27
+ export function resolveConfigValue(
377
28
  name: string,
378
29
  options: ResolveConfigValueOptions = {},
379
30
  ): Promise<string | undefined> {
380
- const keys = envKeysForName(name).toArray();
381
- if (keys.length === 0) return undefined;
382
- const sources = resolveSources(options);
383
- let appEnvMap: Record<string, string> | undefined;
384
- const values = (async function* () {
385
- for (const source of sources) {
386
- switch (source) {
387
- case "explicit":
388
- yield readMap(keys, options.explicit);
389
- break;
390
- case "cli":
391
- yield readMap(keys, options.cli);
392
- break;
393
- case "env":
394
- yield readEnv(keys);
395
- break;
396
- case "bundle":
397
- if (appEnvMap === undefined) appEnvMap = await resolveAppEnvMap(options);
398
- yield readAppEnv(keys, appEnvMap);
399
- break;
400
- default:
401
- throw ValidationError.invalidValue(
402
- "sources",
403
- source,
404
- "one of: explicit, cli, env, bundle",
405
- );
406
- }
407
- }
408
- })();
409
- for await (const value of values) {
410
- if (value) return value;
411
- }
412
- return undefined;
413
- }
414
-
415
- /**
416
- * Sources with `cli` included, in CLI-first order. Use for dev commands that
417
- * accept flag overrides.
418
- */
419
- export function withCliSources(sources: ConfigSource[] = defaultConfigSources): ConfigSource[] {
420
- const rest = sources.filter((source) => source !== "cli" && source !== "explicit");
421
- return ["cli", "explicit", ...rest];
31
+ return Promise.resolve(coreConfig.resolveValue(name, options));
422
32
  }
@@ -45,7 +45,6 @@ import {
45
45
  import { config as coreConfig, project } from "@dbx-tools/core";
46
46
  import { async, log, object, string } from "@dbx-tools/shared-core";
47
47
  import { z } from "zod";
48
- import { resolveConfigValue } from "./bundle.ts";
49
48
 
50
49
  import { toContext } from "./databricks.ts";
51
50
  import {
@@ -255,8 +254,8 @@ export function pollDelay(attempt: number, baseMs: number, signal?: AbortSignal)
255
254
  * Pull resolver inputs from `process.env`, parse the address blob, and
256
255
  * layer explicit config on top with this precedence:
257
256
  *
258
- * `config.<field>` > `bundle.resolveConfigValue` (`env`, then bundle
259
- * validate JSON) > whatever {@link parseAddress} recovered from the
257
+ * `config.<field>` > `coreConfig.resolveValue` (shared config sources) >
258
+ * whatever {@link parseAddress} recovered from the
260
259
  * `endpoint` / `LAKEBASE_ENDPOINT` blob.
261
260
  *
262
261
  * Set `config.endpoint` (or `LAKEBASE_ENDPOINT`) to any input
@@ -266,10 +265,10 @@ export function pollDelay(attempt: number, baseMs: number, signal?: AbortSignal)
266
265
  export async function readLakebaseInputs(
267
266
  config?: LakebaseResolverInputs,
268
267
  ): Promise<LakebaseResolverInputs> {
269
- const rawAddress = config?.endpoint ?? (await resolveConfigValue("LAKEBASE_ENDPOINT"));
268
+ const rawAddress = config?.endpoint ?? coreConfig.resolveValue("LAKEBASE_ENDPOINT");
270
269
  const parsed = parseAddress(rawAddress);
271
- const portEnv = parsePort(await resolveConfigValue("PGPORT"));
272
- const sslModeEnv = parseSslMode(await resolveConfigValue("PGSSLMODE"));
270
+ const portEnv = parsePort(coreConfig.resolveValue("PGPORT"));
271
+ const sslModeEnv = parseSslMode(coreConfig.resolveValue("PGSSLMODE"));
273
272
  return {
274
273
  project: config?.project ?? parsed.project,
275
274
  branch: config?.branch ?? parsed.branch,
@@ -277,8 +276,8 @@ export async function readLakebaseInputs(
277
276
  // bare hostnames set `host` instead and leave `endpoint` undefined
278
277
  // until the REST resolver fills it in.
279
278
  endpoint: parsed.endpoint,
280
- database: config?.database ?? (await resolveConfigValue("PGDATABASE")) ?? parsed.database,
281
- host: config?.host ?? (await resolveConfigValue("PGHOST")) ?? parsed.host,
279
+ database: config?.database ?? coreConfig.resolveValue("PGDATABASE") ?? parsed.database,
280
+ host: config?.host ?? coreConfig.resolveValue("PGHOST") ?? parsed.host,
282
281
  port: config?.port ?? portEnv ?? parsed.port,
283
282
  sslMode: config?.sslMode ?? sslModeEnv ?? parsed.sslMode,
284
283
  autoCreate: config?.autoCreate,