@databricks/appkit 0.61.0 → 0.62.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 (196) hide show
  1. package/CLAUDE.md +1 -0
  2. package/NOTICE.md +1 -0
  3. package/dist/agents/databricks.d.ts.map +1 -1
  4. package/dist/agents/databricks.js.map +1 -1
  5. package/dist/agents/supervisor-api.d.ts.map +1 -1
  6. package/dist/agents/supervisor-api.js.map +1 -1
  7. package/dist/app/index.d.ts.map +1 -1
  8. package/dist/app/index.js.map +1 -1
  9. package/dist/appkit/package.js +1 -1
  10. package/dist/cache/index.d.ts.map +1 -1
  11. package/dist/cache/index.js.map +1 -1
  12. package/dist/cache/storage/memory.js.map +1 -1
  13. package/dist/cache/storage/persistent.js.map +1 -1
  14. package/dist/cli/commands/codemod/index.js.map +1 -1
  15. package/dist/cli/commands/codemod/on-plugins-ready.js.map +1 -1
  16. package/dist/cli/commands/docs.js.map +1 -1
  17. package/dist/cli/commands/doctor/bundle.js.map +1 -1
  18. package/dist/cli/commands/doctor/index.js.map +1 -1
  19. package/dist/cli/commands/doctor/report.js.map +1 -1
  20. package/dist/cli/commands/doctor/resolve-targets.js +4 -6
  21. package/dist/cli/commands/doctor/resolve-targets.js.map +1 -1
  22. package/dist/cli/commands/doctor/run.js.map +1 -1
  23. package/dist/cli/commands/generate-types.js.map +1 -1
  24. package/dist/cli/commands/lint.js.map +1 -1
  25. package/dist/cli/commands/plugin/add-resource/add-resource.js.map +1 -1
  26. package/dist/cli/commands/plugin/create/create.js.map +1 -1
  27. package/dist/cli/commands/plugin/create/prompt-resource.js.map +1 -1
  28. package/dist/cli/commands/plugin/create/scaffold.js.map +1 -1
  29. package/dist/cli/commands/plugin/index.js.map +1 -1
  30. package/dist/cli/commands/plugin/list/list.js.map +1 -1
  31. package/dist/cli/commands/plugin/promote/promote.js.map +1 -1
  32. package/dist/cli/commands/plugin/sync/sync.js.map +1 -1
  33. package/dist/cli/commands/plugin/validate/validate-manifest.js.map +1 -1
  34. package/dist/cli/commands/plugin/validate/validate.js.map +1 -1
  35. package/dist/cli/commands/registry/add.js.map +1 -1
  36. package/dist/cli/commands/registry/client.js.map +1 -1
  37. package/dist/cli/commands/registry/config-writer.js.map +1 -1
  38. package/dist/cli/commands/registry/env-reconcile.js.map +1 -1
  39. package/dist/cli/commands/registry/env-writer.js.map +1 -1
  40. package/dist/cli/commands/registry/index.js.map +1 -1
  41. package/dist/cli/commands/registry/info.js.map +1 -1
  42. package/dist/cli/commands/registry/list.js.map +1 -1
  43. package/dist/cli/commands/registry/requirements.js.map +1 -1
  44. package/dist/cli/commands/registry/server-register.js.map +1 -1
  45. package/dist/cli/commands/registry/workspace-picker.js.map +1 -1
  46. package/dist/cli/commands/setup.js.map +1 -1
  47. package/dist/cli/index.js.map +1 -1
  48. package/dist/connectors/files/client.js.map +1 -1
  49. package/dist/connectors/lakebase/index.d.ts.map +1 -1
  50. package/dist/connectors/lakebase/index.js.map +1 -1
  51. package/dist/connectors/lakebase/pool-manager.d.ts.map +1 -1
  52. package/dist/connectors/lakebase/pool-manager.js.map +1 -1
  53. package/dist/connectors/lakebase/routing-pool.d.ts.map +1 -1
  54. package/dist/connectors/lakebase/routing-pool.js.map +1 -1
  55. package/dist/connectors/mcp/client.d.ts.map +1 -1
  56. package/dist/connectors/mcp/client.js.map +1 -1
  57. package/dist/connectors/sql-warehouse/client.js.map +1 -1
  58. package/dist/context/client-options.js.map +1 -1
  59. package/dist/context/execution-context.d.ts.map +1 -1
  60. package/dist/context/execution-context.js.map +1 -1
  61. package/dist/context/index.d.ts +1 -1
  62. package/dist/context/service-context.d.ts +55 -3
  63. package/dist/context/service-context.d.ts.map +1 -1
  64. package/dist/context/service-context.js.map +1 -1
  65. package/dist/core/agent/build-toolkit.js.map +1 -1
  66. package/dist/core/agent/load-agents.d.ts.map +1 -1
  67. package/dist/core/agent/load-agents.js.map +1 -1
  68. package/dist/core/agent/run-agent.d.ts.map +1 -1
  69. package/dist/core/agent/run-agent.js.map +1 -1
  70. package/dist/core/agent/toolkit-resolver.js.map +1 -1
  71. package/dist/core/agent/tools/define-tool.d.ts.map +1 -1
  72. package/dist/core/agent/tools/define-tool.js.map +1 -1
  73. package/dist/core/agent/tools/tool.d.ts.map +1 -1
  74. package/dist/core/agent/tools/tool.js.map +1 -1
  75. package/dist/core/agent/types.d.ts.map +1 -1
  76. package/dist/core/agent/types.js.map +1 -1
  77. package/dist/core/appkit.d.ts.map +1 -1
  78. package/dist/core/appkit.js.map +1 -1
  79. package/dist/core/lifecycle-manager.js.map +1 -1
  80. package/dist/core/plugin-context.d.ts +13 -0
  81. package/dist/core/plugin-context.d.ts.map +1 -1
  82. package/dist/core/plugin-context.js +12 -1
  83. package/dist/core/plugin-context.js.map +1 -1
  84. package/dist/errors/configuration.d.ts.map +1 -1
  85. package/dist/errors/configuration.js.map +1 -1
  86. package/dist/logging/logger.js.map +1 -1
  87. package/dist/logging/wide-event-emitter.js.map +1 -1
  88. package/dist/plugin/dev-reader.d.ts.map +1 -1
  89. package/dist/plugin/dev-reader.js.map +1 -1
  90. package/dist/plugin/interceptors/cache.js.map +1 -1
  91. package/dist/plugin/interceptors/retry.js.map +1 -1
  92. package/dist/plugin/interceptors/telemetry.js.map +1 -1
  93. package/dist/plugin/plugin.d.ts +2 -2
  94. package/dist/plugin/plugin.d.ts.map +1 -1
  95. package/dist/plugin/plugin.js.map +1 -1
  96. package/dist/plugins/agents/agents.d.ts.map +1 -1
  97. package/dist/plugins/agents/agents.js.map +1 -1
  98. package/dist/plugins/agents/event-translator.js.map +1 -1
  99. package/dist/plugins/agents/thread-store.js.map +1 -1
  100. package/dist/plugins/ai-search/ai-search.d.ts.map +1 -1
  101. package/dist/plugins/ai-search/ai-search.js.map +1 -1
  102. package/dist/plugins/analytics/analytics.d.ts.map +1 -1
  103. package/dist/plugins/analytics/analytics.js.map +1 -1
  104. package/dist/plugins/analytics/mv/cache.js.map +1 -1
  105. package/dist/plugins/analytics/mv/constants.js.map +1 -1
  106. package/dist/plugins/analytics/mv/formatters.js.map +1 -1
  107. package/dist/plugins/analytics/mv/metadata.js.map +1 -1
  108. package/dist/plugins/analytics/mv/registry.js.map +1 -1
  109. package/dist/plugins/analytics/mv/schemas.js.map +1 -1
  110. package/dist/plugins/analytics/query.js.map +1 -1
  111. package/dist/plugins/analytics/result-delivery.js.map +1 -1
  112. package/dist/plugins/files/helpers.js.map +1 -1
  113. package/dist/plugins/files/plugin.d.ts.map +1 -1
  114. package/dist/plugins/files/plugin.js.map +1 -1
  115. package/dist/plugins/files/types.d.ts.map +1 -1
  116. package/dist/plugins/genie/genie.d.ts.map +1 -1
  117. package/dist/plugins/genie/genie.js.map +1 -1
  118. package/dist/plugins/jobs/plugin.d.ts.map +1 -1
  119. package/dist/plugins/jobs/plugin.js.map +1 -1
  120. package/dist/plugins/jobs/types.d.ts.map +1 -1
  121. package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
  122. package/dist/plugins/lakebase/lakebase.js.map +1 -1
  123. package/dist/plugins/lakebase/types.d.ts.map +1 -1
  124. package/dist/plugins/server/base-server.js.map +1 -1
  125. package/dist/plugins/server/client-config-sanitizer.js.map +1 -1
  126. package/dist/plugins/server/index.d.ts.map +1 -1
  127. package/dist/plugins/server/index.js.map +1 -1
  128. package/dist/plugins/server/react-source-loc-vite-plugin.js.map +1 -1
  129. package/dist/plugins/server/remote-tunnel/remote-tunnel-controller.js.map +1 -1
  130. package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js.map +1 -1
  131. package/dist/plugins/server/static-server.js.map +1 -1
  132. package/dist/plugins/server/utils.js.map +1 -1
  133. package/dist/plugins/server/vite-dev-server.js.map +1 -1
  134. package/dist/plugins/serving/schema-filter.js.map +1 -1
  135. package/dist/plugins/serving/serving.d.ts.map +1 -1
  136. package/dist/plugins/serving/serving.js.map +1 -1
  137. package/dist/plugins/ui-variants/index.js.map +1 -1
  138. package/dist/registry/manifest-loader.d.ts.map +1 -1
  139. package/dist/registry/manifest-loader.js.map +1 -1
  140. package/dist/registry/resource-registry.d.ts.map +1 -1
  141. package/dist/registry/resource-registry.js.map +1 -1
  142. package/dist/registry/types.d.ts.map +1 -1
  143. package/dist/registry/types.js.map +1 -1
  144. package/dist/schemas/manifest.d.ts.map +1 -1
  145. package/dist/schemas/manifest.js.map +1 -1
  146. package/dist/schemas/metric-fqn.js.map +1 -1
  147. package/dist/shared/src/plugin.d.ts.map +1 -1
  148. package/dist/shared/src/schemas/manifest.d.ts.map +1 -1
  149. package/dist/shared/src/schemas/metric-fqn.js.map +1 -1
  150. package/dist/shared/src/schemas/metric-metadata-bundle.js.map +1 -1
  151. package/dist/shared/src/schemas/metric-source.js.map +1 -1
  152. package/dist/shared/src/sse/analytics.js.map +1 -1
  153. package/dist/shared/src/workspace-client/legacy.js.map +1 -1
  154. package/dist/shared/src/workspace-client/types.d.ts.map +1 -1
  155. package/dist/stream/sse-writer.js.map +1 -1
  156. package/dist/stream/stream-manager.d.ts.map +1 -1
  157. package/dist/stream/stream-manager.js.map +1 -1
  158. package/dist/stream/types.js.map +1 -1
  159. package/dist/telemetry/instrumentations.js.map +1 -1
  160. package/dist/telemetry/telemetry-manager.js.map +1 -1
  161. package/dist/telemetry/telemetry-provider.js.map +1 -1
  162. package/dist/telemetry/trace-sampler.js.map +1 -1
  163. package/dist/testing/expect-stream.d.ts +111 -0
  164. package/dist/testing/expect-stream.d.ts.map +1 -0
  165. package/dist/testing/expect-stream.js +154 -0
  166. package/dist/testing/expect-stream.js.map +1 -0
  167. package/dist/testing/fixtures.d.ts +257 -0
  168. package/dist/testing/fixtures.d.ts.map +1 -0
  169. package/dist/testing/fixtures.js +385 -0
  170. package/dist/testing/fixtures.js.map +1 -0
  171. package/dist/testing/index.d.ts +5 -0
  172. package/dist/testing/index.js +5 -0
  173. package/dist/testing/test-plugin-context.d.ts +158 -0
  174. package/dist/testing/test-plugin-context.d.ts.map +1 -0
  175. package/dist/testing/test-plugin-context.js +139 -0
  176. package/dist/testing/test-plugin-context.js.map +1 -0
  177. package/dist/type-generator/cache.js.map +1 -1
  178. package/dist/type-generator/index.js.map +1 -1
  179. package/dist/type-generator/migration.js.map +1 -1
  180. package/dist/type-generator/mv-registry/config.js.map +1 -1
  181. package/dist/type-generator/query-registry.js.map +1 -1
  182. package/dist/type-generator/serving/cache.js.map +1 -1
  183. package/dist/type-generator/serving/generator.js.map +1 -1
  184. package/dist/type-generator/serving/server-file-extractor.d.ts.map +1 -1
  185. package/dist/type-generator/serving/server-file-extractor.js.map +1 -1
  186. package/dist/type-generator/serving/vite-plugin.d.ts.map +1 -1
  187. package/dist/type-generator/serving/vite-plugin.js.map +1 -1
  188. package/dist/type-generator/vite-plugin.d.ts.map +1 -1
  189. package/dist/type-generator/vite-plugin.js.map +1 -1
  190. package/dist/workspace-client/legacy.js.map +1 -1
  191. package/dist/workspace-client/types.d.ts.map +1 -1
  192. package/docs/plugins/testing.md +245 -0
  193. package/llms.txt +1 -0
  194. package/package.json +15 -2
  195. package/sbom.cdx.json +1 -1
  196. package/skills/appkit-ui-variants/SKILL.md +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixtures.js","names":[],"sources":["../../src/testing/fixtures.ts"],"sourcesContent":["import type { Span, SpanOptions } from \"@opentelemetry/api\";\nimport type { IAppRouter } from \"shared\";\nimport { afterEach, beforeEach, vi } from \"vitest\";\n\nimport { CacheManager } from \"../cache\";\nimport type { ServiceContextState } from \"../context/service-context\";\nimport { ServiceContext } from \"../context/service-context\";\nimport type { InstrumentConfig, ITelemetry } from \"../telemetry/types\";\n\n// Test fixtures intentionally use loose shapes; `noExplicitAny` is disabled\n// repo-wide (see biome.json), so a local alias keeps the intent readable.\ntype Any = any;\n\n/**\n * Creates a mock telemetry provider for testing. Every span/meter/logger is a\n * `vi.fn()` no-op, so plugins that trace, count, or log run without a live\n * OpenTelemetry pipeline. Passed into {@link createTestPluginContext} as the one\n * injectable production seam.\n */\nexport function createMockTelemetry(): ITelemetry {\n const mockSpan: Span = {\n addLink: vi.fn(),\n addLinks: vi.fn(),\n end: vi.fn(),\n setAttribute: vi.fn(),\n setAttributes: vi.fn(),\n setStatus: vi.fn(),\n recordException: vi.fn(),\n updateName: vi.fn(),\n addEvent: vi.fn(),\n isRecording: vi.fn().mockReturnValue(false),\n spanContext: vi.fn(),\n };\n\n return {\n getTracer: vi.fn().mockReturnValue({\n startActiveSpan: vi.fn().mockImplementation((...args: Any[]) => {\n const fn = args[args.length - 1];\n if (typeof fn === \"function\") {\n return fn(mockSpan);\n }\n return undefined;\n }),\n }),\n getMeter: vi.fn().mockReturnValue({\n createCounter: vi.fn().mockReturnValue({ add: vi.fn() }),\n createHistogram: vi.fn().mockReturnValue({ record: vi.fn() }),\n }),\n getLogger: vi.fn().mockReturnValue({\n emit: vi.fn(),\n }),\n emit: vi.fn(),\n startActiveSpan: vi\n .fn()\n .mockImplementation(\n async (\n _name: string,\n _options: SpanOptions,\n fn: (span: Span) => Promise<Any>,\n _tracerOptions?: InstrumentConfig,\n ) => {\n return await fn(mockSpan);\n },\n ),\n registerInstrumentations: vi.fn(),\n };\n}\n\n/**\n * Creates a mock Express router that captures registered handlers so a test\n * can pull a handler back out by method + path and invoke it directly.\n */\nexport function createMockRouter(): {\n router: IAppRouter;\n handlers: Record<string, Any>;\n getHandler: (method: string, path: string) => Any;\n} {\n const handlers: Record<string, Any> = {};\n\n const mockRouter = {\n get: vi.fn((path: string, handler: Any) => {\n handlers[`GET:${path}`] = handler;\n }),\n post: vi.fn((path: string, handler: Any) => {\n handlers[`POST:${path}`] = handler;\n }),\n put: vi.fn((path: string, handler: Any) => {\n handlers[`PUT:${path}`] = handler;\n }),\n delete: vi.fn((path: string, handler: Any) => {\n handlers[`DELETE:${path}`] = handler;\n }),\n patch: vi.fn((path: string, handler: Any) => {\n handlers[`PATCH:${path}`] = handler;\n }),\n } as unknown as IAppRouter;\n\n return {\n router: mockRouter,\n handlers,\n getHandler: (method: string, path: string) =>\n handlers[`${method.toUpperCase()}:${path}`],\n };\n}\n\n/**\n * On-behalf-of shorthand for {@link createMockRequest}. `true` uses the default\n * test user; an object picks the identity. Sets the forwarded headers the real\n * `Plugin.asUser` reads (`x-forwarded-access-token`, `x-forwarded-user`, and —\n * when given — `x-forwarded-email`), so an OBO test is one flag instead of\n * hand-rolled headers.\n */\nexport type OboOption =\n | boolean\n | {\n /** `x-forwarded-user` — defaults to `\"test-user\"`. */\n userId?: string;\n /** `x-forwarded-access-token` — defaults to `\"test-user-token\"`. */\n token?: string;\n /** `x-forwarded-email` — omitted unless provided. */\n email?: string;\n };\n\n/** Build the forwarded identity headers an `obo` option implies. */\nfunction oboHeaders(obo: Exclude<OboOption, false>): Record<string, string> {\n const opts = obo === true ? {} : obo;\n const headers: Record<string, string> = {\n \"x-forwarded-access-token\": opts.token ?? \"test-user-token\",\n \"x-forwarded-user\": opts.userId ?? \"test-user\",\n };\n if (opts.email) headers[\"x-forwarded-email\"] = opts.email;\n return headers;\n}\n\n/**\n * Creates a mock Express request. Pass `overrides` to set `params`, `query`,\n * `body`, `headers`, etc.\n *\n * For on-behalf-of tests, pass `obo` instead of hand-adding forwarded headers —\n * `createMockRequest({ obo: true })` sets the identity headers the real\n * `asUser` requires. Any explicit `headers` you also pass win over the ones\n * `obo` generates, so you can override a single field.\n *\n * @example\n * ```ts\n * createMockRequest({ obo: true }); // default test user + token\n * createMockRequest({ obo: { userId: \"alice\" } }); // pick the user\n * ```\n */\nexport function createMockRequest(overrides: Any = {}) {\n const { obo, headers: headerOverrides, ...rest } = overrides;\n\n // `obo` seeds the forwarded identity headers; an explicit `headers` override\n // still wins (merged last) so a test can tweak or drop a single field.\n //\n // Keys are lowercased on the way in, the way Node's parser gives them to\n // Express. `header()` looks up lowercased, so storing as-given would file a\n // mixed-case override under a second key and leave the obo one winning.\n const headers: Record<string, unknown> = Object.fromEntries(\n Object.entries({\n ...(obo ? oboHeaders(obo) : {}),\n ...headerOverrides,\n }).map(([name, value]) => [name.toLowerCase(), value]),\n );\n\n const req = {\n params: {},\n query: {},\n body: {},\n header: function (name: string) {\n return this.headers[name.toLowerCase()];\n },\n // `...rest` keeps the original override power over every default above;\n // `headers` is applied last as the one managed field (obo + overrides).\n ...rest,\n headers,\n };\n return req;\n}\n\n/**\n * Creates a mock Express response object. `write`/`send`/`setHeader` flip\n * `headersSent`, `end` flips `writableEnded` and fires any `close` listener —\n * enough for streaming handlers that branch on those flags.\n *\n * Every chunk passed to `write` (and a final chunk to `end`) is captured, so a\n * streaming route's real SSE output can be replayed: pass the response straight\n * to {@link expectStream}, or call `sseResponse()` for a real `Response`.\n *\n * @example Assert what a streaming route emitted\n * ```ts\n * const res = createMockResponse();\n * await plugin._handleStream(req, res);\n * await expectStream(res).toEmit(\"status\", \"result\");\n * ```\n */\nexport function createMockResponse() {\n const eventListeners: Record<string, Array<(...args: Any[]) => void>> = {};\n const chunks: string[] = [];\n\n const res = {\n // Flips to true once headers/body have gone out — mirrors Express so\n // streaming handlers can branch between a JSON error (pre-headers) and\n // aborting the socket (mid-stream).\n headersSent: false,\n status: vi.fn().mockReturnThis(),\n json: vi.fn().mockReturnThis(),\n send: vi.fn(function (this: Any) {\n this.headersSent = true;\n return this;\n }),\n sendStatus: vi.fn().mockReturnThis(),\n end: vi.fn(function (this: Any, chunk?: unknown) {\n // Express allows `end(chunk)` and `end(callback)`; capture only a data\n // chunk, never the completion callback.\n if (chunk != null && typeof chunk !== \"function\") {\n chunks.push(String(chunk));\n }\n this.writableEnded = true;\n if (eventListeners.close) {\n for (const handler of eventListeners.close) {\n handler();\n }\n }\n return this;\n }),\n write: vi.fn(function (this: Any, chunk?: unknown) {\n this.headersSent = true;\n if (chunk != null) chunks.push(String(chunk));\n // Return `this` (truthy) rather than a boolean: handlers that gate on\n // backpressure (`if (res.write(buf)) …`) then take the no-wait path.\n return this;\n }),\n setHeader: vi.fn(function (this: Any) {\n this.headersSent = true;\n return this;\n }),\n flushHeaders: vi.fn().mockReturnThis(),\n destroy: vi.fn().mockReturnThis(),\n on: vi.fn(function (\n this: Any,\n event: string,\n handler: (...args: Any[]) => void,\n ) {\n if (!eventListeners[event]) {\n eventListeners[event] = [];\n }\n eventListeners[event].push(handler);\n return this;\n }),\n off: vi.fn(function (\n this: Any,\n event: string,\n handler: (...args: Any[]) => void,\n ) {\n if (eventListeners[event]) {\n eventListeners[event] = eventListeners[event].filter(\n (h) => h !== handler,\n );\n }\n return this;\n }),\n writableEnded: false,\n /**\n * The SSE body captured so far, as a real `Response` — the bridge from a\n * `res.write`-based handler into {@link expectStream}. `expectStream`\n * detects this method and calls it for you, so `expectStream(res)` and\n * `expectStream(res.sseResponse())` are equivalent.\n */\n sseResponse(): Response {\n return new Response(chunks.join(\"\"));\n },\n };\n return res;\n}\n\n/**\n * Sets up common environment variables for Databricks testing so code that\n * reads `DATABRICKS_HOST` / `DATABRICKS_WAREHOUSE_ID` finds test values.\n */\nexport function setupDatabricksEnv(overrides: Record<string, string> = {}) {\n process.env.DATABRICKS_HOST = \"https://test.databricks.com\";\n process.env.DATABRICKS_WAREHOUSE_ID = \"test-warehouse-id\";\n Object.assign(process.env, overrides);\n}\n\n/**\n * Clears AppKit's process-wide cache singleton so cached values don't leak\n * between tests in the same file.\n *\n * The cache `attach()` seeds is shared by every test in a file (Vitest isolates\n * files, not tests within a file). Call this in `beforeEach` when one test's\n * cached value must not be seen by the next, or mid-test to force a cache miss\n * before asserting a subsequent hit.\n *\n * No-ops when the cache has not been initialized yet, so it is safe to call\n * before any `attach()`.\n *\n * @example\n * ```ts\n * beforeEach(async () => {\n * await resetTestCache();\n * });\n * ```\n */\nexport async function resetTestCache(): Promise<void> {\n let cache: ReturnType<typeof CacheManager.getInstanceSync>;\n try {\n cache = CacheManager.getInstanceSync();\n } catch {\n // Not initialized yet — nothing to clear.\n return;\n }\n await cache.clear();\n}\n\n/**\n * Context options for running tests with mocked service/user context\n */\nexport interface TestContextOptions {\n /** Mock WorkspaceClient for service principal operations */\n serviceDatabricksClient?: Any;\n /** Mock WorkspaceClient for user operations */\n userDatabricksClient?: Any;\n /** User ID for user context */\n userId?: string;\n /** Service user ID */\n serviceUserId?: string;\n /** Warehouse ID */\n warehouseId?: string;\n /** Workspace ID */\n workspaceId?: string;\n}\n\n/**\n * Creates a default mock WorkspaceClient for testing (SQL succeeds, warehouse\n * RUNNING).\n */\nexport function createMockWorkspaceClient() {\n return {\n statementExecution: {\n executeStatement: vi.fn().mockResolvedValue({\n status: { state: \"SUCCEEDED\" },\n result: { data: [] },\n }),\n },\n // Analytics route now calls `warehouses.get` before issuing SQL to\n // ensure the warehouse is RUNNING. Default to RUNNING so existing\n // tests that only care about SQL behaviour aren't affected.\n warehouses: {\n get: vi.fn().mockResolvedValue({ state: \"RUNNING\" }),\n start: vi.fn().mockResolvedValue(undefined),\n },\n };\n}\n\n/**\n * Builds a {@link ServiceContextState} value for testing without touching the\n * singleton. Internal building block for {@link mockServiceContext}, which\n * installs the state as spies — that installer is the public entry point.\n */\nfunction buildServiceContextState(\n options: TestContextOptions = {},\n): ServiceContextState {\n return {\n client: (options.serviceDatabricksClient ||\n createMockWorkspaceClient()) as Any,\n serviceUserId: options.serviceUserId || \"test-service-user\",\n warehouseId: Promise.resolve(options.warehouseId || \"test-warehouse-id\"),\n workspaceId: Promise.resolve(options.workspaceId || \"test-workspace-id\"),\n };\n}\n\n/**\n * Mocks the `ServiceContext` singleton for testing — spies `get`,\n * `initialize`, `isInitialized`, and `createUserContext` so code that resolves\n * the service principal or an on-behalf-of user context gets test doubles.\n * Call in `beforeEach`; call the returned `restore()` in `afterEach`.\n *\n * @returns The mock context plus the spies and a `restore()` helper.\n */\nexport function mockServiceContext(options: TestContextOptions = {}) {\n const serviceContext = buildServiceContextState(options);\n\n const getSpy = vi\n .spyOn(ServiceContext, \"get\")\n .mockReturnValue(serviceContext);\n\n const initSpy = vi\n .spyOn(ServiceContext, \"initialize\")\n .mockResolvedValue(serviceContext);\n\n const isInitializedSpy = vi\n .spyOn(ServiceContext, \"isInitialized\")\n .mockReturnValue(true);\n\n const createUserContextSpy = vi\n .spyOn(ServiceContext, \"createUserContext\")\n .mockImplementation((_token: string, userId: string, userName?: string) => {\n return {\n client: (options.userDatabricksClient ||\n createMockWorkspaceClient()) as Any,\n userId,\n userName,\n warehouseId: serviceContext.warehouseId,\n workspaceId: serviceContext.workspaceId,\n isUserContext: true,\n };\n });\n\n return {\n serviceContext,\n getSpy,\n initSpy,\n isInitializedSpy,\n createUserContextSpy,\n restore: () => {\n getSpy.mockRestore();\n initSpy.mockRestore();\n isInitializedSpy.mockRestore();\n createUserContextSpy.mockRestore();\n },\n };\n}\n\n/** The handle {@link mockServiceContext} returns (spies + `restore`). */\nexport type ServiceContextMock = ReturnType<typeof mockServiceContext>;\n\n/**\n * Registers a fresh {@link mockServiceContext} before each test and restores it\n * after — the whole `beforeEach`/`afterEach` dance in one line.\n *\n * Call it at the top of a `describe` block (or module top-level), NOT inside a\n * test: Vitest's `beforeEach`/`afterEach` only register during collection, so a\n * call from within a test body registers nothing for that test.\n *\n * Returns a **live** accessor, not the handle: each `beforeEach` builds fresh\n * spies, so reading `.current` inside a test always sees that test's mock. A\n * handle captured once would go stale after the first hook runs.\n *\n * @example\n * ```ts\n * describe(\"my plugin\", () => {\n * const ctx = useServiceContextMock({ warehouseId: \"wh-1\" });\n *\n * test(\"resolves the warehouse\", async () => {\n * await myHandler(req, res);\n * expect(ctx.current.getSpy).toHaveBeenCalled();\n * });\n * });\n * ```\n *\n * @returns `{ current }` — the active {@link ServiceContextMock} for the test.\n */\nexport function useServiceContextMock(options: TestContextOptions = {}): {\n readonly current: ServiceContextMock;\n} {\n let handle: ServiceContextMock | undefined;\n\n beforeEach(() => {\n handle = mockServiceContext(options);\n });\n\n afterEach(() => {\n handle?.restore();\n handle = undefined;\n });\n\n return {\n get current(): ServiceContextMock {\n if (!handle) {\n throw new Error(\n \"useServiceContextMock: no active mock. Call useServiceContextMock() \" +\n \"at the top of a describe block (not inside a test), and read \" +\n \"`.current` from within a test.\",\n );\n }\n return handle;\n },\n };\n}\n\n/**\n * Runs a test function within a mocked service context: installs the mock,\n * runs `fn`, and restores the singleton afterward.\n */\nexport async function runWithRequestContext<T>(\n fn: () => T | Promise<T>,\n context?: TestContextOptions,\n): Promise<T> {\n const mocks = mockServiceContext(context);\n\n try {\n return await fn();\n } finally {\n mocks.restore();\n }\n}\n\n/**\n * Builds a SUCCEEDED SQL statement response with a synthetic statement id,\n * `data_array` rows, and a manifest schema derived from `columns`.\n */\nexport function createSuccessfulSQLResponse(\n data: Any[][],\n columns: Array<{ name: string; type_name?: string }>,\n) {\n return {\n status: { state: \"SUCCEEDED\" },\n statement_id: `stmt-${Date.now()}`,\n result: {\n data_array: data,\n },\n manifest: {\n schema: {\n columns: columns.map((col) => ({\n name: col.name,\n type_name: col.type_name ?? \"STRING\",\n })),\n },\n },\n };\n}\n\n/** Builds a FAILED SQL statement response carrying `errorMessage`. */\nexport function createFailedSQLResponse(errorMessage: string) {\n return {\n status: {\n state: \"FAILED\",\n error: {\n message: errorMessage,\n },\n },\n statement_id: `stmt-${Date.now()}`,\n };\n}\n\n/**\n * A WorkspaceClient whose `executeStatement`/`getStatement` are bare `vi.fn()`s\n * (no default resolution) so a test can script exactly what SQL returns.\n * `warehouses.get` defaults to RUNNING.\n */\nexport function createConfigurableMockWorkspaceClient() {\n const executeStatement = vi.fn();\n const getStatement = vi.fn();\n // Analytics route now calls `warehouses.get` before issuing SQL; default to\n // RUNNING so callers that don't care about warehouse readiness don't have\n // to wire it up.\n const warehousesGet = vi.fn().mockResolvedValue({ state: \"RUNNING\" });\n const warehousesStart = vi.fn().mockResolvedValue(undefined);\n\n const client = {\n statementExecution: {\n executeStatement,\n getStatement,\n },\n warehouses: {\n get: warehousesGet,\n start: warehousesStart,\n },\n };\n\n return {\n client,\n mocks: {\n executeStatement,\n getStatement,\n warehousesGet,\n warehousesStart,\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,sBAAkC;CAChD,MAAM,WAAiB;EACrB,SAA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AAOH,eAAsB,sBACpB,IACA,SACY;CACZ,MAAM,QAAQ,mBAAmB,QAAQ;AAEzC,KAAI;AACF,SAAO,MAAM,IAAI;WACT;AACR,QAAM,SAAS;;;;;;;AAQnB,SAAgB,4BACd,MACA,SACA;AACA,QAAO;EACL,QAAQ,EAAE,OAAO,aAAa;EAC9B,cAAc,QAAQ,KAAK,KAAK;EAChC,QAAQ,EACN,YAAY,MACb;EACD,UAAU,EACR,QAAQ,EACN,SAAS,QAAQ,KAAK,SAAS;GAC7B,MAAM,IAAI;GACV,WAAW,IAAI,aAAa;GAC7B,EAAE,EACJ,EACF;EACF;;;AAIH,SAAgB,wBAAwB,cAAsB;AAC5D,QAAO;EACL,QAAQ;GACN,OAAO;GACP,OAAO,EACL,SAAS,cACV;GACF;EACD,cAAc,QAAQ,KAAK,KAAK;EACjC;;;;;;;AAQH,SAAgB,wCAAwC;CACtD,MAAM,mBAAmB,GAAG,IAAI;CAChC,MAAM,eAAe,GAAG,IAAI;CAI5B,MAAM,gBAAgB,GAAG,IAAI,CAAC,kBAAkB,EAAE,OAAO,WAAW,CAAC;CACrE,MAAM,kBAAkB,GAAG,IAAI,CAAC,kBAAkB,OAAU;AAa5D,QAAO;EACL,QAZa;GACb,oBAAoB;IAClB;IACA;IACD;GACD,YAAY;IACV,KAAK;IACL,OAAO;IACR;GACF;EAIC,OAAO;GACL;GACA;GACA;GACA;GACD;EACF"}
