@databricks/appkit-ui 0.91.2 → 0.92.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/NOTICE.md CHANGED
@@ -9,20 +9,20 @@ This Software contains code from the following open source projects:
9
9
  | [@ast-grep/napi](https://www.npmjs.com/package/@ast-grep/napi) | 0.37.0 | MIT | https://ast-grep.github.io |
10
10
  | [@clack/prompts](https://www.npmjs.com/package/@clack/prompts) | 1.0.1 | MIT | https://github.com/bombshell-dev/clack/tree/main/packages/prompts#readme |
11
11
  | [@opentelemetry/api](https://www.npmjs.com/package/@opentelemetry/api) | 1.9.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/api |
12
- | [@opentelemetry/api-logs](https://www.npmjs.com/package/@opentelemetry/api-logs) | 0.219.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/api-logs |
13
- | [@opentelemetry/auto-instrumentations-node](https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node) | 0.77.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/auto-instrumentations-node#readme |
14
- | [@opentelemetry/exporter-logs-otlp-proto](https://www.npmjs.com/package/@opentelemetry/exporter-logs-otlp-proto) | 0.219.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-logs-otlp-proto |
15
- | [@opentelemetry/exporter-metrics-otlp-proto](https://www.npmjs.com/package/@opentelemetry/exporter-metrics-otlp-proto) | 0.219.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-exporter-metrics-otlp-proto |
16
- | [@opentelemetry/exporter-trace-otlp-proto](https://www.npmjs.com/package/@opentelemetry/exporter-trace-otlp-proto) | 0.219.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-trace-otlp-proto |
17
- | [@opentelemetry/instrumentation](https://www.npmjs.com/package/@opentelemetry/instrumentation) | 0.219.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation |
18
- | [@opentelemetry/instrumentation-express](https://www.npmjs.com/package/@opentelemetry/instrumentation-express) | 0.67.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express#readme |
19
- | [@opentelemetry/instrumentation-http](https://www.npmjs.com/package/@opentelemetry/instrumentation-http) | 0.219.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http |
20
- | [@opentelemetry/resources](https://www.npmjs.com/package/@opentelemetry/resources) | 2.8.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-resources |
21
- | [@opentelemetry/sdk-logs](https://www.npmjs.com/package/@opentelemetry/sdk-logs) | 0.219.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/sdk-logs |
22
- | [@opentelemetry/sdk-metrics](https://www.npmjs.com/package/@opentelemetry/sdk-metrics) | 2.8.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/sdk-metrics |
23
- | [@opentelemetry/sdk-trace-base](https://www.npmjs.com/package/@opentelemetry/sdk-trace-base) | 2.8.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-base |
24
- | [@opentelemetry/sdk-trace-node](https://www.npmjs.com/package/@opentelemetry/sdk-trace-node) | 2.8.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node |
25
- | [@opentelemetry/semantic-conventions](https://www.npmjs.com/package/@opentelemetry/semantic-conventions) | 1.38.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions |
12
+ | [@opentelemetry/api-logs](https://www.npmjs.com/package/@opentelemetry/api-logs) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/api-logs |
13
+ | [@opentelemetry/auto-instrumentations-node](https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node) | 0.81.2 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/auto-instrumentations-node#readme |
14
+ | [@opentelemetry/exporter-logs-otlp-proto](https://www.npmjs.com/package/@opentelemetry/exporter-logs-otlp-proto) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-logs-otlp-proto |
15
+ | [@opentelemetry/exporter-metrics-otlp-proto](https://www.npmjs.com/package/@opentelemetry/exporter-metrics-otlp-proto) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-exporter-metrics-otlp-proto |
16
+ | [@opentelemetry/exporter-trace-otlp-proto](https://www.npmjs.com/package/@opentelemetry/exporter-trace-otlp-proto) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/exporter-trace-otlp-proto |
17
+ | [@opentelemetry/instrumentation](https://www.npmjs.com/package/@opentelemetry/instrumentation) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation |
18
+ | [@opentelemetry/instrumentation-express](https://www.npmjs.com/package/@opentelemetry/instrumentation-express) | 0.71.1 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express#readme |
19
+ | [@opentelemetry/instrumentation-http](https://www.npmjs.com/package/@opentelemetry/instrumentation-http) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/opentelemetry-instrumentation-http |
20
+ | [@opentelemetry/resources](https://www.npmjs.com/package/@opentelemetry/resources) | 2.12.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-resources |
21
+ | [@opentelemetry/sdk-logs](https://www.npmjs.com/package/@opentelemetry/sdk-logs) | 0.223.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/experimental/packages/sdk-logs |
22
+ | [@opentelemetry/sdk-metrics](https://www.npmjs.com/package/@opentelemetry/sdk-metrics) | 2.12.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/sdk-metrics |
23
+ | [@opentelemetry/sdk-trace-base](https://www.npmjs.com/package/@opentelemetry/sdk-trace-base) | 2.12.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-base |
24
+ | [@opentelemetry/sdk-trace-node](https://www.npmjs.com/package/@opentelemetry/sdk-trace-node) | 2.12.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node |
25
+ | [@opentelemetry/semantic-conventions](https://www.npmjs.com/package/@opentelemetry/semantic-conventions) | 1.38.0, 1.44.0 | Apache-2.0 | https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions |
26
26
  | [@radix-ui/react-accordion](https://www.npmjs.com/package/@radix-ui/react-accordion) | 1.2.12 | MIT | https://radix-ui.com/primitives |
27
27
  | [@radix-ui/react-alert-dialog](https://www.npmjs.com/package/@radix-ui/react-alert-dialog) | 1.1.15 | MIT | https://radix-ui.com/primitives |
28
28
  | [@radix-ui/react-aspect-ratio](https://www.npmjs.com/package/@radix-ui/react-aspect-ratio) | 1.1.8 | MIT | https://radix-ui.com/primitives |
@@ -57,17 +57,17 @@ This Software contains code from the following open source projects:
57
57
  | [clsx](https://www.npmjs.com/package/clsx) | 2.1.1 | MIT | https://github.com/lukeed/clsx#readme |
58
58
  | [cmdk](https://www.npmjs.com/package/cmdk) | 1.1.1 | MIT | https://github.com/pacocoursey/cmdk#readme |
59
59
  | [commander](https://www.npmjs.com/package/commander) | 2.20.3, 5.1.0, 7.2.0, 8.3.0, 10.0.1, 12.1.0 | MIT | https://github.com/tj/commander.js#readme |
60
- | [dompurify](https://www.npmjs.com/package/dompurify) | 3.4.11 | (MPL-2.0 OR Apache-2.0) | https://github.com/cure53/DOMPurify |
60
+ | [dompurify](https://www.npmjs.com/package/dompurify) | 3.4.17 | (MPL-2.0 OR Apache-2.0) | https://github.com/cure53/DOMPurify |
61
61
  | [dotenv](https://www.npmjs.com/package/dotenv) | 16.6.1 | BSD-2-Clause | https://github.com/motdotla/dotenv#readme |
62
62
  | [drizzle-orm](https://www.npmjs.com/package/drizzle-orm) | 0.45.2 | Apache-2.0 | https://orm.drizzle.team |
63
- | [echarts](https://www.npmjs.com/package/echarts) | 6.0.0 | Apache-2.0 | https://echarts.apache.org |
63
+ | [echarts](https://www.npmjs.com/package/echarts) | 6.1.0 | Apache-2.0 | https://echarts.apache.org |
64
64
  | [echarts-for-react](https://www.npmjs.com/package/echarts-for-react) | 3.0.5 | MIT | https://github.com/hustcc/echarts-for-react |
65
65
  | [embla-carousel-react](https://www.npmjs.com/package/embla-carousel-react) | 8.6.0 | MIT | https://www.embla-carousel.com |
66
- | [express](https://www.npmjs.com/package/express) | 4.22.2 | MIT | http://expressjs.com/ |
66
+ | [express](https://www.npmjs.com/package/express) | 4.22.3 | MIT | http://expressjs.com/ |
67
67
  | [get-port](https://www.npmjs.com/package/get-port) | 7.2.0 | MIT | https://github.com/sindresorhus/get-port#readme |
68
68
  | [input-otp](https://www.npmjs.com/package/input-otp) | 1.4.2 | MIT | https://input-otp.rodz.dev/ |
69
69
  | [jiti](https://www.npmjs.com/package/jiti) | 1.21.7, 2.6.1 | MIT | https://github.com/unjs/jiti#readme |
70
- | [js-yaml](https://www.npmjs.com/package/js-yaml) | 3.14.2, 4.3.1 | MIT | https://github.com/nodeca/js-yaml#readme |
70
+ | [js-yaml](https://www.npmjs.com/package/js-yaml) | 3.14.2, 4.3.2 | MIT | https://github.com/nodeca/js-yaml#readme |
71
71
  | [lucide-react](https://www.npmjs.com/package/lucide-react) | 0.554.0 | ISC | https://lucide.dev |
72
72
  | [magic-string](https://www.npmjs.com/package/magic-string) | 0.30.21 | MIT | https://github.com/Rich-Harris/magic-string#readme |
73
73
  | [marked](https://www.npmjs.com/package/marked) | 16.4.2, 17.0.3 | MIT | https://marked.js.org |
@@ -83,6 +83,6 @@ This Software contains code from the following open source projects:
83
83
  | [tailwind-merge](https://www.npmjs.com/package/tailwind-merge) | 3.4.0 | MIT | https://github.com/dcastil/tailwind-merge |
84
84
  | [vaul](https://www.npmjs.com/package/vaul) | 1.1.2 | MIT | https://vaul.emilkowal.ski/ |
85
85
  | [ws](https://www.npmjs.com/package/ws) | 7.5.10, 8.21.0 | MIT | https://github.com/websockets/ws |
86
- | [yaml](https://www.npmjs.com/package/yaml) | 2.8.2 | ISC | https://eemeli.org/yaml/ |
87
- | [zod](https://www.npmjs.com/package/zod) | 4.3.6 | MIT | https://zod.dev |
86
+ | [yaml](https://www.npmjs.com/package/yaml) | 2.9.1 | ISC | https://eemeli.org/yaml/ |
87
+ | [zod](https://www.npmjs.com/package/zod) | 4.6.7 | MIT | https://zod.dev |
88
88
 
@@ -179,6 +179,20 @@ const probeFunction = async (client, target) => {
179
179
  return classifyError(err, target);
180
180
  }
181
181
  };
182
+ const probeModelService = async (client, target) => {
183
+ const name = field(target, "name");
184
+ if (!name) return missingField("name");
185
+ try {
186
+ const res = await client.request({
187
+ method: "GET",
188
+ path: `/api/2.1/unity-catalog/model-services/${encodeURIComponent(name)}`
189
+ });
190
+ if (res.ok) return EXISTENCE_OK;
191
+ throw Object.assign(new Error(await res.text()), { statusCode: res.status });
192
+ } catch (err) {
193
+ return classifyError(err, target);
194
+ }
195
+ };
182
196
  function lakebaseAuthHint(message) {
183
197
  if (/password authentication failed/i.test(message)) return "Lakebase uses an OAuth token as the password, so this usually means the PGUSER/role doesn't match your identity. Check PGUSER is your exact login.";
184
198
  }
@@ -229,6 +243,7 @@ const PROBES = {
229
243
  volume: probeVolume,
230
244
  vector_search_index: probeVectorIndex,
231
245
  uc_function: probeFunction,
246
+ model_service: probeModelService,
232
247
  postgres: probePostgres
233
248
  };
234
249
  async function runExistenceProbe(client, target) {
@@ -1 +1 @@
1
- {"version":3,"file":"checks-existence.js","names":[],"sources":["../../../../src/cli/commands/doctor/checks-existence.ts"],"sourcesContent":["/**\n * Layer: existence — per-resource-type probes that prove a declared resource\n * exists and is reachable via the cheapest read the SDK offers.\n *\n * The client is typed structurally against the facade's modular clients.\n */\n\nimport {\n AppkitNotInstalledError,\n getLakebasePool,\n type LakebasePoolHandle,\n} from \"./databricks-client\";\nimport type { LayerResult, ResourceTarget } from \"./types\";\nimport { errorMessage } from \"./utils\";\n\n/** A passing existence check. Shared, never mutated by callers. */\nconst EXISTENCE_OK: LayerResult = { layer: \"existence\", status: \"ok\" };\n\ninterface DoctorWorkspaceClient {\n warehouses: {\n getWarehouse: (r: { id: string }) => Promise<{ state?: string }>;\n };\n genie: {\n genieGetSpace: (r: { spaceId: string }) => Promise<unknown>;\n };\n jobs: {\n getJob: (r: { jobId: bigint }) => Promise<unknown>;\n };\n vectorSearch: {\n getVectorIndex: (r: { name: string }) => Promise<unknown>;\n };\n modelServing: {\n getInferenceEndpoint: (r: { name: string }) => Promise<unknown>;\n };\n volumes: {\n getVolume: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n functions: {\n getFunction: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n}\n\ntype ExistenceProbe = (\n client: DoctorWorkspaceClient,\n target: ResourceTarget,\n) => Promise<LayerResult>;\n\n// Read the HTTP status / Databricks error code off an ApiError structurally.\n// Two shapes can reach here: the wrapper's `ApiError` (`statusCode` /\n// `errorCode`) and the modular SDK's (`httpStatusCode` / `code`).\nfunction statusCodeOf(err: unknown): number | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { statusCode?: unknown; httpStatusCode?: unknown };\n const code = e.statusCode ?? e.httpStatusCode;\n return typeof code === \"number\" && code >= 0 ? code : undefined;\n}\n\nfunction errorCodeOf(err: unknown): string | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { errorCode?: unknown; code?: unknown };\n const code = e.errorCode ?? e.code;\n return typeof code === \"string\" && code.length > 0 ? code : undefined;\n}\n\n// The SDK message often embeds a JSON blob; pull the inner `message` out so\n// doctor prints one clean line, not a dump.\nfunction cleanMessage(err: unknown): string {\n const raw = errorMessage(err);\n const m = raw.match(/\"message\"\\s*:\\s*\"([^\"]+)\"/);\n return m ? m[1] : raw;\n}\n\n/** The resource's configured identifier (id / name / path / host), for short\n * messages. */\nfunction displayId(target: ResourceTarget): string | null {\n return field(target, \"id\", \"name\", \"path\", \"index_name\", \"indexName\", \"host\");\n}\n\nfunction classifyError(err: unknown, target: ResourceTarget): LayerResult {\n const status = statusCodeOf(err);\n const errorCode = errorCodeOf(err);\n const message = cleanMessage(err);\n const id = displayId(target);\n const quoted = id ? `\"${id}\"` : null;\n\n if (status === 404 || errorCode === \"RESOURCE_DOES_NOT_EXIST\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"NOT_FOUND\",\n detail: quoted ? `${quoted} not found` : \"not found\",\n };\n }\n // A malformed id/name often comes back as 400 rather than 404.\n if (status === 400 || errorCode === \"INVALID_PARAMETER_VALUE\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_VALUE\",\n detail: quoted\n ? `${quoted} is not a valid id/name`\n : `invalid id/name: ${message}`,\n };\n }\n // A 403 is genuinely ambiguous: several APIs (jobs, warehouses) return it for a\n // resource that doesn't exist as well as for one you can't read, so claiming\n // \"no permission\" outright would misdiagnose a wrong id. Say both.\n if (status === 403 || errorCode === \"PERMISSION_DENIED\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"ACCESS_DENIED\",\n detail: quoted\n ? `${quoted} not found, or you don't have access to it`\n : \"not found, or you don't have access to it\",\n };\n }\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"PROBE_FAILED\",\n detail: quoted\n ? `read failed for ${quoted}: ${message}`\n : `read failed: ${message}`,\n };\n}\n\n/** Normalizes a field key so camelCase (`indexName`) and snake_case\n * (`index_name`) spellings match. */\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_-]/g, \"\");\n}\n\n/** Looks up a resolved field value by any of the accepted key spellings. */\nfunction field(target: ResourceTarget, ...names: string[]): string | null {\n const wanted = new Set(names.map(normalizeKey));\n for (const [key, value] of Object.entries(target.fieldValues)) {\n if (wanted.has(normalizeKey(key)) && value.length > 0) return value;\n }\n return null;\n}\n\nfunction missingField(fieldName: string): LayerResult {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"MISSING_FIELD\",\n detail: `no ${fieldName} configured — can't probe`,\n };\n}\n\nconst probeWarehouse: ExistenceProbe = async (client, target) => {\n const id = field(target, \"id\");\n if (!id) return missingField(\"id\");\n try {\n const wh = await client.warehouses.getWarehouse({ id });\n const state = wh.state;\n if (state && state !== \"RUNNING\") {\n return {\n layer: \"existence\",\n status: \"warn\",\n code: \"WAREHOUSE_NOT_RUNNING\",\n detail: `warehouse exists but is ${state} (will cold-start on first query)`,\n };\n }\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeServing: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n // The API only accepts a name; if configured by id, probe with it anyway and\n // flag the likely cause on failure.\n const idOnly = name === null ? field(target, \"id\") : null;\n const value = name ?? idOnly;\n if (!value) return missingField(\"name\");\n try {\n await client.modelServing.getInferenceEndpoint({ name: value });\n return EXISTENCE_OK;\n } catch (err) {\n const result = classifyError(err, target);\n if (idOnly && result.status === \"error\") {\n result.hint =\n \"Serving endpoints are looked up by name, but this resource is configured by id. Set DATABRICKS_SERVING_ENDPOINT_NAME to the endpoint's name.\";\n }\n return result;\n }\n};\n\nconst probeGenie: ExistenceProbe = async (client, target) => {\n const spaceId = field(target, \"id\");\n if (!spaceId) return missingField(\"id\");\n try {\n await client.genie.genieGetSpace({ spaceId });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeJob: ExistenceProbe = async (client, target) => {\n const raw = field(target, \"id\");\n if (!raw) return missingField(\"id\");\n const id = raw.trim();\n // Validate the digits directly rather than via Number(): job ids are int64, so\n // past 2^53 Number() silently rounds (and Number.isInteger still passes),\n // which would probe a *different* job and report a false not-found. A string\n // check also rejects \"1e3\" and \"0x10\", both of which Number() would accept.\n if (!/^\\d+$/.test(id)) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_ID\",\n detail: `\"${raw}\" is not a valid job id (expected an integer)`,\n };\n }\n try {\n // BigInt keeps int64 precision (the digits were validated above).\n await client.jobs.getJob({ jobId: BigInt(id) });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVolume: ExistenceProbe = async (client, target) => {\n // The read API wants the 3-level name (catalog.schema.volume), but the env\n // value is usually a /Volumes/... path.\n const raw = field(target, \"path\", \"name\");\n if (!raw) return missingField(\"path\");\n const name = toThreeLevelVolumeName(raw);\n if (!name) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_NAME\",\n detail: `\"${raw}\" is not a valid volume path (expected /Volumes/catalog/schema/volume or catalog.schema.volume)`,\n };\n }\n try {\n await client.volumes.getVolume({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVectorIndex: ExistenceProbe = async (client, target) => {\n const name = field(target, \"indexName\", \"index_name\", \"name\");\n if (!name) return missingField(\"indexName\");\n try {\n await client.vectorSearch.getVectorIndex({ name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeFunction: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n if (!name) return missingField(\"name\");\n try {\n await client.functions.getFunction({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nfunction lakebaseAuthHint(message: string): string | undefined {\n if (/password authentication failed/i.test(message)) {\n return (\n \"Lakebase uses an OAuth token as the password, so this usually means the\" +\n \" PGUSER/role doesn't match your identity. Check PGUSER is your exact\" +\n \" login.\"\n );\n }\n return undefined;\n}\n\n// Lakebase has no cheap control-plane `.get()`, so existence is proven by a\n// real connection + `SELECT 1`.\nconst probePostgres: ExistenceProbe = async (client, target) => {\n if (!field(target, \"endpointPath\") && !field(target, \"host\")) {\n return missingField(\"host/endpoint\");\n }\n\n let pool: LakebasePoolHandle | null = null;\n try {\n pool = await getLakebasePool(client);\n await pool.query(\"SELECT 1\");\n return EXISTENCE_OK;\n } catch (err) {\n if (err instanceof AppkitNotInstalledError) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"APPKIT_NOT_INSTALLED\",\n detail: err.message,\n };\n }\n const message = cleanMessage(err);\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"CONNECTION_FAILED\",\n detail: `could not connect to Lakebase Postgres: ${message}`,\n hint: lakebaseAuthHint(message),\n };\n } finally {\n if (pool) {\n try {\n await pool.end();\n } catch {\n // best-effort close\n }\n }\n }\n};\n\n/**\n * Normalizes a volume reference to the SDK's 3-level `catalog.schema.volume`\n * name, accepting either an already-dotted name or a `/Volumes/c/s/v/...` path.\n */\nexport function toThreeLevelVolumeName(raw: string): string | null {\n const trimmed = raw.trim();\n if (/^[^./\\s]+\\.[^./\\s]+\\.[^./\\s]+$/.test(trimmed)) return trimmed;\n\n const m = trimmed.match(/^\\/Volumes\\/([^/]+)\\/([^/]+)\\/([^/]+)/);\n if (m) return `${m[1]}.${m[2]}.${m[3]}`;\n\n return null;\n}\n\n// Unlisted types fall through to NOT_IMPLEMENTED in runExistenceProbe.\nconst PROBES: Record<string, ExistenceProbe> = {\n sql_warehouse: probeWarehouse,\n serving_endpoint: probeServing,\n genie_space: probeGenie,\n job: probeJob,\n volume: probeVolume,\n vector_search_index: probeVectorIndex,\n uc_function: probeFunction,\n postgres: probePostgres,\n};\n\nexport async function runExistenceProbe(\n client: unknown,\n target: ResourceTarget,\n): Promise<LayerResult> {\n const probe = PROBES[target.type];\n if (!probe) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"NOT_IMPLEMENTED\",\n detail: `existence check not implemented for ${target.type}`,\n };\n }\n return probe(client as DoctorWorkspaceClient, target);\n}\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,eAA4B;CAAE,OAAO;CAAa,QAAQ;CAAM;AAkCtE,SAAS,aAAa,KAAkC;AACtD,KAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;CAC5C,MAAM,IAAI;CACV,MAAM,OAAO,EAAE,cAAc,EAAE;AAC/B,QAAO,OAAO,SAAS,YAAY,QAAQ,IAAI,OAAO;;AAGxD,SAAS,YAAY,KAAkC;AACrD,KAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;CAC5C,MAAM,IAAI;CACV,MAAM,OAAO,EAAE,aAAa,EAAE;AAC9B,QAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO;;AAK9D,SAAS,aAAa,KAAsB;CAC1C,MAAM,MAAM,aAAa,IAAI;CAC7B,MAAM,IAAI,IAAI,MAAM,4BAA4B;AAChD,QAAO,IAAI,EAAE,KAAK;;;;AAKpB,SAAS,UAAU,QAAuC;AACxD,QAAO,MAAM,QAAQ,MAAM,QAAQ,QAAQ,cAAc,aAAa,OAAO;;AAG/E,SAAS,cAAc,KAAc,QAAqC;CACxE,MAAM,SAAS,aAAa,IAAI;CAChC,MAAM,YAAY,YAAY,IAAI;CAClC,MAAM,UAAU,aAAa,IAAI;CACjC,MAAM,KAAK,UAAU,OAAO;CAC5B,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK;AAEhC,KAAI,WAAW,OAAO,cAAc,0BAClC,QAAO;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,QAAQ,SAAS,GAAG,OAAO,cAAc;EAC1C;AAGH,KAAI,WAAW,OAAO,cAAc,0BAClC,QAAO;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,QAAQ,SACJ,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,KAAI,EAAG,QAAO,GAAG,EAAE,GAAG,GAAG,EAAE,GAAG,GAAG,EAAE;AAEnC,QAAO;;AAIT,MAAM,SAAyC;CAC7C,eAAe;CACf,kBAAkB;CAClB,aAAa;CACb,KAAK;CACL,QAAQ;CACR,qBAAqB;CACrB,aAAa;CACb,UAAU;CACX;AAED,eAAsB,kBACpB,QACA,QACsB;CACtB,MAAM,QAAQ,OAAO,OAAO;AAC5B,KAAI,CAAC,MACH,QAAO;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,QAAQ,uCAAuC,OAAO;EACvD;AAEH,QAAO,MAAM,QAAiC,OAAO"}
1
+ {"version":3,"file":"checks-existence.js","names":[],"sources":["../../../../src/cli/commands/doctor/checks-existence.ts"],"sourcesContent":["/**\n * Layer: existence — per-resource-type probes that prove a declared resource\n * exists and is reachable via the cheapest read the SDK offers.\n *\n * The client is typed structurally against the facade's modular clients.\n */\n\nimport {\n AppkitNotInstalledError,\n getLakebasePool,\n type LakebasePoolHandle,\n} from \"./databricks-client\";\nimport type { LayerResult, ResourceTarget } from \"./types\";\nimport { errorMessage } from \"./utils\";\n\n/** A passing existence check. Shared, never mutated by callers. */\nconst EXISTENCE_OK: LayerResult = { layer: \"existence\", status: \"ok\" };\n\ninterface DoctorWorkspaceClient {\n warehouses: {\n getWarehouse: (r: { id: string }) => Promise<{ state?: string }>;\n };\n genie: {\n genieGetSpace: (r: { spaceId: string }) => Promise<unknown>;\n };\n jobs: {\n getJob: (r: { jobId: bigint }) => Promise<unknown>;\n };\n vectorSearch: {\n getVectorIndex: (r: { name: string }) => Promise<unknown>;\n };\n modelServing: {\n getInferenceEndpoint: (r: { name: string }) => Promise<unknown>;\n };\n volumes: {\n getVolume: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n functions: {\n getFunction: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n request: (r: { method: string; path: string }) => Promise<Response>;\n}\n\ntype ExistenceProbe = (\n client: DoctorWorkspaceClient,\n target: ResourceTarget,\n) => Promise<LayerResult>;\n\n// Read the HTTP status / Databricks error code off an ApiError structurally.\n// Two shapes can reach here: the wrapper's `ApiError` (`statusCode` /\n// `errorCode`) and the modular SDK's (`httpStatusCode` / `code`).\nfunction statusCodeOf(err: unknown): number | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { statusCode?: unknown; httpStatusCode?: unknown };\n const code = e.statusCode ?? e.httpStatusCode;\n return typeof code === \"number\" && code >= 0 ? code : undefined;\n}\n\nfunction errorCodeOf(err: unknown): string | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { errorCode?: unknown; code?: unknown };\n const code = e.errorCode ?? e.code;\n return typeof code === \"string\" && code.length > 0 ? code : undefined;\n}\n\n// The SDK message often embeds a JSON blob; pull the inner `message` out so\n// doctor prints one clean line, not a dump.\nfunction cleanMessage(err: unknown): string {\n const raw = errorMessage(err);\n const m = raw.match(/\"message\"\\s*:\\s*\"([^\"]+)\"/);\n return m ? m[1] : raw;\n}\n\n/** The resource's configured identifier (id / name / path / host), for short\n * messages. */\nfunction displayId(target: ResourceTarget): string | null {\n return field(target, \"id\", \"name\", \"path\", \"index_name\", \"indexName\", \"host\");\n}\n\nfunction classifyError(err: unknown, target: ResourceTarget): LayerResult {\n const status = statusCodeOf(err);\n const errorCode = errorCodeOf(err);\n const message = cleanMessage(err);\n const id = displayId(target);\n const quoted = id ? `\"${id}\"` : null;\n\n if (status === 404 || errorCode === \"RESOURCE_DOES_NOT_EXIST\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"NOT_FOUND\",\n detail: quoted ? `${quoted} not found` : \"not found\",\n };\n }\n // A malformed id/name often comes back as 400 rather than 404.\n if (status === 400 || errorCode === \"INVALID_PARAMETER_VALUE\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_VALUE\",\n detail: quoted\n ? `${quoted} is not a valid id/name`\n : `invalid id/name: ${message}`,\n };\n }\n // A 403 is genuinely ambiguous: several APIs (jobs, warehouses) return it for a\n // resource that doesn't exist as well as for one you can't read, so claiming\n // \"no permission\" outright would misdiagnose a wrong id. Say both.\n if (status === 403 || errorCode === \"PERMISSION_DENIED\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"ACCESS_DENIED\",\n detail: quoted\n ? `${quoted} not found, or you don't have access to it`\n : \"not found, or you don't have access to it\",\n };\n }\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"PROBE_FAILED\",\n detail: quoted\n ? `read failed for ${quoted}: ${message}`\n : `read failed: ${message}`,\n };\n}\n\n/** Normalizes a field key so camelCase (`indexName`) and snake_case\n * (`index_name`) spellings match. */\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_-]/g, \"\");\n}\n\n/** Looks up a resolved field value by any of the accepted key spellings. */\nfunction field(target: ResourceTarget, ...names: string[]): string | null {\n const wanted = new Set(names.map(normalizeKey));\n for (const [key, value] of Object.entries(target.fieldValues)) {\n if (wanted.has(normalizeKey(key)) && value.length > 0) return value;\n }\n return null;\n}\n\nfunction missingField(fieldName: string): LayerResult {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"MISSING_FIELD\",\n detail: `no ${fieldName} configured — can't probe`,\n };\n}\n\nconst probeWarehouse: ExistenceProbe = async (client, target) => {\n const id = field(target, \"id\");\n if (!id) return missingField(\"id\");\n try {\n const wh = await client.warehouses.getWarehouse({ id });\n const state = wh.state;\n if (state && state !== \"RUNNING\") {\n return {\n layer: \"existence\",\n status: \"warn\",\n code: \"WAREHOUSE_NOT_RUNNING\",\n detail: `warehouse exists but is ${state} (will cold-start on first query)`,\n };\n }\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeServing: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n // The API only accepts a name; if configured by id, probe with it anyway and\n // flag the likely cause on failure.\n const idOnly = name === null ? field(target, \"id\") : null;\n const value = name ?? idOnly;\n if (!value) return missingField(\"name\");\n try {\n await client.modelServing.getInferenceEndpoint({ name: value });\n return EXISTENCE_OK;\n } catch (err) {\n const result = classifyError(err, target);\n if (idOnly && result.status === \"error\") {\n result.hint =\n \"Serving endpoints are looked up by name, but this resource is configured by id. Set DATABRICKS_SERVING_ENDPOINT_NAME to the endpoint's name.\";\n }\n return result;\n }\n};\n\nconst probeGenie: ExistenceProbe = async (client, target) => {\n const spaceId = field(target, \"id\");\n if (!spaceId) return missingField(\"id\");\n try {\n await client.genie.genieGetSpace({ spaceId });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeJob: ExistenceProbe = async (client, target) => {\n const raw = field(target, \"id\");\n if (!raw) return missingField(\"id\");\n const id = raw.trim();\n // Validate the digits directly rather than via Number(): job ids are int64, so\n // past 2^53 Number() silently rounds (and Number.isInteger still passes),\n // which would probe a *different* job and report a false not-found. A string\n // check also rejects \"1e3\" and \"0x10\", both of which Number() would accept.\n if (!/^\\d+$/.test(id)) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_ID\",\n detail: `\"${raw}\" is not a valid job id (expected an integer)`,\n };\n }\n try {\n // BigInt keeps int64 precision (the digits were validated above).\n await client.jobs.getJob({ jobId: BigInt(id) });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVolume: ExistenceProbe = async (client, target) => {\n // The read API wants the 3-level name (catalog.schema.volume), but the env\n // value is usually a /Volumes/... path.\n const raw = field(target, \"path\", \"name\");\n if (!raw) return missingField(\"path\");\n const name = toThreeLevelVolumeName(raw);\n if (!name) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_NAME\",\n detail: `\"${raw}\" is not a valid volume path (expected /Volumes/catalog/schema/volume or catalog.schema.volume)`,\n };\n }\n try {\n await client.volumes.getVolume({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVectorIndex: ExistenceProbe = async (client, target) => {\n const name = field(target, \"indexName\", \"index_name\", \"name\");\n if (!name) return missingField(\"indexName\");\n try {\n await client.vectorSearch.getVectorIndex({ name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeFunction: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n if (!name) return missingField(\"name\");\n try {\n await client.functions.getFunction({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\n// request() resolves on any status; throw non-OK so classifyError reads it.\nconst probeModelService: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n if (!name) return missingField(\"name\");\n try {\n const res = await client.request({\n method: \"GET\",\n path: `/api/2.1/unity-catalog/model-services/${encodeURIComponent(name)}`,\n });\n if (res.ok) return EXISTENCE_OK;\n throw Object.assign(new Error(await res.text()), {\n statusCode: res.status,\n });\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nfunction lakebaseAuthHint(message: string): string | undefined {\n if (/password authentication failed/i.test(message)) {\n return (\n \"Lakebase uses an OAuth token as the password, so this usually means the\" +\n \" PGUSER/role doesn't match your identity. Check PGUSER is your exact\" +\n \" login.\"\n );\n }\n return undefined;\n}\n\n// Lakebase has no cheap control-plane `.get()`, so existence is proven by a\n// real connection + `SELECT 1`.\nconst probePostgres: ExistenceProbe = async (client, target) => {\n if (!field(target, \"endpointPath\") && !field(target, \"host\")) {\n return missingField(\"host/endpoint\");\n }\n\n let pool: LakebasePoolHandle | null = null;\n try {\n pool = await getLakebasePool(client);\n await pool.query(\"SELECT 1\");\n return EXISTENCE_OK;\n } catch (err) {\n if (err instanceof AppkitNotInstalledError) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"APPKIT_NOT_INSTALLED\",\n detail: err.message,\n };\n }\n const message = cleanMessage(err);\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"CONNECTION_FAILED\",\n detail: `could not connect to Lakebase Postgres: ${message}`,\n hint: lakebaseAuthHint(message),\n };\n } finally {\n if (pool) {\n try {\n await pool.end();\n } catch {\n // best-effort close\n }\n }\n }\n};\n\n/**\n * Normalizes a volume reference to the SDK's 3-level `catalog.schema.volume`\n * name, accepting either an already-dotted name or a `/Volumes/c/s/v/...` path.\n */\nexport function toThreeLevelVolumeName(raw: string): string | null {\n const trimmed = raw.trim();\n if (/^[^./\\s]+\\.[^./\\s]+\\.[^./\\s]+$/.test(trimmed)) return trimmed;\n\n const m = trimmed.match(/^\\/Volumes\\/([^/]+)\\/([^/]+)\\/([^/]+)/);\n if (m) return `${m[1]}.${m[2]}.${m[3]}`;\n\n return null;\n}\n\n// Unlisted types fall through to NOT_IMPLEMENTED in runExistenceProbe.\nconst PROBES: Record<string, ExistenceProbe> = {\n sql_warehouse: probeWarehouse,\n serving_endpoint: probeServing,\n genie_space: probeGenie,\n job: probeJob,\n volume: probeVolume,\n vector_search_index: probeVectorIndex,\n uc_function: probeFunction,\n model_service: probeModelService,\n postgres: probePostgres,\n};\n\nexport async function runExistenceProbe(\n client: unknown,\n target: ResourceTarget,\n): Promise<LayerResult> {\n const probe = PROBES[target.type];\n if (!probe) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"NOT_IMPLEMENTED\",\n detail: `existence check not implemented for ${target.type}`,\n };\n }\n return probe(client as DoctorWorkspaceClient, target);\n}\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,eAA4B;CAAE,OAAO;CAAa,QAAQ;CAAM;AAmCtE,SAAS,aAAa,KAAkC;AACtD,KAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;CAC5C,MAAM,IAAI;CACV,MAAM,OAAO,EAAE,cAAc,EAAE;AAC/B,QAAO,OAAO,SAAS,YAAY,QAAQ,IAAI,OAAO;;AAGxD,SAAS,YAAY,KAAkC;AACrD,KAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;CAC5C,MAAM,IAAI;CACV,MAAM,OAAO,EAAE,aAAa,EAAE;AAC9B,QAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO;;AAK9D,SA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;CACX;AAED,eAAsB,kBACpB,QACA,QACsB;CACtB,MAAM,QAAQ,OAAO,OAAO;AAC5B,KAAI,CAAC,MACH,QAAO;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,QAAQ,uCAAuC,OAAO;EACvD;AAEH,QAAO,MAAM,QAAiC,OAAO"}
@@ -37,6 +37,10 @@ const DEFAULT_FIELDS_BY_TYPE = {
37
37
  env: "DATABRICKS_SERVING_ENDPOINT_ID",
38
38
  description: "Serving endpoint ID"
39
39
  } },
40
+ model_service: { name: {
41
+ env: "DATABRICKS_MODEL_SERVICE_NAME",
42
+ description: "Model service full name (catalog.schema.name)"
43
+ } },
40
44
  volume: { name: {
41
45
  env: "VOLUME_NAME",
42
46
  description: "Volume name"
@@ -1 +1 @@
1
- {"version":3,"file":"resource-defaults.js","names":[],"sources":["../../../../../src/cli/commands/plugin/create/resource-defaults.ts"],"sourcesContent":["/**\n * Resource type and permission defaults for plugin scaffolding.\n * Values are sourced from the canonical Zod schemas in `schemas/manifest`,\n * surfaced through the `schema-resources` module.\n */\n\nimport {\n getResourceTypeOptions,\n getResourceTypePermissions,\n type ResourceTypeOption,\n} from \"../schema-resources\";\n\nexport const MANIFEST_SCHEMA_ID =\n \"https://databricks.github.io/appkit/schemas/plugin-manifest.schema.json\";\n\nexport type { ResourceTypeOption };\n\n/** Resource types from schema resourceType enum (value, human label). */\nexport const RESOURCE_TYPE_OPTIONS: ResourceTypeOption[] =\n getResourceTypeOptions();\n\n/** All valid permissions per resource type, from schema allOf/if-then rules. */\nexport const PERMISSIONS_BY_TYPE: Record<string, string[]> =\n getResourceTypePermissions();\n\n/** Default (first) permission per resource type for scaffolding. */\nexport const DEFAULT_PERMISSION_BY_TYPE: Record<string, string> =\n Object.fromEntries(\n Object.entries(PERMISSIONS_BY_TYPE).map(([type, perms]) => [\n type,\n perms[0],\n ]),\n );\n\n/** Default fields per resource type: field key -> { env, description }. */\nexport const DEFAULT_FIELDS_BY_TYPE: Record<\n string,\n Record<string, { env: string; description?: string }>\n> = {\n sql_warehouse: {\n id: { env: \"DATABRICKS_WAREHOUSE_ID\", description: \"SQL Warehouse ID\" },\n },\n secret: {\n scope: { env: \"SECRET_SCOPE\", description: \"Secret scope name\" },\n key: { env: \"SECRET_KEY\", description: \"Secret key\" },\n },\n job: {\n id: { env: \"DATABRICKS_JOB_ID\", description: \"Job ID\" },\n },\n serving_endpoint: {\n id: {\n env: \"DATABRICKS_SERVING_ENDPOINT_ID\",\n description: \"Serving endpoint ID\",\n },\n },\n volume: {\n name: { env: \"VOLUME_NAME\", description: \"Volume name\" },\n },\n vector_search_index: {\n endpoint_name: {\n env: \"VECTOR_SEARCH_ENDPOINT_NAME\",\n description: \"Vector search endpoint name\",\n },\n index_name: {\n env: \"VECTOR_SEARCH_INDEX_NAME\",\n description: \"Vector search index name\",\n },\n },\n uc_function: {\n name: {\n env: \"UC_FUNCTION_NAME\",\n description: \"Unity Catalog function name\",\n },\n },\n uc_connection: {\n name: {\n env: \"UC_CONNECTION_NAME\",\n description: \"Unity Catalog connection name\",\n },\n },\n database: {\n instance_name: {\n env: \"DATABRICKS_INSTANCE_NAME\",\n description: \"Databricks instance name\",\n },\n database_name: {\n env: \"DATABASE_NAME\",\n description: \"Database name\",\n },\n },\n genie_space: {\n id: { env: \"GENIE_SPACE_ID\", description: \"Genie Space ID\" },\n },\n experiment: {\n id: { env: \"MLFLOW_EXPERIMENT_ID\", description: \"MLflow experiment ID\" },\n },\n app: {\n id: { env: \"DATABRICKS_APP_ID\", description: \"Databricks App ID\" },\n },\n};\n\n/** Valid resource type values from the schema. */\nexport function getValidResourceTypes(): string[] {\n return RESOURCE_TYPE_OPTIONS.map((o) => o.value);\n}\n\n/** Humanized alias from resource type (e.g. sql_warehouse -> \"SQL Warehouse\"). */\nexport function humanizeResourceType(type: string): string {\n const option = RESOURCE_TYPE_OPTIONS.find((o) => o.value === type);\n return option ? option.label : type.replace(/_/g, \" \");\n}\n\n/** Kebab-case resource key from type (e.g. sql_warehouse -> \"sql-warehouse\"). */\nexport function resourceKeyFromType(type: string): string {\n return type.replace(/_/g, \"-\");\n}\n\n/** Get default fields for a resource type; fallback to single id field. */\nexport function getDefaultFieldsForType(\n type: string,\n): Record<string, { env: string; description?: string }> {\n const known = DEFAULT_FIELDS_BY_TYPE[type];\n if (known) return known;\n const key = resourceKeyFromType(type);\n const envName = `DATABRICKS_${key.toUpperCase().replace(/-/g, \"_\")}_ID`;\n return {\n id: { env: envName, description: `${humanizeResourceType(type)} ID` },\n };\n}\n"],"mappings":";;;;;;;;AAYA,MAAa,qBACX;;AAKF,MAAa,wBACX,wBAAwB;;AAG1B,MAAa,sBACX,4BAA4B;;AAG9B,MAAa,6BACX,OAAO,YACL,OAAO,QAAQ,oBAAoB,CAAC,KAAK,CAAC,MAAM,WAAW,CACzD,MACA,MAAM,GACP,CAAC,CACH;;AAGH,MAAa,yBAGT;CACF,eAAe,EACb,IAAI;EAAE,KAAK;EAA2B,aAAa;EAAoB,EACxE;CACD,QAAQ;EACN,OAAO;GAAE,KAAK;GAAgB,aAAa;GAAqB;EAChE,KAAK;GAAE,KAAK;GAAc,aAAa;GAAc;EACtD;CACD,KAAK,EACH,IAAI;EAAE,KAAK;EAAqB,aAAa;EAAU,EACxD;CACD,kBAAkB,EAChB,IAAI;EACF,KAAK;EACL,aAAa;EACd,EACF;CACD,QAAQ,EACN,MAAM;EAAE,KAAK;EAAe,aAAa;EAAe,EACzD;CACD,qBAAqB;EACnB,eAAe;GACb,KAAK;GACL,aAAa;GACd;EACD,YAAY;GACV,KAAK;GACL,aAAa;GACd;EACF;CACD,aAAa,EACX,MAAM;EACJ,KAAK;EACL,aAAa;EACd,EACF;CACD,eAAe,EACb,MAAM;EACJ,KAAK;EACL,aAAa;EACd,EACF;CACD,UAAU;EACR,eAAe;GACb,KAAK;GACL,aAAa;GACd;EACD,eAAe;GACb,KAAK;GACL,aAAa;GACd;EACF;CACD,aAAa,EACX,IAAI;EAAE,KAAK;EAAkB,aAAa;EAAkB,EAC7D;CACD,YAAY,EACV,IAAI;EAAE,KAAK;EAAwB,aAAa;EAAwB,EACzE;CACD,KAAK,EACH,IAAI;EAAE,KAAK;EAAqB,aAAa;EAAqB,EACnE;CACF;;AAGD,SAAgB,wBAAkC;AAChD,QAAO,sBAAsB,KAAK,MAAM,EAAE,MAAM;;;AAIlD,SAAgB,qBAAqB,MAAsB;CACzD,MAAM,SAAS,sBAAsB,MAAM,MAAM,EAAE,UAAU,KAAK;AAClE,QAAO,SAAS,OAAO,QAAQ,KAAK,QAAQ,MAAM,IAAI;;;AAIxD,SAAgB,oBAAoB,MAAsB;AACxD,QAAO,KAAK,QAAQ,MAAM,IAAI;;;AAIhC,SAAgB,wBACd,MACuD;CACvD,MAAM,QAAQ,uBAAuB;AACrC,KAAI,MAAO,QAAO;AAGlB,QAAO,EACL,IAAI;EAAE,KAFQ,cADJ,oBAAoB,KAAK,CACH,aAAa,CAAC,QAAQ,MAAM,IAAI,CAAC;EAE7C,aAAa,GAAG,qBAAqB,KAAK,CAAC;EAAM,EACtE"}
1
+ {"version":3,"file":"resource-defaults.js","names":[],"sources":["../../../../../src/cli/commands/plugin/create/resource-defaults.ts"],"sourcesContent":["/**\n * Resource type and permission defaults for plugin scaffolding.\n * Values are sourced from the canonical Zod schemas in `schemas/manifest`,\n * surfaced through the `schema-resources` module.\n */\n\nimport {\n getResourceTypeOptions,\n getResourceTypePermissions,\n type ResourceTypeOption,\n} from \"../schema-resources\";\n\nexport const MANIFEST_SCHEMA_ID =\n \"https://databricks.github.io/appkit/schemas/plugin-manifest.schema.json\";\n\nexport type { ResourceTypeOption };\n\n/** Resource types from schema resourceType enum (value, human label). */\nexport const RESOURCE_TYPE_OPTIONS: ResourceTypeOption[] =\n getResourceTypeOptions();\n\n/** All valid permissions per resource type, from schema allOf/if-then rules. */\nexport const PERMISSIONS_BY_TYPE: Record<string, string[]> =\n getResourceTypePermissions();\n\n/** Default (first) permission per resource type for scaffolding. */\nexport const DEFAULT_PERMISSION_BY_TYPE: Record<string, string> =\n Object.fromEntries(\n Object.entries(PERMISSIONS_BY_TYPE).map(([type, perms]) => [\n type,\n perms[0],\n ]),\n );\n\n/** Default fields per resource type: field key -> { env, description }. */\nexport const DEFAULT_FIELDS_BY_TYPE: Record<\n string,\n Record<string, { env: string; description?: string }>\n> = {\n sql_warehouse: {\n id: { env: \"DATABRICKS_WAREHOUSE_ID\", description: \"SQL Warehouse ID\" },\n },\n secret: {\n scope: { env: \"SECRET_SCOPE\", description: \"Secret scope name\" },\n key: { env: \"SECRET_KEY\", description: \"Secret key\" },\n },\n job: {\n id: { env: \"DATABRICKS_JOB_ID\", description: \"Job ID\" },\n },\n serving_endpoint: {\n id: {\n env: \"DATABRICKS_SERVING_ENDPOINT_ID\",\n description: \"Serving endpoint ID\",\n },\n },\n model_service: {\n name: {\n env: \"DATABRICKS_MODEL_SERVICE_NAME\",\n description: \"Model service full name (catalog.schema.name)\",\n },\n },\n volume: {\n name: { env: \"VOLUME_NAME\", description: \"Volume name\" },\n },\n vector_search_index: {\n endpoint_name: {\n env: \"VECTOR_SEARCH_ENDPOINT_NAME\",\n description: \"Vector search endpoint name\",\n },\n index_name: {\n env: \"VECTOR_SEARCH_INDEX_NAME\",\n description: \"Vector search index name\",\n },\n },\n uc_function: {\n name: {\n env: \"UC_FUNCTION_NAME\",\n description: \"Unity Catalog function name\",\n },\n },\n uc_connection: {\n name: {\n env: \"UC_CONNECTION_NAME\",\n description: \"Unity Catalog connection name\",\n },\n },\n database: {\n instance_name: {\n env: \"DATABRICKS_INSTANCE_NAME\",\n description: \"Databricks instance name\",\n },\n database_name: {\n env: \"DATABASE_NAME\",\n description: \"Database name\",\n },\n },\n genie_space: {\n id: { env: \"GENIE_SPACE_ID\", description: \"Genie Space ID\" },\n },\n experiment: {\n id: { env: \"MLFLOW_EXPERIMENT_ID\", description: \"MLflow experiment ID\" },\n },\n app: {\n id: { env: \"DATABRICKS_APP_ID\", description: \"Databricks App ID\" },\n },\n};\n\n/** Valid resource type values from the schema. */\nexport function getValidResourceTypes(): string[] {\n return RESOURCE_TYPE_OPTIONS.map((o) => o.value);\n}\n\n/** Humanized alias from resource type (e.g. sql_warehouse -> \"SQL Warehouse\"). */\nexport function humanizeResourceType(type: string): string {\n const option = RESOURCE_TYPE_OPTIONS.find((o) => o.value === type);\n return option ? option.label : type.replace(/_/g, \" \");\n}\n\n/** Kebab-case resource key from type (e.g. sql_warehouse -> \"sql-warehouse\"). */\nexport function resourceKeyFromType(type: string): string {\n return type.replace(/_/g, \"-\");\n}\n\n/** Get default fields for a resource type; fallback to single id field. */\nexport function getDefaultFieldsForType(\n type: string,\n): Record<string, { env: string; description?: string }> {\n const known = DEFAULT_FIELDS_BY_TYPE[type];\n if (known) return known;\n const key = resourceKeyFromType(type);\n const envName = `DATABRICKS_${key.toUpperCase().replace(/-/g, \"_\")}_ID`;\n return {\n id: { env: envName, description: `${humanizeResourceType(type)} ID` },\n };\n}\n"],"mappings":";;;;;;;;AAYA,MAAa,qBACX;;AAKF,MAAa,wBACX,wBAAwB;;AAG1B,MAAa,sBACX,4BAA4B;;AAG9B,MAAa,6BACX,OAAO,YACL,OAAO,QAAQ,oBAAoB,CAAC,KAAK,CAAC,MAAM,WAAW,CACzD,MACA,MAAM,GACP,CAAC,CACH;;AAGH,MAAa,yBAGT;CACF,eAAe,EACb,IAAI;EAAE,KAAK;EAA2B,aAAa;EAAoB,EACxE;CACD,QAAQ;EACN,OAAO;GAAE,KAAK;GAAgB,aAAa;GAAqB;EAChE,KAAK;GAAE,KAAK;GAAc,aAAa;GAAc;EACtD;CACD,KAAK,EACH,IAAI;EAAE,KAAK;EAAqB,aAAa;EAAU,EACxD;CACD,kBAAkB,EAChB,IAAI;EACF,KAAK;EACL,aAAa;EACd,EACF;CACD,eAAe,EACb,MAAM;EACJ,KAAK;EACL,aAAa;EACd,EACF;CACD,QAAQ,EACN,MAAM;EAAE,KAAK;EAAe,aAAa;EAAe,EACzD;CACD,qBAAqB;EACnB,eAAe;GACb,KAAK;GACL,aAAa;GACd;EACD,YAAY;GACV,KAAK;GACL,aAAa;GACd;EACF;CACD,aAAa,EACX,MAAM;EACJ,KAAK;EACL,aAAa;EACd,EACF;CACD,eAAe,EACb,MAAM;EACJ,KAAK;EACL,aAAa;EACd,EACF;CACD,UAAU;EACR,eAAe;GACb,KAAK;GACL,aAAa;GACd;EACD,eAAe;GACb,KAAK;GACL,aAAa;GACd;EACF;CACD,aAAa,EACX,IAAI;EAAE,KAAK;EAAkB,aAAa;EAAkB,EAC7D;CACD,YAAY,EACV,IAAI;EAAE,KAAK;EAAwB,aAAa;EAAwB,EACzE;CACD,KAAK,EACH,IAAI;EAAE,KAAK;EAAqB,aAAa;EAAqB,EACnE;CACF;;AAGD,SAAgB,wBAAkC;AAChD,QAAO,sBAAsB,KAAK,MAAM,EAAE,MAAM;;;AAIlD,SAAgB,qBAAqB,MAAsB;CACzD,MAAM,SAAS,sBAAsB,MAAM,MAAM,EAAE,UAAU,KAAK;AAClE,QAAO,SAAS,OAAO,QAAQ,KAAK,QAAQ,MAAM,IAAI;;;AAIxD,SAAgB,oBAAoB,MAAsB;AACxD,QAAO,KAAK,QAAQ,MAAM,IAAI;;;AAIhC,SAAgB,wBACd,MACuD;CACvD,MAAM,QAAQ,uBAAuB;AACrC,KAAI,MAAO,QAAO;AAGlB,QAAO,EACL,IAAI;EAAE,KAFQ,cADJ,oBAAoB,KAAK,CACH,aAAa,CAAC,QAAQ,MAAM,IAAI,CAAC;EAE7C,aAAa,GAAG,qBAAqB,KAAK,CAAC;EAAM,EACtE"}
@@ -1,4 +1,4 @@
1
- import { appPermissionSchema, databasePermissionSchema, experimentPermissionSchema, genieSpacePermissionSchema, jobPermissionSchema, postgresPermissionSchema, resourceTypeSchema, secretPermissionSchema, servingEndpointPermissionSchema, sqlWarehousePermissionSchema, ucConnectionPermissionSchema, ucFunctionPermissionSchema, vectorSearchIndexPermissionSchema, volumePermissionSchema } from "../../../schemas/manifest.js";
1
+ import { appPermissionSchema, databasePermissionSchema, experimentPermissionSchema, genieSpacePermissionSchema, jobPermissionSchema, modelServicePermissionSchema, postgresPermissionSchema, resourceTypeSchema, secretPermissionSchema, servingEndpointPermissionSchema, sqlWarehousePermissionSchema, ucConnectionPermissionSchema, ucFunctionPermissionSchema, vectorSearchIndexPermissionSchema, volumePermissionSchema } from "../../../schemas/manifest.js";
2
2
 
3
3
  //#region src/cli/commands/plugin/schema-resources.ts
4
4
  /**
@@ -30,6 +30,7 @@ const PERMISSION_SCHEMAS_BY_TYPE = {
30
30
  job: jobPermissionSchema,
31
31
  sql_warehouse: sqlWarehousePermissionSchema,
32
32
  serving_endpoint: servingEndpointPermissionSchema,
33
+ model_service: modelServicePermissionSchema,
33
34
  volume: volumePermissionSchema,
34
35
  vector_search_index: vectorSearchIndexPermissionSchema,
35
36
  uc_function: ucFunctionPermissionSchema,
@@ -1 +1 @@
1
- {"version":3,"file":"schema-resources.js","names":[],"sources":["../../../../src/cli/commands/plugin/schema-resources.ts"],"sourcesContent":["/**\n * Resource types and permissions sourced from the canonical Zod schemas in\n * `schemas/manifest.ts`. Single source of truth so create, add-resource, and\n * validate stay in sync with the schema.\n *\n * Values are constant at module load (direct Zod imports, no runtime JSON-schema\n * read), so no caching is needed.\n */\nimport {\n appPermissionSchema,\n databasePermissionSchema,\n experimentPermissionSchema,\n genieSpacePermissionSchema,\n jobPermissionSchema,\n postgresPermissionSchema,\n resourceTypeSchema,\n secretPermissionSchema,\n servingEndpointPermissionSchema,\n sqlWarehousePermissionSchema,\n ucConnectionPermissionSchema,\n ucFunctionPermissionSchema,\n vectorSearchIndexPermissionSchema,\n volumePermissionSchema,\n} from \"../../../schemas/manifest\";\n\nexport interface ResourceTypeOption {\n value: string;\n label: string;\n}\n\n/** Optional display overrides for acronyms (e.g. SQL, UC). Omitted entries use title-case of value. */\nconst LABEL_OVERRIDES: Record<string, string> = {\n sql_warehouse: \"SQL Warehouse\",\n uc_function: \"UC Function\",\n uc_connection: \"UC Connection\",\n};\n\nfunction humanize(value: string): string {\n if (LABEL_OVERRIDES[value]) return LABEL_OVERRIDES[value];\n return value.replace(/_/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n/**\n * Map from resource type literal to its permission enum schema. Mirrors the\n * `allOf + if/then` block in the previous hand-written JSON Schema, but driven\n * directly from the Zod source. Add an entry here when extending\n * `resourceTypeSchema`.\n */\nconst PERMISSION_SCHEMAS_BY_TYPE = {\n secret: secretPermissionSchema,\n job: jobPermissionSchema,\n sql_warehouse: sqlWarehousePermissionSchema,\n serving_endpoint: servingEndpointPermissionSchema,\n volume: volumePermissionSchema,\n vector_search_index: vectorSearchIndexPermissionSchema,\n uc_function: ucFunctionPermissionSchema,\n uc_connection: ucConnectionPermissionSchema,\n database: databasePermissionSchema,\n postgres: postgresPermissionSchema,\n genie_space: genieSpacePermissionSchema,\n experiment: experimentPermissionSchema,\n app: appPermissionSchema,\n} as const;\n\n/**\n * Resource type options (value + label) from `resourceTypeSchema.options`.\n */\nexport function getResourceTypeOptions(): ResourceTypeOption[] {\n return resourceTypeSchema.options.map((value) => ({\n value,\n label: humanize(value),\n }));\n}\n\n/**\n * Permissions per resource type, derived from each type's per-type permission\n * schema's `.options` array. Order is weakest-to-strongest (matches Zod enum\n * declaration order, which the original JSON Schema also preserved).\n */\nexport function getResourceTypePermissions(): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const [type, schema] of Object.entries(PERMISSION_SCHEMAS_BY_TYPE)) {\n out[type] = [...schema.options];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,MAAM,kBAA0C;CAC9C,eAAe;CACf,aAAa;CACb,eAAe;CAChB;AAED,SAAS,SAAS,OAAuB;AACvC,KAAI,gBAAgB,OAAQ,QAAO,gBAAgB;AACnD,QAAO,MAAM,QAAQ,MAAM,IAAI,CAAC,QAAQ,UAAU,MAAM,EAAE,aAAa,CAAC;;;;;;;;AAS1E,MAAM,6BAA6B;CACjC,QAAQ;CACR,KAAK;CACL,eAAe;CACf,kBAAkB;CAClB,QAAQ;CACR,qBAAqB;CACrB,aAAa;CACb,eAAe;CACf,UAAU;CACV,UAAU;CACV,aAAa;CACb,YAAY;CACZ,KAAK;CACN;;;;AAKD,SAAgB,yBAA+C;AAC7D,QAAO,mBAAmB,QAAQ,KAAK,WAAW;EAChD;EACA,OAAO,SAAS,MAAM;EACvB,EAAE;;;;;;;AAQL,SAAgB,6BAAuD;CACrE,MAAM,MAAgC,EAAE;AACxC,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,2BAA2B,CACrE,KAAI,QAAQ,CAAC,GAAG,OAAO,QAAQ;AAEjC,QAAO"}
1
+ {"version":3,"file":"schema-resources.js","names":[],"sources":["../../../../src/cli/commands/plugin/schema-resources.ts"],"sourcesContent":["/**\n * Resource types and permissions sourced from the canonical Zod schemas in\n * `schemas/manifest.ts`. Single source of truth so create, add-resource, and\n * validate stay in sync with the schema.\n *\n * Values are constant at module load (direct Zod imports, no runtime JSON-schema\n * read), so no caching is needed.\n */\nimport {\n appPermissionSchema,\n databasePermissionSchema,\n experimentPermissionSchema,\n genieSpacePermissionSchema,\n jobPermissionSchema,\n modelServicePermissionSchema,\n postgresPermissionSchema,\n resourceTypeSchema,\n secretPermissionSchema,\n servingEndpointPermissionSchema,\n sqlWarehousePermissionSchema,\n ucConnectionPermissionSchema,\n ucFunctionPermissionSchema,\n vectorSearchIndexPermissionSchema,\n volumePermissionSchema,\n} from \"../../../schemas/manifest\";\n\nexport interface ResourceTypeOption {\n value: string;\n label: string;\n}\n\n/** Optional display overrides for acronyms (e.g. SQL, UC). Omitted entries use title-case of value. */\nconst LABEL_OVERRIDES: Record<string, string> = {\n sql_warehouse: \"SQL Warehouse\",\n uc_function: \"UC Function\",\n uc_connection: \"UC Connection\",\n};\n\nfunction humanize(value: string): string {\n if (LABEL_OVERRIDES[value]) return LABEL_OVERRIDES[value];\n return value.replace(/_/g, \" \").replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n/**\n * Map from resource type literal to its permission enum schema. Mirrors the\n * `allOf + if/then` block in the previous hand-written JSON Schema, but driven\n * directly from the Zod source. Add an entry here when extending\n * `resourceTypeSchema`.\n */\nconst PERMISSION_SCHEMAS_BY_TYPE = {\n secret: secretPermissionSchema,\n job: jobPermissionSchema,\n sql_warehouse: sqlWarehousePermissionSchema,\n serving_endpoint: servingEndpointPermissionSchema,\n model_service: modelServicePermissionSchema,\n volume: volumePermissionSchema,\n vector_search_index: vectorSearchIndexPermissionSchema,\n uc_function: ucFunctionPermissionSchema,\n uc_connection: ucConnectionPermissionSchema,\n database: databasePermissionSchema,\n postgres: postgresPermissionSchema,\n genie_space: genieSpacePermissionSchema,\n experiment: experimentPermissionSchema,\n app: appPermissionSchema,\n} as const;\n\n/**\n * Resource type options (value + label) from `resourceTypeSchema.options`.\n */\nexport function getResourceTypeOptions(): ResourceTypeOption[] {\n return resourceTypeSchema.options.map((value) => ({\n value,\n label: humanize(value),\n }));\n}\n\n/**\n * Permissions per resource type, derived from each type's per-type permission\n * schema's `.options` array. Order is weakest-to-strongest (matches Zod enum\n * declaration order, which the original JSON Schema also preserved).\n */\nexport function getResourceTypePermissions(): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const [type, schema] of Object.entries(PERMISSION_SCHEMAS_BY_TYPE)) {\n out[type] = [...schema.options];\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;AAgCA,MAAM,kBAA0C;CAC9C,eAAe;CACf,aAAa;CACb,eAAe;CAChB;AAED,SAAS,SAAS,OAAuB;AACvC,KAAI,gBAAgB,OAAQ,QAAO,gBAAgB;AACnD,QAAO,MAAM,QAAQ,MAAM,IAAI,CAAC,QAAQ,UAAU,MAAM,EAAE,aAAa,CAAC;;;;;;;;AAS1E,MAAM,6BAA6B;CACjC,QAAQ;CACR,KAAK;CACL,eAAe;CACf,kBAAkB;CAClB,eAAe;CACf,QAAQ;CACR,qBAAqB;CACrB,aAAa;CACb,eAAe;CACf,UAAU;CACV,UAAU;CACV,aAAa;CACb,YAAY;CACZ,KAAK;CACN;;;;AAKD,SAAgB,yBAA+C;AAC7D,QAAO,mBAAmB,QAAQ,KAAK,WAAW;EAChD;EACA,OAAO,SAAS,MAAM;EACvB,EAAE;;;;;;;AAQL,SAAgB,6BAAuD;CACrE,MAAM,MAAgC,EAAE;AACxC,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,2BAA2B,CACrE,KAAI,QAAQ,CAAC,GAAG,OAAO,QAAQ;AAEjC,QAAO"}
@@ -1,5 +1,5 @@
1
1
  import { collectEnvNeeds, parseEnv, reconcileEnv, serializeEnvAppend } from "./env-reconcile.js";
2
- import { composeResourceId, isFlatListable, isParentContext, listParentContextStep, listWorkspaceResources, parentContextDepth } from "./workspace-picker.js";
2
+ import { DEFAULT_PARENTS, composeResourceId, isFlatListable, isParentContext, listParentContextStep, listWorkspaceResources, parentContextDepth } from "./workspace-picker.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import pc from "picocolors";
@@ -7,6 +7,7 @@ import pc from "picocolors";
7
7
  //#region src/cli/commands/registry/env-writer.ts
8
8
  /** Sentinel select value meaning "let me type the id myself". */
9
9
  const MANUAL = "__manual__";
10
+ const BROWSE = "__browse__";
10
11
  /**
11
12
  * Max resources shown in a picker select. Real workspaces can have thousands
12
13
  * (e.g. 5000+ SQL warehouses); an unbounded select is unusable. Beyond this we
@@ -90,6 +91,18 @@ async function autocompleteFrom(message, choices) {
90
91
  */
91
92
  async function pickParentContext(need, profile) {
92
93
  const depth = parentContextDepth(need.resourceType);
94
+ const defaults = DEFAULT_PARENTS[need.resourceType];
95
+ if (defaults) {
96
+ const step = listParentContextStep(need.resourceType, defaults.length, defaults, profile);
97
+ if (step && step.choices.length > 0) {
98
+ const picked = await selectFrom(`${need.env} — pick a ${step.key} in ${defaults.join(".")}`, [...capChoices(step.choices, step.key), {
99
+ value: BROWSE,
100
+ label: "Browse other catalogs..."
101
+ }]);
102
+ if (picked === null || picked === MANUAL) return void 0;
103
+ if (picked !== BROWSE) return composeResourceId(need.resourceType, [...defaults, picked]);
104
+ }
105
+ }
93
106
  const picks = [];
94
107
  for (let i = 0; i < depth; i++) {
95
108
  const step = listParentContextStep(need.resourceType, i, picks, profile);
@@ -1 +1 @@
1
- {"version":3,"file":"env-writer.js","names":[],"sources":["../../../../src/cli/commands/registry/env-writer.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport pc from \"picocolors\";\n\nimport type { BindingValueNeed } from \"./config-plan\";\nimport {\n collectEnvNeeds,\n type EnvNeed,\n type EnvResolution,\n parseEnv,\n reconcileEnv,\n serializeEnvAppend,\n type ValueProvider,\n} from \"./env-reconcile\";\nimport type { ResourceRequirementRow } from \"./requirements\";\nimport {\n composeResourceId,\n isFlatListable,\n isParentContext,\n listParentContextStep,\n listWorkspaceResources,\n parentContextDepth,\n} from \"./workspace-picker\";\n\nexport interface EnvSyncOptions {\n /** Directory holding `.env` / `.env.example` (the app root). */\n cwd: string;\n /** true = never prompt (agent/CI). Uses flag values or leaves unset. */\n nonInteractive: boolean;\n /** Pre-supplied env values from flags, e.g. { DATABRICKS_WAREHOUSE_ID: \"abc\" }. */\n values?: Record<string, string>;\n /** Databricks profile for the workspace picker (else the CLI default). */\n profile?: string;\n}\n\n/** Sentinel select value meaning \"let me type the id myself\". */\nconst MANUAL = \"__manual__\";\n\n/**\n * Max resources shown in a picker select. Real workspaces can have thousands\n * (e.g. 5000+ SQL warehouses); an unbounded select is unusable. Beyond this we\n * show the first N and log how many were hidden — never silently drop — and the\n * \"Enter manually\" option always lets the user type an id the list omits.\n */\nconst PICKER_LIMIT = 25;\n\n/** Reads a `.env`-style file into a map; empty when the file is absent. */\nfunction readEnvFile(file: string): Record<string, string> {\n if (!fs.existsSync(file)) return {};\n return parseEnv(fs.readFileSync(file, \"utf-8\"));\n}\n\n/** Appends text to a file, creating it (with a trailing newline) if needed. */\nfunction appendToFile(file: string, text: string): void {\n if (text === \"\") return;\n if (fs.existsSync(file)) {\n const existing = fs.readFileSync(file, \"utf-8\");\n const sep = existing.length > 0 && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n fs.writeFileSync(file, existing + sep + text);\n } else {\n fs.writeFileSync(file, text);\n }\n}\n\n/**\n * Caps a choice list to {@link PICKER_LIMIT} for display, logging how many were\n * hidden so the truncation is never silent. The caller always appends an\n * \"Enter manually\" option, so an omitted resource is still reachable.\n */\nexport function capChoices<T>(\n choices: T[],\n resourceType: string,\n limit = PICKER_LIMIT,\n): T[] {\n if (choices.length <= limit) return choices;\n console.log(\n pc.dim(\n ` ${choices.length} ${resourceType}s found; showing first ${limit}. ` +\n 'Use \"Enter manually\" if yours is not listed.',\n ),\n );\n return choices.slice(0, limit);\n}\n\n/** Free-text prompt for one env need; undefined to skip. */\nasync function promptText(need: EnvNeed): Promise<string | undefined> {\n const { isCancel, text } = await import(\"@clack/prompts\");\n const tag = need.required ? \"required\" : \"optional\";\n const answer = await text({\n message: `${need.env} (${need.resourceType}, ${tag})`,\n placeholder: need.description ?? \"leave blank to skip\",\n });\n if (isCancel(answer)) return undefined;\n const value = (answer ?? \"\").trim();\n return value === \"\" ? undefined : value;\n}\n\n/** Presents one workspace list as a select; MANUAL/cancel handled by caller. */\nasync function selectFrom(\n message: string,\n choices: { value: string; label: string }[],\n): Promise<string | typeof MANUAL | null> {\n const { isCancel, select } = await import(\"@clack/prompts\");\n const picked = await select({\n message,\n options: [...choices, { value: MANUAL, label: \"Enter manually / skip\" }],\n });\n if (isCancel(picked)) return null;\n return String(picked) as string | typeof MANUAL;\n}\n\n/**\n * Type-to-filter picker over the full choice list (no cap): the user searches\n * by name/id as they type. Appends \"Enter manually\" so an omitted value is\n * still reachable. Returns MANUAL to fall through to free-text, or null on\n * cancel.\n */\nasync function autocompleteFrom(\n message: string,\n choices: { value: string; label: string }[],\n): Promise<string | typeof MANUAL | null> {\n const { autocomplete, isCancel } = await import(\"@clack/prompts\");\n const picked = await autocomplete({\n message,\n options: [...choices, { value: MANUAL, label: \"Enter manually / skip\" }],\n placeholder: \"type to search…\",\n });\n if (isCancel(picked)) return null;\n return String(picked) as string | typeof MANUAL;\n}\n\n/**\n * Drill-down picker for parent-context types (volume→catalog/schema,\n * secret→scope, vector_search_index→endpoint). Walks each step, listing the\n * next level from the prior pick. Returns the final resource id, or undefined\n * to fall back to free-text (on cancel, empty level, or MANUAL at any step).\n */\nasync function pickParentContext(\n need: EnvNeed,\n profile: string | undefined,\n): Promise<string | undefined> {\n const depth = parentContextDepth(need.resourceType);\n const picks: string[] = [];\n for (let i = 0; i < depth; i++) {\n const step = listParentContextStep(need.resourceType, i, picks, profile);\n if (!step || step.choices.length === 0) {\n console.log(\n pc.dim(\n ` No ${step?.key ?? need.resourceType} found — enter the id manually.`,\n ),\n );\n return undefined;\n }\n const picked = await selectFrom(\n `${need.env} — pick a ${step.key}`,\n capChoices(step.choices, step.key),\n );\n if (picked === null || picked === MANUAL) return undefined;\n picks.push(picked);\n }\n // Compose the id from the picks: most types end on a self-qualified id, but a\n // secret needs both scope and key (scope/key).\n return composeResourceId(need.resourceType, picks);\n}\n\n/**\n * Builds the value provider. Precedence: --env flag, then (interactive only) a\n * workspace picker — flat select for flat-listable types, drill-down for\n * parent-context types — else a free-text prompt. The picker degrades to\n * free-text whenever the workspace can't be listed (no profile, offline, auth\n * error, empty) so it never hard-fails.\n */\nfunction makeProvider(opts: EnvSyncOptions): ValueProvider {\n return async (need: EnvNeed) => {\n const fromFlag = opts.values?.[need.env];\n if (fromFlag !== undefined) return fromFlag;\n if (opts.nonInteractive) return undefined;\n\n if (isFlatListable(need.resourceType)) {\n const { choices, truncated, error } = await listWorkspaceResources(\n need.resourceType,\n opts.profile,\n );\n if (choices.length > 0) {\n if (truncated) {\n console.log(\n pc.dim(\n ` Showing the first ${choices.length} ${need.resourceType}s; use \"Enter manually\" if yours isn't listed.`,\n ),\n );\n }\n const picked = await autocompleteFrom(\n `${need.env} — search ${need.resourceType}s`,\n choices,\n );\n if (picked === null) return undefined;\n if (picked !== MANUAL) return picked;\n // fall through to free-text\n } else if (error) {\n // Listing failed (usually auth/profile) — say so, don't pretend the\n // workspace is empty, and point at the fix.\n console.log(\n pc.yellow(\n ` Couldn't list ${need.resourceType}s from the workspace (${error}).`,\n ),\n );\n console.log(\n pc.dim(\n \" Enter an id manually, or re-run with --profile <name> (or set DATABRICKS_CONFIG_PROFILE) so the picker can reach the workspace.\",\n ),\n );\n } else {\n console.log(\n pc.dim(\n ` No ${need.resourceType} found in the workspace — enter an id manually.`,\n ),\n );\n }\n } else if (isParentContext(need.resourceType)) {\n const picked = await pickParentContext(need, opts.profile);\n if (picked !== undefined) return picked;\n // fall through to free-text\n }\n\n return promptText(need);\n };\n}\n\n/**\n * Reconciles a plugin's declared resource env vars into the app's local `.env`\n * (and mirrors variable names into `.env.example`). Never overwrites keys the\n * user already set; skips platform-injected fields. Returns the per-var\n * resolutions so callers can report what happened.\n */\nexport async function syncEnv(\n rows: ResourceRequirementRow[],\n opts: EnvSyncOptions,\n): Promise<EnvResolution[]> {\n const needs = collectEnvNeeds(rows);\n if (needs.length === 0) return [];\n\n const envPath = path.join(opts.cwd, \".env\");\n const examplePath = path.join(opts.cwd, \".env.example\");\n const existing = readEnvFile(envPath);\n\n const resolutions = await reconcileEnv(needs, {\n existing,\n provide: makeProvider(opts),\n });\n\n const written = resolutions.filter(\n (r): r is EnvResolution & { value: string } =>\n r.status === \"written\" && r.value !== undefined,\n );\n appendToFile(\n envPath,\n serializeEnvAppend(written.map((r) => ({ env: r.env, value: r.value }))),\n );\n\n // .env.example carries the variable names (no secret values), and only for\n // vars not already documented there.\n const exampleExisting = readEnvFile(examplePath);\n const newExampleKeys = needs.filter((n) => !(n.env in exampleExisting));\n appendToFile(\n examplePath,\n serializeEnvAppend(newExampleKeys.map((n) => ({ env: n.env, value: \"\" }))),\n );\n\n return resolutions;\n}\n\n/**\n * Prompts for the {@link BindingValueNeed}s that `.env` reconciliation can't\n * collect, returning a `fieldKey -> value` map for buildConfigPlan. Values are\n * not written to `.env` (these fields have no env var). Non-interactive mode\n * uses `values[fieldKey]` if provided, else leaves the field unset.\n */\nexport async function collectBindingValues(\n needs: BindingValueNeed[],\n opts: EnvSyncOptions,\n): Promise<Record<string, string>> {\n const { isCancel, text } = await import(\"@clack/prompts\");\n const out: Record<string, string> = {};\n for (const need of needs) {\n const fromFlag = opts.values?.[need.fieldKey];\n if (fromFlag !== undefined) {\n out[need.fieldKey] = fromFlag;\n continue;\n }\n if (opts.nonInteractive) continue;\n const answer = await text({\n message: `${need.fieldKey} (${need.resourceType}) — required for databricks.yml`,\n placeholder: need.description ?? \"leave blank to set before deploy\",\n });\n if (isCancel(answer)) continue;\n const value = (answer ?? \"\").trim();\n if (value !== \"\") out[need.fieldKey] = value;\n }\n return out;\n}\n\n/** Prints a concise summary of what env reconciliation did. */\nexport function reportEnvResolutions(resolutions: EnvResolution[]): void {\n if (resolutions.length === 0) return;\n const written = resolutions.filter((r) => r.status === \"written\");\n const already = resolutions.filter((r) => r.status === \"already-set\");\n const skipped = resolutions.filter((r) => r.status === \"skipped\");\n\n if (written.length > 0) {\n console.log(\n `${pc.green(\"Wrote to .env:\")} ${written.map((r) => r.env).join(\", \")}`,\n );\n }\n if (already.length > 0) {\n console.log(pc.dim(`Already set: ${already.map((r) => r.env).join(\", \")}`));\n }\n if (skipped.length > 0) {\n console.log(\n `${pc.yellow(\"Left unset (set before deploy):\")} ${skipped\n .map((r) => r.env)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":";;;;;;;;AAqCA,MAAM,SAAS;;;;;;;AAQf,MAAM,eAAe;;AAGrB,SAAS,YAAY,MAAsC;AACzD,KAAI,CAAC,GAAG,WAAW,KAAK,CAAE,QAAO,EAAE;AACnC,QAAO,SAAS,GAAG,aAAa,MAAM,QAAQ,CAAC;;;AAIjD,SAAS,aAAa,MAAc,MAAoB;AACtD,KAAI,SAAS,GAAI;AACjB,KAAI,GAAG,WAAW,KAAK,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AAC;AACF,MAAI,SAAS,OAAO,CAAE;EACtB,MAAM,SAAS,UAAU,IAAI,MAAM;AACnC,MAAI,UAAU,GAAI,KAAI,KAAK,YAAY;;AAEzC,QAAO;;;AAIT,SAAgB,qBAAqB,aAAoC;AACvE,KAAI,YAAY,WAAW,EAAG;CAC9B,MAAM,UAAU,YAAY,QAAQ,MAAM,EAAE,WAAW,UAAU;CACjE,MAAM,UAAU,YAAY,QAAQ,MAAM,EAAE,WAAW,cAAc;CACrE,MAAM,UAAU,YAAY,QAAQ,MAAM,EAAE,WAAW,UAAU;AAEjE,KAAI,QAAQ,SAAS,EACnB,SAAQ,IACN,GAAG,GAAG,MAAM,iBAAiB,CAAC,GAAG,QAAQ,KAAK,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,GACtE;AAEH,KAAI,QAAQ,SAAS,EACnB,SAAQ,IAAI,GAAG,IAAI,gBAAgB,QAAQ,KAAK,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAE7E,KAAI,QAAQ,SAAS,EACnB,SAAQ,IACN,GAAG,GAAG,OAAO,kCAAkC,CAAC,GAAG,QAChD,KAAK,MAAM,EAAE,IAAI,CACjB,KAAK,KAAK,GACd"}
1
+ {"version":3,"file":"env-writer.js","names":[],"sources":["../../../../src/cli/commands/registry/env-writer.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport pc from \"picocolors\";\n\nimport type { BindingValueNeed } from \"./config-plan\";\nimport {\n collectEnvNeeds,\n type EnvNeed,\n type EnvResolution,\n parseEnv,\n reconcileEnv,\n serializeEnvAppend,\n type ValueProvider,\n} from \"./env-reconcile\";\nimport type { ResourceRequirementRow } from \"./requirements\";\nimport {\n composeResourceId,\n DEFAULT_PARENTS,\n isFlatListable,\n isParentContext,\n listParentContextStep,\n listWorkspaceResources,\n parentContextDepth,\n} from \"./workspace-picker\";\n\nexport interface EnvSyncOptions {\n /** Directory holding `.env` / `.env.example` (the app root). */\n cwd: string;\n /** true = never prompt (agent/CI). Uses flag values or leaves unset. */\n nonInteractive: boolean;\n /** Pre-supplied env values from flags, e.g. { DATABRICKS_WAREHOUSE_ID: \"abc\" }. */\n values?: Record<string, string>;\n /** Databricks profile for the workspace picker (else the CLI default). */\n profile?: string;\n}\n\n/** Sentinel select value meaning \"let me type the id myself\". */\nconst MANUAL = \"__manual__\";\nconst BROWSE = \"__browse__\";\n\n/**\n * Max resources shown in a picker select. Real workspaces can have thousands\n * (e.g. 5000+ SQL warehouses); an unbounded select is unusable. Beyond this we\n * show the first N and log how many were hidden — never silently drop — and the\n * \"Enter manually\" option always lets the user type an id the list omits.\n */\nconst PICKER_LIMIT = 25;\n\n/** Reads a `.env`-style file into a map; empty when the file is absent. */\nfunction readEnvFile(file: string): Record<string, string> {\n if (!fs.existsSync(file)) return {};\n return parseEnv(fs.readFileSync(file, \"utf-8\"));\n}\n\n/** Appends text to a file, creating it (with a trailing newline) if needed. */\nfunction appendToFile(file: string, text: string): void {\n if (text === \"\") return;\n if (fs.existsSync(file)) {\n const existing = fs.readFileSync(file, \"utf-8\");\n const sep = existing.length > 0 && !existing.endsWith(\"\\n\") ? \"\\n\" : \"\";\n fs.writeFileSync(file, existing + sep + text);\n } else {\n fs.writeFileSync(file, text);\n }\n}\n\n/**\n * Caps a choice list to {@link PICKER_LIMIT} for display, logging how many were\n * hidden so the truncation is never silent. The caller always appends an\n * \"Enter manually\" option, so an omitted resource is still reachable.\n */\nexport function capChoices<T>(\n choices: T[],\n resourceType: string,\n limit = PICKER_LIMIT,\n): T[] {\n if (choices.length <= limit) return choices;\n console.log(\n pc.dim(\n ` ${choices.length} ${resourceType}s found; showing first ${limit}. ` +\n 'Use \"Enter manually\" if yours is not listed.',\n ),\n );\n return choices.slice(0, limit);\n}\n\n/** Free-text prompt for one env need; undefined to skip. */\nasync function promptText(need: EnvNeed): Promise<string | undefined> {\n const { isCancel, text } = await import(\"@clack/prompts\");\n const tag = need.required ? \"required\" : \"optional\";\n const answer = await text({\n message: `${need.env} (${need.resourceType}, ${tag})`,\n placeholder: need.description ?? \"leave blank to skip\",\n });\n if (isCancel(answer)) return undefined;\n const value = (answer ?? \"\").trim();\n return value === \"\" ? undefined : value;\n}\n\n/** Presents one workspace list as a select; MANUAL/cancel handled by caller. */\nasync function selectFrom(\n message: string,\n choices: { value: string; label: string }[],\n): Promise<string | typeof MANUAL | null> {\n const { isCancel, select } = await import(\"@clack/prompts\");\n const picked = await select({\n message,\n options: [...choices, { value: MANUAL, label: \"Enter manually / skip\" }],\n });\n if (isCancel(picked)) return null;\n return String(picked) as string | typeof MANUAL;\n}\n\n/**\n * Type-to-filter picker over the full choice list (no cap): the user searches\n * by name/id as they type. Appends \"Enter manually\" so an omitted value is\n * still reachable. Returns MANUAL to fall through to free-text, or null on\n * cancel.\n */\nasync function autocompleteFrom(\n message: string,\n choices: { value: string; label: string }[],\n): Promise<string | typeof MANUAL | null> {\n const { autocomplete, isCancel } = await import(\"@clack/prompts\");\n const picked = await autocomplete({\n message,\n options: [...choices, { value: MANUAL, label: \"Enter manually / skip\" }],\n placeholder: \"type to search…\",\n });\n if (isCancel(picked)) return null;\n return String(picked) as string | typeof MANUAL;\n}\n\n/**\n * Drill-down picker for parent-context types (volume→catalog/schema,\n * secret→scope, vector_search_index→endpoint). Walks each step, listing the\n * next level from the prior pick. Returns the final resource id, or undefined\n * to fall back to free-text (on cancel, empty level, or MANUAL at any step).\n */\nasync function pickParentContext(\n need: EnvNeed,\n profile: string | undefined,\n): Promise<string | undefined> {\n const depth = parentContextDepth(need.resourceType);\n const defaults = DEFAULT_PARENTS[need.resourceType];\n if (defaults) {\n // Open on the default parents; an empty listing falls through to the walk.\n const step = listParentContextStep(\n need.resourceType,\n defaults.length,\n defaults,\n profile,\n );\n if (step && step.choices.length > 0) {\n const picked = await selectFrom(\n `${need.env} — pick a ${step.key} in ${defaults.join(\".\")}`,\n [\n ...capChoices(step.choices, step.key),\n { value: BROWSE, label: \"Browse other catalogs...\" },\n ],\n );\n if (picked === null || picked === MANUAL) return undefined;\n if (picked !== BROWSE) {\n return composeResourceId(need.resourceType, [...defaults, picked]);\n }\n }\n }\n const picks: string[] = [];\n for (let i = 0; i < depth; i++) {\n const step = listParentContextStep(need.resourceType, i, picks, profile);\n if (!step || step.choices.length === 0) {\n console.log(\n pc.dim(\n ` No ${step?.key ?? need.resourceType} found — enter the id manually.`,\n ),\n );\n return undefined;\n }\n const picked = await selectFrom(\n `${need.env} — pick a ${step.key}`,\n capChoices(step.choices, step.key),\n );\n if (picked === null || picked === MANUAL) return undefined;\n picks.push(picked);\n }\n // Compose the id from the picks: most types end on a self-qualified id, but a\n // secret needs both scope and key (scope/key).\n return composeResourceId(need.resourceType, picks);\n}\n\n/**\n * Builds the value provider. Precedence: --env flag, then (interactive only) a\n * workspace picker — flat select for flat-listable types, drill-down for\n * parent-context types — else a free-text prompt. The picker degrades to\n * free-text whenever the workspace can't be listed (no profile, offline, auth\n * error, empty) so it never hard-fails.\n */\nfunction makeProvider(opts: EnvSyncOptions): ValueProvider {\n return async (need: EnvNeed) => {\n const fromFlag = opts.values?.[need.env];\n if (fromFlag !== undefined) return fromFlag;\n if (opts.nonInteractive) return undefined;\n\n if (isFlatListable(need.resourceType)) {\n const { choices, truncated, error } = await listWorkspaceResources(\n need.resourceType,\n opts.profile,\n );\n if (choices.length > 0) {\n if (truncated) {\n console.log(\n pc.dim(\n ` Showing the first ${choices.length} ${need.resourceType}s; use \"Enter manually\" if yours isn't listed.`,\n ),\n );\n }\n const picked = await autocompleteFrom(\n `${need.env} — search ${need.resourceType}s`,\n choices,\n );\n if (picked === null) return undefined;\n if (picked !== MANUAL) return picked;\n // fall through to free-text\n } else if (error) {\n // Listing failed (usually auth/profile) — say so, don't pretend the\n // workspace is empty, and point at the fix.\n console.log(\n pc.yellow(\n ` Couldn't list ${need.resourceType}s from the workspace (${error}).`,\n ),\n );\n console.log(\n pc.dim(\n \" Enter an id manually, or re-run with --profile <name> (or set DATABRICKS_CONFIG_PROFILE) so the picker can reach the workspace.\",\n ),\n );\n } else {\n console.log(\n pc.dim(\n ` No ${need.resourceType} found in the workspace — enter an id manually.`,\n ),\n );\n }\n } else if (isParentContext(need.resourceType)) {\n const picked = await pickParentContext(need, opts.profile);\n if (picked !== undefined) return picked;\n // fall through to free-text\n }\n\n return promptText(need);\n };\n}\n\n/**\n * Reconciles a plugin's declared resource env vars into the app's local `.env`\n * (and mirrors variable names into `.env.example`). Never overwrites keys the\n * user already set; skips platform-injected fields. Returns the per-var\n * resolutions so callers can report what happened.\n */\nexport async function syncEnv(\n rows: ResourceRequirementRow[],\n opts: EnvSyncOptions,\n): Promise<EnvResolution[]> {\n const needs = collectEnvNeeds(rows);\n if (needs.length === 0) return [];\n\n const envPath = path.join(opts.cwd, \".env\");\n const examplePath = path.join(opts.cwd, \".env.example\");\n const existing = readEnvFile(envPath);\n\n const resolutions = await reconcileEnv(needs, {\n existing,\n provide: makeProvider(opts),\n });\n\n const written = resolutions.filter(\n (r): r is EnvResolution & { value: string } =>\n r.status === \"written\" && r.value !== undefined,\n );\n appendToFile(\n envPath,\n serializeEnvAppend(written.map((r) => ({ env: r.env, value: r.value }))),\n );\n\n // .env.example carries the variable names (no secret values), and only for\n // vars not already documented there.\n const exampleExisting = readEnvFile(examplePath);\n const newExampleKeys = needs.filter((n) => !(n.env in exampleExisting));\n appendToFile(\n examplePath,\n serializeEnvAppend(newExampleKeys.map((n) => ({ env: n.env, value: \"\" }))),\n );\n\n return resolutions;\n}\n\n/**\n * Prompts for the {@link BindingValueNeed}s that `.env` reconciliation can't\n * collect, returning a `fieldKey -> value` map for buildConfigPlan. Values are\n * not written to `.env` (these fields have no env var). Non-interactive mode\n * uses `values[fieldKey]` if provided, else leaves the field unset.\n */\nexport async function collectBindingValues(\n needs: BindingValueNeed[],\n opts: EnvSyncOptions,\n): Promise<Record<string, string>> {\n const { isCancel, text } = await import(\"@clack/prompts\");\n const out: Record<string, string> = {};\n for (const need of needs) {\n const fromFlag = opts.values?.[need.fieldKey];\n if (fromFlag !== undefined) {\n out[need.fieldKey] = fromFlag;\n continue;\n }\n if (opts.nonInteractive) continue;\n const answer = await text({\n message: `${need.fieldKey} (${need.resourceType}) — required for databricks.yml`,\n placeholder: need.description ?? \"leave blank to set before deploy\",\n });\n if (isCancel(answer)) continue;\n const value = (answer ?? \"\").trim();\n if (value !== \"\") out[need.fieldKey] = value;\n }\n return out;\n}\n\n/** Prints a concise summary of what env reconciliation did. */\nexport function reportEnvResolutions(resolutions: EnvResolution[]): void {\n if (resolutions.length === 0) return;\n const written = resolutions.filter((r) => r.status === \"written\");\n const already = resolutions.filter((r) => r.status === \"already-set\");\n const skipped = resolutions.filter((r) => r.status === \"skipped\");\n\n if (written.length > 0) {\n console.log(\n `${pc.green(\"Wrote to .env:\")} ${written.map((r) => r.env).join(\", \")}`,\n );\n }\n if (already.length > 0) {\n console.log(pc.dim(`Already set: ${already.map((r) => r.env).join(\", \")}`));\n }\n if (skipped.length > 0) {\n console.log(\n `${pc.yellow(\"Left unset (set before deploy):\")} ${skipped\n .map((r) => r.env)\n .join(\", \")}`,\n );\n }\n}\n"],"mappings":";;;;;;;;AAsCA,MAAM,SAAS;AACf,MAAM,SAAS;;;;;;;AAQf,MAAM,eAAe;;AAGrB,SAAS,YAAY,MAAsC;AACzD,KAAI,CAAC,GAAG,WAAW,KAAK,CAAE,QAAO,EAAE;AACnC,QAAO,SAAS,GAAG,aAAa,MAAM,QAAQ,CAAC;;;AAIjD,SAAS,aAAa,MAAc,MAAoB;AACtD,KAAI,SAAS,GAAI;AACjB,KAAI,GAAG,WAAW,KAAK,EAAE;EACvB,MAAM,WAAW,GAAG,aAAa,MAAM,QAAQ;EAC/C,MAAM,MAAM,SAAS,SAAS,KAAK,CAAC,SAAS,SAAS,KAAK,GAAG,OAAO;AACrE,KAAG,cAAc,MAAM,WAAW,MAAM,KAAK;OAE7C,IAAG,cAAc,MAAM,KAAK;;;;;;;AAShC,SAAgB,WACd,SACA,cACA,QAAQ,cAC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,MAAM,WAAW,KAAK,SAAS,KAAK;AACpC,MAAI,aAAa,QAAW;AAC1B,OAAI,KAAK,YAAY;AACrB;;AAEF,MAAI,KAAK,eAAgB;EACzB,MAAM,SAAS,MAAM,KAAK;GACxB,SAAS,GAAG,KAAK,SAAS,IAAI,KAAK,aAAa;GAChD,aAAa,KAAK,eAAe;GAClC,CAAC;AACF,MAAI,SAAS,OAAO,CAAE;EACtB,MAAM,SAAS,UAAU,IAAI,MAAM;AACnC,MAAI,UAAU,GAAI,KAAI,KAAK,YAAY;;AAEzC,QAAO;;;AAIT,SAAgB,qBAAqB,aAAoC;AACvE,KAAI,YAAY,WAAW,EAAG;CAC9B,MAAM,UAAU,YAAY,QAAQ,MAAM,EAAE,WAAW,UAAU;CACjE,MAAM,UAAU,YAAY,QAAQ,MAAM,EAAE,WAAW,cAAc;CACrE,MAAM,UAAU,YAAY,QAAQ,MAAM,EAAE,WAAW,UAAU;AAEjE,KAAI,QAAQ,SAAS,EACnB,SAAQ,IACN,GAAG,GAAG,MAAM,iBAAiB,CAAC,GAAG,QAAQ,KAAK,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,GACtE;AAEH,KAAI,QAAQ,SAAS,EACnB,SAAQ,IAAI,GAAG,IAAI,gBAAgB,QAAQ,KAAK,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,GAAG,CAAC;AAE7E,KAAI,QAAQ,SAAS,EACnB,SAAQ,IACN,GAAG,GAAG,OAAO,kCAAkC,CAAC,GAAG,QAChD,KAAK,MAAM,EAAE,IAAI,CACjB,KAAK,KAAK,GACd"}
@@ -279,6 +279,41 @@ const PARENT_CONTEXT_CHAINS = {
279
279
  })
280
280
  }
281
281
  ],
282
+ model_service: [
283
+ {
284
+ key: "catalog",
285
+ list: () => ({
286
+ command: ["catalogs", "list"],
287
+ idField: "name",
288
+ labelField: "name"
289
+ })
290
+ },
291
+ {
292
+ key: "schema",
293
+ list: ([catalog]) => ({
294
+ command: [
295
+ "schemas",
296
+ "list",
297
+ catalog
298
+ ],
299
+ idField: "name",
300
+ labelField: "name"
301
+ })
302
+ },
303
+ {
304
+ key: "model service",
305
+ list: ([catalog, schema]) => ({
306
+ command: [
307
+ "ai-gateway",
308
+ "list-model-services",
309
+ "--parent",
310
+ `schemas/${catalog}.${schema}`
311
+ ],
312
+ idField: "name",
313
+ stripPrefix: "model-services/"
314
+ })
315
+ }
316
+ ],
282
317
  secret: [{
283
318
  key: "scope",
284
319
  list: () => ({
@@ -318,6 +353,8 @@ const PARENT_CONTEXT_CHAINS = {
318
353
  })
319
354
  }]
320
355
  };
356
+ /** Parents a drill-down opens on first; the full walk stays one pick away. */
357
+ const DEFAULT_PARENTS = { model_service: ["system", "ai"] };
321
358
  /** True when a resource type needs a parent-context drill-down to list. */
322
359
  function isParentContext(resourceType) {
323
360
  return resourceType in PARENT_CONTEXT_CHAINS;
@@ -336,9 +373,17 @@ function listParentContextStep(resourceType, stepIndex, parents, profile, runner
336
373
  choices: []
337
374
  };
338
375
  const spec = step.list(parents);
376
+ const choices = runList(spec.command, spec.idField, spec.labelField, profile, runner);
377
+ const prefix = spec.stripPrefix;
339
378
  return {
340
379
  key: step.key,
341
- choices: runList(spec.command, spec.idField, spec.labelField, profile, runner)
380
+ choices: prefix ? choices.map(({ value }) => {
381
+ const bare = value.startsWith(prefix) ? value.slice(prefix.length) : value;
382
+ return {
383
+ value: bare,
384
+ label: bare
385
+ };
386
+ }) : choices
342
387
  };
343
388
  }
344
389
  /** Number of drill-down steps for a parent-context type (0 if not one). */
@@ -359,5 +404,5 @@ function composeResourceId(resourceType, picks) {
359
404
  }
360
405
 
361
406
  //#endregion
362
- export { composeResourceId, isFlatListable, isParentContext, listParentContextStep, listWorkspaceResources, parentContextDepth };
407
+ export { DEFAULT_PARENTS, composeResourceId, isFlatListable, isParentContext, listParentContextStep, listWorkspaceResources, parentContextDepth };
363
408
  //# sourceMappingURL=workspace-picker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-picker.js","names":[],"sources":["../../../../src/cli/commands/registry/workspace-picker.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\n\nimport {\n createWorkspaceClient,\n type WorkspaceClient,\n} from \"../../../workspace-client\";\n\n/**\n * Lists a user's real Databricks workspace resources so `appkit add` can offer\n * a picker instead of blind free-text entry.\n *\n * Flat resource types are listed through the sanctioned `workspace-client`\n * facade's modular SDK clients.\n * Parent-context types (volume, uc_function, secret, vector_search_index) still\n * shell out to the `databricks` CLI for their drill-down. Every path fails\n * soft: any error returns an empty list and the caller drops to free-text entry.\n */\n\n/** A workspace resource choice surfaced in the picker. */\nexport interface WorkspaceChoice {\n /** Value written to the env var (the resource id/name). */\n value: string;\n /** Human label shown in the picker (name, falling back to value). */\n label: string;\n}\n\n/**\n * Per-type SDK lister: streams a resource type off the WorkspaceClient into\n * `{value,label}` choices. `list()` returns an async iterable of raw SDK\n * objects; `toChoice` maps each to a picker choice. The SDK auto-paginates, so\n * we simply iterate to completion.\n */\ninterface SdkLister {\n list: (client: WorkspaceClient) => AsyncIterable<unknown>;\n toChoice: (item: Record<string, unknown>) => WorkspaceChoice | null;\n}\n\n/** Builds a `{value,label}` from an id field and optional label field. */\nfunction choiceFrom(\n item: Record<string, unknown>,\n idField: string,\n labelField?: string,\n): WorkspaceChoice | null {\n const id = item[idField];\n if (id === undefined || id === null) return null;\n const value = String(id);\n const rawLabel = labelField ? item[labelField] : undefined;\n const label =\n typeof rawLabel === \"string\" && rawLabel.length > 0\n ? `${rawLabel} (${value})`\n : value;\n return { value, label };\n}\n\n/**\n * Follows page tokens until exhausted. The repeated-token guard avoids an\n * infinite loop if the API echoes a token back.\n */\nasync function* paginate(\n fetchPage: (\n pageToken?: string,\n ) => Promise<{ items?: unknown[]; next?: string }>,\n): AsyncIterable<unknown> {\n let pageToken: string | undefined;\n do {\n const { items, next } = await fetchPage(pageToken);\n for (const item of items ?? []) yield item;\n if (next && next === pageToken) break;\n pageToken = next;\n } while (pageToken);\n}\n\n/** listInferenceEndpoints is unpaginated; adapt its single page. */\nasync function* iterateServingEndpoints(\n client: WorkspaceClient,\n): AsyncIterable<unknown> {\n const res = await client.modelServing.listInferenceEndpoints({});\n yield* res.endpoints ?? [];\n}\n\n/** Genie listSpaces returns a single page; follow `nextPageToken`. */\nfunction iterateGenieSpaces(client: WorkspaceClient): AsyncIterable<unknown> {\n return paginate(async (pageToken) => {\n const res = await client.genie.genieListSpaces(\n pageToken ? { pageToken } : {},\n );\n return { items: res.spaces, next: res.nextPageToken };\n });\n}\n\n/** Flat, top-level listable resource types, backed by SDK services. */\nexport const SDK_LISTERS: Record<string, SdkLister> = {\n sql_warehouse: {\n list: (c) => c.warehouses.listWarehousesIter({}),\n toChoice: (i) => choiceFrom(i, \"id\", \"name\"),\n },\n job: {\n list: (c) => c.jobs.listJobsIter({}),\n // job name lives under settings.name; id is top-level jobId (a bigint)\n toChoice: (i) => {\n const settings = i.settings as { name?: string } | undefined;\n return choiceFrom({ ...i, name: settings?.name }, \"jobId\", \"name\");\n },\n },\n serving_endpoint: {\n list: iterateServingEndpoints,\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n uc_connection: {\n list: (c) => c.connections.listConnectionsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"fullName\"),\n },\n database: {\n list: (c) => c.database.listDatabaseInstancesIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n genie_space: {\n list: iterateGenieSpaces,\n toChoice: (i) => choiceFrom(i, \"spaceId\", \"title\"),\n },\n experiment: {\n list: (c) => c.experiments.listExperimentsIter({}),\n toChoice: (i) => choiceFrom(i, \"experimentId\", \"name\"),\n },\n app: {\n list: (c) => c.apps.listAppsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n};\n\n/** True when a resource type can be listed flat (no parent context). */\nexport function isFlatListable(resourceType: string): boolean {\n return resourceType in SDK_LISTERS;\n}\n\n/**\n * Constructs a workspace client for the given profile (or default resolution),\n * via the sanctioned `workspace-client` facade.\n */\nexport function makeWorkspaceClient(profile?: string): WorkspaceClient {\n return createWorkspaceClient(profile ? { profile } : {});\n}\n\n/**\n * Max resources fetched for the picker. `list()` paginates lazily, so on a large\n * workspace (5000+ warehouses) breaking out at the cap stops pagination early;\n * the picker's \"Enter manually\" option covers anything beyond it.\n */\nexport const MAX_PICKER_RESULTS = 200;\n\n/** A listing result plus whether it was truncated at the fetch cap. */\nexport interface WorkspaceListing {\n choices: WorkspaceChoice[];\n truncated: boolean;\n /** Short reason the listing failed (auth/config/network), if it did — lets\n * the caller distinguish a real error from a genuinely empty workspace. */\n error?: string;\n}\n\n/** First line of an error, capped, for a user-facing one-liner. */\nfunction shortErrorMessage(err: unknown): string {\n const msg = err instanceof Error ? err.message : String(err);\n return msg.split(\"\\n\")[0].trim().slice(0, 200);\n}\n\n/**\n * Lists workspace resources of a flat-listable type via the SDK, stopping at\n * MAX_PICKER_RESULTS so pagination doesn't drain a huge workspace. Returns an\n * empty listing on any failure (unknown type, auth/config error, network) so\n * the caller can fall back to free-text entry. `clientFactory` is injectable\n * for tests.\n */\nexport async function listWorkspaceResources(\n resourceType: string,\n profile?: string,\n clientFactory: (profile?: string) => WorkspaceClient = makeWorkspaceClient,\n): Promise<WorkspaceListing> {\n const lister = SDK_LISTERS[resourceType];\n if (!lister) return { choices: [], truncated: false };\n try {\n const client = clientFactory(profile);\n const choices: WorkspaceChoice[] = [];\n let truncated = false;\n for await (const item of lister.list(client)) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = lister.toChoice(item as Record<string, unknown>);\n if (!choice) continue;\n choices.push(choice);\n if (choices.length >= MAX_PICKER_RESULTS) {\n // Stop iterating — halts the async iterator, so no further pages fetch.\n truncated = true;\n break;\n }\n }\n return { choices, truncated };\n } catch (err) {\n // Don't swallow silently: return the reason so the caller can tell the user\n // the picker fell back because listing failed (typically auth/profile), not\n // because the workspace has none of this resource.\n return { choices: [], truncated: false, error: shortErrorMessage(err) };\n }\n}\n\n/** Runs a databricks CLI subcommand returning JSON; injectable for tests. */\nexport type CliRunner = (args: string[]) => {\n status: number | null;\n stdout: string;\n};\n\nconst defaultRunner: CliRunner = (args) => {\n // Parent-context lists can be large; raise maxBuffer well above the 1MB\n // default so a big JSON response isn't truncated into \"no resources found\".\n const res = spawnSync(\"databricks\", args, {\n encoding: \"utf-8\",\n maxBuffer: 64 * 1024 * 1024,\n });\n return { status: res.status, stdout: res.stdout ?? \"\" };\n};\n\n/**\n * Extracts `{value,label}` choices from a parsed CLI list response. The CLI\n * returns either a bare array or an object wrapping one; we scan for the first\n * array of objects. Items missing the id field are skipped.\n */\nexport function toChoices(\n parsed: unknown,\n idField: string,\n labelField?: string,\n): WorkspaceChoice[] {\n const arr = firstArray(parsed);\n const choices: WorkspaceChoice[] = [];\n for (const item of arr) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = choiceFrom(\n item as Record<string, unknown>,\n idField,\n labelField,\n );\n if (choice) choices.push(choice);\n }\n return choices;\n}\n\n/** Finds the first array in a CLI response (bare array or single wrapper key). */\nfunction firstArray(parsed: unknown): unknown[] {\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === \"object\") {\n for (const v of Object.values(parsed)) {\n if (Array.isArray(v)) return v;\n }\n }\n return [];\n}\n\n/**\n * Runs a `databricks … list -o json` command and returns parsed choices, or\n * [] on any failure (CLI missing/errored, empty, non-JSON). `command` is the\n * argv after `databricks`; `-o json` and `-p <profile>` are appended.\n * Used for the parent-context drill-down (catalogs/schemas/scopes/endpoints).\n */\nexport function runList(\n command: string[],\n idField: string,\n labelField: string | undefined,\n profile: string | undefined,\n runner: CliRunner = defaultRunner,\n): WorkspaceChoice[] {\n const args = [...command, \"-o\", \"json\"];\n if (profile) args.push(\"-p\", profile);\n\n let result: { status: number | null; stdout: string };\n try {\n result = runner(args);\n } catch {\n return [];\n }\n if (result.status !== 0 || !result.stdout.trim()) return [];\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(result.stdout);\n } catch {\n return [];\n }\n return toChoices(parsed, idField, labelField);\n}\n\n/**\n * A drill-down step for a parent-context resource type. `list(parents)` builds\n * the CLI argv given the values picked in prior steps (e.g. [catalog] → schema\n * list command). `key` labels the step for prompts.\n */\nexport interface ParentContextStep {\n key: string;\n list: (parents: string[]) => {\n command: string[];\n idField: string;\n labelField?: string;\n };\n}\n\n/**\n * Drill-down chains for parent-context resource types. Each ends by listing\n * the resource itself; earlier steps list the parents to pick first.\n * Positional-arg CLI gotcha: `databricks schemas list <CATALOG>` etc. take the\n * parent as a positional, not a flag.\n */\nexport const PARENT_CONTEXT_CHAINS: Record<string, ParentContextStep[]> = {\n volume: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"volume\",\n list: ([catalog, schema]) => ({\n command: [\"volumes\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n uc_function: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"function\",\n list: ([catalog, schema]) => ({\n command: [\"functions\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n secret: [\n {\n key: \"scope\",\n list: () => ({\n command: [\"secrets\", \"list-scopes\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"key\",\n list: ([scope]) => ({\n command: [\"secrets\", \"list-secrets\", scope],\n idField: \"key\",\n labelField: \"key\",\n }),\n },\n ],\n vector_search_index: [\n {\n key: \"endpoint\",\n list: () => ({\n command: [\"vector-search-endpoints\", \"list-endpoints\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"index\",\n list: ([endpoint]) => ({\n command: [\"vector-search-indexes\", \"list-indexes\", endpoint],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n ],\n};\n\n/** True when a resource type needs a parent-context drill-down to list. */\nexport function isParentContext(resourceType: string): boolean {\n return resourceType in PARENT_CONTEXT_CHAINS;\n}\n\n/** One resolved step of a drill-down: the choices to present at this level. */\nexport interface DrillStep {\n key: string;\n choices: WorkspaceChoice[];\n}\n\n/**\n * Lists the choices for a single drill-down step given the values picked so\n * far. Returns [] on failure. The caller drives the interaction (present\n * `choices`, collect a pick, call again with it appended to `parents`).\n */\nexport function listParentContextStep(\n resourceType: string,\n stepIndex: number,\n parents: string[],\n profile?: string,\n runner: CliRunner = defaultRunner,\n): DrillStep | null {\n const chain = PARENT_CONTEXT_CHAINS[resourceType];\n if (!chain || stepIndex >= chain.length) return null;\n const step = chain[stepIndex];\n // Prior picks become positional CLI args; a value starting with `-` would be\n // parsed as a flag, so refuse it (empty step → free-text fallback). Real\n // catalog/schema/scope/endpoint names never start with `-`.\n if (parents.some((p) => p.startsWith(\"-\"))) {\n return { key: step.key, choices: [] };\n }\n const spec = step.list(parents);\n return {\n key: step.key,\n choices: runList(\n spec.command,\n spec.idField,\n spec.labelField,\n profile,\n runner,\n ),\n };\n}\n\n/** Number of drill-down steps for a parent-context type (0 if not one). */\nexport function parentContextDepth(resourceType: string): number {\n return PARENT_CONTEXT_CHAINS[resourceType]?.length ?? 0;\n}\n\n/**\n * Builds the final resource identifier from the values picked across a\n * drill-down. Most types end on a self-qualified id (volume/uc_function list\n * `full_name`; a vector-search index name is already catalog.schema-qualified),\n * so the last pick is the whole answer. A `secret` is addressed by both its\n * scope and key (`scope/key`) — returning only the key drops the scope and\n * yields a value that can't locate the secret — so its picks are joined.\n */\nexport function composeResourceId(\n resourceType: string,\n picks: string[],\n): string {\n if (resourceType === \"secret\") return picks.join(\"/\");\n return picks[picks.length - 1];\n}\n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AAQ,sBAAsB;AACpC,KAAI,CAAC,SAAS,aAAa,MAAM,OAAQ,QAAO;CAChD,MAAM,OAAO,MAAM;AAInB,KAAI,QAAQ,MAAM,MAAM,EAAE,WAAW,IAAI,CAAC,CACxC,QAAO;EAAE,KAAK,KAAK;EAAK,SAAS,EAAE;EAAE;CAEvC,MAAM,OAAO,KAAK,KAAK,QAAQ;AAC/B,QAAO;EACL,KAAK,KAAK;EACV,SAAS,QACP,KAAK,SACL,KAAK,SACL,KAAK,YACL,SACA,OACD;EACF;;;AAIH,SAAgB,mBAAmB,cAA8B;AAC/D,QAAO,sBAAsB,eAAe,UAAU;;;;;;;;;;AAWxD,SAAgB,kBACd,cACA,OACQ;AACR,KAAI,iBAAiB,SAAU,QAAO,MAAM,KAAK,IAAI;AACrD,QAAO,MAAM,MAAM,SAAS"}
1
+ {"version":3,"file":"workspace-picker.js","names":[],"sources":["../../../../src/cli/commands/registry/workspace-picker.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\n\nimport {\n createWorkspaceClient,\n type WorkspaceClient,\n} from \"../../../workspace-client\";\n\n/**\n * Lists a user's real Databricks workspace resources so `appkit add` can offer\n * a picker instead of blind free-text entry.\n *\n * Flat resource types are listed through the sanctioned `workspace-client`\n * facade's modular SDK clients.\n * Parent-context types (volume, uc_function, secret, vector_search_index) still\n * shell out to the `databricks` CLI for their drill-down. Every path fails\n * soft: any error returns an empty list and the caller drops to free-text entry.\n */\n\n/** A workspace resource choice surfaced in the picker. */\nexport interface WorkspaceChoice {\n /** Value written to the env var (the resource id/name). */\n value: string;\n /** Human label shown in the picker (name, falling back to value). */\n label: string;\n}\n\n/**\n * Per-type SDK lister: streams a resource type off the WorkspaceClient into\n * `{value,label}` choices. `list()` returns an async iterable of raw SDK\n * objects; `toChoice` maps each to a picker choice. The SDK auto-paginates, so\n * we simply iterate to completion.\n */\ninterface SdkLister {\n list: (client: WorkspaceClient) => AsyncIterable<unknown>;\n toChoice: (item: Record<string, unknown>) => WorkspaceChoice | null;\n}\n\n/** Builds a `{value,label}` from an id field and optional label field. */\nfunction choiceFrom(\n item: Record<string, unknown>,\n idField: string,\n labelField?: string,\n): WorkspaceChoice | null {\n const id = item[idField];\n if (id === undefined || id === null) return null;\n const value = String(id);\n const rawLabel = labelField ? item[labelField] : undefined;\n const label =\n typeof rawLabel === \"string\" && rawLabel.length > 0\n ? `${rawLabel} (${value})`\n : value;\n return { value, label };\n}\n\n/**\n * Follows page tokens until exhausted. The repeated-token guard avoids an\n * infinite loop if the API echoes a token back.\n */\nasync function* paginate(\n fetchPage: (\n pageToken?: string,\n ) => Promise<{ items?: unknown[]; next?: string }>,\n): AsyncIterable<unknown> {\n let pageToken: string | undefined;\n do {\n const { items, next } = await fetchPage(pageToken);\n for (const item of items ?? []) yield item;\n if (next && next === pageToken) break;\n pageToken = next;\n } while (pageToken);\n}\n\n/** listInferenceEndpoints is unpaginated; adapt its single page. */\nasync function* iterateServingEndpoints(\n client: WorkspaceClient,\n): AsyncIterable<unknown> {\n const res = await client.modelServing.listInferenceEndpoints({});\n yield* res.endpoints ?? [];\n}\n\n/** Genie listSpaces returns a single page; follow `nextPageToken`. */\nfunction iterateGenieSpaces(client: WorkspaceClient): AsyncIterable<unknown> {\n return paginate(async (pageToken) => {\n const res = await client.genie.genieListSpaces(\n pageToken ? { pageToken } : {},\n );\n return { items: res.spaces, next: res.nextPageToken };\n });\n}\n\n/** Flat, top-level listable resource types, backed by SDK services. */\nexport const SDK_LISTERS: Record<string, SdkLister> = {\n sql_warehouse: {\n list: (c) => c.warehouses.listWarehousesIter({}),\n toChoice: (i) => choiceFrom(i, \"id\", \"name\"),\n },\n job: {\n list: (c) => c.jobs.listJobsIter({}),\n // job name lives under settings.name; id is top-level jobId (a bigint)\n toChoice: (i) => {\n const settings = i.settings as { name?: string } | undefined;\n return choiceFrom({ ...i, name: settings?.name }, \"jobId\", \"name\");\n },\n },\n serving_endpoint: {\n list: iterateServingEndpoints,\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n uc_connection: {\n list: (c) => c.connections.listConnectionsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"fullName\"),\n },\n database: {\n list: (c) => c.database.listDatabaseInstancesIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n genie_space: {\n list: iterateGenieSpaces,\n toChoice: (i) => choiceFrom(i, \"spaceId\", \"title\"),\n },\n experiment: {\n list: (c) => c.experiments.listExperimentsIter({}),\n toChoice: (i) => choiceFrom(i, \"experimentId\", \"name\"),\n },\n app: {\n list: (c) => c.apps.listAppsIter({}),\n toChoice: (i) => choiceFrom(i, \"name\", \"name\"),\n },\n};\n\n/** True when a resource type can be listed flat (no parent context). */\nexport function isFlatListable(resourceType: string): boolean {\n return resourceType in SDK_LISTERS;\n}\n\n/**\n * Constructs a workspace client for the given profile (or default resolution),\n * via the sanctioned `workspace-client` facade.\n */\nexport function makeWorkspaceClient(profile?: string): WorkspaceClient {\n return createWorkspaceClient(profile ? { profile } : {});\n}\n\n/**\n * Max resources fetched for the picker. `list()` paginates lazily, so on a large\n * workspace (5000+ warehouses) breaking out at the cap stops pagination early;\n * the picker's \"Enter manually\" option covers anything beyond it.\n */\nexport const MAX_PICKER_RESULTS = 200;\n\n/** A listing result plus whether it was truncated at the fetch cap. */\nexport interface WorkspaceListing {\n choices: WorkspaceChoice[];\n truncated: boolean;\n /** Short reason the listing failed (auth/config/network), if it did — lets\n * the caller distinguish a real error from a genuinely empty workspace. */\n error?: string;\n}\n\n/** First line of an error, capped, for a user-facing one-liner. */\nfunction shortErrorMessage(err: unknown): string {\n const msg = err instanceof Error ? err.message : String(err);\n return msg.split(\"\\n\")[0].trim().slice(0, 200);\n}\n\n/**\n * Lists workspace resources of a flat-listable type via the SDK, stopping at\n * MAX_PICKER_RESULTS so pagination doesn't drain a huge workspace. Returns an\n * empty listing on any failure (unknown type, auth/config error, network) so\n * the caller can fall back to free-text entry. `clientFactory` is injectable\n * for tests.\n */\nexport async function listWorkspaceResources(\n resourceType: string,\n profile?: string,\n clientFactory: (profile?: string) => WorkspaceClient = makeWorkspaceClient,\n): Promise<WorkspaceListing> {\n const lister = SDK_LISTERS[resourceType];\n if (!lister) return { choices: [], truncated: false };\n try {\n const client = clientFactory(profile);\n const choices: WorkspaceChoice[] = [];\n let truncated = false;\n for await (const item of lister.list(client)) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = lister.toChoice(item as Record<string, unknown>);\n if (!choice) continue;\n choices.push(choice);\n if (choices.length >= MAX_PICKER_RESULTS) {\n // Stop iterating — halts the async iterator, so no further pages fetch.\n truncated = true;\n break;\n }\n }\n return { choices, truncated };\n } catch (err) {\n // Don't swallow silently: return the reason so the caller can tell the user\n // the picker fell back because listing failed (typically auth/profile), not\n // because the workspace has none of this resource.\n return { choices: [], truncated: false, error: shortErrorMessage(err) };\n }\n}\n\n/** Runs a databricks CLI subcommand returning JSON; injectable for tests. */\nexport type CliRunner = (args: string[]) => {\n status: number | null;\n stdout: string;\n};\n\nconst defaultRunner: CliRunner = (args) => {\n // Parent-context lists can be large; raise maxBuffer well above the 1MB\n // default so a big JSON response isn't truncated into \"no resources found\".\n const res = spawnSync(\"databricks\", args, {\n encoding: \"utf-8\",\n maxBuffer: 64 * 1024 * 1024,\n });\n return { status: res.status, stdout: res.stdout ?? \"\" };\n};\n\n/**\n * Extracts `{value,label}` choices from a parsed CLI list response. The CLI\n * returns either a bare array or an object wrapping one; we scan for the first\n * array of objects. Items missing the id field are skipped.\n */\nexport function toChoices(\n parsed: unknown,\n idField: string,\n labelField?: string,\n): WorkspaceChoice[] {\n const arr = firstArray(parsed);\n const choices: WorkspaceChoice[] = [];\n for (const item of arr) {\n if (typeof item !== \"object\" || item === null) continue;\n const choice = choiceFrom(\n item as Record<string, unknown>,\n idField,\n labelField,\n );\n if (choice) choices.push(choice);\n }\n return choices;\n}\n\n/** Finds the first array in a CLI response (bare array or single wrapper key). */\nfunction firstArray(parsed: unknown): unknown[] {\n if (Array.isArray(parsed)) return parsed;\n if (parsed && typeof parsed === \"object\") {\n for (const v of Object.values(parsed)) {\n if (Array.isArray(v)) return v;\n }\n }\n return [];\n}\n\n/**\n * Runs a `databricks … list -o json` command and returns parsed choices, or\n * [] on any failure (CLI missing/errored, empty, non-JSON). `command` is the\n * argv after `databricks`; `-o json` and `-p <profile>` are appended.\n * Used for the parent-context drill-down (catalogs/schemas/scopes/endpoints).\n */\nexport function runList(\n command: string[],\n idField: string,\n labelField: string | undefined,\n profile: string | undefined,\n runner: CliRunner = defaultRunner,\n): WorkspaceChoice[] {\n const args = [...command, \"-o\", \"json\"];\n if (profile) args.push(\"-p\", profile);\n\n let result: { status: number | null; stdout: string };\n try {\n result = runner(args);\n } catch {\n return [];\n }\n if (result.status !== 0 || !result.stdout.trim()) return [];\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(result.stdout);\n } catch {\n return [];\n }\n return toChoices(parsed, idField, labelField);\n}\n\n/**\n * A drill-down step for a parent-context resource type. `list(parents)` builds\n * the CLI argv given the values picked in prior steps (e.g. [catalog] → schema\n * list command). `key` labels the step for prompts.\n */\nexport interface ParentContextStep {\n key: string;\n list: (parents: string[]) => {\n command: string[];\n idField: string;\n labelField?: string;\n /** Prefix stripped from each listed id (label and value). */\n stripPrefix?: string;\n };\n}\n\n/**\n * Drill-down chains for parent-context resource types. Each ends by listing\n * the resource itself; earlier steps list the parents to pick first.\n * Positional-arg CLI gotcha: `databricks schemas list <CATALOG>` etc. take the\n * parent as a positional, not a flag.\n */\nexport const PARENT_CONTEXT_CHAINS: Record<string, ParentContextStep[]> = {\n volume: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"volume\",\n list: ([catalog, schema]) => ({\n command: [\"volumes\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n uc_function: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"function\",\n list: ([catalog, schema]) => ({\n command: [\"functions\", \"list\", catalog, schema],\n idField: \"full_name\",\n labelField: \"name\",\n }),\n },\n ],\n model_service: [\n {\n key: \"catalog\",\n list: () => ({\n command: [\"catalogs\", \"list\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"schema\",\n list: ([catalog]) => ({\n command: [\"schemas\", \"list\", catalog],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"model service\",\n list: ([catalog, schema]) => ({\n command: [\n \"ai-gateway\",\n \"list-model-services\",\n \"--parent\",\n `schemas/${catalog}.${schema}`,\n ],\n idField: \"name\",\n // Listed as model-services/{catalog}.{schema}.{name}; apps bind the full name.\n stripPrefix: \"model-services/\",\n }),\n },\n ],\n secret: [\n {\n key: \"scope\",\n list: () => ({\n command: [\"secrets\", \"list-scopes\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"key\",\n list: ([scope]) => ({\n command: [\"secrets\", \"list-secrets\", scope],\n idField: \"key\",\n labelField: \"key\",\n }),\n },\n ],\n vector_search_index: [\n {\n key: \"endpoint\",\n list: () => ({\n command: [\"vector-search-endpoints\", \"list-endpoints\"],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n {\n key: \"index\",\n list: ([endpoint]) => ({\n command: [\"vector-search-indexes\", \"list-indexes\", endpoint],\n idField: \"name\",\n labelField: \"name\",\n }),\n },\n ],\n};\n\n/** Parents a drill-down opens on first; the full walk stays one pick away. */\nexport const DEFAULT_PARENTS: Record<string, string[]> = {\n model_service: [\"system\", \"ai\"],\n};\n\n/** True when a resource type needs a parent-context drill-down to list. */\nexport function isParentContext(resourceType: string): boolean {\n return resourceType in PARENT_CONTEXT_CHAINS;\n}\n\n/** One resolved step of a drill-down: the choices to present at this level. */\nexport interface DrillStep {\n key: string;\n choices: WorkspaceChoice[];\n}\n\n/**\n * Lists the choices for a single drill-down step given the values picked so\n * far. Returns [] on failure. The caller drives the interaction (present\n * `choices`, collect a pick, call again with it appended to `parents`).\n */\nexport function listParentContextStep(\n resourceType: string,\n stepIndex: number,\n parents: string[],\n profile?: string,\n runner: CliRunner = defaultRunner,\n): DrillStep | null {\n const chain = PARENT_CONTEXT_CHAINS[resourceType];\n if (!chain || stepIndex >= chain.length) return null;\n const step = chain[stepIndex];\n // Prior picks become positional CLI args; a value starting with `-` would be\n // parsed as a flag, so refuse it (empty step → free-text fallback). Real\n // catalog/schema/scope/endpoint names never start with `-`.\n if (parents.some((p) => p.startsWith(\"-\"))) {\n return { key: step.key, choices: [] };\n }\n const spec = step.list(parents);\n const choices = runList(\n spec.command,\n spec.idField,\n spec.labelField,\n profile,\n runner,\n );\n const prefix = spec.stripPrefix;\n return {\n key: step.key,\n choices: prefix\n ? choices.map(({ value }) => {\n const bare = value.startsWith(prefix)\n ? value.slice(prefix.length)\n : value;\n return { value: bare, label: bare };\n })\n : choices,\n };\n}\n\n/** Number of drill-down steps for a parent-context type (0 if not one). */\nexport function parentContextDepth(resourceType: string): number {\n return PARENT_CONTEXT_CHAINS[resourceType]?.length ?? 0;\n}\n\n/**\n * Builds the final resource identifier from the values picked across a\n * drill-down. Most types end on a self-qualified id (volume/uc_function list\n * `full_name`; a vector-search index name is already catalog.schema-qualified),\n * so the last pick is the whole answer. A `secret` is addressed by both its\n * scope and key (`scope/key`) — returning only the key drops the scope and\n * yields a value that can't locate the secret — so its picks are joined.\n */\nexport function composeResourceId(\n resourceType: string,\n picks: string[],\n): string {\n if (resourceType === \"secret\") return picks.join(\"/\");\n return picks[picks.length - 1];\n}\n"],"mappings":";;;;;AAsCA,SAAS,WACP,MACA,SACA,YAC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