@databricks/appkit 0.82.0 → 0.83.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.
Files changed (104) hide show
  1. package/CLAUDE.md +6 -0
  2. package/dist/appkit/package.js +1 -1
  3. package/dist/connectors/lakebase/index.js +1 -1
  4. package/dist/connectors/lakebase/routing-pool.d.ts +1 -1
  5. package/dist/connectors/lakebase/routing-pool.js +3 -3
  6. package/dist/connectors/lakebase/routing-pool.js.map +1 -1
  7. package/dist/context/caller-context.d.ts +22 -0
  8. package/dist/context/caller-context.d.ts.map +1 -0
  9. package/dist/context/caller-context.js +21 -0
  10. package/dist/context/caller-context.js.map +1 -0
  11. package/dist/context/deprecation.js +14 -0
  12. package/dist/context/deprecation.js.map +1 -0
  13. package/dist/context/execution-context.d.ts +12 -4
  14. package/dist/context/execution-context.d.ts.map +1 -1
  15. package/dist/context/execution-context.js +36 -34
  16. package/dist/context/execution-context.js.map +1 -1
  17. package/dist/context/index.d.ts +3 -2
  18. package/dist/context/index.js +2 -1
  19. package/dist/context/service-context.d.ts +18 -12
  20. package/dist/context/service-context.d.ts.map +1 -1
  21. package/dist/context/service-context.js +44 -54
  22. package/dist/context/service-context.js.map +1 -1
  23. package/dist/context/user-context.d.ts +5 -8
  24. package/dist/context/user-context.d.ts.map +1 -1
  25. package/dist/context/user-context.js +33 -6
  26. package/dist/context/user-context.js.map +1 -1
  27. package/dist/core/appkit.d.ts.map +1 -1
  28. package/dist/core/appkit.js +4 -2
  29. package/dist/core/appkit.js.map +1 -1
  30. package/dist/index.d.ts +7 -4
  31. package/dist/index.js +4 -2
  32. package/dist/plugin/plugin.d.ts +2 -2
  33. package/dist/plugin/plugin.d.ts.map +1 -1
  34. package/dist/plugin/plugin.js +6 -6
  35. package/dist/plugin/plugin.js.map +1 -1
  36. package/dist/plugins/agents/agents.d.ts +1 -1
  37. package/dist/plugins/ai-search/ai-search.d.ts +1 -1
  38. package/dist/plugins/analytics/analytics.d.ts +1 -1
  39. package/dist/plugins/analytics/analytics.d.ts.map +1 -1
  40. package/dist/plugins/analytics/analytics.js +3 -1
  41. package/dist/plugins/analytics/analytics.js.map +1 -1
  42. package/dist/plugins/database/database.d.ts +1 -1
  43. package/dist/plugins/files/plugin.d.ts +11 -11
  44. package/dist/plugins/files/plugin.js +17 -17
  45. package/dist/plugins/files/plugin.js.map +1 -1
  46. package/dist/plugins/genie/genie.d.ts +1 -1
  47. package/dist/plugins/jobs/plugin.d.ts +1 -1
  48. package/dist/plugins/lakebase/lakebase.d.ts +1 -1
  49. package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
  50. package/dist/plugins/lakebase/lakebase.js +4 -4
  51. package/dist/plugins/lakebase/lakebase.js.map +1 -1
  52. package/dist/plugins/server/index.d.ts +1 -1
  53. package/dist/plugins/server/index.js +2 -2
  54. package/dist/plugins/server/index.js.map +1 -1
  55. package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js +3 -3
  56. package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js.map +1 -1
  57. package/dist/plugins/server/static-server.js +3 -3
  58. package/dist/plugins/server/static-server.js.map +1 -1
  59. package/dist/plugins/server/utils.js +3 -3
  60. package/dist/plugins/server/utils.js.map +1 -1
  61. package/dist/plugins/server/vite-dev-server.js +4 -4
  62. package/dist/plugins/server/vite-dev-server.js.map +1 -1
  63. package/dist/plugins/serving/serving.d.ts +1 -1
  64. package/dist/resources/index.d.ts +1 -0
  65. package/dist/resources/index.js +3 -0
  66. package/dist/resources/warehouse.d.ts +16 -0
  67. package/dist/resources/warehouse.d.ts.map +1 -0
  68. package/dist/resources/warehouse.js +93 -0
  69. package/dist/resources/warehouse.js.map +1 -0
  70. package/dist/schemas/manifest.d.ts +9 -0
  71. package/dist/schemas/manifest.d.ts.map +1 -1
  72. package/dist/schemas/manifest.js +11 -0
  73. package/dist/schemas/manifest.js.map +1 -1
  74. package/dist/shared/src/schemas/manifest.d.ts +42 -33
  75. package/dist/shared/src/schemas/manifest.d.ts.map +1 -1
  76. package/dist/shared/src/schemas/manifest.js +11 -0
  77. package/dist/shared/src/schemas/manifest.js.map +1 -1
  78. package/dist/testing/create-test-app.js +2 -2
  79. package/dist/testing/create-test-app.js.map +1 -1
  80. package/dist/testing/fixtures.d.ts +3 -2
  81. package/dist/testing/fixtures.d.ts.map +1 -1
  82. package/dist/testing/fixtures.js +21 -14
  83. package/dist/testing/fixtures.js.map +1 -1
  84. package/dist/testing/reset-singletons.js +1 -1
  85. package/dist/type-generator/database/generate.js +3 -3
  86. package/dist/type-generator/database/generate.js.map +1 -1
  87. package/dist/type-generator/migration.js +2 -2
  88. package/dist/type-generator/migration.js.map +1 -1
  89. package/dist/type-generator/serving/server-file-extractor.js +3 -3
  90. package/dist/type-generator/serving/server-file-extractor.js.map +1 -1
  91. package/docs/api/appkit/Class.Plugin.md +1 -1
  92. package/docs/api/appkit/Function.getCurrentActorId.md +12 -0
  93. package/docs/api/appkit/Function.getCurrentPrincipalKey.md +12 -0
  94. package/docs/api/appkit/Function.getExecutionContext.md +5 -3
  95. package/docs/api/appkit/Function.getWarehouseId.md +20 -0
  96. package/docs/api/appkit/Interface.CallerContext.md +41 -0
  97. package/docs/api/appkit/Interface.PluginManifest.md +25 -2
  98. package/docs/api/appkit/TypeAlias.CallerPrincipal.md +13 -0
  99. package/docs/api/appkit/TypeAlias.ExecutionContext.md +6 -0
  100. package/docs/api/appkit.md +6 -0
  101. package/docs/plugins/analytics.md +8 -0
  102. package/llms.txt +6 -0
  103. package/package.json +1 -1
  104. package/sbom.cdx.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"manifest.js","names":[],"sources":["../../../../../shared/src/schemas/manifest.ts"],"sourcesContent":["/**\n * Zod-authoring module for AppKit plugin manifest schemas.\n *\n * Single source of truth for the plugin manifest contract. JSON Schema\n * artifacts published at the docs URL are emitted from these schemas via\n * `tools/generate-json-schema.ts` and live only in `docs/static/schemas/`\n * (no package-internal copies).\n *\n * - Cross-field constraints (cycle/dangling-reference checks, `<PROFILE>`\n * placeholder, post-scaffold instruction non-empty) are refinements\n * co-located with the shape they constrain. Validation is driven through\n * the Standard Schema interface from `validate-manifest.ts`.\n * - `templateFieldEntrySchema` is a transform that emits `origin` from\n * `localOnly`/`value`/`resolve`. The input slot is still allowed so\n * re-parsing previously-synced template manifests does not fail, but the\n * transform always overwrites it — drift-by-construction for hand-edits.\n * - `discoveryDescriptorSchema` is a discriminated union over a `type`\n * literal. The `kind` variant references one of the well-known\n * `resourceKind` values for which AppKit owns the CLI command map (see\n * `RESOURCE_KIND_COMMANDS` below). The `cli` variant is the escape hatch\n * carrying the existing free-form fields (with the `<PROFILE>`\n * refinement). Hierarchical context for volumes (catalog/schema parent\n * walk) is encoded via the kind's `parents` array, not via dependsOn.\n * - Scaffolding rule items carry a `maxLength` (120 chars) so\n * `rules.never[]` / `rules.must[]` / `rules.should[]` stay short\n * directives by contract, and the canonical `TEMPLATE_SCAFFOLDING`\n * constant lives co-located with the scaffolding schemas (sync.ts\n * imports it).\n */\n\nimport { z } from \"zod\";\n\nimport { PLUGIN_NAME_PATTERN } from \"../naming\";\n\n// ── Resource type + per-type permission enums ────────────────────────────\n\nexport const resourceTypeSchema = z\n .enum([\n \"secret\",\n \"job\",\n \"sql_warehouse\",\n \"serving_endpoint\",\n \"volume\",\n \"vector_search_index\",\n \"uc_function\",\n \"uc_connection\",\n \"database\",\n \"postgres\",\n \"genie_space\",\n \"experiment\",\n \"app\",\n ])\n .describe(\"Type of Databricks resource\");\n\nexport const secretPermissionSchema = z\n .enum([\"READ\", \"WRITE\", \"MANAGE\"])\n .describe(\"Permission for secret resources (order: weakest to strongest)\");\n\nexport const jobPermissionSchema = z\n .enum([\"CAN_VIEW\", \"CAN_MANAGE_RUN\", \"CAN_MANAGE\"])\n .describe(\"Permission for job resources (order: weakest to strongest)\");\n\nexport const sqlWarehousePermissionSchema = z\n .enum([\"CAN_USE\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for SQL warehouse resources (order: weakest to strongest)\",\n );\n\nexport const servingEndpointPermissionSchema = z\n .enum([\"CAN_VIEW\", \"CAN_QUERY\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for serving endpoint resources (order: weakest to strongest)\",\n );\n\nexport const volumePermissionSchema = z\n .enum([\"READ_VOLUME\", \"WRITE_VOLUME\"])\n .describe(\"Permission for Unity Catalog volume resources\");\n\nexport const vectorSearchIndexPermissionSchema = z\n .enum([\"SELECT\"])\n .describe(\"Permission for vector search index resources\");\n\nexport const ucFunctionPermissionSchema = z\n .enum([\"EXECUTE\"])\n .describe(\"Permission for Unity Catalog function resources\");\n\nexport const ucConnectionPermissionSchema = z\n .enum([\"USE_CONNECTION\"])\n .describe(\"Permission for Unity Catalog connection resources\");\n\nexport const databasePermissionSchema = z\n .enum([\"CAN_CONNECT_AND_CREATE\"])\n .describe(\"Permission for database resources\");\n\nexport const postgresPermissionSchema = z\n .enum([\"CAN_CONNECT_AND_CREATE\"])\n .describe(\"Permission for Postgres resources\");\n\nexport const genieSpacePermissionSchema = z\n .enum([\"CAN_VIEW\", \"CAN_RUN\", \"CAN_EDIT\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for Genie Space resources (order: weakest to strongest)\",\n );\n\nexport const experimentPermissionSchema = z\n .enum([\"CAN_READ\", \"CAN_EDIT\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for MLflow experiment resources (order: weakest to strongest)\",\n );\n\nexport const appPermissionSchema = z\n .enum([\"CAN_USE\"])\n .describe(\"Permission for Databricks App resources\");\n\n// ── Discovery descriptor (discriminated union) ───────────────────────────\n\n/**\n * Well-known Databricks resource kinds for which AppKit owns the CLI\n * command map. Plugins reference one of these via the `kind` variant of the\n * discovery descriptor; everything else falls back to the free-form `cli`\n * variant.\n *\n * Kept narrow on purpose: each entry costs an addition to\n * `RESOURCE_KIND_COMMANDS` below, which is the single source of truth for\n * how that kind is enumerated.\n */\nexport const resourceKindSchema = z\n .enum([\n \"warehouse\",\n \"genie_space\",\n \"postgres_project\",\n \"postgres_branch\",\n \"postgres_database\",\n \"volume\",\n ])\n .describe(\n \"Well-known Databricks resource kind whose listing command is owned by AppKit (see RESOURCE_KIND_COMMANDS).\",\n );\n\nexport const kindDiscoveryDescriptorSchema = z\n .object({\n type: z\n .literal(\"kind\")\n .describe(\n \"Discriminator: 'kind' uses the AppKit-owned command map for the named resourceKind.\",\n ),\n resourceKind: resourceKindSchema.describe(\n \"Reference to a well-known Databricks resource kind. AppKit owns the CLI command, response shape, and unwrap rules.\",\n ),\n select: z\n .string()\n .optional()\n .describe(\n \"Field name in the parsed CLI response used as the selected value (e.g., 'id'). Defaults to the kind's natural identifier when omitted.\",\n ),\n display: z\n .string()\n .optional()\n .describe(\n \"Field name in the parsed CLI response shown to the user in selection UI. Defaults to `select` if omitted.\",\n ),\n dependsOn: z\n .string()\n .optional()\n .describe(\n \"Name of a sibling field within the same resource that must be resolved first. Used to express ordering dependencies between resource fields.\",\n ),\n shortcut: z\n .string()\n .optional()\n .describe(\n \"Single-value fast-path command that returns exactly one value, skipping interactive selection.\",\n ),\n })\n .strict()\n .describe(\n \"Discovery via a well-known resource kind. AppKit owns the CLI command and unwrap rules for the named kind.\",\n );\n\n/**\n * Shell metacharacters rejected on free-form CLI command strings. Catches the\n * common foot-guns (statement separators, pipes, redirects via shell, command\n * substitution, newlines). Not a security boundary on its own — executors must\n * always pass these via argv, never shell-exec the string. Angle brackets are\n * permitted because `<PROFILE>` (and future `<…>` placeholders) are part of\n * the command-template convention.\n */\nconst SHELL_METACHAR_RE = /[;|&`$\\n\\r]/;\n\nexport const cliDiscoveryDescriptorSchema = z\n .object({\n type: z\n .literal(\"cli\")\n .describe(\n \"Discriminator: 'cli' uses a free-form Databricks CLI command supplied by the plugin.\",\n ),\n cliCommand: z\n .string()\n .describe(\n \"Databricks CLI command that lists resources. Must include <PROFILE>. Shell metacharacters (;|&`$ and newlines) are rejected; for first-party Databricks resources prefer the `kind` variant which uses AppKit's typed command map.\",\n ),\n selectField: z\n .string()\n .describe(\n \"jq-style path to the field used as the selected value (e.g., '.id', '.name').\",\n ),\n displayField: z\n .string()\n .optional()\n .describe(\n \"jq-style path to the field shown to the user in selection UI. Defaults to selectField if omitted.\",\n ),\n dependsOn: z\n .string()\n .optional()\n .describe(\n \"Name of a sibling field within the same resource that must be resolved first. Used to express ordering dependencies between resource fields.\",\n ),\n shortcut: z\n .string()\n .optional()\n .describe(\n \"Single-value fast-path command that returns exactly one value, skipping interactive selection. Shell metacharacters are rejected.\",\n ),\n })\n .strict()\n .refine((descriptor) => descriptor.cliCommand.includes(\"<PROFILE>\"), {\n message: \"must include <PROFILE> placeholder\",\n path: [\"cliCommand\"],\n })\n .refine((descriptor) => !SHELL_METACHAR_RE.test(descriptor.cliCommand), {\n message:\n \"must not contain shell metacharacters (;|&`$ or newlines); use the `kind` variant for typed Databricks resources\",\n path: [\"cliCommand\"],\n })\n .refine(\n (descriptor) =>\n descriptor.shortcut === undefined ||\n !SHELL_METACHAR_RE.test(descriptor.shortcut),\n {\n message: \"must not contain shell metacharacters (;|&`$ or newlines)\",\n path: [\"shortcut\"],\n },\n )\n .describe(\n \"Discovery via a free-form Databricks CLI command. Escape hatch — prefer the `kind` variant when a typed resourceKind covers the resource. This shape is intentionally minimal and may tighten further in future versions.\",\n );\n\nexport const discoveryDescriptorSchema = z\n .discriminatedUnion(\"type\", [\n kindDiscoveryDescriptorSchema,\n cliDiscoveryDescriptorSchema,\n ])\n .describe(\n \"Describes how the CLI discovers values for a resource field. 'kind' references a well-known Databricks resource kind whose command is owned by AppKit; 'cli' is the escape hatch carrying a free-form Databricks CLI command.\",\n );\n\n// ── Resource kind → CLI command map ──────────────────────────────────────\n\n/**\n * Descriptor for how a well-known resource kind is listed via the\n * Databricks CLI.\n *\n * - `command` is the CLI invocation template. It carries two kinds of\n * placeholders:\n * - `<PROFILE>` — substituted with the user's CLI profile by the runner.\n * - `{<fieldName>}` — substituted with the resolved value of the named\n * sibling field (used for `dependsOn` chains).\n * - `unwrap`, when set, is the JSON path into the response wrapper (e.g.,\n * `\"warehouses\"` for `{ warehouses: [...] }`). Omitted when the response\n * is already a flat array.\n * - `parents`, when set, lists transient query inputs the runner must\n * collect (as free-text prompts) before invoking the command. Each\n * `parents[i]` value substitutes the matching `{name}` placeholder in\n * the command string. Unlike `dependsOn` (which references a sibling\n * field on the same resource), `parents` covers inputs that aren't\n * persisted as fields on the resource.\n */\nexport type ResourceKindCommand = {\n command: string;\n unwrap?: string;\n parents?: readonly string[];\n};\n\n/**\n * Single source of truth for AppKit-owned discovery commands.\n *\n * To add a new resource kind: extend `resourceKindSchema` and add an entry\n * here. Plugins reference the kind via `discovery: { type: \"kind\",\n * resourceKind: \"...\" }` and inherit the command + response shape.\n *\n * `unwrap` defaults are unset: the existing core plugin manifests use simple\n * jq paths (`.id`, `.name`, `.full_name`), implying the listed CLI commands\n * return flat arrays. Refine in a follow-up if a kind's CLI returns wrapped\n * data.\n *\n * Volume's catalog/schema parent context is supplied via the `parents`\n * array, which the runner collects from the user as free-text prompts\n * before invoking the listing command.\n */\nexport const RESOURCE_KIND_COMMANDS: Record<\n z.infer<typeof resourceKindSchema>,\n { command: string; unwrap?: string; parents?: readonly string[] }\n> = {\n warehouse: {\n command: \"databricks warehouses list --profile <PROFILE> --output json\",\n },\n genie_space: {\n command: \"databricks genie list-spaces --profile <PROFILE> --output json\",\n },\n postgres_project: {\n command:\n \"databricks postgres list-projects --profile <PROFILE> --output json\",\n },\n postgres_branch: {\n // {project} is a placeholder for the resolved value of the `project`\n // sibling field (declared via `dependsOn: \"project\"` on the kind variant).\n // The Databricks CLI requires the parent project resource name (format\n // `projects/{project_id}`) as a positional argument.\n command:\n \"databricks postgres list-branches {project} --profile <PROFILE> --output json\",\n },\n postgres_database: {\n // {branch} is a placeholder for the resolved value of the `branch`\n // sibling field (declared via `dependsOn: \"branch\"` on the kind variant).\n command:\n \"databricks postgres list-databases {branch} --profile <PROFILE> --output json\",\n },\n volume: {\n // `parents` declares free-text user prompts the runner must collect before\n // invoking the discovery command. Each `parents[i]` value substitutes the\n // matching `{name}` placeholder in the command string above. Unlike\n // `dependsOn` (which references a sibling field on the same resource),\n // `parents` covers transient query inputs that aren't persisted as fields.\n command:\n \"databricks volumes list {catalog} {schema} --profile <PROFILE> --output json\",\n parents: [\"catalog\", \"schema\"] as const,\n },\n};\n\n// ── Resource field entry (plugin manifest variant) ───────────────────────\n\nexport const resourceFieldEntrySchema = z\n .object({\n env: z\n .string()\n .regex(/^[A-Z][A-Z0-9_]*$/)\n .optional()\n .describe(\"Environment variable name for this field\"),\n description: z\n .string()\n .optional()\n .describe(\"Human-readable description for this field\"),\n bundleIgnore: z\n .boolean()\n .optional()\n .describe(\n \"When true, this field is excluded from Databricks bundle configuration (databricks.yml) generation.\",\n ),\n examples: z\n .array(z.string())\n .optional()\n .describe(\"Example values showing the expected format for this field\"),\n localOnly: z\n .boolean()\n .optional()\n .describe(\n \"When true, this field is only generated for local .env files. The Databricks Apps platform auto-injects it at deploy time.\",\n ),\n value: z\n .string()\n .optional()\n .describe(\n \"Static value for this field. Used when no prompted or resolved value exists.\",\n ),\n resolve: z\n .string()\n .regex(/^[a-z_]+:[a-zA-Z]+$/)\n .optional()\n .describe(\n \"Named resolver prefixed by resource type (e.g., 'postgres:host'). The CLI resolves this value during the init prompt flow.\",\n ),\n discovery: discoveryDescriptorSchema.optional(),\n })\n .strict()\n .describe(\n \"Defines a single field for a resource. Each field has its own environment variable and optional description. Single-value types use one key (e.g. id); multi-value types (database, secret) use multiple (e.g. instance_name, database_name or scope, key).\",\n );\n\n// ── Resource requirement (per-type permission discriminator) ─────────────\n\n/**\n * Build a per-type variant. Each variant fixes `type` to a literal and constrains\n * `permission` to the matching enum, mirroring the existing JSON Schema's\n * `allOf + if/then` block. `fields` and the rest of the shape come from a\n * shared base.\n */\nconst resourceRequirementBaseShape = {\n alias: z\n .string()\n .min(1)\n .describe(\n \"Human-readable label for UI/display only. Deduplication uses resourceKey, not alias.\",\n ),\n resourceKey: z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/)\n .describe(\n \"Stable key for machine use: deduplication, env naming, composite keys, app.yaml. Required for registry lookup.\",\n ),\n description: z\n .string()\n .min(1)\n .describe(\"Human-readable description of why this resource is needed\"),\n fields: z\n .record(z.string(), resourceFieldEntrySchema)\n .refine((obj) => Object.keys(obj).length >= 1, {\n message: \"fields must contain at least one entry\",\n })\n .optional()\n .describe(\n \"Map of field name to env and optional description. Single-value types use one key (e.g. id); multi-value (database, secret) use multiple (e.g. instance_name, database_name or scope, key).\",\n ),\n};\n\n/**\n * Adds the cycle/dangling-reference cross-field check to a resource variant.\n * Iterates the resource's `fields`, validates each `discovery.dependsOn` target\n * is a sibling field name, then runs DFS over the dependsOn graph to detect\n * cycles. Issue paths target either the offending field's `dependsOn` slot or\n * the resource itself for cycles.\n */\nfunction refineResourceDependsOn(\n resource: { fields?: Record<string, { discovery?: { dependsOn?: string } }> },\n ctx: z.core.$RefinementCtx,\n): void {\n if (!resource.fields) return;\n const fieldNames = new Set(Object.keys(resource.fields));\n\n // Pass 1: validate dependsOn references and build the dependency graph.\n const deps = new Map<string, string>();\n for (const [name, field] of Object.entries(resource.fields)) {\n const dep = field.discovery?.dependsOn;\n if (!dep) continue;\n if (!fieldNames.has(dep)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"fields\", name, \"discovery\", \"dependsOn\"],\n message: `references non-existent sibling field '${dep}'`,\n });\n }\n deps.set(name, dep);\n }\n\n // Pass 2: detect cycles via DFS. Emit one issue per cycle found.\n const visited = new Set<string>();\n const visiting = new Set<string>();\n\n function dfs(node: string, chain: string[]): string[] | null {\n if (visiting.has(node)) return [...chain, node];\n if (visited.has(node)) return null;\n visiting.add(node);\n const next = deps.get(node);\n if (next) {\n const cycle = dfs(next, [...chain, node]);\n if (cycle) return cycle;\n }\n visiting.delete(node);\n visited.add(node);\n return null;\n }\n\n for (const node of deps.keys()) {\n if (visited.has(node)) continue;\n const cycle = dfs(node, []);\n if (cycle) {\n ctx.addIssue({\n code: \"custom\",\n path: [],\n message: `discovery.dependsOn creates a cycle: ${cycle.join(\" → \")}`,\n });\n // One cycle error per resource is enough.\n break;\n }\n }\n}\n\nfunction makeResourceVariant<\n TType extends z.ZodLiteral<string>,\n TPerm extends z.ZodTypeAny,\n>(typeLiteral: TType, permission: TPerm) {\n return z\n .object({\n type: typeLiteral,\n ...resourceRequirementBaseShape,\n permission: permission.describe(\n \"Required permission level. Validated per resource type.\",\n ),\n })\n .strict()\n .superRefine(refineResourceDependsOn);\n}\n\nexport const resourceRequirementSchema = z\n .discriminatedUnion(\"type\", [\n makeResourceVariant(z.literal(\"secret\"), secretPermissionSchema),\n makeResourceVariant(z.literal(\"job\"), jobPermissionSchema),\n makeResourceVariant(\n z.literal(\"sql_warehouse\"),\n sqlWarehousePermissionSchema,\n ),\n makeResourceVariant(\n z.literal(\"serving_endpoint\"),\n servingEndpointPermissionSchema,\n ),\n makeResourceVariant(z.literal(\"volume\"), volumePermissionSchema),\n makeResourceVariant(\n z.literal(\"vector_search_index\"),\n vectorSearchIndexPermissionSchema,\n ),\n makeResourceVariant(z.literal(\"uc_function\"), ucFunctionPermissionSchema),\n makeResourceVariant(\n z.literal(\"uc_connection\"),\n ucConnectionPermissionSchema,\n ),\n makeResourceVariant(z.literal(\"database\"), databasePermissionSchema),\n makeResourceVariant(z.literal(\"postgres\"), postgresPermissionSchema),\n makeResourceVariant(z.literal(\"genie_space\"), genieSpacePermissionSchema),\n makeResourceVariant(z.literal(\"experiment\"), experimentPermissionSchema),\n makeResourceVariant(z.literal(\"app\"), appPermissionSchema),\n ])\n .describe(\n \"Declares a resource requirement for a plugin. Can be defined statically in a manifest or dynamically via getResourceRequirements().\",\n );\n\n// ── Config schema (recursive) ────────────────────────────────────────────\n\nexport const configSchemaPropertySchema: z.ZodType = z.lazy(() =>\n z\n .object({\n type: z.enum([\n \"object\",\n \"array\",\n \"string\",\n \"number\",\n \"boolean\",\n \"integer\",\n ]),\n description: z.string().optional(),\n default: z.unknown().optional(),\n enum: z.array(z.unknown()).optional(),\n properties: z.record(z.string(), configSchemaPropertySchema).optional(),\n items: configSchemaPropertySchema.optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n minLength: z.number().int().min(0).optional(),\n maxLength: z.number().int().min(0).optional(),\n required: z.array(z.string()).optional(),\n // `additionalProperties` is a standard JSON Schema keyword used by core\n // plugin manifests (e.g., serving, ai-search, genie) to constrain\n // dictionary-shaped properties. Allowed on nested property entries as\n // either a boolean or a sub-schema, mirroring JSON Schema semantics.\n additionalProperties: z\n .union([z.boolean(), configSchemaPropertySchema])\n .optional(),\n })\n .strict(),\n);\n\nexport const configSchemaSchema: z.ZodType = z.lazy(() =>\n z\n .object({\n type: z.enum([\"object\", \"array\", \"string\", \"number\", \"boolean\"]),\n properties: z.record(z.string(), configSchemaPropertySchema).optional(),\n items: configSchemaSchema.optional(),\n required: z.array(z.string()).optional(),\n additionalProperties: z.boolean().optional(),\n })\n .strict(),\n);\n\n// ── Plugin-level scaffolding rules ───────────────────────────────────────\n\n/**\n * Per-item upper bound on plugin-level scaffolding rule strings. Matches the\n * template-level `SCAFFOLDING_RULE_MAX_LENGTH` defined below — rules at both\n * levels are short directives, not prose. The literal value lives here (and\n * not by reference to the template-side constant) because this declaration\n * is read in source order and the template constant is declared later.\n */\nconst PLUGIN_SCAFFOLDING_RULE_MAX_LENGTH = 120;\n\nconst pluginScaffoldingRuleItemSchema = z\n .string()\n .min(1)\n .max(\n PLUGIN_SCAFFOLDING_RULE_MAX_LENGTH,\n `rule entries must be ≤ ${PLUGIN_SCAFFOLDING_RULE_MAX_LENGTH} chars`,\n );\n\nexport const pluginScaffoldingRulesSchema = z\n .object({\n must: z\n .array(pluginScaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must always perform.\"),\n should: z\n .array(pluginScaffoldingRuleItemSchema)\n .optional()\n .describe(\"Recommended actions for the scaffolding agent.\"),\n never: z\n .array(pluginScaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must never perform.\"),\n })\n .strict()\n .superRefine((rules, ctx) => {\n // (a) Reject duplicate entries within any single array.\n const buckets: Array<[\"must\" | \"should\" | \"never\", string[] | undefined]> =\n [\n [\"must\", rules.must],\n [\"should\", rules.should],\n [\"never\", rules.never],\n ];\n for (const [bucketName, items] of buckets) {\n if (!items) continue;\n const seen = new Map<string, number>();\n items.forEach((item, idx) => {\n const prev = seen.get(item);\n if (prev === undefined) {\n seen.set(item, idx);\n return;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [bucketName, idx],\n message: `duplicate rule entry: \"${item}\" already declared at index ${prev}`,\n });\n });\n }\n // (b) Reject a string that appears in more than one of must/should/never.\n type Bucket = \"must\" | \"should\" | \"never\";\n const owner = new Map<string, Bucket>();\n for (const [bucketName, items] of buckets) {\n if (!items) continue;\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const existing = owner.get(item);\n if (existing === undefined) {\n owner.set(item, bucketName);\n continue;\n }\n if (existing !== bucketName) {\n ctx.addIssue({\n code: \"custom\",\n path: [bucketName, i],\n message: `rule entry \"${item}\" appears in both '${existing}' and '${bucketName}'; rules must belong to exactly one bucket`,\n });\n }\n }\n }\n })\n .describe(\n \"Structured rules for scaffolding agents declared at the plugin level. Each rule is a short directive (≤120 chars).\",\n );\n\n// ── Plugin manifest (root) ───────────────────────────────────────────────\n\nexport const pluginManifestSchema = z\n .object({\n $schema: z\n .string()\n .optional()\n .describe(\"Reference to the JSON Schema for validation\"),\n name: z\n .string()\n .regex(PLUGIN_NAME_PATTERN)\n .describe(\n \"Plugin identifier and JS binding. Must start with a lowercase letter; camelCase for multi-word names (e.g. aiSearch).\",\n ),\n displayName: z\n .string()\n .min(1)\n .describe(\"Human-readable display name for UI and CLI\"),\n description: z\n .string()\n .min(1)\n .describe(\"Brief description of what the plugin does\"),\n resources: z\n .object({\n required: z\n .array(resourceRequirementSchema)\n .describe(\n \"Resources that must be available for the plugin to function\",\n ),\n optional: z\n .array(resourceRequirementSchema)\n .describe(\n \"Resources that enhance functionality but are not mandatory\",\n ),\n })\n .strict()\n .describe(\"Databricks resource requirements for this plugin\"),\n config: z\n .object({\n schema: configSchemaSchema.optional(),\n })\n .strict()\n .optional()\n .describe(\"Configuration schema for the plugin\"),\n author: z.string().optional().describe(\"Author name or organization\"),\n version: z\n .string()\n .regex(/^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.]+)?$/)\n .optional()\n .describe(\"Plugin version (semver format)\"),\n repository: z\n .url()\n .optional()\n .describe(\"URL to the plugin's source repository\"),\n keywords: z\n .array(z.string())\n .optional()\n .describe(\"Keywords for plugin discovery\"),\n license: z.string().optional().describe(\"SPDX license identifier\"),\n onSetupMessage: z\n .string()\n .optional()\n .describe(\n \"Message displayed to the user after project initialization. Use this to inform about manual setup steps (e.g. environment variables, resource provisioning).\",\n ),\n hidden: z\n .boolean()\n .optional()\n .describe(\n \"When true, this plugin is excluded from the template plugins manifest (appkit.plugins.json) during sync.\",\n ),\n devOnly: z\n .boolean()\n .optional()\n .describe(\n \"When true, this plugin is only registered when NODE_ENV === 'development'. In any other environment createApp skips it entirely (not constructed, no routes, resources not validated). Use for dev-only tooling that must never run in a deployed app.\",\n ),\n stability: z\n .enum([\"beta\", \"ga\"])\n .optional()\n .describe(\n \"Plugin stability level. Beta plugins may have breaking API changes between minor releases but are on a path to GA. GA (general availability) plugins follow semver strictly.\",\n ),\n deprecated: z\n .boolean()\n .optional()\n .describe(\n \"When true, the plugin is deprecated. It still ships and functions, but tooling (e.g. `appkit plugin list`) may hide or flag it. The recommended replacement is noted in the plugin description.\",\n ),\n scaffolding: z\n .object({\n rules: pluginScaffoldingRulesSchema\n .optional()\n .describe(\n \"Structured rules for scaffolding agents declared at the plugin level.\",\n ),\n })\n .strict()\n .optional()\n .describe(\n \"Plugin-level scaffolding metadata consumed by scaffolding agents. Symmetric with template-level `scaffolding`.\",\n ),\n })\n .strict()\n .describe(\n \"Schema for Databricks AppKit plugin manifest files. Defines plugin metadata, resource requirements, and configuration options.\",\n );\n\n// ── Origin enum ──────────────────────────────────────────────────────────\n\nexport const originSchema = z\n .enum([\"user\", \"platform\", \"static\", \"cli\"])\n .describe(\n \"How the field value is determined. Computed during sync, not authored by plugin developers.\",\n );\n\n// ── Template field entry (origin computed by transform) ─────────────────\n\n/**\n * Derives the canonical origin of a resource field value from its shape.\n *\n * - `localOnly: true` → `\"platform\"` (auto-injected by the Databricks Apps\n * platform at deploy time; takes precedence over `value`/`resolve`).\n * - `value !== undefined` → `\"static\"` (hardcoded value).\n * - `resolve !== undefined` → `\"cli\"` (resolved by the CLI during init).\n * - else → `\"user\"` (user must provide the value at init time).\n *\n * The single source for this rule: `plugin sync`'s transform stamps `origin`\n * with it, and consumers that read an authored manifest (no stamped `origin`)\n * derive it through this rather than re-implementing the cascade.\n */\nexport function computeOriginFromField(field: {\n localOnly?: boolean;\n value?: string;\n resolve?: string;\n}): z.infer<typeof originSchema> {\n if (field.localOnly) return \"platform\";\n if (field.value !== undefined) return \"static\";\n if (field.resolve !== undefined) return \"cli\";\n return \"user\";\n}\n\n/**\n * Template field entry: extends the plugin manifest field entry with an\n * optional `origin` input slot, then runs a `.transform()` that overwrites\n * `origin` with the computed value. Allowing `origin` on input means\n * re-parsing a previously-synced template manifest does not fail; emitting\n * `origin` always means hand-edits in synced JSON are silently corrected\n * on the next parse — drift-by-construction.\n */\nexport const templateFieldEntrySchema = resourceFieldEntrySchema\n .extend({ origin: originSchema.optional() })\n .transform((field) => ({\n ...field,\n origin: computeOriginFromField(field),\n }));\n\n// ── Template resource requirement (uses templateFieldEntrySchema) ────────\n\nconst templateResourceRequirementBaseShape = {\n alias: z\n .string()\n .min(1)\n .describe(\"Human-readable label for UI/display only.\"),\n resourceKey: z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/)\n .describe(\n \"Stable key for machine use: deduplication, env naming, composite keys.\",\n ),\n description: z\n .string()\n .min(1)\n .describe(\"Human-readable description of why this resource is needed\"),\n fields: z\n .record(z.string(), templateFieldEntrySchema)\n .refine((obj) => Object.keys(obj).length >= 1, {\n message: \"fields must contain at least one entry\",\n })\n .optional()\n .describe(\"Map of field name to field entry with computed origin.\"),\n};\n\nfunction makeTemplateResourceVariant<\n TType extends z.ZodLiteral<string>,\n TPerm extends z.ZodTypeAny,\n>(typeLiteral: TType, permission: TPerm) {\n return z\n .object({\n type: typeLiteral,\n ...templateResourceRequirementBaseShape,\n permission: permission.describe(\n \"Required permission level. Validated per resource type.\",\n ),\n })\n .strict()\n .superRefine(refineResourceDependsOn);\n}\n\nexport const templateResourceRequirementSchema = z\n .discriminatedUnion(\"type\", [\n makeTemplateResourceVariant(z.literal(\"secret\"), secretPermissionSchema),\n makeTemplateResourceVariant(z.literal(\"job\"), jobPermissionSchema),\n makeTemplateResourceVariant(\n z.literal(\"sql_warehouse\"),\n sqlWarehousePermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"serving_endpoint\"),\n servingEndpointPermissionSchema,\n ),\n makeTemplateResourceVariant(z.literal(\"volume\"), volumePermissionSchema),\n makeTemplateResourceVariant(\n z.literal(\"vector_search_index\"),\n vectorSearchIndexPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"uc_function\"),\n ucFunctionPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"uc_connection\"),\n ucConnectionPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"database\"),\n databasePermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"postgres\"),\n postgresPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"genie_space\"),\n genieSpacePermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"experiment\"),\n experimentPermissionSchema,\n ),\n makeTemplateResourceVariant(z.literal(\"app\"), appPermissionSchema),\n ])\n .describe(\n \"Resource requirement with template-specific field entries (includes computed origin).\",\n );\n\n// ── Template plugin (extends plugin manifest) ────────────────────────────\n\nexport const templatePluginSchema = z\n .object({\n name: z\n .string()\n .regex(PLUGIN_NAME_PATTERN)\n .describe(\n \"Plugin identifier and JS binding. Must start with a lowercase letter; camelCase for multi-word names (e.g. aiSearch).\",\n ),\n displayName: z\n .string()\n .min(1)\n .describe(\"Human-readable display name for UI and CLI\"),\n description: z\n .string()\n .min(1)\n .describe(\"Brief description of what the plugin does\"),\n package: z\n .string()\n .min(1)\n .describe(\"NPM package name that provides this plugin\"),\n requiredByTemplate: z\n .boolean()\n .optional()\n .describe(\n \"When true, this plugin is required by the template and cannot be deselected during CLI init. The user will only be prompted to configure its resources. When absent or false, the plugin is optional and the user can choose whether to include it.\",\n ),\n onSetupMessage: z\n .string()\n .optional()\n .describe(\n \"Message displayed to the user after project initialization. Use this to inform about manual setup steps (e.g. environment variables, resource provisioning).\",\n ),\n stability: z\n .enum([\"beta\", \"ga\"])\n .optional()\n .describe(\n \"Plugin stability level. Beta is heading to GA; APIs may change between minor releases. GA (general availability) follows semver.\",\n ),\n deprecated: z\n .boolean()\n .optional()\n .describe(\n \"When true, the plugin is deprecated. It still ships and functions, but tooling (e.g. `appkit plugin list`) may hide or flag it. The recommended replacement is noted in the plugin description.\",\n ),\n scaffolding: z\n .object({\n rules: pluginScaffoldingRulesSchema\n .optional()\n .describe(\n \"Structured rules for scaffolding agents propagated from the plugin manifest.\",\n ),\n })\n .strict()\n .optional()\n .describe(\n \"Plugin-level scaffolding metadata propagated from the plugin manifest.\",\n ),\n resources: z\n .object({\n required: z\n .array(templateResourceRequirementSchema)\n .describe(\n \"Resources that must be available for the plugin to function\",\n ),\n optional: z\n .array(templateResourceRequirementSchema)\n .describe(\n \"Resources that enhance functionality but are not mandatory\",\n ),\n })\n .strict()\n .describe(\"Databricks resource requirements for this plugin\"),\n })\n .strict()\n .describe(\"Plugin manifest with package source information\");\n\n// ── Scaffolding descriptor ───────────────────────────────────────────────\n\nexport const scaffoldingFlagSchema = z\n .object({\n description: z.string().describe(\"Human-readable description of the flag.\"),\n required: z.boolean().optional().describe(\"Whether this flag is required.\"),\n pattern: z\n .string()\n .optional()\n .describe(\"Regex pattern for validating the flag value.\"),\n default: z.string().optional().describe(\"Default value for this flag.\"),\n })\n .strict()\n .describe(\"A flag for the scaffolding command.\");\n\n/**\n * Per-item upper bound on scaffolding rule strings. The intent is to enforce\n * \"short directive\" by contract — long paragraphs fail validation and force\n * authors to split prose into discrete actionable items.\n */\nconst SCAFFOLDING_RULE_MAX_LENGTH = 120;\n\nconst scaffoldingRuleItemSchema = z\n .string()\n .max(\n SCAFFOLDING_RULE_MAX_LENGTH,\n `rule item must be ≤ ${SCAFFOLDING_RULE_MAX_LENGTH} chars`,\n );\n\nexport const scaffoldingRulesSchema = z\n .object({\n never: z\n .array(scaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must never perform.\"),\n must: z\n .array(scaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must always perform.\"),\n should: z\n .array(scaffoldingRuleItemSchema)\n .optional()\n .describe(\n \"Recommended actions for the scaffolding agent (parity with plugin-level rules).\",\n ),\n })\n .strict()\n .describe(\"Structured rules for scaffolding agents.\");\n\nexport const scaffoldingDescriptorSchema = z\n .object({\n command: z\n .string()\n .describe(\"The scaffolding command (e.g., 'databricks apps init').\"),\n flags: z\n .record(z.string(), scaffoldingFlagSchema)\n .optional()\n .describe(\"Map of flag name to flag descriptor.\"),\n rules: scaffoldingRulesSchema\n .optional()\n .describe(\"Structured rules for scaffolding agents.\"),\n })\n .strict()\n .describe(\n \"Describes the scaffolding command, flags, and rules for project initialization.\",\n );\n\n/**\n * Canonical scaffolding descriptor for the `databricks apps init` command,\n * embedded in v2.0 template manifests to guide scaffolding agents.\n *\n * Co-located with `scaffoldingDescriptorSchema` so any change to the rule set\n * (or the schema's `maxLength` ceiling) shows up next to its consumer. The\n * `satisfies` annotation gives compile-time validation that the literal\n * matches the schema's input shape; if a `must`/`never` entry exceeds the\n * `maxLength` ceiling at runtime, `scaffoldingDescriptorSchema.parse` would\n * surface the breach in tests.\n */\nexport const TEMPLATE_SCAFFOLDING = {\n command: \"databricks apps init\",\n flags: {\n \"--name\": {\n description:\n \"Project name — sets {{.projectName}} in package.json, databricks.yml, and .env. Required for non-interactive scaffolding.\",\n required: true,\n pattern: \"^[a-z][a-z0-9-]*$\",\n },\n \"--template\": {\n description: \"Template path (local directory or GitHub URL)\",\n required: false,\n },\n \"--version\": {\n description: \"AppKit version to use; defaults to auto-detected\",\n required: false,\n },\n \"--features\": {\n description:\n \"Plugins to enable (comma-separated, no spaces; must match keys in this manifest's plugins map)\",\n required: false,\n pattern: \"^[a-zA-Z0-9_-]+(,[a-zA-Z0-9_-]+)*$\",\n },\n \"--set\": {\n description:\n \"Set resource values (format: plugin.resourceKey.field=value, repeatable)\",\n required: false,\n },\n \"--output-dir\": {\n description: \"Directory to write the project to\",\n required: false,\n },\n \"--description\": {\n description: \"App description\",\n required: false,\n },\n \"--run\": {\n description: \"Run the app after creation (none, dev, dev-remote)\",\n required: false,\n },\n \"--auto-approve\": {\n description:\n \"Pass as a bare flag (no value) to skip prompts for optional resources. Not recommended for agent-driven init — conflicts with the 'ask user when in doubt' rule.\",\n required: false,\n },\n \"--profile\": {\n description:\n \"Databricks CLI profile to use for authentication (global flag)\",\n required: false,\n },\n },\n rules: {\n must: [\n \"Treat `databricks apps init` output as starter code, not requirements; adapt or replace it to match the requested app\",\n \"Keep all secrets and credentials only in app.yaml, databricks.yml, and/or .env\",\n ],\n should: [\"ask user when in doubt of resource to use for plugin\"],\n never: [\n \"guess resources when multiple or no options are available\",\n \"embed secrets in files that will go to the client-bundle\",\n ],\n },\n} satisfies z.infer<typeof scaffoldingDescriptorSchema>;\n\n// ── Template plugins manifest (root) ─────────────────────────────────────\n\nexport const templatePluginsManifestSchema = z\n .object({\n $schema: z\n .string()\n .optional()\n .describe(\"Reference to the JSON Schema for validation\"),\n version: z\n .enum([\"1.0\", \"1.1\", \"2.0\"])\n .describe(\"Schema version for the template plugins manifest\"),\n plugins: z\n .record(z.string(), templatePluginSchema)\n .describe(\"Map of plugin name to plugin manifest with package source\"),\n scaffolding: scaffoldingDescriptorSchema\n .optional()\n .describe(\n \"Describes the scaffolding command and its configuration for project initialization.\",\n ),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (value.version === \"2.0\" && !value.scaffolding) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"scaffolding\"],\n message: \"scaffolding is required when version is '2.0'\",\n });\n }\n })\n .describe(\n \"Aggregated plugin manifest for AppKit templates. Read by Databricks CLI during init to discover available plugins and their resource requirements.\",\n );\n\n// ── Inferred types ───────────────────────────────────────────────────────\n\nexport type ResourceType = z.infer<typeof resourceTypeSchema>;\nexport type SecretPermission = z.infer<typeof secretPermissionSchema>;\nexport type JobPermission = z.infer<typeof jobPermissionSchema>;\nexport type SqlWarehousePermission = z.infer<\n typeof sqlWarehousePermissionSchema\n>;\nexport type ServingEndpointPermission = z.infer<\n typeof servingEndpointPermissionSchema\n>;\nexport type VolumePermission = z.infer<typeof volumePermissionSchema>;\nexport type VectorSearchIndexPermission = z.infer<\n typeof vectorSearchIndexPermissionSchema\n>;\nexport type UcFunctionPermission = z.infer<typeof ucFunctionPermissionSchema>;\nexport type UcConnectionPermission = z.infer<\n typeof ucConnectionPermissionSchema\n>;\nexport type DatabasePermission = z.infer<typeof databasePermissionSchema>;\nexport type PostgresPermission = z.infer<typeof postgresPermissionSchema>;\nexport type GenieSpacePermission = z.infer<typeof genieSpacePermissionSchema>;\nexport type ExperimentPermission = z.infer<typeof experimentPermissionSchema>;\nexport type AppPermission = z.infer<typeof appPermissionSchema>;\nexport type ResourceKind = z.infer<typeof resourceKindSchema>;\nexport type KindDiscoveryDescriptor = z.infer<\n typeof kindDiscoveryDescriptorSchema\n>;\nexport type CliDiscoveryDescriptor = z.infer<\n typeof cliDiscoveryDescriptorSchema\n>;\nexport type DiscoveryDescriptor = z.infer<typeof discoveryDescriptorSchema>;\nexport type ResourceFieldEntry = z.infer<typeof resourceFieldEntrySchema>;\nexport type ResourceRequirement = z.infer<typeof resourceRequirementSchema>;\nexport type ConfigSchemaProperty = z.infer<typeof configSchemaPropertySchema>;\nexport type ConfigSchema = z.infer<typeof configSchemaSchema>;\nexport type PluginScaffoldingRules = z.infer<\n typeof pluginScaffoldingRulesSchema\n>;\nexport type PluginManifest = z.infer<typeof pluginManifestSchema>;\nexport type Origin = z.infer<typeof originSchema>;\n// Template-side types use `z.input` so callers can construct a TemplatePlugin\n// from a parsed PluginManifest before the field-level origin transform runs.\n// `writeManifest` parses every field through `templateFieldEntrySchema` at\n// write-time, so the on-disk shape always has origin populated. The runtime\n// invariant: origin is *always* present after sync writes; the type slot\n// stays optional so the in-memory pipeline does not need to fabricate origin\n// before assignment.\nexport type TemplateFieldEntry = z.input<typeof templateFieldEntrySchema>;\nexport type TemplateResourceRequirement = z.input<\n typeof templateResourceRequirementSchema\n>;\nexport type TemplatePlugin = z.input<typeof templatePluginSchema>;\nexport type ScaffoldingFlag = z.infer<typeof scaffoldingFlagSchema>;\nexport type ScaffoldingRules = z.infer<typeof scaffoldingRulesSchema>;\nexport type ScaffoldingDescriptor = z.infer<typeof scaffoldingDescriptorSchema>;\nexport type TemplatePluginsManifest = z.input<\n typeof templatePluginsManifestSchema\n>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,qBAAqB,EAC/B,KAAK;CACJ;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,CACD,SAAS,8BAA8B;AAE1C,MAAa,yBAAyB,EACnC,KAAK;CAAC;CAAQ;CAAS;CAAS,CAAC,CACjC,SAAS,gEAAgE;AAE5E,MAAa,sBAAsB,EAChC,KAAK;CAAC;CAAY;CAAkB;CAAa,CAAC,CAClD,SAAS,6DAA6D;AAEzE,MAAa,+BAA+B,EACzC,KAAK,CAAC,WAAW,aAAa,CAAC,CAC/B,SACC,uEACD;AAEH,MAAa,kCAAkC,EAC5C,KAAK;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ACR,SAAS,sCAAsC;;;;;;AAOlD,MAAM,8BAA8B;AAEpC,MAAM,4BAA4B,EAC/B,QAAQ,CACR,IACC,6BACA,uBAAuB,4BAA4B,QACpD;AAEH,MAAa,yBAAyB,EACnC,OAAO;CACN,OAAO,EACJ,MAAM,0BAA0B,CAChC,UAAU,CACV,SAAS,oDAAoD;CAChE,MAAM,EACH,MAAM,0BAA0B,CAChC,UAAU,CACV,SAAS,qDAAqD;CACjE,QAAQ,EACL,MAAM,0BAA0B,CAChC,UAAU,CACV,SACC,kFACD;CACJ,CAAC,CACD,QAAQ,CACR,SAAS,2CAA2C;AAEvD,MAAa,8BAA8B,EACxC,OAAO;CACN,SAAS,EACN,QAAQ,CACR,SAAS,0DAA0D;CACtE,OAAO,EACJ,OAAO,EAAE,QAAQ,EAAE,sBAAsB,CACzC,UAAU,CACV,SAAS,uCAAuC;CACnD,OAAO,uBACJ,UAAU,CACV,SAAS,2CAA2C;CACxD,CAAC,CACD,QAAQ,CACR,SACC,kFACD;AA+EH,MAAa,gCAAgC,EAC1C,OAAO;CACN,SAAS,EACN,QAAQ,CACR,UAAU,CACV,SAAS,8CAA8C;CAC1D,SAAS,EACN,KAAK;EAAC;EAAO;EAAO;EAAM,CAAC,CAC3B,SAAS,mDAAmD;CAC/D,SAAS,EACN,OAAO,EAAE,QAAQ,EAAE,qBAAqB,CACxC,SAAS,4DAA4D;CACxE,aAAa,4BACV,UAAU,CACV,SACC,sFACD;CACJ,CAAC,CACD,QAAQ,CACR,aAAa,OAAO,QAAQ;AAC3B,KAAI,MAAM,YAAY,SAAS,CAAC,MAAM,YACpC,KAAI,SAAS;EACX,MAAM;EACN,MAAM,CAAC,cAAc;EACrB,SAAS;EACV,CAAC;EAEJ,CACD,SACC,qJACD"}