@@ -0,0 +1,5 @@
1
+ import { PluginContext } from "../core/plugin-context.js";
2
+ import { CapturedSSEResponse, ExpectStreamOptions, StreamAssertion, StreamEvent, StreamSource, expectStream, parseSSEResponse } from "./expect-stream.js";
3
+ import { OboOption, ServiceContextMock, TestContextOptions, createConfigurableMockWorkspaceClient, createFailedSQLResponse, createMockRequest, createMockResponse, createMockRouter, createMockTelemetry, createMockWorkspaceClient, createSuccessfulSQLResponse, mockServiceContext, resetTestCache, runWithRequestContext, setupDatabricksEnv, useServiceContextMock } from "./fixtures.js";
4
+ import { FakeProvider, FakeProviders, FakeToolResponse, RecordedRoute, RecordedToolCall, TestPluginContext, createTestPluginContext } from "./test-plugin-context.js";
5
+ export { type CapturedSSEResponse, type ExpectStreamOptions, type FakeProvider, type FakeProviders, type FakeToolResponse, type OboOption, type PluginContext, type RecordedRoute, type RecordedToolCall, type ServiceContextMock, type StreamAssertion, type StreamEvent, type StreamSource, type TestContextOptions, type TestPluginContext, createConfigurableMockWorkspaceClient, createFailedSQLResponse, createMockRequest, createMockResponse, createMockRouter, createMockTelemetry, createMockWorkspaceClient, createSuccessfulSQLResponse, createTestPluginContext, expectStream, mockServiceContext, parseSSEResponse, resetTestCache, runWithRequestContext, setupDatabricksEnv, useServiceContextMock };
@@ -0,0 +1,5 @@
1
+ import { expectStream, parseSSEResponse } from "./expect-stream.js";
2
+ import { createConfigurableMockWorkspaceClient, createFailedSQLResponse, createMockRequest, createMockResponse, createMockRouter, createMockTelemetry, createMockWorkspaceClient, createSuccessfulSQLResponse, mockServiceContext, resetTestCache, runWithRequestContext, setupDatabricksEnv, useServiceContextMock } from "./fixtures.js";
3
+ import { createTestPluginContext } from "./test-plugin-context.js";
4
+
5
+ export { createConfigurableMockWorkspaceClient, createFailedSQLResponse, createMockRequest, createMockResponse, createMockRouter, createMockTelemetry, createMockWorkspaceClient, createSuccessfulSQLResponse, createTestPluginContext, expectStream, mockServiceContext, parseSSEResponse, resetTestCache, runWithRequestContext, setupDatabricksEnv, useServiceContextMock };
@@ -0,0 +1,158 @@
1
+ import { AgentToolDefinition } from "../shared/src/agent.js";
2
+ import "../shared/src/index.js";
3
+ import { ITelemetry } from "../telemetry/types.js";
4
+ import "../telemetry/index.js";
5
+ import { PluginContext } from "../core/plugin-context.js";
6
+ import { Plugin } from "../plugin/plugin.js";
7
+ import "../plugin/index.js";
8
+ import express from "express";
9
+
10
+ //#region src/testing/test-plugin-context.d.ts
11
+ /**
12
+ * A concrete (non-function) fake tool response — returned as-is. Covers the
13
+ * JSON-serializable shapes a tool call yields (rows, objects, primitives,
14
+ * nullish). A bare `unknown` is intentionally not used here: unioned with the
15
+ * function form below it would collapse to `unknown` and strip contextual
16
+ * types from the callback's parameters.
17
+ */
18
+ type FakeToolValue = Record<string, unknown> | unknown[] | string | number | boolean | null;
19
+ /**
20
+ * A canned tool response. Either a static {@link FakeToolValue} returned
21
+ * as-is, or a function of the call arguments (and the abort signal
22
+ * `PluginContext.executeTool` composes) so a fake can assert on inputs or
23
+ * simulate slow/aborting work. Returning a promise is supported (the return
24
+ * type is intentionally `unknown`, which also covers `Promise<...>`).
25
+ */
26
+ type FakeToolResponse = FakeToolValue | ((args: unknown, signal?: AbortSignal) => unknown);
27
+ /**
28
+ * Fake connector responses, keyed by plugin name and then tool name:
29
+ *
30
+ * ```ts
31
+ * createTestPluginContext({ analytics: { query: fixtureRows } });
32
+ * ```
33
+ *
34
+ * Each top-level key registers a fake {@link ToolProvider} under that plugin
35
+ * name; each inner key becomes a tool that returns the mapped response.
36
+ */
37
+ type FakeProviders = Record<string, Record<string, FakeToolResponse>>;
38
+ /** A single dispatch observed by a fake provider. */
39
+ interface RecordedToolCall {
40
+ /** Registered plugin name (the key in {@link FakeProviders}). */
41
+ plugin: string;
42
+ /** Tool name passed to `executeAgentTool`. */
43
+ tool: string;
44
+ /** Arguments the tool received. */
45
+ args: unknown;
46
+ /** The abort signal `executeTool` composed (timeout ∘ caller). */
47
+ signal?: AbortSignal;
48
+ /**
49
+ * Whether the dispatch was resolved through the on-behalf-of (`asUser`)
50
+ * path. `PluginContext.executeTool` always calls `provider.asUser(req)`, so
51
+ * for a tool reached through `executeTool` this is `true` — and, because the
52
+ * fake `asUser` enforces the same token precondition as the real
53
+ * {@link Plugin.asUser}, a request with no `x-forwarded-access-token` makes
54
+ * that call **throw** rather than record `asUser: true`. The meaningful
55
+ * assertions are therefore: a well-formed request records `asUser: true`
56
+ * with {@link userId} set, and a token-less request rejects.
57
+ *
58
+ * The fake replicates the token precondition only, not the real dev-mode
59
+ * OTel `isDevOboFallback()` marker — assert OBO here, not via that flag.
60
+ */
61
+ asUser: boolean;
62
+ /**
63
+ * The user the on-behalf-of scope resolved to (from `x-forwarded-user`), or
64
+ * `undefined` for a service-principal call (`asUser: false`). Lets a test
65
+ * assert the tool ran as the expected end user, not just that OBO was used.
66
+ */
67
+ userId?: string;
68
+ }
69
+ /** A single route registered through the context's `addRoute`/`addMiddleware`. */
70
+ interface RecordedRoute {
71
+ method: string;
72
+ path: string;
73
+ /**
74
+ * The raw handlers as passed to `addRoute` — before `PluginContext` wraps
75
+ * them with `forwardAsyncErrors`. Recorded here so aliasing assertions
76
+ * ("both routes mount the same handler") can compare the original
77
+ * references, which the wrapped express-level handlers no longer share.
78
+ */
79
+ handlers: express.RequestHandler[];
80
+ }
81
+ /** A fake tool provider registered on a mock context. */
82
+ interface FakeProvider {
83
+ /** Every `asUser(req)` the context resolved for this provider. */
84
+ asUserRequests: express.Request[];
85
+ /** Definitions returned from `getAgentTools()`. */
86
+ tools: AgentToolDefinition[];
87
+ }
88
+ /**
89
+ * The result of {@link createTestPluginContext}: the real `PluginContext` plus the
90
+ * seams a test needs to drive and inspect it.
91
+ */
92
+ interface TestPluginContext {
93
+ /** The real {@link PluginContext}, constructed with mock telemetry. */
94
+ ctx: PluginContext;
95
+ /**
96
+ * The mock telemetry provider injected into the {@link PluginContext}.
97
+ * Captures the spans the *context* opens (notably `executeTool`) — not the
98
+ * plugin's own spans: `attachContext` rebuilds the plugin's `this.telemetry`
99
+ * from the real `TelemetryManager`, so plugin-internal spans do not land here.
100
+ */
101
+ telemetry: ITelemetry;
102
+ /**
103
+ * Tool dispatches observed across all fake providers, in call order. Live —
104
+ * read it after the action under test runs.
105
+ */
106
+ toolCalls: RecordedToolCall[];
107
+ /**
108
+ * Routes registered through the context, in registration order. Live —
109
+ * populated when the plugin calls `addRoute`/`addMiddleware`.
110
+ */
111
+ routes: RecordedRoute[];
112
+ /** Fake providers by plugin name, for direct assertions. */
113
+ providers: Map<string, FakeProvider>;
114
+ /**
115
+ * Register (or replace) a fake tool provider after construction.
116
+ * Same shape as one {@link FakeProviders} entry.
117
+ */
118
+ registerProvider(name: string, tools: Record<string, FakeToolResponse>): void;
119
+ /**
120
+ * Attach this context to a plugin the production way: seed an in-memory
121
+ * cache (if AppKit hasn't already), then call `plugin.attachContext`, which
122
+ * also rebuilds the plugin's telemetry and flips `isReady` to `true`. Await
123
+ * it before exercising handlers that read `this.context`, `this.cache`, or
124
+ * gate on `isReady`. Returns the same plugin for chaining.
125
+ */
126
+ attach<P extends Plugin>(plugin: P): Promise<P>;
127
+ }
128
+ /**
129
+ * Build a real {@link PluginContext} with faked edges for testing — no live
130
+ * workspace, no OpenTelemetry pipeline, no network.
131
+ *
132
+ * The context is the *real* class, so route buffering, the tool registry,
133
+ * timeout composition, and the on-behalf-of (`asUser`) path all run for real.
134
+ * Only three edges are faked, matching the seams the class actually has:
135
+ *
136
+ * - **Telemetry** is a mock provider injected into the context (the one
137
+ * injectable production seam); it records the context's own spans, not the
138
+ * plugin's.
139
+ * - **Tool providers** are fakes registered through the existing public
140
+ * `registerToolProvider`; their `asUser`/`executeAgentTool` are recorded.
141
+ * - **Routes** are captured by wrapping the public `addRoute`/`addMiddleware`.
142
+ *
143
+ * Nothing about `PluginContext` is reimplemented.
144
+ *
145
+ * @param fakes - Canned tool responses keyed by plugin then tool name.
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * const mock = createTestPluginContext({ analytics: { query: fixtureRows } });
150
+ * await mock.attach(agentsPlugin);
151
+ * // ...exercise a handler that dispatches analytics.query...
152
+ * expect(mock.toolCalls[0]).toMatchObject({ plugin: "analytics", asUser: true });
153
+ * ```
154
+ */
155
+ declare function createTestPluginContext(fakes?: FakeProviders): TestPluginContext;
156
+ //#endregion
157
+ export { FakeProvider, FakeProviders, FakeToolResponse, RecordedRoute, RecordedToolCall, TestPluginContext, createTestPluginContext };
158
+ //# sourceMappingURL=test-plugin-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-plugin-context.d.ts","names":[],"sources":["../../src/testing/test-plugin-context.ts"],"mappings":";;;;;;;;;;;;;;;AAa+C;;KAU1C,aAAA,GACD,MAAA;;;AAcJ;;;;;KAAY,gBAAA,GACR,aAAA,KACE,IAAA,WAAe,MAAA,GAAS,WAAA;;;;;AAY9B;;;;;;KAAY,aAAA,GAAgB,MAAA,SAAe,MAAA,SAAe,gBAAA;;UAGzC,gBAAA;EAH0B;EAKzC,MAAA;EALwE;EAOxE,IAAA;EAJe;EAMf,IAAA;;EAEA,MAAA,GAAS,WAAA;EANT;;;;;;;;;AA8BF;;;;EAVE,MAAA;EAYA;;;;;EANA,MAAA;AAAA;;UAIe,aAAA;EACf,MAAA;EACA,IAAA;EAagB;;;;;;EANhB,QAAA,EAAU,OAAA,CAAQ,cAAA;AAAA;;UAIH,YAAA;EAoBJ;EAlBX,cAAA,EAAgB,OAAA,CAAQ,OAAA;EA4BhB;EA1BR,KAAA,EAAO,mBAAA;AAAA;;;;;UAOQ,iBAAA;EAkCsB;EAhCrC,GAAA,EAAK,aAAA;EAgCuC;;;;;;EAzB5C,SAAA,EAAW,UAAA;EAUX;;;;EALA,SAAA,EAAW,gBAAA;EAYX;;;;EAPA,MAAA,EAAQ,aAAA;EAeR;EAbA,SAAA,EAAW,GAAA,SAAY,YAAA;EAaN;;;;EARjB,gBAAA,CAAiB,IAAA,UAAc,KAAA,EAAO,MAAA,SAAe,gBAAA;EAQP;;AA8BhD;;;;;EA9BE,MAAA,WAAiB,MAAA,EAAQ,MAAA,EAAQ,CAAA,GAAI,OAAA,CAAQ,CAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA8B/B,uBAAA,CACd,KAAA,GAAO,aAAA,GACN,iBAAA"}
@@ -0,0 +1,139 @@
1
+ import { AuthenticationError } from "../errors/authentication.js";
2
+ import "../errors/index.js";
3
+ import { InMemoryStorage } from "../cache/storage/memory.js";
4
+ import "../cache/storage/index.js";
5
+ import { CacheManager } from "../cache/index.js";
6
+ import { PluginContext, isToolProvider } from "../core/plugin-context.js";
7
+ import { createMockTelemetry } from "./fixtures.js";
8
+
9
+ //#region src/testing/test-plugin-context.ts
10
+ /**
11
+ * Build a real {@link PluginContext} with faked edges for testing — no live
12
+ * workspace, no OpenTelemetry pipeline, no network.
13
+ *
14
+ * The context is the *real* class, so route buffering, the tool registry,
15
+ * timeout composition, and the on-behalf-of (`asUser`) path all run for real.
16
+ * Only three edges are faked, matching the seams the class actually has:
17
+ *
18
+ * - **Telemetry** is a mock provider injected into the context (the one
19
+ * injectable production seam); it records the context's own spans, not the
20
+ * plugin's.
21
+ * - **Tool providers** are fakes registered through the existing public
22
+ * `registerToolProvider`; their `asUser`/`executeAgentTool` are recorded.
23
+ * - **Routes** are captured by wrapping the public `addRoute`/`addMiddleware`.
24
+ *
25
+ * Nothing about `PluginContext` is reimplemented.
26
+ *
27
+ * @param fakes - Canned tool responses keyed by plugin then tool name.
28
+ *
29
+ * @example
30
+ * ```ts
31
+ * const mock = createTestPluginContext({ analytics: { query: fixtureRows } });
32
+ * await mock.attach(agentsPlugin);
33
+ * // ...exercise a handler that dispatches analytics.query...
34
+ * expect(mock.toolCalls[0]).toMatchObject({ plugin: "analytics", asUser: true });
35
+ * ```
36
+ */
37
+ function createTestPluginContext(fakes = {}) {
38
+ const telemetry = createMockTelemetry();
39
+ const ctx = new PluginContext({ telemetry });
40
+ const toolCalls = [];
41
+ const routes = [];
42
+ const providers = /* @__PURE__ */ new Map();
43
+ const realAddRoute = ctx.addRoute.bind(ctx);
44
+ ctx.addRoute = (method, path, ...handlers) => {
45
+ routes.push({
46
+ method,
47
+ path,
48
+ handlers
49
+ });
50
+ realAddRoute(method, path, ...handlers);
51
+ };
52
+ const realAddMiddleware = ctx.addMiddleware.bind(ctx);
53
+ ctx.addMiddleware = (path, ...handlers) => {
54
+ routes.push({
55
+ method: "use",
56
+ path,
57
+ handlers
58
+ });
59
+ realAddMiddleware(path, ...handlers);
60
+ };
61
+ function registerProvider(name, tools) {
62
+ const record = {
63
+ asUserRequests: [],
64
+ tools: Object.keys(tools).map((toolName) => ({
65
+ name: toolName,
66
+ description: `Fake tool ${name}.${toolName}`,
67
+ parameters: { type: "object" }
68
+ }))
69
+ };
70
+ providers.set(name, record);
71
+ const resolve = async (toolName, args, signal, asUser, userId) => {
72
+ toolCalls.push({
73
+ plugin: name,
74
+ tool: toolName,
75
+ args,
76
+ signal,
77
+ asUser,
78
+ userId
79
+ });
80
+ if (!Object.hasOwn(tools, toolName)) throw new Error(`createTestPluginContext: plugin "${name}" has no fake tool "${toolName}". Available: ${Object.keys(tools).join(", ") || "(none)"}`);
81
+ const response = tools[toolName];
82
+ return typeof response === "function" ? await response(args, signal) : response;
83
+ };
84
+ const base = {
85
+ getAgentTools: () => record.tools,
86
+ executeAgentTool: (toolName, args, signal) => resolve(toolName, args, signal, false, void 0)
87
+ };
88
+ const asUser = (req) => {
89
+ record.asUserRequests.push(req);
90
+ const token = req.header?.("x-forwarded-access-token")?.trim();
91
+ const userId = req.header?.("x-forwarded-user")?.trim();
92
+ const isDev = process.env.NODE_ENV === "development";
93
+ if (!token && !isDev) throw AuthenticationError.missingToken("user token");
94
+ if (token && !userId && !isDev) throw AuthenticationError.missingUserId();
95
+ return {
96
+ ...base,
97
+ executeAgentTool: (toolName, args, signal) => resolve(toolName, args, signal, true, userId)
98
+ };
99
+ };
100
+ const provider = {
101
+ name,
102
+ setup: async () => {},
103
+ injectRoutes: () => {},
104
+ getEndpoints: () => ({}),
105
+ ...base,
106
+ asUser
107
+ };
108
+ ctx.registerToolProvider(name, provider);
109
+ }
110
+ for (const [name, tools] of Object.entries(fakes)) registerProvider(name, tools);
111
+ async function attach(plugin) {
112
+ if (!cacheReady()) await CacheManager.getInstance({ storage: new InMemoryStorage({}) });
113
+ plugin.attachContext({ context: ctx });
114
+ ctx.registerPlugin(plugin.name, plugin);
115
+ if (isToolProvider(plugin) && !providers.has(plugin.name)) ctx.registerToolProvider(plugin.name, plugin);
116
+ return plugin;
117
+ }
118
+ return {
119
+ ctx,
120
+ telemetry,
121
+ toolCalls,
122
+ routes,
123
+ providers,
124
+ registerProvider,
125
+ attach
126
+ };
127
+ }
128
+ function cacheReady() {
129
+ try {
130
+ CacheManager.getInstanceSync();
131
+ return true;
132
+ } catch {
133
+ return false;
134
+ }
135
+ }
136
+
137
+ //#endregion
138
+ export { createTestPluginContext };
139
+ //# sourceMappingURL=test-plugin-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-plugin-context.js","names":[],"sources":["../../src/testing/test-plugin-context.ts"],"sourcesContent":["import type express from \"express\";\nimport type {\n AgentToolDefinition,\n BasePlugin,\n IAppRequest,\n ToolProvider,\n} from \"shared\";\n\nimport { CacheManager } from \"../cache\";\nimport { InMemoryStorage } from \"../cache/storage\";\nimport { isToolProvider, PluginContext } from \"../core/plugin-context\";\nimport { AuthenticationError } from \"../errors\";\nimport type { Plugin } from \"../plugin\";\nimport type { ITelemetry } from \"../telemetry\";\nimport { createMockTelemetry } from \"./fixtures\";\n\n/**\n * A concrete (non-function) fake tool response — returned as-is. Covers the\n * JSON-serializable shapes a tool call yields (rows, objects, primitives,\n * nullish). A bare `unknown` is intentionally not used here: unioned with the\n * function form below it would collapse to `unknown` and strip contextual\n * types from the callback's parameters.\n */\ntype FakeToolValue =\n | Record<string, unknown>\n | unknown[]\n | string\n | number\n | boolean\n | null;\n\n/**\n * A canned tool response. Either a static {@link FakeToolValue} returned\n * as-is, or a function of the call arguments (and the abort signal\n * `PluginContext.executeTool` composes) so a fake can assert on inputs or\n * simulate slow/aborting work. Returning a promise is supported (the return\n * type is intentionally `unknown`, which also covers `Promise<...>`).\n */\nexport type FakeToolResponse =\n | FakeToolValue\n | ((args: unknown, signal?: AbortSignal) => unknown);\n\n/**\n * Fake connector responses, keyed by plugin name and then tool name:\n *\n * ```ts\n * createTestPluginContext({ analytics: { query: fixtureRows } });\n * ```\n *\n * Each top-level key registers a fake {@link ToolProvider} under that plugin\n * name; each inner key becomes a tool that returns the mapped response.\n */\nexport type FakeProviders = Record<string, Record<string, FakeToolResponse>>;\n\n/** A single dispatch observed by a fake provider. */\nexport interface RecordedToolCall {\n /** Registered plugin name (the key in {@link FakeProviders}). */\n plugin: string;\n /** Tool name passed to `executeAgentTool`. */\n tool: string;\n /** Arguments the tool received. */\n args: unknown;\n /** The abort signal `executeTool` composed (timeout ∘ caller). */\n signal?: AbortSignal;\n /**\n * Whether the dispatch was resolved through the on-behalf-of (`asUser`)\n * path. `PluginContext.executeTool` always calls `provider.asUser(req)`, so\n * for a tool reached through `executeTool` this is `true` — and, because the\n * fake `asUser` enforces the same token precondition as the real\n * {@link Plugin.asUser}, a request with no `x-forwarded-access-token` makes\n * that call **throw** rather than record `asUser: true`. The meaningful\n * assertions are therefore: a well-formed request records `asUser: true`\n * with {@link userId} set, and a token-less request rejects.\n *\n * The fake replicates the token precondition only, not the real dev-mode\n * OTel `isDevOboFallback()` marker — assert OBO here, not via that flag.\n */\n asUser: boolean;\n /**\n * The user the on-behalf-of scope resolved to (from `x-forwarded-user`), or\n * `undefined` for a service-principal call (`asUser: false`). Lets a test\n * assert the tool ran as the expected end user, not just that OBO was used.\n */\n userId?: string;\n}\n\n/** A single route registered through the context's `addRoute`/`addMiddleware`. */\nexport interface RecordedRoute {\n method: string;\n path: string;\n /**\n * The raw handlers as passed to `addRoute` — before `PluginContext` wraps\n * them with `forwardAsyncErrors`. Recorded here so aliasing assertions\n * (\"both routes mount the same handler\") can compare the original\n * references, which the wrapped express-level handlers no longer share.\n */\n handlers: express.RequestHandler[];\n}\n\n/** A fake tool provider registered on a mock context. */\nexport interface FakeProvider {\n /** Every `asUser(req)` the context resolved for this provider. */\n asUserRequests: express.Request[];\n /** Definitions returned from `getAgentTools()`. */\n tools: AgentToolDefinition[];\n}\n\n/**\n * The result of {@link createTestPluginContext}: the real `PluginContext` plus the\n * seams a test needs to drive and inspect it.\n */\nexport interface TestPluginContext {\n /** The real {@link PluginContext}, constructed with mock telemetry. */\n ctx: PluginContext;\n /**\n * The mock telemetry provider injected into the {@link PluginContext}.\n * Captures the spans the *context* opens (notably `executeTool`) — not the\n * plugin's own spans: `attachContext` rebuilds the plugin's `this.telemetry`\n * from the real `TelemetryManager`, so plugin-internal spans do not land here.\n */\n telemetry: ITelemetry;\n /**\n * Tool dispatches observed across all fake providers, in call order. Live —\n * read it after the action under test runs.\n */\n toolCalls: RecordedToolCall[];\n /**\n * Routes registered through the context, in registration order. Live —\n * populated when the plugin calls `addRoute`/`addMiddleware`.\n */\n routes: RecordedRoute[];\n /** Fake providers by plugin name, for direct assertions. */\n providers: Map<string, FakeProvider>;\n /**\n * Register (or replace) a fake tool provider after construction.\n * Same shape as one {@link FakeProviders} entry.\n */\n registerProvider(name: string, tools: Record<string, FakeToolResponse>): void;\n /**\n * Attach this context to a plugin the production way: seed an in-memory\n * cache (if AppKit hasn't already), then call `plugin.attachContext`, which\n * also rebuilds the plugin's telemetry and flips `isReady` to `true`. Await\n * it before exercising handlers that read `this.context`, `this.cache`, or\n * gate on `isReady`. Returns the same plugin for chaining.\n */\n attach<P extends Plugin>(plugin: P): Promise<P>;\n}\n\n/**\n * Build a real {@link PluginContext} with faked edges for testing — no live\n * workspace, no OpenTelemetry pipeline, no network.\n *\n * The context is the *real* class, so route buffering, the tool registry,\n * timeout composition, and the on-behalf-of (`asUser`) path all run for real.\n * Only three edges are faked, matching the seams the class actually has:\n *\n * - **Telemetry** is a mock provider injected into the context (the one\n * injectable production seam); it records the context's own spans, not the\n * plugin's.\n * - **Tool providers** are fakes registered through the existing public\n * `registerToolProvider`; their `asUser`/`executeAgentTool` are recorded.\n * - **Routes** are captured by wrapping the public `addRoute`/`addMiddleware`.\n *\n * Nothing about `PluginContext` is reimplemented.\n *\n * @param fakes - Canned tool responses keyed by plugin then tool name.\n *\n * @example\n * ```ts\n * const mock = createTestPluginContext({ analytics: { query: fixtureRows } });\n * await mock.attach(agentsPlugin);\n * // ...exercise a handler that dispatches analytics.query...\n * expect(mock.toolCalls[0]).toMatchObject({ plugin: \"analytics\", asUser: true });\n * ```\n */\nexport function createTestPluginContext(\n fakes: FakeProviders = {},\n): TestPluginContext {\n const telemetry = createMockTelemetry();\n const ctx = new PluginContext({ telemetry });\n\n const toolCalls: RecordedToolCall[] = [];\n const routes: RecordedRoute[] = [];\n const providers = new Map<string, FakeProvider>();\n\n // Wrap the public route API so raw (pre-wrap) handlers are inspectable while\n // the real buffering/flush path stays intact.\n const realAddRoute = ctx.addRoute.bind(ctx);\n ctx.addRoute = (\n method: string,\n path: string,\n ...handlers: express.RequestHandler[]\n ): void => {\n routes.push({ method, path, handlers });\n realAddRoute(method, path, ...handlers);\n };\n const realAddMiddleware = ctx.addMiddleware.bind(ctx);\n ctx.addMiddleware = (\n path: string,\n ...handlers: express.RequestHandler[]\n ): void => {\n routes.push({ method: \"use\", path, handlers });\n realAddMiddleware(path, ...handlers);\n };\n\n function registerProvider(\n name: string,\n tools: Record<string, FakeToolResponse>,\n ): void {\n const record: FakeProvider = {\n asUserRequests: [],\n tools: Object.keys(tools).map((toolName) => ({\n name: toolName,\n description: `Fake tool ${name}.${toolName}`,\n parameters: { type: \"object\" },\n })),\n };\n providers.set(name, record);\n\n const resolve = async (\n toolName: string,\n args: unknown,\n signal: AbortSignal | undefined,\n asUser: boolean,\n userId: string | undefined,\n ): Promise<unknown> => {\n toolCalls.push({\n plugin: name,\n tool: toolName,\n args,\n signal,\n asUser,\n userId,\n });\n // `Object.hasOwn`, not `tools[toolName] === undefined`: a tool named\n // \"constructor\"/\"toString\"/etc. would otherwise resolve to an inherited\n // Object.prototype method and be invoked instead of reported missing.\n if (!Object.hasOwn(tools, toolName)) {\n throw new Error(\n `createTestPluginContext: plugin \"${name}\" has no fake tool \"${toolName}\". ` +\n `Available: ${Object.keys(tools).join(\", \") || \"(none)\"}`,\n );\n }\n const response = tools[toolName];\n return typeof response === \"function\"\n ? await (response as (a: unknown, s?: AbortSignal) => unknown)(\n args,\n signal,\n )\n : response;\n };\n\n const base: ToolProvider = {\n getAgentTools: () => record.tools,\n executeAgentTool: (toolName, args, signal) =>\n resolve(toolName, args, signal, false, undefined),\n };\n\n // Mirror the real `Plugin.asUser` token precondition (plugin.ts) so the\n // recorded `asUser` flag reflects genuine user-scope resolution rather than\n // being unconditionally true: a request with no `x-forwarded-access-token`\n // throws `missingToken` (production behavior), except in development where\n // the real code skips impersonation. This is edge-faking of asUser's\n // *contract*, not a reimplementation of `runInUserContext`/`ServiceContext`.\n //\n // Deliberately NOT reproduced: the real dev-mode path sets an OTel\n // `DEV_OBO_FALLBACK_KEY` marker (read by `isDevOboFallback()`). That key is\n // module-private telemetry plumbing; assert OBO via the recorded\n // `asUser`/`userId` fields, not `isDevOboFallback()`.\n const asUser = (req: IAppRequest): ToolProvider => {\n record.asUserRequests.push(req as express.Request);\n const token = (req as express.Request)\n .header?.(\"x-forwarded-access-token\")\n ?.trim();\n const userId = (req as express.Request)\n .header?.(\"x-forwarded-user\")\n ?.trim();\n const isDev = process.env.NODE_ENV === \"development\";\n\n if (!token && !isDev) {\n throw AuthenticationError.missingToken(\"user token\");\n }\n if (token && !userId && !isDev) {\n throw AuthenticationError.missingUserId();\n }\n\n return {\n ...base,\n executeAgentTool: (toolName, args, signal) =>\n resolve(toolName, args, signal, true, userId),\n };\n };\n\n // `registerToolProvider` expects the full ToolProviderPlugin shape\n // (BasePlugin & ToolProvider & { asUser }). executeTool only ever calls\n // `asUser` and `executeAgentTool`; the remaining BasePlugin surface is\n // never touched for a registered provider, so a focused fake plus a cast\n // is sufficient and avoids reimplementing a plugin.\n const provider = {\n name,\n setup: async () => {},\n injectRoutes: () => {},\n getEndpoints: () => ({}),\n ...base,\n asUser,\n } as unknown as BasePlugin &\n ToolProvider & {\n asUser: (req: IAppRequest) => ToolProvider;\n };\n\n ctx.registerToolProvider(name, provider);\n }\n\n for (const [name, tools] of Object.entries(fakes)) {\n registerProvider(name, tools);\n }\n\n async function attach<P extends Plugin>(plugin: P): Promise<P> {\n // Seed a real in-memory cache if AppKit hasn't initialized one. Idempotent:\n // getInstance returns any existing singleton (e.g. one a suite already set\n // up) and ignores the storage argument in that case.\n if (!cacheReady()) {\n await CacheManager.getInstance({ storage: new InMemoryStorage({}) });\n }\n plugin.attachContext({ context: ctx });\n\n // Mirror what AppKit core does after attachContext (core/appkit.ts): put\n // the plugin in the registry so `getPlugins()`/`getPluginNames()`/\n // `hasPlugin()` and any sibling-plugin lookup behave as in production. Only\n // register it as a tool provider when it actually is one AND its name does\n // not collide with an injected fake — the fakes are the authored test\n // doubles and must not be overwritten by the plugin under test.\n ctx.registerPlugin(plugin.name, plugin as unknown as BasePlugin);\n if (isToolProvider(plugin) && !providers.has(plugin.name)) {\n ctx.registerToolProvider(\n plugin.name,\n plugin as unknown as Parameters<typeof ctx.registerToolProvider>[1],\n );\n }\n return plugin;\n }\n\n return {\n ctx,\n telemetry,\n toolCalls,\n routes,\n providers,\n registerProvider,\n attach,\n };\n}\n\nfunction cacheReady(): boolean {\n try {\n CacheManager.getInstanceSync();\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+KA,SAAgB,wBACd,QAAuB,EAAE,EACN;CACnB,MAAM,YAAY,qBAAqB;CACvC,MAAM,MAAM,IAAI,cAAc,EAAE,WAAW,CAAC;CAE5C,MAAM,YAAgC,EAAE;CACxC,MAAM,SAA0B,EAAE;CAClC,MAAM,4BAAY,IAAI,KAA2B;CAIjD,MAAM,eAAe,IAAI,SAAS,KAAK,IAAI;AAC3C,KAAI,YACF,QACA,MACA,GAAG,aACM;AACT,SAAO,KAAK;GAAE;GAAQ;GAAM;GAAU,CAAC;AACvC,eAAa,QAAQ,MAAM,GAAG,SAAS;;CAEzC,MAAM,oBAAoB,IAAI,cAAc,KAAK,IAAI;AACrD,KAAI,iBACF,MACA,GAAG,aACM;AACT,SAAO,KAAK;GAAE,QAAQ;GAAO;GAAM;GAAU,CAAC;AAC9C,oBAAkB,MAAM,GAAG,SAAS;;CAGtC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AqB,MAAM,SAAS;;AAG1C,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,MAAM,CAC/C,kBAAiB,MAAM,MAAM;CAG/B,eAAe,OAAyB,QAAuB;AAI7D,MAAI,CAAC,YAAY,CACf,OAAM,aAAa,YAAY,EAAE,SAAS,IAAI,gBAAgB,EAAE,CAAC,EAAE,CAAC;AAEtE,SAAO,cAAc,EAAE,SAAS,KAAK,CAAC;AAQtC,MAAI,eAAe,OAAO,MAAM,OAAgC;AAChE,MAAI,eAAe,OAAO,IAAI,CAAC,UAAU,IAAI,OAAO,KAAK,CACvD,KAAI,qBACF,OAAO,MACP,OACD;AAEH,SAAO;;AAGT,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACD;;AAGH,SAAS,aAAsB;AAC7B,KAAI;AACF,eAAa,iBAAiB;AAC9B,SAAO;SACD;AACN,SAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"cache.js","names":[],"sources":["../../src/type-generator/cache.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createLogger } from \"../logging/logger\";\nimport type { MetricSchema } from \"./mv-registry/types\";\n\nconst logger = createLogger(\"type-generator:cache\");\n\n/**\n * Cache types\n * @property hash - the hash of the SQL query\n * @property type - the type of the query\n * @property retry - when true the entry never satisfies a cache hit, so the\n * query is re-described on the next pass; fresh successful describes\n * persist `retry: false`\n */\ninterface CacheEntry {\n hash: string;\n type: string;\n retry: boolean;\n}\n\n/**\n * One cached metric-view DESCRIBE outcome.\n *\n * `hash` is md5 over `\"<source>|<lane>\"` — the two config inputs that\n * determine a DESCRIBE — so editing either invalidates the entry. `schema`\n * is the full {@link MetricSchema} persisted verbatim (it is JSON-safe by\n * design), letting a warm pass regenerate the metric artifact without a\n * single warehouse call.\n */\nexport interface MetricCacheEntry {\n hash: string;\n schema: MetricSchema;\n retry: boolean;\n}\n\n/**\n * Structural gate for reviving a cached metric entry at partition time.\n *\n * The cache file lives in `node_modules/.databricks` and is plain JSON —\n * hand-edits, truncation, or a stale writer can leave entries whose shape no\n * longer matches {@link MetricCacheEntry}. A malformed entry must read as a\n * cache MISS (re-describe) rather than crash the pass or render revived\n * garbage into the artifacts.\n */\nexport function isRevivableMetricCacheEntry(entry: unknown): boolean {\n if (typeof entry !== \"object\" || entry === null) return false;\n const e = entry as Record<string, unknown>;\n if (typeof e.hash !== \"string\" || typeof e.retry !== \"boolean\") {\n return false;\n }\n const schema = e.schema;\n if (typeof schema !== \"object\" || schema === null || Array.isArray(schema)) {\n return false;\n }\n const s = schema as Record<string, unknown>;\n const isColumnArray = (value: unknown): boolean =>\n Array.isArray(value) &&\n value.every(\n (col) =>\n typeof col === \"object\" &&\n col !== null &&\n typeof (col as Record<string, unknown>).name === \"string\" &&\n typeof (col as Record<string, unknown>).type === \"string\",\n );\n return (\n typeof s.key === \"string\" &&\n typeof s.source === \"string\" &&\n (s.lane === \"sp\" || s.lane === \"obo\") &&\n (s.degraded === undefined || typeof s.degraded === \"boolean\") &&\n isColumnArray(s.measures) &&\n isColumnArray(s.dimensions)\n );\n}\n\n/**\n * Cache interface\n * @property version - the version of the cache\n * @property queries - the queries in the cache\n * @property metrics - cached metric-view schemas keyed by metric key.\n */\ninterface Cache {\n version: string;\n queries: Record<string, CacheEntry>;\n metrics?: Record<string, MetricCacheEntry>;\n}\n\nexport const CACHE_VERSION = \"3\";\nconst CACHE_FILE = \".appkit-types-cache.json\";\nconst CACHE_DIR = path.join(\n process.cwd(),\n \"node_modules\",\n \".databricks\",\n \"appkit\",\n);\n\n/**\n * Hash the SQL query\n * Uses MD5 to hash the SQL query\n * @param sql - the SQL query to hash\n * @returns - the hash of the SQL query\n */\nexport function hashSQL(sql: string): string {\n return crypto.createHash(\"md5\").update(sql).digest(\"hex\");\n}\n\n/**\n * Change detector stored on {@link MetricCacheEntry.hash}: md5 over\n * `\"<source>|<lane>\"` — the two config inputs that determine a DESCRIBE —\n * so editing either invalidates the entry.\n */\nexport function metricCacheHash(source: string, lane: string): string {\n return hashSQL(`${source}|${lane}`);\n}\n\n/**\n * Load the cache from the file system\n * If the cache is not found, run the query explain\n * @returns - the cache\n */\nexport async function loadCache(): Promise<Cache> {\n const cachePath = path.join(CACHE_DIR, CACHE_FILE);\n try {\n await fs.mkdir(CACHE_DIR, { recursive: true });\n\n const raw = await fs.readFile(cachePath, \"utf8\");\n const cache = JSON.parse(raw) as Cache;\n if (cache.version === CACHE_VERSION) {\n return cache;\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n logger.warn(\"Cache file is corrupted, flushing cache completely.\");\n }\n }\n return { version: CACHE_VERSION, queries: {} };\n}\n\n/**\n * Save the cache to the file system\n * @param cache - cache object to save\n */\nexport async function saveCache(cache: Cache): Promise<void> {\n const cachePath = path.join(CACHE_DIR, CACHE_FILE);\n await fs.writeFile(cachePath, JSON.stringify(cache, null, 2), \"utf8\");\n}\n"],"mappings":";;;;;;AAMA,MAAM,SAAS,aAAa,uBAAuB;;;;;;;;;;AAwCnD,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,IAAI;AACV,KAAI,OAAO,EAAE,SAAS,YAAY,OAAO,EAAE,UAAU,UACnD,QAAO;CAET,MAAM,SAAS,EAAE;AACjB,KAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,OAAO,CACxE,QAAO;CAET,MAAM,IAAI;CACV,MAAM,iBAAiB,UACrB,MAAM,QAAQ,MAAM,IACpB,MAAM,OACH,QACC,OAAO,QAAQ,YACf,QAAQ,QACR,OAAQ,IAAgC,SAAS,YACjD,OAAQ,IAAgC,SAAS,SACpD;AACH,QACE,OAAO,EAAE,QAAQ,YACjB,OAAO,EAAE,WAAW,aACnB,EAAE,SAAS,QAAQ,EAAE,SAAS,WAC9B,EAAE,aAAa,UAAa,OAAO,EAAE,aAAa,cACnD,cAAc,EAAE,SAAS,IACzB,cAAc,EAAE,WAAW;;AAgB/B,MAAa,gBAAgB;AAC7B,MAAM,aAAa;AACnB,MAAM,YAAY,KAAK,KACrB,QAAQ,KAAK,EACb,gBACA,eACA,SACD;;;;;;;AAQD,SAAgB,QAAQ,KAAqB;AAC3C,QAAO,OAAO,WAAW,MAAM,CAAC,OAAO,IAAI,CAAC,OAAO,MAAM;;;;;;;AAQ3D,SAAgB,gBAAgB,QAAgB,MAAsB;AACpE,QAAO,QAAQ,GAAG,OAAO,GAAG,OAAO;;;;;;;AAQrC,eAAsB,YAA4B;CAChD,MAAM,YAAY,KAAK,KAAK,WAAW,WAAW;AAClD,KAAI;AACF,QAAM,GAAG,MAAM,WAAW,EAAE,WAAW,MAAM,CAAC;EAE9C,MAAM,MAAM,MAAM,GAAG,SAAS,WAAW,OAAO;EAChD,MAAM,QAAQ,KAAK,MAAM,IAAI;AAC7B,MAAI,MAAM,YAAY,cACpB,QAAO;UAEF,KAAK;AACZ,MAAK,IAA8B,SAAS,SAC1C,QAAO,KAAK,sDAAsD;;AAGtE,QAAO;EAAE,SAAS;EAAe,SAAS,EAAE;EAAE;;;;;;AAOhD,eAAsB,UAAU,OAA6B;CAC3D,MAAM,YAAY,KAAK,KAAK,WAAW,WAAW;AAClD,OAAM,GAAG,UAAU,WAAW,KAAK,UAAU,OAAO,MAAM,EAAE,EAAE,OAAO"}
1
+ {"version":3,"file":"cache.js","names":[],"sources":["../../src/type-generator/cache.ts"],"sourcesContent":["import crypto from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { createLogger } from \"../logging/logger\";\nimport type { MetricSchema } from \"./mv-registry/types\";\n\nconst logger = createLogger(\"type-generator:cache\");\n\n/**\n * Cache types\n * @property hash - the hash of the SQL query\n * @property type - the type of the query\n * @property retry - when true the entry never satisfies a cache hit, so the\n * query is re-described on the next pass; fresh successful describes\n * persist `retry: false`\n */\ninterface CacheEntry {\n hash: string;\n type: string;\n retry: boolean;\n}\n\n/**\n * One cached metric-view DESCRIBE outcome.\n *\n * `hash` is md5 over `\"<source>|<lane>\"` — the two config inputs that\n * determine a DESCRIBE — so editing either invalidates the entry. `schema`\n * is the full {@link MetricSchema} persisted verbatim (it is JSON-safe by\n * design), letting a warm pass regenerate the metric artifact without a\n * single warehouse call.\n */\nexport interface MetricCacheEntry {\n hash: string;\n schema: MetricSchema;\n retry: boolean;\n}\n\n/**\n * Structural gate for reviving a cached metric entry at partition time.\n *\n * The cache file lives in `node_modules/.databricks` and is plain JSON —\n * hand-edits, truncation, or a stale writer can leave entries whose shape no\n * longer matches {@link MetricCacheEntry}. A malformed entry must read as a\n * cache MISS (re-describe) rather than crash the pass or render revived\n * garbage into the artifacts.\n */\nexport function isRevivableMetricCacheEntry(entry: unknown): boolean {\n if (typeof entry !== \"object\" || entry === null) return false;\n const e = entry as Record<string, unknown>;\n if (typeof e.hash !== \"string\" || typeof e.retry !== \"boolean\") {\n return false;\n }\n const schema = e.schema;\n if (typeof schema !== \"object\" || schema === null || Array.isArray(schema)) {\n return false;\n }\n const s = schema as Record<string, unknown>;\n const isColumnArray = (value: unknown): boolean =>\n Array.isArray(value) &&\n value.every(\n (col) =>\n typeof col === \"object\" &&\n col !== null &&\n typeof (col as Record<string, unknown>).name === \"string\" &&\n typeof (col as Record<string, unknown>).type === \"string\",\n );\n return (\n typeof s.key === \"string\" &&\n typeof s.source === \"string\" &&\n (s.lane === \"sp\" || s.lane === \"obo\") &&\n (s.degraded === undefined || typeof s.degraded === \"boolean\") &&\n isColumnArray(s.measures) &&\n isColumnArray(s.dimensions)\n );\n}\n\n/**\n * Cache interface\n * @property version - the version of the cache\n * @property queries - the queries in the cache\n * @property metrics - cached metric-view schemas keyed by metric key.\n */\ninterface Cache {\n version: string;\n queries: Record<string, CacheEntry>;\n metrics?: Record<string, MetricCacheEntry>;\n}\n\nexport const CACHE_VERSION = \"3\";\nconst CACHE_FILE = \".appkit-types-cache.json\";\nconst CACHE_DIR = path.join(\n process.cwd(),\n \"node_modules\",\n \".databricks\",\n \"appkit\",\n);\n\n/**\n * Hash the SQL query\n * Uses MD5 to hash the SQL query\n * @param sql - the SQL query to hash\n * @returns - the hash of the SQL query\n */\nexport function hashSQL(sql: string): string {\n return crypto.createHash(\"md5\").update(sql).digest(\"hex\");\n}\n\n/**\n * Change detector stored on {@link MetricCacheEntry.hash}: md5 over\n * `\"<source>|<lane>\"` — the two config inputs that determine a DESCRIBE —\n * so editing either invalidates the entry.\n */\nexport function metricCacheHash(source: string, lane: string): string {\n return hashSQL(`${source}|${lane}`);\n}\n\n/**\n * Load the cache from the file system\n * If the cache is not found, run the query explain\n * @returns - the cache\n */\nexport async function loadCache(): Promise<Cache> {\n const cachePath = path.join(CACHE_DIR, CACHE_FILE);\n try {\n await fs.mkdir(CACHE_DIR, { recursive: true });\n\n const raw = await fs.readFile(cachePath, \"utf8\");\n const cache = JSON.parse(raw) as Cache;\n if (cache.version === CACHE_VERSION) {\n return cache;\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n logger.warn(\"Cache file is corrupted, flushing cache completely.\");\n }\n }\n return { version: CACHE_VERSION, queries: {} };\n}\n\n/**\n * Save the cache to the file system\n * @param cache - cache object to save\n */\nexport async function saveCache(cache: Cache): Promise<void> {\n const cachePath = path.join(CACHE_DIR, CACHE_FILE);\n await fs.writeFile(cachePath, JSON.stringify(cache, null, 2), \"utf8\");\n}\n"],"mappings":";;;;;;AAOA,MAAM,SAAS,aAAa,uBAAuB;;;;;;;;;;AAwCnD,SAAgB,4BAA4B,OAAyB;AACnE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,IAAI;AACV,KAAI,OAAO,EAAE,SAAS,YAAY,OAAO,EAAE,UAAU,UACnD,QAAO;CAET,MAAM,SAAS,EAAE;AACjB,KAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,OAAO,CACxE,QAAO;CAET,MAAM,IAAI;CACV,MAAM,iB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