1
+ {"version":3,"file":"manifest.js","names":[],"sources":["../../../../../shared/src/schemas/manifest.ts"],"sourcesContent":["/**\n * Zod-authoring module for AppKit plugin manifest schemas.\n *\n * Single source of truth for the plugin manifest contract. JSON Schema\n * artifacts published at the docs URL are emitted from these schemas via\n * `tools/generate-json-schema.ts` and live only in `docs/static/schemas/`\n * (no package-internal copies).\n *\n * - Cross-field constraints (cycle/dangling-reference checks, `<PROFILE>`\n * placeholder, post-scaffold instruction non-empty) are refinements\n * co-located with the shape they constrain. Validation is driven through\n * the Standard Schema interface from `validate-manifest.ts`.\n * - `templateFieldEntrySchema` is a transform that emits `origin` from\n * `localOnly`/`value`/`resolve`. The input slot is still allowed so\n * re-parsing previously-synced template manifests does not fail, but the\n * transform always overwrites it — drift-by-construction for hand-edits.\n * - `discoveryDescriptorSchema` is a discriminated union over a `type`\n * literal. The `kind` variant references one of the well-known\n * `resourceKind` values for which AppKit owns the CLI command map (see\n * `RESOURCE_KIND_COMMANDS` below). The `cli` variant is the escape hatch\n * carrying the existing free-form fields (with the `<PROFILE>`\n * refinement). Hierarchical context for volumes (catalog/schema parent\n * walk) is encoded via the kind's `parents` array, not via dependsOn.\n * - Scaffolding rule items carry a `maxLength` (120 chars) so\n * `rules.never[]` / `rules.must[]` / `rules.should[]` stay short\n * directives by contract, and the canonical `TEMPLATE_SCAFFOLDING`\n * constant lives co-located with the scaffolding schemas (sync.ts\n * imports it).\n */\n\nimport { z } from \"zod\";\n\nimport { PLUGIN_NAME_PATTERN } from \"../naming\";\n\n// ── Resource type + per-type permission enums ────────────────────────────\n\nexport const resourceTypeSchema = z\n .enum([\n \"secret\",\n \"job\",\n \"sql_warehouse\",\n \"serving_endpoint\",\n \"volume\",\n \"vector_search_index\",\n \"uc_function\",\n \"uc_connection\",\n \"database\",\n \"postgres\",\n \"genie_space\",\n \"experiment\",\n \"app\",\n ])\n .describe(\"Type of Databricks resource\");\n\n/** Apps user_api_scopes for resource types with confirmed OBO support. */\nexport const SCOPE_BY_TYPE = {\n sql_warehouse: \"sql\", // sql:restricted-query is the read-only variant.\n serving_endpoint: \"model-serving\",\n genie_space: \"genie\",\n volume: \"files\",\n vector_search_index: \"vector-search\",\n uc_connection: \"catalog.connections\",\n // uc_function uses sql, or mcp.functions through managed MCP. Confirm later.\n // experiment and job are SP-only; there is no mlflow or jobs scope.\n} as const satisfies Partial<Record<ResourceType, string>>;\n\n// A postgres user_api_scope exists, so Lakebase is platform-OBO-capable.\n// It stays app-only for v1 because the connector connects as the SP today (audit A7).\nexport const APP_ONLY_RESOURCE_TYPES: ReadonlySet<ResourceType> = new Set([\n \"secret\",\n \"database\",\n \"postgres\",\n]);\n\n/** Capabilities that need a user_api_scope but have no resource ID. */\nexport const capabilityScopeSchema = z.enum([\n \"ai-gateway\",\n \"mcp.external\",\n \"mcp.functions\",\n \"workspace.workspace\",\n \"catalog.catalogs:read\",\n \"catalog.schemas:read\",\n \"catalog.tables:read\",\n]);\n\nexport type CapabilityScope = z.infer<typeof capabilityScopeSchema>;\n\nexport const secretPermissionSchema = z\n .enum([\"READ\", \"WRITE\", \"MANAGE\"])\n .describe(\"Permission for secret resources (order: weakest to strongest)\");\n\nexport const jobPermissionSchema = z\n .enum([\"CAN_VIEW\", \"CAN_MANAGE_RUN\", \"CAN_MANAGE\"])\n .describe(\"Permission for job resources (order: weakest to strongest)\");\n\nexport const sqlWarehousePermissionSchema = z\n .enum([\"CAN_USE\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for SQL warehouse resources (order: weakest to strongest)\",\n );\n\nexport const servingEndpointPermissionSchema = z\n .enum([\"CAN_VIEW\", \"CAN_QUERY\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for serving endpoint resources (order: weakest to strongest)\",\n );\n\nexport const volumePermissionSchema = z\n .enum([\"READ_VOLUME\", \"WRITE_VOLUME\"])\n .describe(\"Permission for Unity Catalog volume resources\");\n\nexport const vectorSearchIndexPermissionSchema = z\n .enum([\"SELECT\"])\n .describe(\"Permission for vector search index resources\");\n\nexport const ucFunctionPermissionSchema = z\n .enum([\"EXECUTE\"])\n .describe(\"Permission for Unity Catalog function resources\");\n\nexport const ucConnectionPermissionSchema = z\n .enum([\"USE_CONNECTION\"])\n .describe(\"Permission for Unity Catalog connection resources\");\n\nexport const databasePermissionSchema = z\n .enum([\"CAN_CONNECT_AND_CREATE\"])\n .describe(\"Permission for database resources\");\n\nexport const postgresPermissionSchema = z\n .enum([\"CAN_CONNECT_AND_CREATE\"])\n .describe(\"Permission for Postgres resources\");\n\nexport const genieSpacePermissionSchema = z\n .enum([\"CAN_VIEW\", \"CAN_RUN\", \"CAN_EDIT\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for Genie Space resources (order: weakest to strongest)\",\n );\n\nexport const experimentPermissionSchema = z\n .enum([\"CAN_READ\", \"CAN_EDIT\", \"CAN_MANAGE\"])\n .describe(\n \"Permission for MLflow experiment resources (order: weakest to strongest)\",\n );\n\nexport const appPermissionSchema = z\n .enum([\"CAN_USE\"])\n .describe(\"Permission for Databricks App resources\");\n\n// ── Discovery descriptor (discriminated union) ───────────────────────────\n\n/**\n * Well-known Databricks resource kinds for which AppKit owns the CLI\n * command map. Plugins reference one of these via the `kind` variant of the\n * discovery descriptor; everything else falls back to the free-form `cli`\n * variant.\n *\n * Kept narrow on purpose: each entry costs an addition to\n * `RESOURCE_KIND_COMMANDS` below, which is the single source of truth for\n * how that kind is enumerated.\n */\nexport const resourceKindSchema = z\n .enum([\n \"warehouse\",\n \"genie_space\",\n \"postgres_project\",\n \"postgres_branch\",\n \"postgres_database\",\n \"volume\",\n ])\n .describe(\n \"Well-known Databricks resource kind whose listing command is owned by AppKit (see RESOURCE_KIND_COMMANDS).\",\n );\n\nexport const kindDiscoveryDescriptorSchema = z\n .object({\n type: z\n .literal(\"kind\")\n .describe(\n \"Discriminator: 'kind' uses the AppKit-owned command map for the named resourceKind.\",\n ),\n resourceKind: resourceKindSchema.describe(\n \"Reference to a well-known Databricks resource kind. AppKit owns the CLI command, response shape, and unwrap rules.\",\n ),\n select: z\n .string()\n .optional()\n .describe(\n \"Field name in the parsed CLI response used as the selected value (e.g., 'id'). Defaults to the kind's natural identifier when omitted.\",\n ),\n display: z\n .string()\n .optional()\n .describe(\n \"Field name in the parsed CLI response shown to the user in selection UI. Defaults to `select` if omitted.\",\n ),\n dependsOn: z\n .string()\n .optional()\n .describe(\n \"Name of a sibling field within the same resource that must be resolved first. Used to express ordering dependencies between resource fields.\",\n ),\n shortcut: z\n .string()\n .optional()\n .describe(\n \"Single-value fast-path command that returns exactly one value, skipping interactive selection.\",\n ),\n })\n .strict()\n .describe(\n \"Discovery via a well-known resource kind. AppKit owns the CLI command and unwrap rules for the named kind.\",\n );\n\n/**\n * Shell metacharacters rejected on free-form CLI command strings. Catches the\n * common foot-guns (statement separators, pipes, redirects via shell, command\n * substitution, newlines). Not a security boundary on its own — executors must\n * always pass these via argv, never shell-exec the string. Angle brackets are\n * permitted because `<PROFILE>` (and future `<…>` placeholders) are part of\n * the command-template convention.\n */\nconst SHELL_METACHAR_RE = /[;|&`$\\n\\r]/;\n\nexport const cliDiscoveryDescriptorSchema = z\n .object({\n type: z\n .literal(\"cli\")\n .describe(\n \"Discriminator: 'cli' uses a free-form Databricks CLI command supplied by the plugin.\",\n ),\n cliCommand: z\n .string()\n .describe(\n \"Databricks CLI command that lists resources. Must include <PROFILE>. Shell metacharacters (;|&`$ and newlines) are rejected; for first-party Databricks resources prefer the `kind` variant which uses AppKit's typed command map.\",\n ),\n selectField: z\n .string()\n .describe(\n \"jq-style path to the field used as the selected value (e.g., '.id', '.name').\",\n ),\n displayField: z\n .string()\n .optional()\n .describe(\n \"jq-style path to the field shown to the user in selection UI. Defaults to selectField if omitted.\",\n ),\n dependsOn: z\n .string()\n .optional()\n .describe(\n \"Name of a sibling field within the same resource that must be resolved first. Used to express ordering dependencies between resource fields.\",\n ),\n shortcut: z\n .string()\n .optional()\n .describe(\n \"Single-value fast-path command that returns exactly one value, skipping interactive selection. Shell metacharacters are rejected.\",\n ),\n })\n .strict()\n .refine((descriptor) => descriptor.cliCommand.includes(\"<PROFILE>\"), {\n message: \"must include <PROFILE> placeholder\",\n path: [\"cliCommand\"],\n })\n .refine((descriptor) => !SHELL_METACHAR_RE.test(descriptor.cliCommand), {\n message:\n \"must not contain shell metacharacters (;|&`$ or newlines); use the `kind` variant for typed Databricks resources\",\n path: [\"cliCommand\"],\n })\n .refine(\n (descriptor) =>\n descriptor.shortcut === undefined ||\n !SHELL_METACHAR_RE.test(descriptor.shortcut),\n {\n message: \"must not contain shell metacharacters (;|&`$ or newlines)\",\n path: [\"shortcut\"],\n },\n )\n .describe(\n \"Discovery via a free-form Databricks CLI command. Escape hatch — prefer the `kind` variant when a typed resourceKind covers the resource. This shape is intentionally minimal and may tighten further in future versions.\",\n );\n\nexport const discoveryDescriptorSchema = z\n .discriminatedUnion(\"type\", [\n kindDiscoveryDescriptorSchema,\n cliDiscoveryDescriptorSchema,\n ])\n .describe(\n \"Describes how the CLI discovers values for a resource field. 'kind' references a well-known Databricks resource kind whose command is owned by AppKit; 'cli' is the escape hatch carrying a free-form Databricks CLI command.\",\n );\n\n// ── Resource kind → CLI command map ──────────────────────────────────────\n\n/**\n * Descriptor for how a well-known resource kind is listed via the\n * Databricks CLI.\n *\n * - `command` is the CLI invocation template. It carries two kinds of\n * placeholders:\n * - `<PROFILE>` — substituted with the user's CLI profile by the runner.\n * - `{<fieldName>}` — substituted with the resolved value of the named\n * sibling field (used for `dependsOn` chains).\n * - `unwrap`, when set, is the JSON path into the response wrapper (e.g.,\n * `\"warehouses\"` for `{ warehouses: [...] }`). Omitted when the response\n * is already a flat array.\n * - `parents`, when set, lists transient query inputs the runner must\n * collect (as free-text prompts) before invoking the command. Each\n * `parents[i]` value substitutes the matching `{name}` placeholder in\n * the command string. Unlike `dependsOn` (which references a sibling\n * field on the same resource), `parents` covers inputs that aren't\n * persisted as fields on the resource.\n */\nexport type ResourceKindCommand = {\n command: string;\n unwrap?: string;\n parents?: readonly string[];\n};\n\n/**\n * Single source of truth for AppKit-owned discovery commands.\n *\n * To add a new resource kind: extend `resourceKindSchema` and add an entry\n * here. Plugins reference the kind via `discovery: { type: \"kind\",\n * resourceKind: \"...\" }` and inherit the command + response shape.\n *\n * `unwrap` defaults are unset: the existing core plugin manifests use simple\n * jq paths (`.id`, `.name`, `.full_name`), implying the listed CLI commands\n * return flat arrays. Refine in a follow-up if a kind's CLI returns wrapped\n * data.\n *\n * Volume's catalog/schema parent context is supplied via the `parents`\n * array, which the runner collects from the user as free-text prompts\n * before invoking the listing command.\n */\nexport const RESOURCE_KIND_COMMANDS: Record<\n z.infer<typeof resourceKindSchema>,\n { command: string; unwrap?: string; parents?: readonly string[] }\n> = {\n warehouse: {\n command: \"databricks warehouses list --profile <PROFILE> --output json\",\n },\n genie_space: {\n command: \"databricks genie list-spaces --profile <PROFILE> --output json\",\n },\n postgres_project: {\n command:\n \"databricks postgres list-projects --profile <PROFILE> --output json\",\n },\n postgres_branch: {\n // {project} is a placeholder for the resolved value of the `project`\n // sibling field (declared via `dependsOn: \"project\"` on the kind variant).\n // The Databricks CLI requires the parent project resource name (format\n // `projects/{project_id}`) as a positional argument.\n command:\n \"databricks postgres list-branches {project} --profile <PROFILE> --output json\",\n },\n postgres_database: {\n // {branch} is a placeholder for the resolved value of the `branch`\n // sibling field (declared via `dependsOn: \"branch\"` on the kind variant).\n command:\n \"databricks postgres list-databases {branch} --profile <PROFILE> --output json\",\n },\n volume: {\n // `parents` declares free-text user prompts the runner must collect before\n // invoking the discovery command. Each `parents[i]` value substitutes the\n // matching `{name}` placeholder in the command string above. Unlike\n // `dependsOn` (which references a sibling field on the same resource),\n // `parents` covers transient query inputs that aren't persisted as fields.\n command:\n \"databricks volumes list {catalog} {schema} --profile <PROFILE> --output json\",\n parents: [\"catalog\", \"schema\"] as const,\n },\n};\n\n// ── Resource field entry (plugin manifest variant) ───────────────────────\n\nexport const resourceFieldEntrySchema = z\n .object({\n env: z\n .string()\n .regex(/^[A-Z][A-Z0-9_]*$/)\n .optional()\n .describe(\"Environment variable name for this field\"),\n description: z\n .string()\n .optional()\n .describe(\"Human-readable description for this field\"),\n bundleIgnore: z\n .boolean()\n .optional()\n .describe(\n \"When true, this field is excluded from Databricks bundle configuration (databricks.yml) generation.\",\n ),\n examples: z\n .array(z.string())\n .optional()\n .describe(\"Example values showing the expected format for this field\"),\n localOnly: z\n .boolean()\n .optional()\n .describe(\n \"When true, this field is only generated for local .env files. The Databricks Apps platform auto-injects it at deploy time.\",\n ),\n value: z\n .string()\n .optional()\n .describe(\n \"Static value for this field. Used when no prompted or resolved value exists.\",\n ),\n resolve: z\n .string()\n .regex(/^[a-z_]+:[a-zA-Z]+$/)\n .optional()\n .describe(\n \"Named resolver prefixed by resource type (e.g., 'postgres:host'). The CLI resolves this value during the init prompt flow.\",\n ),\n discovery: discoveryDescriptorSchema.optional(),\n })\n .strict()\n .describe(\n \"Defines a single field for a resource. Each field has its own environment variable and optional description. Single-value types use one key (e.g. id); multi-value types (database, secret) use multiple (e.g. instance_name, database_name or scope, key).\",\n );\n\n// ── Resource requirement (per-type permission discriminator) ─────────────\n\n/**\n * Build a per-type variant. Each variant fixes `type` to a literal and constrains\n * `permission` to the matching enum, mirroring the existing JSON Schema's\n * `allOf + if/then` block. `fields` and the rest of the shape come from a\n * shared base.\n */\nconst resourceRequirementBaseShape = {\n alias: z\n .string()\n .min(1)\n .describe(\n \"Human-readable label for UI/display only. Deduplication uses resourceKey, not alias.\",\n ),\n resourceKey: z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/)\n .describe(\n \"Stable key for machine use: deduplication, env naming, composite keys, app.yaml. Required for registry lookup.\",\n ),\n description: z\n .string()\n .min(1)\n .describe(\"Human-readable description of why this resource is needed\"),\n fields: z\n .record(z.string(), resourceFieldEntrySchema)\n .refine((obj) => Object.keys(obj).length >= 1, {\n message: \"fields must contain at least one entry\",\n })\n .optional()\n .describe(\n \"Map of field name to env and optional description. Single-value types use one key (e.g. id); multi-value (database, secret) use multiple (e.g. instance_name, database_name or scope, key).\",\n ),\n};\n\n/**\n * Adds the cycle/dangling-reference cross-field check to a resource variant.\n * Iterates the resource's `fields`, validates each `discovery.dependsOn` target\n * is a sibling field name, then runs DFS over the dependsOn graph to detect\n * cycles. Issue paths target either the offending field's `dependsOn` slot or\n * the resource itself for cycles.\n */\nfunction refineResourceDependsOn(\n resource: { fields?: Record<string, { discovery?: { dependsOn?: string } }> },\n ctx: z.core.$RefinementCtx,\n): void {\n if (!resource.fields) return;\n const fieldNames = new Set(Object.keys(resource.fields));\n\n // Pass 1: validate dependsOn references and build the dependency graph.\n const deps = new Map<string, string>();\n for (const [name, field] of Object.entries(resource.fields)) {\n const dep = field.discovery?.dependsOn;\n if (!dep) continue;\n if (!fieldNames.has(dep)) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"fields\", name, \"discovery\", \"dependsOn\"],\n message: `references non-existent sibling field '${dep}'`,\n });\n }\n deps.set(name, dep);\n }\n\n // Pass 2: detect cycles via DFS. Emit one issue per cycle found.\n const visited = new Set<string>();\n const visiting = new Set<string>();\n\n function dfs(node: string, chain: string[]): string[] | null {\n if (visiting.has(node)) return [...chain, node];\n if (visited.has(node)) return null;\n visiting.add(node);\n const next = deps.get(node);\n if (next) {\n const cycle = dfs(next, [...chain, node]);\n if (cycle) return cycle;\n }\n visiting.delete(node);\n visited.add(node);\n return null;\n }\n\n for (const node of deps.keys()) {\n if (visited.has(node)) continue;\n const cycle = dfs(node, []);\n if (cycle) {\n ctx.addIssue({\n code: \"custom\",\n path: [],\n message: `discovery.dependsOn creates a cycle: ${cycle.join(\" → \")}`,\n });\n // One cycle error per resource is enough.\n break;\n }\n }\n}\n\nfunction makeResourceVariant<\n TType extends z.ZodLiteral<string>,\n TPerm extends z.ZodTypeAny,\n>(typeLiteral: TType, permission: TPerm) {\n return z\n .object({\n type: typeLiteral,\n ...resourceRequirementBaseShape,\n permission: permission.describe(\n \"Required permission level. Validated per resource type.\",\n ),\n })\n .strict()\n .superRefine(refineResourceDependsOn);\n}\n\nexport const resourceRequirementSchema = z\n .discriminatedUnion(\"type\", [\n makeResourceVariant(z.literal(\"secret\"), secretPermissionSchema),\n makeResourceVariant(z.literal(\"job\"), jobPermissionSchema),\n makeResourceVariant(\n z.literal(\"sql_warehouse\"),\n sqlWarehousePermissionSchema,\n ),\n makeResourceVariant(\n z.literal(\"serving_endpoint\"),\n servingEndpointPermissionSchema,\n ),\n makeResourceVariant(z.literal(\"volume\"), volumePermissionSchema),\n makeResourceVariant(\n z.literal(\"vector_search_index\"),\n vectorSearchIndexPermissionSchema,\n ),\n makeResourceVariant(z.literal(\"uc_function\"), ucFunctionPermissionSchema),\n makeResourceVariant(\n z.literal(\"uc_connection\"),\n ucConnectionPermissionSchema,\n ),\n makeResourceVariant(z.literal(\"database\"), databasePermissionSchema),\n makeResourceVariant(z.literal(\"postgres\"), postgresPermissionSchema),\n makeResourceVariant(z.literal(\"genie_space\"), genieSpacePermissionSchema),\n makeResourceVariant(z.literal(\"experiment\"), experimentPermissionSchema),\n makeResourceVariant(z.literal(\"app\"), appPermissionSchema),\n ])\n .describe(\n \"Declares a resource requirement for a plugin. Can be defined statically in a manifest or dynamically via getResourceRequirements().\",\n );\n\n// ── Config schema (recursive) ────────────────────────────────────────────\n\nexport const configSchemaPropertySchema: z.ZodType = z.lazy(() =>\n z\n .object({\n type: z.enum([\n \"object\",\n \"array\",\n \"string\",\n \"number\",\n \"boolean\",\n \"integer\",\n ]),\n description: z.string().optional(),\n default: z.unknown().optional(),\n enum: z.array(z.unknown()).optional(),\n properties: z.record(z.string(), configSchemaPropertySchema).optional(),\n items: configSchemaPropertySchema.optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n minLength: z.number().int().min(0).optional(),\n maxLength: z.number().int().min(0).optional(),\n required: z.array(z.string()).optional(),\n // `additionalProperties` is a standard JSON Schema keyword used by core\n // plugin manifests (e.g., serving, ai-search, genie) to constrain\n // dictionary-shaped properties. Allowed on nested property entries as\n // either a boolean or a sub-schema, mirroring JSON Schema semantics.\n additionalProperties: z\n .union([z.boolean(), configSchemaPropertySchema])\n .optional(),\n })\n .strict(),\n);\n\nexport const configSchemaSchema: z.ZodType = z.lazy(() =>\n z\n .object({\n type: z.enum([\"object\", \"array\", \"string\", \"number\", \"boolean\"]),\n properties: z.record(z.string(), configSchemaPropertySchema).optional(),\n items: configSchemaSchema.optional(),\n required: z.array(z.string()).optional(),\n additionalProperties: z.boolean().optional(),\n })\n .strict(),\n);\n\n// ── Plugin-level scaffolding rules ───────────────────────────────────────\n\n/**\n * Per-item upper bound on plugin-level scaffolding rule strings. Matches the\n * template-level `SCAFFOLDING_RULE_MAX_LENGTH` defined below — rules at both\n * levels are short directives, not prose. The literal value lives here (and\n * not by reference to the template-side constant) because this declaration\n * is read in source order and the template constant is declared later.\n */\nconst PLUGIN_SCAFFOLDING_RULE_MAX_LENGTH = 120;\n\nconst pluginScaffoldingRuleItemSchema = z\n .string()\n .min(1)\n .max(\n PLUGIN_SCAFFOLDING_RULE_MAX_LENGTH,\n `rule entries must be ≤ ${PLUGIN_SCAFFOLDING_RULE_MAX_LENGTH} chars`,\n );\n\nexport const pluginScaffoldingRulesSchema = z\n .object({\n must: z\n .array(pluginScaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must always perform.\"),\n should: z\n .array(pluginScaffoldingRuleItemSchema)\n .optional()\n .describe(\"Recommended actions for the scaffolding agent.\"),\n never: z\n .array(pluginScaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must never perform.\"),\n })\n .strict()\n .superRefine((rules, ctx) => {\n // (a) Reject duplicate entries within any single array.\n const buckets: Array<[\"must\" | \"should\" | \"never\", string[] | undefined]> =\n [\n [\"must\", rules.must],\n [\"should\", rules.should],\n [\"never\", rules.never],\n ];\n for (const [bucketName, items] of buckets) {\n if (!items) continue;\n const seen = new Map<string, number>();\n items.forEach((item, idx) => {\n const prev = seen.get(item);\n if (prev === undefined) {\n seen.set(item, idx);\n return;\n }\n ctx.addIssue({\n code: \"custom\",\n path: [bucketName, idx],\n message: `duplicate rule entry: \"${item}\" already declared at index ${prev}`,\n });\n });\n }\n // (b) Reject a string that appears in more than one of must/should/never.\n type Bucket = \"must\" | \"should\" | \"never\";\n const owner = new Map<string, Bucket>();\n for (const [bucketName, items] of buckets) {\n if (!items) continue;\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const existing = owner.get(item);\n if (existing === undefined) {\n owner.set(item, bucketName);\n continue;\n }\n if (existing !== bucketName) {\n ctx.addIssue({\n code: \"custom\",\n path: [bucketName, i],\n message: `rule entry \"${item}\" appears in both '${existing}' and '${bucketName}'; rules must belong to exactly one bucket`,\n });\n }\n }\n }\n })\n .describe(\n \"Structured rules for scaffolding agents declared at the plugin level. Each rule is a short directive (≤120 chars).\",\n );\n\n// ── Plugin manifest (root) ───────────────────────────────────────────────\n\nexport const pluginManifestSchema = z\n .object({\n scopes: z\n .array(capabilityScopeSchema)\n .optional()\n .describe(\"Capability-only user_api_scopes with no resource ID.\"),\n $schema: z\n .string()\n .optional()\n .describe(\"Reference to the JSON Schema for validation\"),\n name: z\n .string()\n .regex(PLUGIN_NAME_PATTERN)\n .describe(\n \"Plugin identifier and JS binding. Must start with a lowercase letter; camelCase for multi-word names (e.g. aiSearch).\",\n ),\n displayName: z\n .string()\n .min(1)\n .describe(\"Human-readable display name for UI and CLI\"),\n description: z\n .string()\n .min(1)\n .describe(\"Brief description of what the plugin does\"),\n resources: z\n .object({\n required: z\n .array(resourceRequirementSchema)\n .describe(\n \"Resources that must be available for the plugin to function\",\n ),\n optional: z\n .array(resourceRequirementSchema)\n .describe(\n \"Resources that enhance functionality but are not mandatory\",\n ),\n })\n .strict()\n .describe(\"Databricks resource requirements for this plugin\"),\n config: z\n .object({\n schema: configSchemaSchema.optional(),\n })\n .strict()\n .optional()\n .describe(\"Configuration schema for the plugin\"),\n author: z.string().optional().describe(\"Author name or organization\"),\n version: z\n .string()\n .regex(/^\\d+\\.\\d+\\.\\d+(-[a-zA-Z0-9.]+)?$/)\n .optional()\n .describe(\"Plugin version (semver format)\"),\n repository: z\n .url()\n .optional()\n .describe(\"URL to the plugin's source repository\"),\n keywords: z\n .array(z.string())\n .optional()\n .describe(\"Keywords for plugin discovery\"),\n license: z.string().optional().describe(\"SPDX license identifier\"),\n onSetupMessage: z\n .string()\n .optional()\n .describe(\n \"Message displayed to the user after project initialization. Use this to inform about manual setup steps (e.g. environment variables, resource provisioning).\",\n ),\n hidden: z\n .boolean()\n .optional()\n .describe(\n \"When true, this plugin is excluded from the template plugins manifest (appkit.plugins.json) during sync.\",\n ),\n devOnly: z\n .boolean()\n .optional()\n .describe(\n \"When true, this plugin is only registered when NODE_ENV === 'development'. In any other environment createApp skips it entirely (not constructed, no routes, resources not validated). Use for dev-only tooling that must never run in a deployed app.\",\n ),\n stability: z\n .enum([\"beta\", \"ga\"])\n .optional()\n .describe(\n \"Plugin stability level. Beta plugins may have breaking API changes between minor releases but are on a path to GA. GA (general availability) plugins follow semver strictly.\",\n ),\n deprecated: z\n .boolean()\n .optional()\n .describe(\n \"When true, the plugin is deprecated. It still ships and functions, but tooling (e.g. `appkit plugin list`) may hide or flag it. The recommended replacement is noted in the plugin description.\",\n ),\n scaffolding: z\n .object({\n rules: pluginScaffoldingRulesSchema\n .optional()\n .describe(\n \"Structured rules for scaffolding agents declared at the plugin level.\",\n ),\n })\n .strict()\n .optional()\n .describe(\n \"Plugin-level scaffolding metadata consumed by scaffolding agents. Symmetric with template-level `scaffolding`.\",\n ),\n })\n .strict()\n .describe(\n \"Schema for Databricks AppKit plugin manifest files. Defines plugin metadata, resource requirements, and configuration options.\",\n );\n\n// ── Origin enum ──────────────────────────────────────────────────────────\n\nexport const originSchema = z\n .enum([\"user\", \"platform\", \"static\", \"cli\"])\n .describe(\n \"How the field value is determined. Computed during sync, not authored by plugin developers.\",\n );\n\n// ── Template field entry (origin computed by transform) ─────────────────\n\n/**\n * Derives the canonical origin of a resource field value from its shape.\n *\n * - `localOnly: true` → `\"platform\"` (auto-injected by the Databricks Apps\n * platform at deploy time; takes precedence over `value`/`resolve`).\n * - `value !== undefined` → `\"static\"` (hardcoded value).\n * - `resolve !== undefined` → `\"cli\"` (resolved by the CLI during init).\n * - else → `\"user\"` (user must provide the value at init time).\n *\n * The single source for this rule: `plugin sync`'s transform stamps `origin`\n * with it, and consumers that read an authored manifest (no stamped `origin`)\n * derive it through this rather than re-implementing the cascade.\n */\nexport function computeOriginFromField(field: {\n localOnly?: boolean;\n value?: string;\n resolve?: string;\n}): z.infer<typeof originSchema> {\n if (field.localOnly) return \"platform\";\n if (field.value !== undefined) return \"static\";\n if (field.resolve !== undefined) return \"cli\";\n return \"user\";\n}\n\n/**\n * Template field entry: extends the plugin manifest field entry with an\n * optional `origin` input slot, then runs a `.transform()` that overwrites\n * `origin` with the computed value. Allowing `origin` on input means\n * re-parsing a previously-synced template manifest does not fail; emitting\n * `origin` always means hand-edits in synced JSON are silently corrected\n * on the next parse — drift-by-construction.\n */\nexport const templateFieldEntrySchema = resourceFieldEntrySchema\n .extend({ origin: originSchema.optional() })\n .transform((field) => ({\n ...field,\n origin: computeOriginFromField(field),\n }));\n\n// ── Template resource requirement (uses templateFieldEntrySchema) ────────\n\nconst templateResourceRequirementBaseShape = {\n alias: z\n .string()\n .min(1)\n .describe(\"Human-readable label for UI/display only.\"),\n resourceKey: z\n .string()\n .regex(/^[a-z][a-z0-9-]*$/)\n .describe(\n \"Stable key for machine use: deduplication, env naming, composite keys.\",\n ),\n description: z\n .string()\n .min(1)\n .describe(\"Human-readable description of why this resource is needed\"),\n fields: z\n .record(z.string(), templateFieldEntrySchema)\n .refine((obj) => Object.keys(obj).length >= 1, {\n message: \"fields must contain at least one entry\",\n })\n .optional()\n .describe(\"Map of field name to field entry with computed origin.\"),\n};\n\nfunction makeTemplateResourceVariant<\n TType extends z.ZodLiteral<string>,\n TPerm extends z.ZodTypeAny,\n>(typeLiteral: TType, permission: TPerm) {\n return z\n .object({\n type: typeLiteral,\n ...templateResourceRequirementBaseShape,\n permission: permission.describe(\n \"Required permission level. Validated per resource type.\",\n ),\n })\n .strict()\n .superRefine(refineResourceDependsOn);\n}\n\nexport const templateResourceRequirementSchema = z\n .discriminatedUnion(\"type\", [\n makeTemplateResourceVariant(z.literal(\"secret\"), secretPermissionSchema),\n makeTemplateResourceVariant(z.literal(\"job\"), jobPermissionSchema),\n makeTemplateResourceVariant(\n z.literal(\"sql_warehouse\"),\n sqlWarehousePermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"serving_endpoint\"),\n servingEndpointPermissionSchema,\n ),\n makeTemplateResourceVariant(z.literal(\"volume\"), volumePermissionSchema),\n makeTemplateResourceVariant(\n z.literal(\"vector_search_index\"),\n vectorSearchIndexPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"uc_function\"),\n ucFunctionPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"uc_connection\"),\n ucConnectionPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"database\"),\n databasePermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"postgres\"),\n postgresPermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"genie_space\"),\n genieSpacePermissionSchema,\n ),\n makeTemplateResourceVariant(\n z.literal(\"experiment\"),\n experimentPermissionSchema,\n ),\n makeTemplateResourceVariant(z.literal(\"app\"), appPermissionSchema),\n ])\n .describe(\n \"Resource requirement with template-specific field entries (includes computed origin).\",\n );\n\n// ── Template plugin (extends plugin manifest) ────────────────────────────\n\nexport const templatePluginSchema = z\n .object({\n name: z\n .string()\n .regex(PLUGIN_NAME_PATTERN)\n .describe(\n \"Plugin identifier and JS binding. Must start with a lowercase letter; camelCase for multi-word names (e.g. aiSearch).\",\n ),\n displayName: z\n .string()\n .min(1)\n .describe(\"Human-readable display name for UI and CLI\"),\n description: z\n .string()\n .min(1)\n .describe(\"Brief description of what the plugin does\"),\n package: z\n .string()\n .min(1)\n .describe(\"NPM package name that provides this plugin\"),\n requiredByTemplate: z\n .boolean()\n .optional()\n .describe(\n \"When true, this plugin is required by the template and cannot be deselected during CLI init. The user will only be prompted to configure its resources. When absent or false, the plugin is optional and the user can choose whether to include it.\",\n ),\n onSetupMessage: z\n .string()\n .optional()\n .describe(\n \"Message displayed to the user after project initialization. Use this to inform about manual setup steps (e.g. environment variables, resource provisioning).\",\n ),\n stability: z\n .enum([\"beta\", \"ga\"])\n .optional()\n .describe(\n \"Plugin stability level. Beta is heading to GA; APIs may change between minor releases. GA (general availability) follows semver.\",\n ),\n deprecated: z\n .boolean()\n .optional()\n .describe(\n \"When true, the plugin is deprecated. It still ships and functions, but tooling (e.g. `appkit plugin list`) may hide or flag it. The recommended replacement is noted in the plugin description.\",\n ),\n scaffolding: z\n .object({\n rules: pluginScaffoldingRulesSchema\n .optional()\n .describe(\n \"Structured rules for scaffolding agents propagated from the plugin manifest.\",\n ),\n })\n .strict()\n .optional()\n .describe(\n \"Plugin-level scaffolding metadata propagated from the plugin manifest.\",\n ),\n resources: z\n .object({\n required: z\n .array(templateResourceRequirementSchema)\n .describe(\n \"Resources that must be available for the plugin to function\",\n ),\n optional: z\n .array(templateResourceRequirementSchema)\n .describe(\n \"Resources that enhance functionality but are not mandatory\",\n ),\n })\n .strict()\n .describe(\"Databricks resource requirements for this plugin\"),\n })\n .strict()\n .describe(\"Plugin manifest with package source information\");\n\n// ── Scaffolding descriptor ───────────────────────────────────────────────\n\nexport const scaffoldingFlagSchema = z\n .object({\n description: z.string().describe(\"Human-readable description of the flag.\"),\n required: z.boolean().optional().describe(\"Whether this flag is required.\"),\n pattern: z\n .string()\n .optional()\n .describe(\"Regex pattern for validating the flag value.\"),\n default: z.string().optional().describe(\"Default value for this flag.\"),\n })\n .strict()\n .describe(\"A flag for the scaffolding command.\");\n\n/**\n * Per-item upper bound on scaffolding rule strings. The intent is to enforce\n * \"short directive\" by contract — long paragraphs fail validation and force\n * authors to split prose into discrete actionable items.\n */\nconst SCAFFOLDING_RULE_MAX_LENGTH = 120;\n\nconst scaffoldingRuleItemSchema = z\n .string()\n .max(\n SCAFFOLDING_RULE_MAX_LENGTH,\n `rule item must be ≤ ${SCAFFOLDING_RULE_MAX_LENGTH} chars`,\n );\n\nexport const scaffoldingRulesSchema = z\n .object({\n never: z\n .array(scaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must never perform.\"),\n must: z\n .array(scaffoldingRuleItemSchema)\n .optional()\n .describe(\"Actions the scaffolding agent must always perform.\"),\n should: z\n .array(scaffoldingRuleItemSchema)\n .optional()\n .describe(\n \"Recommended actions for the scaffolding agent (parity with plugin-level rules).\",\n ),\n })\n .strict()\n .describe(\"Structured rules for scaffolding agents.\");\n\nexport const scaffoldingDescriptorSchema = z\n .object({\n command: z\n .string()\n .describe(\"The scaffolding command (e.g., 'databricks apps init').\"),\n flags: z\n .record(z.string(), scaffoldingFlagSchema)\n .optional()\n .describe(\"Map of flag name to flag descriptor.\"),\n rules: scaffoldingRulesSchema\n .optional()\n .describe(\"Structured rules for scaffolding agents.\"),\n })\n .strict()\n .describe(\n \"Describes the scaffolding command, flags, and rules for project initialization.\",\n );\n\n/**\n * Canonical scaffolding descriptor for the `databricks apps init` command,\n * embedded in v2.0 template manifests to guide scaffolding agents.\n *\n * Co-located with `scaffoldingDescriptorSchema` so any change to the rule set\n * (or the schema's `maxLength` ceiling) shows up next to its consumer. The\n * `satisfies` annotation gives compile-time validation that the literal\n * matches the schema's input shape; if a `must`/`never` entry exceeds the\n * `maxLength` ceiling at runtime, `scaffoldingDescriptorSchema.parse` would\n * surface the breach in tests.\n */\nexport const TEMPLATE_SCAFFOLDING = {\n command: \"databricks apps init\",\n flags: {\n \"--name\": {\n description:\n \"Project name — sets {{.projectName}} in package.json, databricks.yml, and .env. Required for non-interactive scaffolding.\",\n required: true,\n pattern: \"^[a-z][a-z0-9-]*$\",\n },\n \"--template\": {\n description: \"Template path (local directory or GitHub URL)\",\n required: false,\n },\n \"--version\": {\n description: \"AppKit version to use; defaults to auto-detected\",\n required: false,\n },\n \"--features\": {\n description:\n \"Plugins to enable (comma-separated, no spaces; must match keys in this manifest's plugins map)\",\n required: false,\n pattern: \"^[a-zA-Z0-9_-]+(,[a-zA-Z0-9_-]+)*$\",\n },\n \"--set\": {\n description:\n \"Set resource values (format: plugin.resourceKey.field=value, repeatable)\",\n required: false,\n },\n \"--output-dir\": {\n description: \"Directory to write the project to\",\n required: false,\n },\n \"--description\": {\n description: \"App description\",\n required: false,\n },\n \"--run\": {\n description: \"Run the app after creation (none, dev, dev-remote)\",\n required: false,\n },\n \"--auto-approve\": {\n description:\n \"Pass as a bare flag (no value) to skip prompts for optional resources. Not recommended for agent-driven init — conflicts with the 'ask user when in doubt' rule.\",\n required: false,\n },\n \"--profile\": {\n description:\n \"Databricks CLI profile to use for authentication (global flag)\",\n required: false,\n },\n },\n rules: {\n must: [\n \"Treat `databricks apps init` output as starter code, not requirements; adapt or replace it to match the requested app\",\n \"Keep all secrets and credentials only in app.yaml, databricks.yml, and/or .env\",\n ],\n should: [\"ask user when in doubt of resource to use for plugin\"],\n never: [\n \"guess resources when multiple or no options are available\",\n \"embed secrets in files that will go to the client-bundle\",\n ],\n },\n} satisfies z.infer<typeof scaffoldingDescriptorSchema>;\n\n// ── Template plugins manifest (root) ─────────────────────────────────────\n\nexport const templatePluginsManifestSchema = z\n .object({\n $schema: z\n .string()\n .optional()\n .describe(\"Reference to the JSON Schema for validation\"),\n version: z\n .enum([\"1.0\", \"1.1\", \"2.0\"])\n .describe(\"Schema version for the template plugins manifest\"),\n plugins: z\n .record(z.string(), templatePluginSchema)\n .describe(\"Map of plugin name to plugin manifest with package source\"),\n scaffolding: scaffoldingDescriptorSchema\n .optional()\n .describe(\n \"Describes the scaffolding command and its configuration for project initialization.\",\n ),\n })\n .strict()\n .superRefine((value, ctx) => {\n if (value.version === \"2.0\" && !value.scaffolding) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"scaffolding\"],\n message: \"scaffolding is required when version is '2.0'\",\n });\n }\n })\n .describe(\n \"Aggregated plugin manifest for AppKit templates. Read by Databricks CLI during init to discover available plugins and their resource requirements.\",\n );\n\n// ── Inferred types ───────────────────────────────────────────────────────\n\nexport type ResourceType = z.infer<typeof resourceTypeSchema>;\nexport type SecretPermission = z.infer<typeof secretPermissionSchema>;\nexport type JobPermission = z.infer<typeof jobPermissionSchema>;\nexport type SqlWarehousePermission = z.infer<\n typeof sqlWarehousePermissionSchema\n>;\nexport type ServingEndpointPermission = z.infer<\n typeof servingEndpointPermissionSchema\n>;\nexport type VolumePermission = z.infer<typeof volumePermissionSchema>;\nexport type VectorSearchIndexPermission = z.infer<\n typeof vectorSearchIndexPermissionSchema\n>;\nexport type UcFunctionPermission = z.infer<typeof ucFunctionPermissionSchema>;\nexport type UcConnectionPermission = z.infer<\n typeof ucConnectionPermissionSchema\n>;\nexport type DatabasePermission = z.infer<typeof databasePermissionSchema>;\nexport type PostgresPermission = z.infer<typeof postgresPermissionSchema>;\nexport type GenieSpacePermission = z.infer<typeof genieSpacePermissionSchema>;\nexport type ExperimentPermission = z.infer<typeof experimentPermissionSchema>;\nexport type AppPermission = z.infer<typeof appPermissionSchema>;\nexport type ResourceKind = z.infer<typeof resourceKindSchema>;\nexport type KindDiscoveryDescriptor = z.infer<\n typeof kindDiscoveryDescriptorSchema\n>;\nexport type CliDiscoveryDescriptor = z.infer<\n typeof cliDiscoveryDescriptorSchema\n>;\nexport type DiscoveryDescriptor = z.infer<typeof discoveryDescriptorSchema>;\nexport type ResourceFieldEntry = z.infer<typeof resourceFieldEntrySchema>;\nexport type ResourceRequirement = z.infer<typeof resourceRequirementSchema>;\nexport type ConfigSchemaProperty = z.infer<typeof configSchemaPropertySchema>;\nexport type ConfigSchema = z.infer<typeof configSchemaSchema>;\nexport type PluginScaffoldingRules = z.infer<\n typeof pluginScaffoldingRulesSchema\n>;\nexport type PluginManifest = z.infer<typeof pluginManifestSchema>;\nexport type Origin = z.infer<typeof originSchema>;\n// Template-side types use `z.input` so callers can construct a TemplatePlugin\n// from a parsed PluginManifest before the field-level origin transform runs.\n// `writeManifest` parses every field through `templateFieldEntrySchema` at\n// write-time, so the on-disk shape always has origin populated. The runtime\n// invariant: origin is *always* present after sync writes; the type slot\n// stays optional so the in-memory pipeline does not need to fabricate origin\n// before assignment.\nexport type TemplateFieldEntry = z.input<typeof templateFieldEntrySchema>;\nexport type TemplateResourceRequirement = z.input<\n typeof templateResourceRequirementSchema\n>;\nexport type TemplatePlugin = z.input<typeof templatePluginSchema>;\nexport type ScaffoldingFlag = z.infer<typeof scaffoldingFlagSchema>;\nexport type ScaffoldingRules = z.infer<typeof scaffoldingRulesSchema>;\nexport type ScaffoldingDescriptor = z.infer<typeof scaffoldingDescriptorSchema>;\nexport type TemplatePluginsManifest = z.input<\n typeof templatePluginsManifestSchema\n>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,qBAAqB,EAC/B,KAAK;CACJ;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC,CACD,SAAS,8BAA8B;;AAuB1C,MAAa,wBAAwB,EAAE,KAAK;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAIF,MAAa,yBAAyB,EACnC,KAAK;CAAC;CAAQ;CAAS;CAAS,CAAC,CACjC,SAAS,gEAAgE;AAE5E,MAAa,sBAAsB,EAChC,KAAK;CAAC;CAAY;CAAkB;CAAa,CAAC,CAClD,SAAS,6DAA6D;AAEzE,MAAa,+BAA+B,EACzC,KAAK,CAAC,WAAW,aAAa,CAAC,CAC/B,SACC,uEACD;AAEH,MAAa,kCAAkC,EAC5C,KAAK;CAAC;CAAY;CAAa;CAAa,CAAC,CAC7C,SACC,0EACD;AAEH,MAAa,yBAAyB,EACnC,KAAK,CAAC,eAAe,eAAe,CAAC,CACrC,SAAS,gDAAgD;AAE5D,MAAa,oCAAoC,EAC9C,KAAK,CAAC,SAAS,CAAC,CAChB,SAAS,+CAA+C;AAE3D,MAAa,6BAA6B,EACvC,KAAK,CAAC,UAAU,CAAC,CACjB,SAAS,kDAAkD;AAE9D,MAAa,+BAA+B,EACzC,K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AM,0BAA0B,CAChC,UAAU,CACV,SAAS,qDAAqD;CACjE,QAAQ,EACL,MAAM,0BAA0B,CAChC,UAAU,CACV,SACC,kFACD;CACJ,CAAC,CACD,QAAQ,CACR,SAAS,2CAA2C;AAEvD,MAAa,8BAA8B,EACxC,OAAO;CACN,SAAS,EACN,QAAQ,CACR,SAAS,0DAA0D;CACtE,OAAO,EACJ,OAAO,EAAE,QAAQ,EAAE,sBAAsB,CACzC,UAAU,CACV,SAAS,uCAAuC;CACnD,OAAO,uBACJ,UAAU,CACV,SAAS,2CAA2C;CACxD,CAAC,CACD,QAAQ,CACR,SACC,kFACD;AA+EH,MAAa,gCAAgC,EAC1C,OAAO;CACN,SAAS,EACN,QAAQ,CACR,UAAU,CACV,SAAS,8CAA8C;CAC1D,SAAS,EACN,KAAK;EAAC;EAAO;EAAO;EAAM,CAAC,CAC3B,SAAS,mDAAmD;CAC/D,SAAS,EACN,OAAO,EAAE,QAAQ,EAAE,qBAAqB,CACxC,SAAS,4DAA4D;CACxE,aAAa,4BACV,UAAU,CACV,SACC,sFACD;CACJ,CAAC,CACD,QAAQ,CACR,aAAa,OAAO,QAAQ;AAC3B,KAAI,MAAM,YAAY,SAAS,CAAC,MAAM,YACpC,KAAI,SAAS;EACX,MAAM;EACN,MAAM,CAAC,cAAc;EACrB,SAAS;EACV,CAAC;EAEJ,CACD,SACC,qJACD"}
@@ -29,13 +29,13 @@ function releaseEnvBaseline() {
29
29
  Object.assign(process.env, baseline);
30
30
  }
31
31
  /**
32
- * Point `ServiceContext.createUserContext` at the harness's mock so an `obo`
32
+ * Point `ServiceContext.createCallerContext` at the harness's mock so an `obo`
33
33
  * request does not construct a real SDK client from `DATABRICKS_HOST`.
34
34
  *
35
35
  * Mirrors the `createUserContextSpy` in `fixtures.ts`; returns its restore.
36
36
  */
37
37
  function stubUserContext(client) {
38
- const spy = vi.spyOn(ServiceContext, "createUserContext").mockImplementation((token, userId, userName, userEmail) => fakeUserContext(client, ServiceContext.get())(token, userId, userName, userEmail));
38
+ const spy = vi.spyOn(ServiceContext, "createCallerContext").mockImplementation((token, userId, userName, userEmail) => fakeUserContext(client, ServiceContext.get())(token, userId, userName, userEmail));
39
39
  return () => spy.mockRestore();
40
40
  }
41
41
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"create-test-app.js","names":[],"sources":["../../src/testing/create-test-app.ts"],"sourcesContent":["/**\n * Boot a real AppKit app with no workspace, credentials, or network, then call it\n * over real HTTP.\n */\n\nimport type { Server } from \"node:http\";\n\nimport type {\n CacheConfig,\n PluginConstructor,\n PluginData,\n PluginMap,\n} from \"shared\";\nimport { vi } from \"vitest\";\n\nimport { InMemoryStorage } from \"../cache/storage/memory\";\nimport { ServiceContext } from \"../context/service-context\";\nimport { AppKit, disposeApp } from \"../core/appkit\";\nimport type { WorkspaceClient } from \"../workspace-client\";\nimport type { OboOption } from \"./fixtures\";\nimport { fakeUserContext, oboHeaders, setupDatabricksEnv } from \"./fixtures\";\nimport type { CreateMockWorkspaceClientOptions } from \"./mock-workspace-client\";\nimport { createMockWorkspaceClient } from \"./mock-workspace-client\";\nimport { dropCoreSingletons } from \"./reset-singletons\";\n\n// Loose shapes are intentional here; `noExplicitAny` is off repo-wide (see\n// .oxlintrc.json), so a local alias keeps the intent readable.\ntype Any = any;\n\n/**\n * The env snapshot to restore on close, and whether an app currently holds it.\n *\n * One live app at a time (see the guard in `createTestApp`), so a flag suffices.\n */\nlet envBaseline: NodeJS.ProcessEnv | undefined;\nlet harnessAppLive = false;\n\n/** Take the baseline on boot. */\nfunction acquireEnvBaseline(): void {\n envBaseline = { ...process.env };\n harnessAppLive = true;\n}\n\n/** Restore the baseline on close. */\nfunction releaseEnvBaseline(): void {\n harnessAppLive = false;\n if (!envBaseline) return;\n\n const baseline = envBaseline;\n envBaseline = undefined;\n for (const key of Object.keys(process.env)) {\n if (!(key in baseline)) delete process.env[key];\n }\n Object.assign(process.env, baseline);\n}\n\n/** Plugin descriptors, exactly as `createApp` takes them. */\ntype Plugins = PluginData<PluginConstructor, unknown, string>[];\n\n/** Options for {@link createTestApp}. */\nexport interface CreateTestAppOptions<T extends Plugins> {\n /** The plugins under test, as `createApp` takes them. */\n plugins?: T;\n\n /** Dotted-path responses for the built-in mock. Refused when `client` is set. */\n responses?: CreateMockWorkspaceClientOptions[\"responses\"];\n\n /**\n * Make the built-in mock throw when a path with no declared response is\n * called, rather than resolving `undefined`. Refused when `client` is set —\n * configure it on your own client instead.\n */\n strict?: CreateMockWorkspaceClientOptions[\"strict\"];\n\n /**\n * Replaces the built-in mock. You then own `currentUser.me()` — boot reads\n * `currentUser.id` and fails without it.\n */\n client?: WorkspaceClient;\n\n /** Extra env for the boot, restored on `close()`; satisfies declared resources. */\n env?: Record<string, string>;\n\n /** No socket; setup, validation, and teardown still run, request methods throw. */\n server?: false;\n\n /**\n * Defaults to `\"test\"`. `\"development\"` is refused — it throws a `RangeError`\n * in `get-port` on `port: 0`, boots Vite, and relaxes validation.\n *\n * Beyond refusing `development`, this decides error-response redaction:\n * `errorHandlerMiddleware` returns the real message unless `NODE_ENV` is\n * `production`, where a 5xx becomes `\"Server error\"`. Pass `\"production\"` to\n * assert what a deployed app actually returns to a client.\n */\n nodeEnv?: string;\n\n /** Defaults to in-memory, which is what keeps boot offline. */\n cache?: CacheConfig;\n}\n\n/** Per-request options for the {@link TestApp} HTTP methods. */\nexport interface TestRequestOptions {\n /** A non-string value is JSON-encoded with `content-type: application/json`. */\n body?: unknown;\n /** Merged last, so they win over anything the harness sets. */\n headers?: Record<string, string>;\n /** Same convention as `createMockRequest({ obo })`. */\n obo?: OboOption;\n /** Forwarded to `fetch`. */\n signal?: AbortSignal;\n}\n\n/** A booted test app. */\nexport interface TestApp<T extends Plugins> {\n /**\n * Plugin exports by manifest name. Nested rather than spread because `get` and\n * `delete` are plausible plugin names and would collide with the request methods.\n */\n plugins: PluginMap<T>;\n /** The same object a handler resolves at runtime. */\n client: WorkspaceClient;\n /** e.g. `http://127.0.0.1:54321`. Throws when `server: false`. */\n baseUrl: string;\n /** The bound ephemeral port. Throws when `server: false`. */\n port: number;\n /** The underlying HTTP server, or `undefined` with `server: false`. */\n server?: Server;\n\n /** Release the app and restore env. Idempotent. */\n close(): Promise<void>;\n [Symbol.asyncDispose](): Promise<void>;\n\n get(path: string, options?: TestRequestOptions): Promise<Response>;\n post(path: string, options?: TestRequestOptions): Promise<Response>;\n put(path: string, options?: TestRequestOptions): Promise<Response>;\n patch(path: string, options?: TestRequestOptions): Promise<Response>;\n delete(path: string, options?: TestRequestOptions): Promise<Response>;\n}\n\n/**\n * Point `ServiceContext.createUserContext` at the harness's mock so an `obo`\n * request does not construct a real SDK client from `DATABRICKS_HOST`.\n *\n * Mirrors the `createUserContextSpy` in `fixtures.ts`; returns its restore.\n */\nfunction stubUserContext(client: WorkspaceClient): () => void {\n const spy = vi\n .spyOn(ServiceContext, \"createUserContext\")\n .mockImplementation((token, userId, userName, userEmail) =>\n fakeUserContext(client, ServiceContext.get())(\n token,\n userId,\n userName,\n userEmail,\n ),\n );\n return () => spy.mockRestore();\n}\n\n/**\n * Wait for a server to finish binding and return the port it landed on.\n *\n * Needed with `port: 0`: `start()` returns once `listen()` is invoked, before\n * the bind completes, so `address()` is null until the `listening` event fires.\n * `createTestApp` does this for you — reach for it when hand-rolling a server.\n */\nexport async function getListeningPort(server: Server): Promise<number> {\n const addr = server.address();\n if (addr && typeof addr === \"object\" && typeof addr.port === \"number\") {\n return addr.port;\n }\n await new Promise<void>((resolve, reject) => {\n server.once(\"listening\", () => resolve());\n server.once(\"error\", (err) => reject(err));\n });\n const ready = server.address();\n if (!ready || typeof ready !== \"object\") {\n throw new Error(\"Server is listening but address() returned null\");\n }\n return ready.port;\n}\n\n/**\n * Boot a real app — real Express wiring, routes, and resource validation — with\n * no workspace, credentials, or network. `createTestPluginContext` is cheaper\n * when you only need to unit-test wiring.\n *\n * Does **not** validate config values against `manifest.config.schema`; no\n * runtime validator exists for that.\n *\n * @example\n * ```ts\n * const app = await createTestApp({ plugins: [myPlugin()] });\n * try {\n * const res = await app.post(\"/api/my-plugin/thing\", { body: { q: 1 }, obo: true });\n * await expectStream(res).toEmit(\"status\", \"result\");\n * } finally {\n * await app.close();\n * }\n * ```\n */\nexport async function createTestApp<T extends Plugins>(\n options: CreateTestAppOptions<T> = {},\n): Promise<TestApp<T>> {\n const {\n plugins = [] as unknown as T,\n responses,\n strict,\n client: suppliedClient,\n env = {},\n server: serverOption,\n nodeEnv = \"test\",\n cache,\n } = options;\n\n if (nodeEnv === \"development\") {\n throw new Error(\n 'createTestApp: nodeEnv \"development\" is not supported. Dev mode routes ' +\n \"the harness's ephemeral `port: 0` through get-port, which throws a \" +\n \"RangeError, and it also boots a real Vite dev server, downgrades \" +\n \"resource validation to a warning, and stops filtering dev-only \" +\n \"plugins. Pin a port explicitly with your own server plugin if you \" +\n \"need dev behaviour.\",\n );\n }\n\n // Refused rather than half-supported: AppKit's workspace client, cache and\n // on-behalf-of fake are process-wide, so a second live app cannot own its\n // own. Checked before any mutation, so a refused boot leaves the live app\n // untouched.\n if (harnessAppLive) {\n throw new Error(\n \"createTestApp: a harness app is already open. AppKit's workspace \" +\n \"client, cache, and on-behalf-of fake are process-wide, so a second \" +\n \"app would not receive its own `client`/`responses`, and closing \" +\n \"either would un-fake the other's on-behalf-of path. Close the first \" +\n \"app before booting another — `await using`, or try/finally.\",\n );\n }\n\n // Wholesale rather than a whitelist: plugins read vars we cannot enumerate.\n acquireEnvBaseline();\n\n let app: Awaited<ReturnType<typeof AppKit._createApp>> | undefined;\n let restoreUserContext: (() => void) | undefined;\n\n // Runs the booted plugins' shutdown() hooks and closes the server it started;\n // the harness owns dropping the singletons and restoring env. The `as Any` is\n // the one escape hatch the symbol-keyed teardown forces on the harness.\n const disposeBooted = (a: unknown): Promise<void> => (a as Any)[disposeApp]();\n\n try {\n process.env.NODE_ENV = nodeEnv;\n\n // Redundant while NODE_ENV is pinned, but keeps the throw-on-missing-resource\n // contract if that pin ever changes. No opt-out: the warning path is\n // dev-only, and dev is refused.\n process.env.APPKIT_STRICT_VALIDATION = \"true\";\n\n // The workspace ID short-circuits getWorkspaceId's SCIM probe, which would\n // otherwise show up as an apiClient.request call.\n setupDatabricksEnv({\n DATABRICKS_WORKSPACE_ID: \"test-workspace-id\",\n ...env,\n });\n\n dropCoreSingletons();\n\n // `responses` only seeds the built-in mock, so alongside a caller-supplied\n // client it would silently do nothing. Refuse instead, matching the\n // `server: false` conflict below.\n if (suppliedClient && (responses !== undefined || strict !== undefined)) {\n throw new Error(\n \"createTestApp: `responses` and `strict` configure the built-in mock \" +\n \"client, so they do nothing when you also pass `client`. Drop them \" +\n \"and configure your own client instead.\",\n );\n }\n\n // Boot runs ServiceContext.createContext for real, which reads\n // currentUser.id — the mock's built-in default is what lets it through.\n const client =\n suppliedClient ?? createMockWorkspaceClient({ responses, strict });\n\n // createApp({ client }) installs only the service-principal client. An `obo`\n // request reaches ServiceContext.createUserContext, which builds a *real*\n // client from process.env.DATABRICKS_HOST — so the user-scoped path is faked\n // here too, or \"no network\" is false the moment a handler calls asUser.\n restoreUserContext = stubUserContext(client);\n\n // createApp never auto-adds a server, so without this there is nothing to\n // fetch. Lazily imported: the plugin runs dotenv.config() at module load, so\n // a static import would mutate a consumer's env on import of this kit.\n const hasServer = plugins.some((p) => p?.name === \"server\");\n if (serverOption === false && hasServer) {\n // The plugin would still bind a socket while the handle denied one existed.\n throw new Error(\n \"createTestApp: `server: false` conflicts with the server plugin in \" +\n \"`plugins`. Drop one — omit `server: false` to use your plugin, or \" +\n \"remove the plugin to boot without a socket.\",\n );\n }\n const bootPlugins = [...plugins] as Plugins;\n if (serverOption !== false && !hasServer) {\n const { server: serverPlugin } = await import(\"../plugins/server\");\n bootPlugins.push(serverPlugin({ port: 0, host: \"127.0.0.1\" }));\n }\n\n // Both extras are required to stay offline: without explicit storage the\n // cache builds its own client and probes Lakebase, and without the opt-out\n // TelemetryReporter fires an apiClient.request on boot.\n app = await AppKit._createApp({\n plugins: bootPlugins as Any,\n client,\n cache: cache ?? {\n storage: new InMemoryStorage({ enabled: true } as Any),\n },\n disableInternalTelemetry: true,\n // The harness boots repeatedly in one process and runs its own teardown,\n // so it must not accumulate SIGTERM/SIGINT handlers across boots.\n installSignalHandlers: false,\n });\n\n const serverExports = (app as Any).server;\n const httpServer: Server | undefined =\n serverOption === false ? undefined : serverExports?.getServer?.();\n const port = httpServer ? await getListeningPort(httpServer) : undefined;\n const baseUrl = port === undefined ? undefined : `http://127.0.0.1:${port}`;\n\n const bootedApp = app;\n let closed: Promise<void> | undefined;\n\n /** Memoized, so repeated calls are safe in nested `finally`s. */\n const close = () => {\n closed ??= (async () => {\n try {\n await disposeBooted(bootedApp);\n } finally {\n dropCoreSingletons();\n restoreUserContext?.();\n releaseEnvBaseline();\n }\n })();\n return closed;\n };\n\n const request = async (\n method: string,\n path: string,\n reqOptions: TestRequestOptions = {},\n ): Promise<Response> => {\n if (baseUrl === undefined) {\n throw new Error(\n \"createTestApp: no HTTP server was started (server: false), so \" +\n `${method} ${path} cannot be issued.`,\n );\n }\n\n const headers: Record<string, string> = {};\n if (reqOptions.obo) {\n Object.assign(headers, oboHeaders(reqOptions.obo));\n }\n\n let body: string | undefined;\n if (reqOptions.body !== undefined) {\n if (typeof reqOptions.body === \"string\") {\n body = reqOptions.body;\n } else {\n body = JSON.stringify(reqOptions.body);\n headers[\"content-type\"] = \"application/json\";\n }\n }\n\n // Caller headers last, so an explicit content-type or identity wins.\n // Lowercased first: `Headers` comma-joins case variants instead of\n // replacing, so a mixed-case override would corrupt the value into\n // \"alice, bob\" rather than win.\n for (const [name, value] of Object.entries(reqOptions.headers ?? {})) {\n headers[name.toLowerCase()] = value;\n }\n\n return fetch(new URL(path, baseUrl), {\n method,\n headers,\n body,\n signal: reqOptions.signal,\n });\n };\n\n return {\n plugins: bootedApp as unknown as PluginMap<T>,\n client,\n get baseUrl() {\n if (baseUrl === undefined) {\n throw new Error(\n \"createTestApp: no HTTP server was started (server: false).\",\n );\n }\n return baseUrl;\n },\n get port() {\n if (port === undefined) {\n throw new Error(\n \"createTestApp: no HTTP server was started (server: false).\",\n );\n }\n return port;\n },\n server: httpServer,\n close,\n [Symbol.asyncDispose]: close,\n get: (path, o) => request(\"GET\", path, o),\n post: (path, o) => request(\"POST\", path, o),\n put: (path, o) => request(\"PUT\", path, o),\n patch: (path, o) => request(\"PATCH\", path, o),\n delete: (path, o) => request(\"DELETE\", path, o),\n };\n } catch (err) {\n // Teardown must run from the failure path too, or the boot leaks env\n // mutations and singletons into every later test in the file.\n if (app) {\n try {\n await disposeBooted(app);\n } catch {\n // The boot error is the interesting one; don't let teardown mask it.\n }\n }\n // dispose() no longer drops the singletons, and a failure before boot may\n // have left a partial init — drop unconditionally either way.\n dropCoreSingletons();\n restoreUserContext?.();\n releaseEnvBaseline();\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,IAAI;AACJ,IAAI,iBAAiB;;AAGrB,SAAS,qBAA2B;AAClC,eAAc,EAAE,GAAG,QAAQ,KAAK;AAChC,kBAAiB;;;AAInB,SAAS,qBAA2B;AAClC,kBAAiB;AACjB,KAAI,CAAC,YAAa;CAElB,MAAM,WAAW;AACjB,eAAc;AACd,MAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,IAAI,CACxC,KAAI,EAAE,OAAO,UAAW,QAAO,QAAQ,IAAI;AAE7C,QAAO,OAAO,QAAQ,KAAK,SAAS;;;;;;;;AA6FtC,SAAS,gBAAgB,QAAqC;CAC5D,MAAM,MAAM,GACT,MAAM,gBAAgB,oBAAoB,CAC1C,oBAAoB,OAAO,QAAQ,UAAU,cAC5C,gBAAgB,QAAQ,eAAe,KAAK,CAAC,CAC3C,OACA,QACA,UACA,UACD,CACF;AACH,cAAa,IAAI,aAAa;;;;;;;;;AAUhC,eAAsB,iBAAiB,QAAiC;CACtE,MAAM,OAAO,OAAO,SAAS;AAC7B,KAAI,QAAQ,OAAO,SAAS,YAAY,OAAO,KAAK,SAAS,SAC3D,QAAO,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;GACR;IACC,OAAO,eAAe;GACvB,MAAM,MAAM,MAAM,QAAQ,OAAO,MAAM,EAAE;GACzC,OAAO,MAAM,MAAM,QAAQ,QAAQ,MAAM,EAAE;GAC3C,MAAM,MAAM,MAAM,QAAQ,OAAO,MAAM,EAAE;GACzC,QAAQ,MAAM,MAAM,QAAQ,SAAS,MAAM,EAAE;GAC7C,SAAS,MAAM,MAAM,QAAQ,UAAU,MAAM,EAAE;GAChD;UACM,KAAK;AAGZ,MAAI,IACF,KAAI;AACF,SAAM,cAAc,IAAI;UAClB;AAMV,sBAAoB;AACpB,wBAAsB;AACtB,sBAAoB;AACpB,QAAM"}
1
+ {"version":3,"file":"create-test-app.js","names":[],"sources":["../../src/testing/create-test-app.ts"],"sourcesContent":["/**\n * Boot a real AppKit app with no workspace, credentials, or network, then call it\n * over real HTTP.\n */\n\nimport type { Server } from \"node:http\";\n\nimport type {\n CacheConfig,\n PluginConstructor,\n PluginData,\n PluginMap,\n} from \"shared\";\nimport { vi } from \"vitest\";\n\nimport { InMemoryStorage } from \"../cache/storage/memory\";\nimport { ServiceContext } from \"../context/service-context\";\nimport { AppKit, disposeApp } from \"../core/appkit\";\nimport type { WorkspaceClient } from \"../workspace-client\";\nimport type { OboOption } from \"./fixtures\";\nimport { fakeUserContext, oboHeaders, setupDatabricksEnv } from \"./fixtures\";\nimport type { CreateMockWorkspaceClientOptions } from \"./mock-workspace-client\";\nimport { createMockWorkspaceClient } from \"./mock-workspace-client\";\nimport { dropCoreSingletons } from \"./reset-singletons\";\n\n// Loose shapes are intentional here; `noExplicitAny` is off repo-wide (see\n// .oxlintrc.json), so a local alias keeps the intent readable.\ntype Any = any;\n\n/**\n * The env snapshot to restore on close, and whether an app currently holds it.\n *\n * One live app at a time (see the guard in `createTestApp`), so a flag suffices.\n */\nlet envBaseline: NodeJS.ProcessEnv | undefined;\nlet harnessAppLive = false;\n\n/** Take the baseline on boot. */\nfunction acquireEnvBaseline(): void {\n envBaseline = { ...process.env };\n harnessAppLive = true;\n}\n\n/** Restore the baseline on close. */\nfunction releaseEnvBaseline(): void {\n harnessAppLive = false;\n if (!envBaseline) return;\n\n const baseline = envBaseline;\n envBaseline = undefined;\n for (const key of Object.keys(process.env)) {\n if (!(key in baseline)) delete process.env[key];\n }\n Object.assign(process.env, baseline);\n}\n\n/** Plugin descriptors, exactly as `createApp` takes them. */\ntype Plugins = PluginData<PluginConstructor, unknown, string>[];\n\n/** Options for {@link createTestApp}. */\nexport interface CreateTestAppOptions<T extends Plugins> {\n /** The plugins under test, as `createApp` takes them. */\n plugins?: T;\n\n /** Dotted-path responses for the built-in mock. Refused when `client` is set. */\n responses?: CreateMockWorkspaceClientOptions[\"responses\"];\n\n /**\n * Make the built-in mock throw when a path with no declared response is\n * called, rather than resolving `undefined`. Refused when `client` is set —\n * configure it on your own client instead.\n */\n strict?: CreateMockWorkspaceClientOptions[\"strict\"];\n\n /**\n * Replaces the built-in mock. You then own `currentUser.me()` — boot reads\n * `currentUser.id` and fails without it.\n */\n client?: WorkspaceClient;\n\n /** Extra env for the boot, restored on `close()`; satisfies declared resources. */\n env?: Record<string, string>;\n\n /** No socket; setup, validation, and teardown still run, request methods throw. */\n server?: false;\n\n /**\n * Defaults to `\"test\"`. `\"development\"` is refused — it throws a `RangeError`\n * in `get-port` on `port: 0`, boots Vite, and relaxes validation.\n *\n * Beyond refusing `development`, this decides error-response redaction:\n * `errorHandlerMiddleware` returns the real message unless `NODE_ENV` is\n * `production`, where a 5xx becomes `\"Server error\"`. Pass `\"production\"` to\n * assert what a deployed app actually returns to a client.\n */\n nodeEnv?: string;\n\n /** Defaults to in-memory, which is what keeps boot offline. */\n cache?: CacheConfig;\n}\n\n/** Per-request options for the {@link TestApp} HTTP methods. */\nexport interface TestRequestOptions {\n /** A non-string value is JSON-encoded with `content-type: application/json`. */\n body?: unknown;\n /** Merged last, so they win over anything the harness sets. */\n headers?: Record<string, string>;\n /** Same convention as `createMockRequest({ obo })`. */\n obo?: OboOption;\n /** Forwarded to `fetch`. */\n signal?: AbortSignal;\n}\n\n/** A booted test app. */\nexport interface TestApp<T extends Plugins> {\n /**\n * Plugin exports by manifest name. Nested rather than spread because `get` and\n * `delete` are plausible plugin names and would collide with the request methods.\n */\n plugins: PluginMap<T>;\n /** The same object a handler resolves at runtime. */\n client: WorkspaceClient;\n /** e.g. `http://127.0.0.1:54321`. Throws when `server: false`. */\n baseUrl: string;\n /** The bound ephemeral port. Throws when `server: false`. */\n port: number;\n /** The underlying HTTP server, or `undefined` with `server: false`. */\n server?: Server;\n\n /** Release the app and restore env. Idempotent. */\n close(): Promise<void>;\n [Symbol.asyncDispose](): Promise<void>;\n\n get(path: string, options?: TestRequestOptions): Promise<Response>;\n post(path: string, options?: TestRequestOptions): Promise<Response>;\n put(path: string, options?: TestRequestOptions): Promise<Response>;\n patch(path: string, options?: TestRequestOptions): Promise<Response>;\n delete(path: string, options?: TestRequestOptions): Promise<Response>;\n}\n\n/**\n * Point `ServiceContext.createCallerContext` at the harness's mock so an `obo`\n * request does not construct a real SDK client from `DATABRICKS_HOST`.\n *\n * Mirrors the `createUserContextSpy` in `fixtures.ts`; returns its restore.\n */\nfunction stubUserContext(client: WorkspaceClient): () => void {\n const spy = vi\n .spyOn(ServiceContext, \"createCallerContext\")\n .mockImplementation((token, userId, userName, userEmail) =>\n fakeUserContext(client, ServiceContext.get())(\n token,\n userId,\n userName,\n userEmail,\n ),\n );\n return () => spy.mockRestore();\n}\n\n/**\n * Wait for a server to finish binding and return the port it landed on.\n *\n * Needed with `port: 0`: `start()` returns once `listen()` is invoked, before\n * the bind completes, so `address()` is null until the `listening` event fires.\n * `createTestApp` does this for you — reach for it when hand-rolling a server.\n */\nexport async function getListeningPort(server: Server): Promise<number> {\n const addr = server.address();\n if (addr && typeof addr === \"object\" && typeof addr.port === \"number\") {\n return addr.port;\n }\n await new Promise<void>((resolve, reject) => {\n server.once(\"listening\", () => resolve());\n server.once(\"error\", (err) => reject(err));\n });\n const ready = server.address();\n if (!ready || typeof ready !== \"object\") {\n throw new Error(\"Server is listening but address() returned null\");\n }\n return ready.port;\n}\n\n/**\n * Boot a real app — real Express wiring, routes, and resource validation — with\n * no workspace, credentials, or network. `createTestPluginContext` is cheaper\n * when you only need to unit-test wiring.\n *\n * Does **not** validate config values against `manifest.config.schema`; no\n * runtime validator exists for that.\n *\n * @example\n * ```ts\n * const app = await createTestApp({ plugins: [myPlugin()] });\n * try {\n * const res = await app.post(\"/api/my-plugin/thing\", { body: { q: 1 }, obo: true });\n * await expectStream(res).toEmit(\"status\", \"result\");\n * } finally {\n * await app.close();\n * }\n * ```\n */\nexport async function createTestApp<T extends Plugins>(\n options: CreateTestAppOptions<T> = {},\n): Promise<TestApp<T>> {\n const {\n plugins = [] as unknown as T,\n responses,\n strict,\n client: suppliedClient,\n env = {},\n server: serverOption,\n nodeEnv = \"test\",\n cache,\n } = options;\n\n if (nodeEnv === \"development\") {\n throw new Error(\n 'createTestApp: nodeEnv \"development\" is not supported. Dev mode routes ' +\n \"the harness's ephemeral `port: 0` through get-port, which throws a \" +\n \"RangeError, and it also boots a real Vite dev server, downgrades \" +\n \"resource validation to a warning, and stops filtering dev-only \" +\n \"plugins. Pin a port explicitly with your own server plugin if you \" +\n \"need dev behaviour.\",\n );\n }\n\n // Refused rather than half-supported: AppKit's workspace client, cache and\n // on-behalf-of fake are process-wide, so a second live app cannot own its\n // own. Checked before any mutation, so a refused boot leaves the live app\n // untouched.\n if (harnessAppLive) {\n throw new Error(\n \"createTestApp: a harness app is already open. AppKit's workspace \" +\n \"client, cache, and on-behalf-of fake are process-wide, so a second \" +\n \"app would not receive its own `client`/`responses`, and closing \" +\n \"either would un-fake the other's on-behalf-of path. Close the first \" +\n \"app before booting another — `await using`, or try/finally.\",\n );\n }\n\n // Wholesale rather than a whitelist: plugins read vars we cannot enumerate.\n acquireEnvBaseline();\n\n let app: Awaited<ReturnType<typeof AppKit._createApp>> | undefined;\n let restoreUserContext: (() => void) | undefined;\n\n // Runs the booted plugins' shutdown() hooks and closes the server it started;\n // the harness owns dropping the singletons and restoring env. The `as Any` is\n // the one escape hatch the symbol-keyed teardown forces on the harness.\n const disposeBooted = (a: unknown): Promise<void> => (a as Any)[disposeApp]();\n\n try {\n process.env.NODE_ENV = nodeEnv;\n\n // Redundant while NODE_ENV is pinned, but keeps the throw-on-missing-resource\n // contract if that pin ever changes. No opt-out: the warning path is\n // dev-only, and dev is refused.\n process.env.APPKIT_STRICT_VALIDATION = \"true\";\n\n // The workspace ID short-circuits getWorkspaceId's SCIM probe, which would\n // otherwise show up as an apiClient.request call.\n setupDatabricksEnv({\n DATABRICKS_WORKSPACE_ID: \"test-workspace-id\",\n ...env,\n });\n\n dropCoreSingletons();\n\n // `responses` only seeds the built-in mock, so alongside a caller-supplied\n // client it would silently do nothing. Refuse instead, matching the\n // `server: false` conflict below.\n if (suppliedClient && (responses !== undefined || strict !== undefined)) {\n throw new Error(\n \"createTestApp: `responses` and `strict` configure the built-in mock \" +\n \"client, so they do nothing when you also pass `client`. Drop them \" +\n \"and configure your own client instead.\",\n );\n }\n\n // Boot runs ServiceContext.createContext for real, which reads\n // currentUser.id — the mock's built-in default is what lets it through.\n const client =\n suppliedClient ?? createMockWorkspaceClient({ responses, strict });\n\n // createApp({ client }) installs only the service-principal client. An `obo`\n // request reaches ServiceContext.createCallerContext, which builds a *real*\n // client from process.env.DATABRICKS_HOST — so the user-scoped path is faked\n // here too, or \"no network\" is false the moment a handler calls asUser.\n restoreUserContext = stubUserContext(client);\n\n // createApp never auto-adds a server, so without this there is nothing to\n // fetch. Lazily imported: the plugin runs dotenv.config() at module load, so\n // a static import would mutate a consumer's env on import of this kit.\n const hasServer = plugins.some((p) => p?.name === \"server\");\n if (serverOption === false && hasServer) {\n // The plugin would still bind a socket while the handle denied one existed.\n throw new Error(\n \"createTestApp: `server: false` conflicts with the server plugin in \" +\n \"`plugins`. Drop one — omit `server: false` to use your plugin, or \" +\n \"remove the plugin to boot without a socket.\",\n );\n }\n const bootPlugins = [...plugins] as Plugins;\n if (serverOption !== false && !hasServer) {\n const { server: serverPlugin } = await import(\"../plugins/server\");\n bootPlugins.push(serverPlugin({ port: 0, host: \"127.0.0.1\" }));\n }\n\n // Both extras are required to stay offline: without explicit storage the\n // cache builds its own client and probes Lakebase, and without the opt-out\n // TelemetryReporter fires an apiClient.request on boot.\n app = await AppKit._createApp({\n plugins: bootPlugins as Any,\n client,\n cache: cache ?? {\n storage: new InMemoryStorage({ enabled: true } as Any),\n },\n disableInternalTelemetry: true,\n // The harness boots repeatedly in one process and runs its own teardown,\n // so it must not accumulate SIGTERM/SIGINT handlers across boots.\n installSignalHandlers: false,\n });\n\n const serverExports = (app as Any).server;\n const httpServer: Server | undefined =\n serverOption === false ? undefined : serverExports?.getServer?.();\n const port = httpServer ? await getListeningPort(httpServer) : undefined;\n const baseUrl = port === undefined ? undefined : `http://127.0.0.1:${port}`;\n\n const bootedApp = app;\n let closed: Promise<void> | undefined;\n\n /** Memoized, so repeated calls are safe in nested `finally`s. */\n const close = () => {\n closed ??= (async () => {\n try {\n await disposeBooted(bootedApp);\n } finally {\n dropCoreSingletons();\n restoreUserContext?.();\n releaseEnvBaseline();\n }\n })();\n return closed;\n };\n\n const request = async (\n method: string,\n path: string,\n reqOptions: TestRequestOptions = {},\n ): Promise<Response> => {\n if (baseUrl === undefined) {\n throw new Error(\n \"createTestApp: no HTTP server was started (server: false), so \" +\n `${method} ${path} cannot be issued.`,\n );\n }\n\n const headers: Record<string, string> = {};\n if (reqOptions.obo) {\n Object.assign(headers, oboHeaders(reqOptions.obo));\n }\n\n let body: string | undefined;\n if (reqOptions.body !== undefined) {\n if (typeof reqOptions.body === \"string\") {\n body = reqOptions.body;\n } else {\n body = JSON.stringify(reqOptions.body);\n headers[\"content-type\"] = \"application/json\";\n }\n }\n\n // Caller headers last, so an explicit content-type or identity wins.\n // Lowercased first: `Headers` comma-joins case variants instead of\n // replacing, so a mixed-case override would corrupt the value into\n // \"alice, bob\" rather than win.\n for (const [name, value] of Object.entries(reqOptions.headers ?? {})) {\n headers[name.toLowerCase()] = value;\n }\n\n return fetch(new URL(path, baseUrl), {\n method,\n headers,\n body,\n signal: reqOptions.signal,\n });\n };\n\n return {\n plugins: bootedApp as unknown as PluginMap<T>,\n client,\n get baseUrl() {\n if (baseUrl === undefined) {\n throw new Error(\n \"createTestApp: no HTTP server was started (server: false).\",\n );\n }\n return baseUrl;\n },\n get port() {\n if (port === undefined) {\n throw new Error(\n \"createTestApp: no HTTP server was started (server: false).\",\n );\n }\n return port;\n },\n server: httpServer,\n close,\n [Symbol.asyncDispose]: close,\n get: (path, o) => request(\"GET\", path, o),\n post: (path, o) => request(\"POST\", path, o),\n put: (path, o) => request(\"PUT\", path, o),\n patch: (path, o) => request(\"PATCH\", path, o),\n delete: (path, o) => request(\"DELETE\", path, o),\n };\n } catch (err) {\n // Teardown must run from the failure path too, or the boot leaks env\n // mutations and singletons into every later test in the file.\n if (app) {\n try {\n await disposeBooted(app);\n } catch {\n // The boot error is the interesting one; don't let teardown mask it.\n }\n }\n // dispose() no longer drops the singletons, and a failure before boot may\n // have left a partial init — drop unconditionally either way.\n dropCoreSingletons();\n restoreUserContext?.();\n releaseEnvBaseline();\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,IAAI;AACJ,IAAI,iBAAiB;;AAGrB,SAAS,qBAA2B;AAClC,eAAc,EAAE,GAAG,QAAQ,KAAK;AAChC,kBAAiB;;;AAInB,SAAS,qBAA2B;AAClC,kBAAiB;AACjB,KAAI,CAAC,YAAa;CAElB,MAAM,WAAW;AACjB,eAAc;AACd,MAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,IAAI,CACxC,KAAI,EAAE,OAAO,UAAW,QAAO,QAAQ,IAAI;AAE7C,QAAO,OAAO,QAAQ,KAAK,SAAS;;;;;;;;AA6FtC,SAAS,gBAAgB,QAAqC;CAC5D,MAAM,MAAM,GACT,MAAM,gBAAgB,sBAAsB,CAC5C,oBAAoB,OAAO,QAAQ,UAA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;IACnC;IACA;IACA;IACA,QAAQ,WAAW;IACpB,CAAC;;AAGJ,SAAO;GACL,SAAS;GACT;GACA,IAAI,UAAU;AACZ,QAAI,YAAY,OACd,OAAM,IAAI,MACR,6DACD;AAEH,WAAO;;GAET,IAAI,OAAO;AACT,QAAI,SAAS,OACX,OAAM,IAAI,MACR,6DACD;AAEH,WAAO;;GAET,QAAQ;GACR;IACC,OAAO,eAAe;GACvB,MAAM,MAAM,MAAM,QAAQ,OAAO,MAAM,EAAE;GACzC,OAAO,MAAM,MAAM,QAAQ,QAAQ,MAAM,EAAE;GAC3C,MAAM,MAAM,MAAM,QAAQ,OAAO,MAAM,EAAE;GACzC,QAAQ,MAAM,MAAM,QAAQ,SAAS,MAAM,EAAE;GAC7C,SAAS,MAAM,MAAM,QAAQ,UAAU,MAAM,EAAE;GAChD;UACM,KAAK;AAGZ,MAAI,IACF,KAAI;AACF,SAAM,cAAc,IAAI;UAClB;AAMV,sBAAoB;AACpB,wBAAsB;AACtB,sBAAoB;AACpB,QAAM"}
@@ -160,8 +160,9 @@ interface TestContextOptions {
160
160
  }
161
161
  /**
162
162
  * Mocks the `ServiceContext` singleton for testing — spies `get`,
163
- * `initialize`, `isInitialized`, and `createUserContext` so code that resolves
163
+ * `initialize`, `isInitialized`, and `createCallerContext` so code that resolves
164
164
  * the service principal or an on-behalf-of user context gets test doubles.
165
+ * Also supplies the app-level warehouse binding through WarehouseResource.
165
166
  * Call in `beforeEach`; call the returned `restore()` in `afterEach`.
166
167
  *
167
168
  * @returns The mock context plus the spies and a `restore()` helper.
@@ -171,7 +172,7 @@ declare function mockServiceContext(options?: TestContextOptions): {
171
172
  getSpy: vitest.MockInstance<typeof ServiceContext.get>;
172
173
  initSpy: vitest.MockInstance<typeof ServiceContext.initialize>;
173
174
  isInitializedSpy: vitest.MockInstance<typeof ServiceContext.isInitialized>;
174
- createUserContextSpy: vitest.MockInstance<typeof ServiceContext.createUserContext>;
175
+ createUserContextSpy: vitest.MockInstance<typeof ServiceContext.createCallerContext>;
175
176
  restore: () => void;
176
177
  };
177
178
  /** The handle {@link mockServiceContext} returns (spies + `restore`). */
@@ -1 +1 @@
1
- {"version":3,"file":"fixtures.d.ts","names":[],"sources":["../../src/testing/fixtures.ts"],"mappings":";;;;;;;;;KAgBK,GAAA;;;;AAL0C;;;iBAa/B,mBAAA,CAAA,GAAuB,UAAA;;AAAvC;;;iBAqDgB,gBAAA,CAAA;EACd,MAAA,EAAQ,UAAA;EACR,QAAA,EAAU,MAAA,SAAe,GAAA;EACzB,UAAA,GAAa,MAAA,UAAgB,IAAA,aAAiB,GAAA;AAAA;;;;;;;;KAqCpC,SAAA;EAtCV,sDA0CI,MAAA,WA1CqB;EA4CrB,KAAA,WA3CS;EA6CT,KAAA;AAAA;;;;;;;;;;;;;;;;iBAiFU,iBAAA,CAAkB,SAAA,GAAW,GAAA;;;;;;;;;;;;;;;;;iBA+C7B,kBAAA,CAAA;;UAAkB,MAAA,CAAA,IAAA;;QAWC,MAAA,CAAA,IAAA,QAAH,GAAA;;OAKE,MAAA,CAAA,IAAA,QAAH,GAAA,EAAG,KAAA;SAcE,MAAA,CAAA,IAAA,QAAH,GAAA,EAAG,KAAA;aAOI,MAAA,CAAA,IAAA,QAAH,GAAA;;;MAST,MAAA,CAAA,IAAA,QAFhB,GAAA,EAAG,KAAA,UACI,OAAA,MACA,IAAA,EAAM,GAAA;OAWG,MAAA,CAAA,IAAA,QAFhB,GAAA,EAAG,KAAA,UACI,OAAA,MACA,IAAA,EAAM,GAAA;;;;;;;;iBAgBN,QAAA;AAAA;;;;;iBAWH,kBAAA,CAAmB,SAAA,GAAW,MAAA;;;;;;AAA9C;;;;;AAmEA;;;;;;;;;;;;;;;iBAAgB,OAAA,GAAA,CACd,IAAA,EAAM,MAAA,kBACN,EAAA,QAAU,CAAA,GAAI,OAAA,CAAQ,CAAA,IACrB,CAAA,GAAI,OAAA,CAAQ,CAAA;;;;;;;;;AAmDf;;;;;AAcA;;;;;;iBAdsB,cA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,CAAQ,CAAA;;;;;iBAcK,2BAAA,CACd,IAAA,EAAM,GAAA,MACN,OAAA,EAAS,KAAA;EAAQ,IAAA;EAAc,SAAA;AAAA;;;;;;;;;;;;;;;;;;iBAoBjB,uBAAA,CAAwB,YAAA;;;;;;;;;;AAAxC;;;;;;;;;;;;AA+BA;;;;;;iBAAgB,cAAA,CAAe,OAAA;EAC7B,UAAA;EACA,OAAA;EACA,SAAA;AAAA,IACE,QAAA"}
@@ -1,6 +1,8 @@
1
1
  import { ApiError } from "../shared/src/workspace-client/errors.js";
2
2
  import { AuthenticationError } from "../errors/authentication.js";
3
3
  import "../errors/index.js";
4
+ import { WarehouseResource } from "../resources/warehouse.js";
5
+ import { snapshotCallerContext } from "../context/caller-context.js";
4
6
  import { ServiceContext } from "../context/service-context.js";
5
7
  import { CacheManager } from "../cache/index.js";
6
8
  import { createMockWorkspaceClient } from "./mock-workspace-client.js";
@@ -74,7 +76,7 @@ function createMockRouter() {
74
76
  };
75
77
  }
76
78
  /**
77
- * The one fake of `ServiceContext.createUserContext` this kit uses, shared by
79
+ * The one fake of `ServiceContext.createCallerContext` this kit uses, shared by
78
80
  * `mockServiceContext` and `createTestApp`.
79
81
  *
80
82
  * Shared rather than duplicated because the two used to disagree, and neither
@@ -88,16 +90,17 @@ function createMockRouter() {
88
90
  function fakeUserContext(client, ids) {
89
91
  return (token, userId, userName, userEmail) => {
90
92
  if (!token) throw AuthenticationError.missingToken("user token");
91
- return {
93
+ return snapshotCallerContext({
92
94
  client,
93
- userId,
94
- userName,
95
- userEmail,
95
+ principal: {
96
+ type: "user",
97
+ userId,
98
+ userName,
99
+ userEmail
100
+ },
96
101
  tokenFingerprint: createHash("sha256").update(token).digest("hex").slice(0, 16),
97
- warehouseId: ids.warehouseId,
98
- workspaceId: ids.workspaceId,
99
- isUserContext: true
100
- };
102
+ workspaceId: ids.workspaceId
103
+ });
101
104
  };
102
105
  }
103
106
  /**
@@ -319,28 +322,31 @@ async function resetTestCache() {
319
322
  * singleton. Internal building block for {@link mockServiceContext}, which
320
323
  * installs the state as spies — that installer is the public entry point.
321
324
  */
322
- function buildServiceContextState(options = {}) {
325
+ function buildServiceContextState(options, resources) {
323
326
  return {
324
327
  client: options.serviceDatabricksClient || createMockWorkspaceClient(),
325
328
  serviceUserId: options.serviceUserId || "test-service-user",
326
- warehouseId: Promise.resolve(options.warehouseId || "test-warehouse-id"),
329
+ warehouseId: resources.warehouseId,
327
330
  workspaceId: Promise.resolve(options.workspaceId || "test-workspace-id")
328
331
  };
329
332
  }
330
333
  /**
331
334
  * Mocks the `ServiceContext` singleton for testing — spies `get`,
332
- * `initialize`, `isInitialized`, and `createUserContext` so code that resolves
335
+ * `initialize`, `isInitialized`, and `createCallerContext` so code that resolves
333
336
  * the service principal or an on-behalf-of user context gets test doubles.
337
+ * Also supplies the app-level warehouse binding through WarehouseResource.
334
338
  * Call in `beforeEach`; call the returned `restore()` in `afterEach`.
335
339
  *
336
340
  * @returns The mock context plus the spies and a `restore()` helper.
337
341
  */
338
342
  function mockServiceContext(options = {}) {
339
- const serviceContext = buildServiceContextState(options);
343
+ const resources = Object.freeze({ warehouseId: Promise.resolve(options.warehouseId || "test-warehouse-id") });
344
+ const serviceContext = buildServiceContextState(options, resources);
345
+ const resourcesSpy = vi.spyOn(WarehouseResource, "get").mockReturnValue(resources);
340
346
  const getSpy = vi.spyOn(ServiceContext, "get").mockReturnValue(serviceContext);
341
347
  const initSpy = vi.spyOn(ServiceContext, "initialize").mockResolvedValue(serviceContext);
342
348
  const isInitializedSpy = vi.spyOn(ServiceContext, "isInitialized").mockReturnValue(true);
343
- const createUserContextSpy = vi.spyOn(ServiceContext, "createUserContext").mockImplementation(fakeUserContext(options.userDatabricksClient || createMockWorkspaceClient(), serviceContext));
349
+ const createUserContextSpy = vi.spyOn(ServiceContext, "createCallerContext").mockImplementation(fakeUserContext(options.userDatabricksClient || createMockWorkspaceClient(), serviceContext));
344
350
  return {
345
351
  serviceContext,
346
352
  getSpy,
@@ -352,6 +358,7 @@ function mockServiceContext(options = {}) {
352
358
  initSpy.mockRestore();
353
359
  isInitializedSpy.mockRestore();
354
360
  createUserContextSpy.mockRestore();
361
+ resourcesSpy.mockRestore();
355
362
  }
356
363
  };
357
364
  }