@databricks/appkit 0.75.0 → 0.76.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 (114) hide show
  1. package/CLAUDE.md +2 -2
  2. package/dist/appkit/package.js +1 -1
  3. package/dist/beta.d.ts +1 -1
  4. package/dist/beta.js +2 -1
  5. package/dist/cache/index.d.ts +10 -0
  6. package/dist/cache/index.d.ts.map +1 -1
  7. package/dist/cache/index.js +15 -2
  8. package/dist/cache/index.js.map +1 -1
  9. package/dist/cache/storage/persistent.js +1 -1
  10. package/dist/connectors/index.js +1 -1
  11. package/dist/connectors/jobs/client.js +1 -1
  12. package/dist/connectors/lakebase/index.d.ts +2 -2
  13. package/dist/connectors/lakebase/index.d.ts.map +1 -1
  14. package/dist/connectors/lakebase/index.js +25 -2
  15. package/dist/connectors/lakebase/index.js.map +1 -1
  16. package/dist/connectors/mcp/client.js +1 -1
  17. package/dist/connectors/sql-warehouse/client.js +14 -2
  18. package/dist/connectors/sql-warehouse/client.js.map +1 -1
  19. package/dist/context/service-context.js +1 -1
  20. package/dist/core/appkit.d.ts +1 -1
  21. package/dist/core/appkit.d.ts.map +1 -1
  22. package/dist/core/appkit.js +27 -6
  23. package/dist/core/appkit.js.map +1 -1
  24. package/dist/core/lifecycle-manager.js +47 -27
  25. package/dist/core/lifecycle-manager.js.map +1 -1
  26. package/dist/database/errors.js +1 -1
  27. package/dist/index.js +1 -1
  28. package/dist/plugin/dev-reader.js +1 -1
  29. package/dist/plugin/interceptors/retry.js +1 -1
  30. package/dist/plugin/plugin.js +1 -1
  31. package/dist/plugins/analytics/analytics.js +1 -1
  32. package/dist/plugins/analytics/result-delivery.js +1 -1
  33. package/dist/plugins/beta-exports.generated.d.ts +1 -3
  34. package/dist/plugins/beta-exports.generated.js +0 -2
  35. package/dist/plugins/database/config.js +14 -0
  36. package/dist/plugins/database/config.js.map +1 -0
  37. package/dist/plugins/database/database.d.ts +22 -5
  38. package/dist/plugins/database/database.d.ts.map +1 -1
  39. package/dist/plugins/database/database.js +23 -8
  40. package/dist/plugins/database/database.js.map +1 -1
  41. package/dist/plugins/database/lifecycle.js +3 -3
  42. package/dist/plugins/database/lifecycle.js.map +1 -1
  43. package/dist/plugins/database/load-schema.js +40 -0
  44. package/dist/plugins/database/load-schema.js.map +1 -0
  45. package/dist/plugins/database/manifest.js +1 -1
  46. package/dist/plugins/database/types.d.ts +12 -3
  47. package/dist/plugins/database/types.d.ts.map +1 -1
  48. package/dist/plugins/files/plugin.js +1 -1
  49. package/dist/plugins/jobs/plugin.js +1 -1
  50. package/dist/plugins/lakebase/lakebase.js +1 -1
  51. package/dist/plugins/server/index.js +3 -3
  52. package/dist/plugins/server/index.js.map +1 -1
  53. package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js +3 -3
  54. package/dist/plugins/server/remote-tunnel/remote-tunnel-manager.js.map +1 -1
  55. package/dist/plugins/server/static-server.js +3 -3
  56. package/dist/plugins/server/static-server.js.map +1 -1
  57. package/dist/plugins/server/utils.js +3 -3
  58. package/dist/plugins/server/utils.js.map +1 -1
  59. package/dist/plugins/server/vite-dev-server.js +5 -5
  60. package/dist/plugins/server/vite-dev-server.js.map +1 -1
  61. package/dist/registry/manifest-loader.js +1 -1
  62. package/dist/registry/resource-registry.js +1 -1
  63. package/dist/shared/src/schemas/manifest.d.ts +33 -33
  64. package/dist/stream/arrow-stream-processor.js +1 -1
  65. package/dist/stream/stream-manager.js +1 -1
  66. package/dist/telemetry/telemetry-manager.js +17 -0
  67. package/dist/telemetry/telemetry-manager.js.map +1 -1
  68. package/dist/testing/create-test-app.d.ts +111 -0
  69. package/dist/testing/create-test-app.d.ts.map +1 -0
  70. package/dist/testing/create-test-app.js +187 -0
  71. package/dist/testing/create-test-app.js.map +1 -0
  72. package/dist/testing/create-test-plugin.d.ts +17 -0
  73. package/dist/testing/create-test-plugin.d.ts.map +1 -0
  74. package/dist/testing/create-test-plugin.js +22 -0
  75. package/dist/testing/create-test-plugin.js.map +1 -0
  76. package/dist/testing/fixtures.d.ts +51 -35
  77. package/dist/testing/fixtures.d.ts.map +1 -1
  78. package/dist/testing/fixtures.js +129 -54
  79. package/dist/testing/fixtures.js.map +1 -1
  80. package/dist/testing/index.d.ts +8 -3
  81. package/dist/testing/index.js +7 -2
  82. package/dist/testing/mock-workspace-client.d.ts +47 -0
  83. package/dist/testing/mock-workspace-client.d.ts.map +1 -0
  84. package/dist/testing/mock-workspace-client.js +192 -0
  85. package/dist/testing/mock-workspace-client.js.map +1 -0
  86. package/dist/testing/reset-singletons.js +39 -0
  87. package/dist/testing/reset-singletons.js.map +1 -0
  88. package/dist/testing/test-app.d.ts +54 -0
  89. package/dist/testing/test-app.d.ts.map +1 -0
  90. package/dist/testing/test-app.js +55 -0
  91. package/dist/testing/test-app.js.map +1 -0
  92. package/dist/testing/test-cache.d.ts +60 -0
  93. package/dist/testing/test-cache.d.ts.map +1 -0
  94. package/dist/testing/test-cache.js +65 -0
  95. package/dist/testing/test-cache.js.map +1 -0
  96. package/dist/testing/test-plugin-context.d.ts +43 -2
  97. package/dist/testing/test-plugin-context.d.ts.map +1 -1
  98. package/dist/testing/test-plugin-context.js +47 -2
  99. package/dist/testing/test-plugin-context.js.map +1 -1
  100. package/dist/type-generator/database/generate.js +3 -3
  101. package/dist/type-generator/database/generate.js.map +1 -1
  102. package/dist/type-generator/migration.js +2 -2
  103. package/dist/type-generator/migration.js.map +1 -1
  104. package/dist/type-generator/serving/server-file-extractor.js +3 -3
  105. package/dist/type-generator/serving/server-file-extractor.js.map +1 -1
  106. package/docs/api/appkit/Function.createApp.md +9 -9
  107. package/docs/api/appkit/Function.database.md +30 -29
  108. package/docs/api/appkit/TypeAlias.IDatabaseConfig.md +8 -6
  109. package/docs/api/appkit.md +1 -1
  110. package/docs/plugins/database.md +46 -18
  111. package/docs/plugins/testing.md +440 -14
  112. package/llms.txt +2 -2
  113. package/package.json +1 -1
  114. package/sbom.cdx.json +1 -1
@@ -0,0 +1,60 @@
1
+ import { CacheManager } from "../cache/index.js";
2
+
3
+ //#region src/testing/test-cache.d.ts
4
+ /**
5
+ * The handle {@link useTestCache} returns: a live accessor for the real,
6
+ * in-memory {@link CacheManager} active in the current test.
7
+ */
8
+ interface TestCacheHandle {
9
+ /**
10
+ * The real (in-memory) cache for the current test. Each test's `beforeEach`
11
+ * seeds and clears the singleton, so reading this always sees a fresh cache —
12
+ * call `generateKey`, `get`, `has`, or `vi.spyOn(handle.current, "getOrExecute")`
13
+ * to assert real caching behaviour.
14
+ */
15
+ readonly current: CacheManager;
16
+ }
17
+ /**
18
+ * Stand up AppKit's real in-memory cache for a test file and clear it before
19
+ * each test, so a plugin's real caching path runs under test with no mock of
20
+ * the internal `cache` module.
21
+ *
22
+ * Boots the process-wide {@link CacheManager} singleton backed by
23
+ * {@link InMemoryStorage} (idempotent — an already-initialized singleton is
24
+ * reused and the storage argument ignored), then clears it via
25
+ * {@link resetTestCache} in `beforeEach` so each test starts empty. The
26
+ * singleton is left in place: this clears the cache's contents, never the
27
+ * pointer.
28
+ *
29
+ * Because the cache is booted before the test body runs, a plugin constructed
30
+ * in the test — whose constructor reads `CacheManager.getInstanceSync()` —
31
+ * binds `this.cache` to this real cache. So `getOrExecute` genuinely caches and
32
+ * the key is production's real `generateKey`, not a re-implemented fake.
33
+ *
34
+ * Call it at the top of a `describe` block (or module top-level), NOT inside a
35
+ * test: Vitest's `beforeEach`/`afterEach` only register during collection.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * describe("my plugin caches", () => {
40
+ * const testCache = useTestCache();
41
+ *
42
+ * test("second identical request is a cache hit", async () => {
43
+ * const plugin = new MyPlugin(config);
44
+ * // ...drive the same request twice...
45
+ * expect(downstreamMock).toHaveBeenCalledTimes(1);
46
+ * });
47
+ *
48
+ * test("metadata does not change the cache key", () => {
49
+ * const key = testCache.current.generateKey(["query", "SELECT 1"], "svc");
50
+ * expect(key).toBe(testCache.current.generateKey(["query", "SELECT 1"], "svc"));
51
+ * });
52
+ * });
53
+ * ```
54
+ *
55
+ * @returns `{ current }` — the active real {@link CacheManager} for the test.
56
+ */
57
+ declare function useTestCache(): TestCacheHandle;
58
+ //#endregion
59
+ export { TestCacheHandle, useTestCache };
60
+ //# sourceMappingURL=test-cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-cache.d.ts","names":[],"sources":["../../src/testing/test-cache.ts"],"mappings":";;;;;AAUA;;UAAiB,eAAA;EAON;;AA2CX;;;;EA3CW,SAAA,OAAA,EAAS,YAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2CJ,YAAA,CAAA,GAAgB,eAAA"}
@@ -0,0 +1,65 @@
1
+ import { InMemoryStorage } from "../cache/storage/memory.js";
2
+ import "../cache/storage/index.js";
3
+ import { CacheManager } from "../cache/index.js";
4
+ import { resetTestCache } from "./fixtures.js";
5
+ import { afterEach, beforeEach } from "vitest";
6
+
7
+ //#region src/testing/test-cache.ts
8
+ /**
9
+ * Stand up AppKit's real in-memory cache for a test file and clear it before
10
+ * each test, so a plugin's real caching path runs under test with no mock of
11
+ * the internal `cache` module.
12
+ *
13
+ * Boots the process-wide {@link CacheManager} singleton backed by
14
+ * {@link InMemoryStorage} (idempotent — an already-initialized singleton is
15
+ * reused and the storage argument ignored), then clears it via
16
+ * {@link resetTestCache} in `beforeEach` so each test starts empty. The
17
+ * singleton is left in place: this clears the cache's contents, never the
18
+ * pointer.
19
+ *
20
+ * Because the cache is booted before the test body runs, a plugin constructed
21
+ * in the test — whose constructor reads `CacheManager.getInstanceSync()` —
22
+ * binds `this.cache` to this real cache. So `getOrExecute` genuinely caches and
23
+ * the key is production's real `generateKey`, not a re-implemented fake.
24
+ *
25
+ * Call it at the top of a `describe` block (or module top-level), NOT inside a
26
+ * test: Vitest's `beforeEach`/`afterEach` only register during collection.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * describe("my plugin caches", () => {
31
+ * const testCache = useTestCache();
32
+ *
33
+ * test("second identical request is a cache hit", async () => {
34
+ * const plugin = new MyPlugin(config);
35
+ * // ...drive the same request twice...
36
+ * expect(downstreamMock).toHaveBeenCalledTimes(1);
37
+ * });
38
+ *
39
+ * test("metadata does not change the cache key", () => {
40
+ * const key = testCache.current.generateKey(["query", "SELECT 1"], "svc");
41
+ * expect(key).toBe(testCache.current.generateKey(["query", "SELECT 1"], "svc"));
42
+ * });
43
+ * });
44
+ * ```
45
+ *
46
+ * @returns `{ current }` — the active real {@link CacheManager} for the test.
47
+ */
48
+ function useTestCache() {
49
+ let cache;
50
+ beforeEach(async () => {
51
+ cache = await CacheManager.getInstance({ storage: new InMemoryStorage({}) });
52
+ await resetTestCache();
53
+ });
54
+ afterEach(() => {
55
+ cache = void 0;
56
+ });
57
+ return { get current() {
58
+ if (!cache) throw new Error("useTestCache: no active cache. Call useTestCache() at the top of a describe block (not inside a test), and read `.current` from within a test.");
59
+ return cache;
60
+ } };
61
+ }
62
+
63
+ //#endregion
64
+ export { useTestCache };
65
+ //# sourceMappingURL=test-cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-cache.js","names":[],"sources":["../../src/testing/test-cache.ts"],"sourcesContent":["import { afterEach, beforeEach } from \"vitest\";\n\nimport { CacheManager } from \"../cache\";\nimport { InMemoryStorage } from \"../cache/storage\";\nimport { resetTestCache } from \"./fixtures\";\n\n/**\n * The handle {@link useTestCache} returns: a live accessor for the real,\n * in-memory {@link CacheManager} active in the current test.\n */\nexport interface TestCacheHandle {\n /**\n * The real (in-memory) cache for the current test. Each test's `beforeEach`\n * seeds and clears the singleton, so reading this always sees a fresh cache —\n * call `generateKey`, `get`, `has`, or `vi.spyOn(handle.current, \"getOrExecute\")`\n * to assert real caching behaviour.\n */\n readonly current: CacheManager;\n}\n\n/**\n * Stand up AppKit's real in-memory cache for a test file and clear it before\n * each test, so a plugin's real caching path runs under test with no mock of\n * the internal `cache` module.\n *\n * Boots the process-wide {@link CacheManager} singleton backed by\n * {@link InMemoryStorage} (idempotent — an already-initialized singleton is\n * reused and the storage argument ignored), then clears it via\n * {@link resetTestCache} in `beforeEach` so each test starts empty. The\n * singleton is left in place: this clears the cache's contents, never the\n * pointer.\n *\n * Because the cache is booted before the test body runs, a plugin constructed\n * in the test — whose constructor reads `CacheManager.getInstanceSync()` —\n * binds `this.cache` to this real cache. So `getOrExecute` genuinely caches and\n * the key is production's real `generateKey`, not a re-implemented fake.\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.\n *\n * @example\n * ```ts\n * describe(\"my plugin caches\", () => {\n * const testCache = useTestCache();\n *\n * test(\"second identical request is a cache hit\", async () => {\n * const plugin = new MyPlugin(config);\n * // ...drive the same request twice...\n * expect(downstreamMock).toHaveBeenCalledTimes(1);\n * });\n *\n * test(\"metadata does not change the cache key\", () => {\n * const key = testCache.current.generateKey([\"query\", \"SELECT 1\"], \"svc\");\n * expect(key).toBe(testCache.current.generateKey([\"query\", \"SELECT 1\"], \"svc\"));\n * });\n * });\n * ```\n *\n * @returns `{ current }` — the active real {@link CacheManager} for the test.\n */\nexport function useTestCache(): TestCacheHandle {\n let cache: CacheManager | undefined;\n\n beforeEach(async () => {\n // Idempotent: reuses an existing singleton (ignoring the storage arg) or\n // stands up a fresh in-memory one. Keeps the singleton either way.\n cache = await CacheManager.getInstance({\n storage: new InMemoryStorage({}),\n });\n // Fresh contents per test — clears storage without dropping the singleton.\n await resetTestCache();\n });\n\n afterEach(() => {\n cache = undefined;\n });\n\n return {\n get current(): CacheManager {\n if (!cache) {\n throw new Error(\n \"useTestCache: no active cache. Call useTestCache() at the top of a \" +\n \"describe block (not inside a test), and read `.current` from \" +\n \"within a test.\",\n );\n }\n return cache;\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4DA,SAAgB,eAAgC;CAC9C,IAAI;AAEJ,YAAW,YAAY;AAGrB,UAAQ,MAAM,aAAa,YAAY,EACrC,SAAS,IAAI,gBAAgB,EAAE,CAAC,EACjC,CAAC;AAEF,QAAM,gBAAgB;GACtB;AAEF,iBAAgB;AACd,UAAQ;GACR;AAEF,QAAO,EACL,IAAI,UAAwB;AAC1B,MAAI,CAAC,MACH,OAAM,IAAI,MACR,iJAGD;AAEH,SAAO;IAEV"}
@@ -35,6 +35,29 @@ type FakeToolResponse = FakeToolValue | ((args: unknown, signal?: AbortSignal) =
35
35
  * name; each inner key becomes a tool that returns the mapped response.
36
36
  */
37
37
  type FakeProviders = Record<string, Record<string, FakeToolResponse>>;
38
+ /**
39
+ * Options for {@link createTestPluginContext} when called with a second parameter.
40
+ * When provided, `createTestPluginContext` installs a service context seeded
41
+ * from a mock workspace client, plus optional environment variables.
42
+ */
43
+ interface TestPluginContextOptions {
44
+ /**
45
+ * Responses keyed by dotted path (`"jobs.getRun"`) for the mocked workspace
46
+ * client. Passed directly to {@link createMockWorkspaceClient}.
47
+ */
48
+ responses?: Record<string, unknown>;
49
+ /**
50
+ * Environment variables to set for the test. Captured on entry, restored
51
+ * (or deleted if they were unset) on exit via an `afterEach` hook and/or
52
+ * explicit {@link TestPluginContext.restore}.
53
+ */
54
+ env?: Record<string, string>;
55
+ /**
56
+ * If `true`, throw when a workspace client path with no declared response is
57
+ * called, instead of resolving `undefined`. Defaults to `false` (never crash).
58
+ */
59
+ strict?: boolean;
60
+ }
38
61
  /** A single dispatch observed by a fake provider. */
39
62
  interface RecordedToolCall {
40
63
  /** Registered plugin name (the key in {@link FakeProviders}). */
@@ -124,6 +147,14 @@ interface TestPluginContext {
124
147
  * gate on `isReady`. Returns the same plugin for chaining.
125
148
  */
126
149
  attach<P extends Plugin>(plugin: P): Promise<P>;
150
+ /**
151
+ * Restore the service context and environment variables to their pre-test state.
152
+ * Called automatically via `afterEach` when options were provided to
153
+ * `createTestPluginContext`. Can also be called explicitly for escape hatches
154
+ * (e.g., cleanup inside a test body). Idempotent — safe to call multiple times.
155
+ * Only present if the context was created with options.
156
+ */
157
+ restore?: () => void;
127
158
  }
128
159
  /**
129
160
  * Build a real {@link PluginContext} with faked edges for testing — no live
@@ -143,16 +174,26 @@ interface TestPluginContext {
143
174
  * Nothing about `PluginContext` is reimplemented.
144
175
  *
145
176
  * @param fakes - Canned tool responses keyed by plugin then tool name.
177
+ * @param options - When provided, installs a mock workspace client seeded from
178
+ * `responses`, mocks the service context, and sets `env`. Omit it for the
179
+ * original behavior.
146
180
  *
147
181
  * @example
148
182
  * ```ts
183
+ * // No options
149
184
  * const mock = createTestPluginContext({ analytics: { query: fixtureRows } });
150
185
  * await mock.attach(agentsPlugin);
151
186
  * // ...exercise a handler that dispatches analytics.query...
152
187
  * expect(mock.toolCalls[0]).toMatchObject({ plugin: "analytics", asUser: true });
188
+ *
189
+ * // With options — installs service context + seeded client
190
+ * const mock = createTestPluginContext(
191
+ * {},
192
+ * { responses: { "jobs.getRun": { state: "DONE" } } },
193
+ * );
153
194
  * ```
154
195
  */
155
- declare function createTestPluginContext(fakes?: FakeProviders): TestPluginContext;
196
+ declare function createTestPluginContext(fakes?: FakeProviders, options?: TestPluginContextOptions): TestPluginContext;
156
197
  //#endregion
157
- export { FakeProvider, FakeProviders, FakeToolResponse, RecordedRoute, RecordedToolCall, TestPluginContext, createTestPluginContext };
198
+ export { FakeProvider, FakeProviders, FakeToolResponse, RecordedRoute, RecordedToolCall, TestPluginContext, TestPluginContextOptions, createTestPluginContext };
158
199
  //# sourceMappingURL=test-plugin-context.d.ts.map
@@ -1 +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,MAA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;EAtBN,IAAA;EA0B4B;EAxB5B,MAAA,GAAS,WAAA;EAiCuB;;;;;;;;AAIlC;;;;;EAvBE,MAAA;EAyBwB;;;;;EAnBxB,MAAA;AAAA;;UAIe,aAAA;EACf,MAAA;EACA,IAAA;EAyCQ;;;;;;EAlCR,QAAA,EAAU,OAAA,CAAQ,cAAA;AAAA;;UAIH,YAAA;EA6C6B;EA3C5C,cAAA,EAAgB,OAAA,CAAQ,OAAA;EAWnB;EATL,KAAA,EAAO,mBAAA;AAAA;;;;;UAOQ,iBAAA;EAqBJ;EAnBX,GAAA,EAAK,aAAA;EAwBL;;;;;;EAjBA,SAAA,EAAW,UAAA;EAyBM;;;;EApBjB,SAAA,EAAW,gBAAA;EA4BX;;;AAwCF;EA/DE,MAAA,EAAQ,aAAA;;EAER,SAAA,EAAW,GAAA,SAAY,YAAA;EA+Db;;;;EA1DV,gBAAA,CAAiB,IAAA,UAAc,KAAA,EAAO,MAAA,SAAe,gBAAA;EAyDrD;;;;;;;EAjDA,MAAA,WAAiB,MAAA,EAAQ,MAAA,EAAQ,CAAA,GAAI,OAAA,CAAQ,CAAA;;;;;;;;EAQ7C,OAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAwCc,uBAAA,CACd,KAAA,GAAO,aAAA,EACP,OAAA,GAAU,wBAAA,GACT,iBAAA"}
@@ -4,7 +4,9 @@ import { InMemoryStorage } from "../cache/storage/memory.js";
4
4
  import "../cache/storage/index.js";
5
5
  import { CacheManager } from "../cache/index.js";
6
6
  import { PluginContext, isToolProvider } from "../core/plugin-context.js";
7
- import { createMockTelemetry } from "./fixtures.js";
7
+ import { createMockWorkspaceClient } from "./mock-workspace-client.js";
8
+ import { applyEnv, createMockTelemetry, mockServiceContext } from "./fixtures.js";
9
+ import { afterEach, onTestFinished } from "vitest";
8
10
 
9
11
  //#region src/testing/test-plugin-context.ts
10
12
  /**
@@ -25,16 +27,30 @@ import { createMockTelemetry } from "./fixtures.js";
25
27
  * Nothing about `PluginContext` is reimplemented.
26
28
  *
27
29
  * @param fakes - Canned tool responses keyed by plugin then tool name.
30
+ * @param options - When provided, installs a mock workspace client seeded from
31
+ * `responses`, mocks the service context, and sets `env`. Omit it for the
32
+ * original behavior.
28
33
  *
29
34
  * @example
30
35
  * ```ts
36
+ * // No options
31
37
  * const mock = createTestPluginContext({ analytics: { query: fixtureRows } });
32
38
  * await mock.attach(agentsPlugin);
33
39
  * // ...exercise a handler that dispatches analytics.query...
34
40
  * expect(mock.toolCalls[0]).toMatchObject({ plugin: "analytics", asUser: true });
41
+ *
42
+ * // With options — installs service context + seeded client
43
+ * const mock = createTestPluginContext(
44
+ * {},
45
+ * { responses: { "jobs.getRun": { state: "DONE" } } },
46
+ * );
35
47
  * ```
36
48
  */
37
- function createTestPluginContext(fakes = {}) {
49
+ function createTestPluginContext(fakes = {}, options) {
50
+ if (!options) return createTestPluginContextSync(fakes);
51
+ return createTestPluginContextWithOptions(fakes, options);
52
+ }
53
+ function createTestPluginContextSync(fakes) {
38
54
  const telemetry = createMockTelemetry();
39
55
  const ctx = new PluginContext({ telemetry });
40
56
  const toolCalls = [];
@@ -125,6 +141,35 @@ function createTestPluginContext(fakes = {}) {
125
141
  attach
126
142
  };
127
143
  }
144
+ function createTestPluginContextWithOptions(fakes, options) {
145
+ const { responses = {}, env: envVars = {}, strict = false } = options;
146
+ const serviceContextMock = mockServiceContext({ serviceDatabricksClient: createMockWorkspaceClient({
147
+ responses,
148
+ strict
149
+ }) });
150
+ const restoreEnv = applyEnv(envVars);
151
+ const base = createTestPluginContextSync(fakes);
152
+ let hasRestored = false;
153
+ const restore = () => {
154
+ if (hasRestored) return;
155
+ hasRestored = true;
156
+ restoreEnv();
157
+ serviceContextMock.restore();
158
+ };
159
+ try {
160
+ onTestFinished(() => {
161
+ restore();
162
+ });
163
+ } catch {
164
+ afterEach(() => {
165
+ restore();
166
+ });
167
+ }
168
+ return {
169
+ ...base,
170
+ restore
171
+ };
172
+ }
128
173
  function cacheReady() {
129
174
  try {
130
175
  CacheManager.getInstanceSync();
@@ -1 +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,SAAS,iBACP,MACA,OACM;EACN,MAAM,SAAuB;GAC3B,gBAAgB,EAAE;GAClB,OAAO,OAAO,KAAK,MAAM,CAAC,KAAK,cAAc;IAC3C,MAAM;IACN,aAAa,aAAa,KAAK,GAAG;IAClC,YAAY,EAAE,MAAM,UAAU;IAC/B,EAAE;GACJ;AACD,YAAU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AAC,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
+ {"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\";\nimport { afterEach, onTestFinished } from \"vitest\";\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 { applyEnv, createMockTelemetry, mockServiceContext } from \"./fixtures\";\nimport { createMockWorkspaceClient } from \"./mock-workspace-client\";\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/**\n * Options for {@link createTestPluginContext} when called with a second parameter.\n * When provided, `createTestPluginContext` installs a service context seeded\n * from a mock workspace client, plus optional environment variables.\n */\nexport interface TestPluginContextOptions {\n /**\n * Responses keyed by dotted path (`\"jobs.getRun\"`) for the mocked workspace\n * client. Passed directly to {@link createMockWorkspaceClient}.\n */\n responses?: Record<string, unknown>;\n /**\n * Environment variables to set for the test. Captured on entry, restored\n * (or deleted if they were unset) on exit via an `afterEach` hook and/or\n * explicit {@link TestPluginContext.restore}.\n */\n env?: Record<string, string>;\n /**\n * If `true`, throw when a workspace client path with no declared response is\n * called, instead of resolving `undefined`. Defaults to `false` (never crash).\n */\n strict?: boolean;\n}\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 * Restore the service context and environment variables to their pre-test state.\n * Called automatically via `afterEach` when options were provided to\n * `createTestPluginContext`. Can also be called explicitly for escape hatches\n * (e.g., cleanup inside a test body). Idempotent — safe to call multiple times.\n * Only present if the context was created with options.\n */\n restore?: () => void;\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 * @param options - When provided, installs a mock workspace client seeded from\n * `responses`, mocks the service context, and sets `env`. Omit it for the\n * original behavior.\n *\n * @example\n * ```ts\n * // No options\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 * // With options — installs service context + seeded client\n * const mock = createTestPluginContext(\n * {},\n * { responses: { \"jobs.getRun\": { state: \"DONE\" } } },\n * );\n * ```\n */\nexport function createTestPluginContext(\n fakes: FakeProviders = {},\n options?: TestPluginContextOptions,\n): TestPluginContext {\n // No options: original behavior.\n if (!options) {\n return createTestPluginContextSync(fakes);\n }\n\n // Options provided: install the seeded client, service context, and scoped env.\n return createTestPluginContextWithOptions(fakes, options);\n}\n\nfunction createTestPluginContextSync(fakes: FakeProviders): 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 createTestPluginContextWithOptions(\n fakes: FakeProviders,\n options: TestPluginContextOptions,\n): TestPluginContext {\n const { responses = {}, env: envVars = {}, strict = false } = options;\n\n // Build a mock workspace client seeded from responses\n const client = createMockWorkspaceClient({\n responses,\n strict,\n });\n\n // Install the mock service context with the seeded client\n const serviceContextMock = mockServiceContext({\n serviceDatabricksClient: client,\n });\n\n // Set env (captured for restore) via the shared helper.\n const restoreEnv = applyEnv(envVars);\n\n // Create the base context (without options this time, since we're handling everything)\n const base = createTestPluginContextSync(fakes);\n\n // Restore function: restores env and service context (idempotent)\n let hasRestored = false;\n const restore = () => {\n if (hasRestored) return;\n hasRestored = true;\n restoreEnv();\n serviceContextMock.restore();\n };\n\n // Auto-restore after the current test. This helper is documented and used\n // from inside a test body, where a runtime-registered `afterEach` does NOT run\n // for that test (Vitest only collects `afterEach` before the test runs) — the\n // reason the old `afterEach` here silently leaked. `onTestFinished` is the hook\n // built for runtime registration and fires after the creating test. If called\n // at collection scope instead, it throws, so fall back to `afterEach` there.\n try {\n onTestFinished(() => {\n restore();\n });\n } catch {\n afterEach(() => {\n restore();\n });\n }\n\n // Return the context with the restore method\n return {\n ...base,\n restore,\n };\n}\n\nfunction cacheReady(): boolean {\n try {\n CacheManager.getInstanceSync();\n return true;\n } catch {\n return false;\n }\n}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AAM,EAAE,YAAY,EAAE,EAAE,KAAK,UAAU,EAAE,EAAE,SAAS,UAAU;CAS9D,MAAM,qBAAqB,mBAAmB,EAC5C,yBAPa,0BAA0B;EACvC;EACA;EACD,CAAC,EAKD,CAAC;CAGF,MAAM,aAAa,SAAS,QAAQ;CAGpC,MAAM,OAAO,4BAA4B,MAAM;CAG/C,IAAI,cAAc;CAClB,MAAM,gBAAgB;AACpB,MAAI,YAAa;AACjB,gBAAc;AACd,cAAY;AACZ,qBAAmB,SAAS;;AAS9B,KAAI;AACF,uBAAqB;AACnB,YAAS;IACT;SACI;AACN,kBAAgB;AACd,YAAS;IACT;;AAIJ,QAAO;EACL,GAAG;EACH;EACD;;AAGH,SAAS,aAAsB;AAC7B,KAAI;AACF,eAAa,iBAAiB;AAC9B,SAAO;SACD;AACN,SAAO"}
@@ -3,7 +3,7 @@ import { walkSchema } from "./walk-schema.js";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import fs from "node:fs/promises";
5
5
  import path from "node:path";
6
- import fsSync from "node:fs";
6
+ import fs$1 from "node:fs";
7
7
 
8
8
  //#region src/type-generator/database/generate.ts
9
9
  /** Safe diagnostic raised when database declarations cannot be generated. */
@@ -63,7 +63,7 @@ ${walkSchema(schema).map((entry) => ` ${JSON.stringify(entry.name)}: {
63
63
  }
64
64
  /** Atomically replace generated output only when its content changes. */
65
65
  async function writeIfChanged(outFile, content) {
66
- if (fsSync.existsSync(outFile) && await fs.readFile(outFile, "utf8") === content) return;
66
+ if (fs$1.existsSync(outFile) && await fs.readFile(outFile, "utf8") === content) return;
67
67
  await fs.mkdir(path.dirname(outFile), { recursive: true });
68
68
  const temporary = path.join(path.dirname(outFile), `.${path.basename(outFile)}.${randomUUID()}.tmp`);
69
69
  try {
@@ -80,7 +80,7 @@ async function importSchema(schemaFile) {
80
80
  }
81
81
  /** Generate current registry types or neutralize them when loading fails. */
82
82
  async function generateDatabaseTypes(options) {
83
- if (!fsSync.existsSync(options.schemaFile)) {
83
+ if (!fs$1.existsSync(options.schemaFile)) {
84
84
  await writeIfChanged(options.outFile, NEUTRAL_DATABASE_TYPES);
85
85
  return;
86
86
  }
@@ -1 +1 @@
1
- {"version":3,"file":"generate.js","names":[],"sources":["../../../src/type-generator/database/generate.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport fsSync from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { Schema } from \"../../database/schema-builder\";\nimport { assertFinalizedSchema } from \"../../database/schema-builder/define-schema\";\nimport { walkSchema } from \"./walk-schema\";\n\n/** Safe diagnostic raised when database declarations cannot be generated. */\nexport class DatabaseTypegenError extends Error {\n constructor(message = \"Database schema generation failed\") {\n super(message);\n this.name = \"DatabaseTypegenError\";\n }\n}\n\ninterface GenerateDatabaseTypesOptions {\n readonly schemaFile: string;\n readonly outFile: string;\n}\n\nexport const DATABASE_TYPES_FILE = \"database.d.ts\";\n\nfunction schemaLabel(schemaFile: string): string {\n return path.relative(process.cwd(), schemaFile) || schemaFile;\n}\n\nfunction importFailureReason(error: unknown): string {\n if (error instanceof SyntaxError) return \"could not be parsed\";\n let code: unknown;\n try {\n code =\n error && typeof error === \"object\"\n ? Reflect.get(error, \"code\")\n : undefined;\n } catch {\n code = undefined;\n }\n if (code === \"MODULE_NOT_FOUND\" || code === \"ERR_MODULE_NOT_FOUND\") {\n return \"contains an unresolved import\";\n }\n return \"threw while loading\";\n}\n\n/** Empty augmentation used when no valid database schema is available. */\nexport const NEUTRAL_DATABASE_TYPES = `// Auto-generated by AppKit - DO NOT EDIT\nimport \"@databricks/appkit\";\n\ndeclare module \"@databricks/appkit\" {\n interface DatabaseRegistry {}\n}\n`;\n\n/** Render one `DatabaseRegistry` augmentation from a finalized schema. */\nfunction render(schema: Schema): string {\n const entries = walkSchema(schema)\n .map(\n (entry) => ` ${JSON.stringify(entry.name)}: {\n row: ${entry.row};\n publicRow: ${entry.publicRow};\n insert: ${entry.insert};\n update: ${entry.update};\n filters: ${entry.filters};\n includes: ${entry.includes};\n hasPrimaryKey: ${entry.hasPrimaryKey};\n };`,\n )\n .join(\"\\n\");\n return `// Auto-generated by AppKit - DO NOT EDIT\nimport \"@databricks/appkit\";\n\ndeclare module \"@databricks/appkit\" {\n type DatabaseLogicalFilter<T> = T & {\n and?: readonly DatabaseLogicalFilter<T>[];\n or?: readonly DatabaseLogicalFilter<T>[];\n };\n\n interface DatabaseRegistry {\n${entries}\n }\n}\n`;\n}\n\n/** Atomically replace generated output only when its content changes. */\nasync function writeIfChanged(outFile: string, content: string): Promise<void> {\n if (\n fsSync.existsSync(outFile) &&\n (await fs.readFile(outFile, \"utf8\")) === content\n )\n return;\n await fs.mkdir(path.dirname(outFile), { recursive: true });\n const temporary = path.join(\n path.dirname(outFile),\n `.${path.basename(outFile)}.${randomUUID()}.tmp`,\n );\n try {\n await fs.writeFile(temporary, content, \"utf8\");\n await fs.rename(temporary, outFile);\n } finally {\n await fs.rm(temporary, { force: true });\n }\n}\n\n/** Disable Jiti's module cache so watch-mode runs observe schema edits. */\nasync function importSchema(schemaFile: string): Promise<unknown> {\n const { createJiti } = await import(\"jiti\");\n return createJiti(import.meta.url, { moduleCache: false }).import(schemaFile);\n}\n\n/** Generate current registry types or neutralize them when loading fails. */\nexport async function generateDatabaseTypes(\n options: GenerateDatabaseTypesOptions,\n): Promise<void> {\n if (!fsSync.existsSync(options.schemaFile)) {\n await writeIfChanged(options.outFile, NEUTRAL_DATABASE_TYPES);\n return;\n }\n try {\n const module = (await importSchema(options.schemaFile)) as {\n schema?: Schema;\n };\n if (!(\"schema\" in module)) {\n throw new DatabaseTypegenError(\n `Database schema module \"${schemaLabel(options.schemaFile)}\" must export a named \"schema\"`,\n );\n }\n try {\n assertFinalizedSchema(module.schema);\n } catch {\n throw new DatabaseTypegenError(\n `Database schema \"${schemaLabel(options.schemaFile)}\" is not a finalized AppKit schema`,\n );\n }\n await writeIfChanged(options.outFile, render(module.schema));\n } catch (error) {\n // A failed run must not leave stale entities visible to TypeScript.\n await writeIfChanged(options.outFile, NEUTRAL_DATABASE_TYPES);\n throw error instanceof DatabaseTypegenError\n ? error\n : new DatabaseTypegenError(\n `Database schema \"${schemaLabel(options.schemaFile)}\" ${importFailureReason(error)}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YAAY,UAAU,qCAAqC;AACzD,QAAM,QAAQ;AACd,OAAK,OAAO;;;AAShB,MAAa,sBAAsB;AAEnC,SAAS,YAAY,YAA4B;AAC/C,QAAO,KAAK,SAAS,QAAQ,KAAK,EAAE,WAAW,IAAI;;AAGrD,SAAS,oBAAoB,OAAwB;AACnD,KAAI,iBAAiB,YAAa,QAAO;CACzC,IAAI;AACJ,KAAI;AACF,SACE,SAAS,OAAO,UAAU,WACtB,QAAQ,IAAI,OAAO,OAAO,GAC1B;SACA;AACN,SAAO;;AAET,KAAI,SAAS,sBAAsB,SAAS,uBAC1C,QAAO;AAET,QAAO;;;AAIT,MAAa,yBAAyB;;;;;;;;AAStC,SAAS,OAAO,QAAwB;AActC,QAAO;;;;;;;;;;EAbS,WAAW,OAAO,CAC/B,KACE,UAAU,OAAO,KAAK,UAAU,MAAM,KAAK,CAAC;aACtC,MAAM,IAAI;mBACJ,MAAM,UAAU;gBACnB,MAAM,OAAO;gBACb,MAAM,OAAO;iBACZ,MAAM,QAAQ;kBACb,MAAM,SAAS;uBACV,MAAM,cAAc;QAEtC,CACA,KAAK,KAAK,CAWL;;;;;;AAOV,eAAe,eAAe,SAAiB,SAAgC;AAC7E,KACE,OAAO,WAAW,QAAQ,IACzB,MAAM,GAAG,SAAS,SAAS,OAAO,KAAM,QAEzC;AACF,OAAM,GAAG,MAAM,KAAK,QAAQ,QAAQ,EAAE,EAAE,WAAW,MAAM,CAAC;CAC1D,MAAM,YAAY,KAAK,KACrB,KAAK,QAAQ,QAAQ,EACrB,IAAI,KAAK,SAAS,QAAQ,CAAC,GAAG,YAAY,CAAC,MAC5C;AACD,KAAI;AACF,QAAM,GAAG,UAAU,WAAW,SAAS,OAAO;AAC9C,QAAM,GAAG,OAAO,WAAW,QAAQ;WAC3B;AACR,QAAM,GAAG,GAAG,WAAW,EAAE,OAAO,MAAM,CAAC;;;;AAK3C,eAAe,aAAa,YAAsC;CAChE,MAAM,EAAE,eAAe,MAAM,OAAO;AACpC,QAAO,WAAW,OAAO,KAAK,KAAK,EAAE,aAAa,OAAO,CAAC,CAAC,OAAO,WAAW;;;AAI/E,eAAsB,sBACpB,SACe;AACf,KAAI,CAAC,OAAO,WAAW,QAAQ,WAAW,EAAE;AAC1C,QAAM,eAAe,QAAQ,SAAS,uBAAuB;AAC7D;;AAEF,KAAI;EACF,MAAM,SAAU,MAAM,aAAa,QAAQ,WAAW;AAGtD,MAAI,EAAE,YAAY,QAChB,OAAM,IAAI,qBACR,2BAA2B,YAAY,QAAQ,WAAW,CAAC,gCAC5D;AAEH,MAAI;AACF,yBAAsB,OAAO,OAAO;UAC9B;AACN,SAAM,IAAI,qBACR,oBAAoB,YAAY,QAAQ,WAAW,CAAC,oCACrD;;AAEH,QAAM,eAAe,QAAQ,SAAS,OAAO,OAAO,OAAO,CAAC;UACrD,OAAO;AAEd,QAAM,eAAe,QAAQ,SAAS,uBAAuB;AAC7D,QAAM,iBAAiB,uBACnB,QACA,IAAI,qBACF,oBAAoB,YAAY,QAAQ,WAAW,CAAC,IAAI,oBAAoB,MAAM,GACnF"}
1
+ {"version":3,"file":"generate.js","names":["fsSync"],"sources":["../../../src/type-generator/database/generate.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport fsSync from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { Schema } from \"../../database/schema-builder\";\nimport { assertFinalizedSchema } from \"../../database/schema-builder/define-schema\";\nimport { walkSchema } from \"./walk-schema\";\n\n/** Safe diagnostic raised when database declarations cannot be generated. */\nexport class DatabaseTypegenError extends Error {\n constructor(message = \"Database schema generation failed\") {\n super(message);\n this.name = \"DatabaseTypegenError\";\n }\n}\n\ninterface GenerateDatabaseTypesOptions {\n readonly schemaFile: string;\n readonly outFile: string;\n}\n\nexport const DATABASE_TYPES_FILE = \"database.d.ts\";\n\nfunction schemaLabel(schemaFile: string): string {\n return path.relative(process.cwd(), schemaFile) || schemaFile;\n}\n\nfunction importFailureReason(error: unknown): string {\n if (error instanceof SyntaxError) return \"could not be parsed\";\n let code: unknown;\n try {\n code =\n error && typeof error === \"object\"\n ? Reflect.get(error, \"code\")\n : undefined;\n } catch {\n code = undefined;\n }\n if (code === \"MODULE_NOT_FOUND\" || code === \"ERR_MODULE_NOT_FOUND\") {\n return \"contains an unresolved import\";\n }\n return \"threw while loading\";\n}\n\n/** Empty augmentation used when no valid database schema is available. */\nexport const NEUTRAL_DATABASE_TYPES = `// Auto-generated by AppKit - DO NOT EDIT\nimport \"@databricks/appkit\";\n\ndeclare module \"@databricks/appkit\" {\n interface DatabaseRegistry {}\n}\n`;\n\n/** Render one `DatabaseRegistry` augmentation from a finalized schema. */\nfunction render(schema: Schema): string {\n const entries = walkSchema(schema)\n .map(\n (entry) => ` ${JSON.stringify(entry.name)}: {\n row: ${entry.row};\n publicRow: ${entry.publicRow};\n insert: ${entry.insert};\n update: ${entry.update};\n filters: ${entry.filters};\n includes: ${entry.includes};\n hasPrimaryKey: ${entry.hasPrimaryKey};\n };`,\n )\n .join(\"\\n\");\n return `// Auto-generated by AppKit - DO NOT EDIT\nimport \"@databricks/appkit\";\n\ndeclare module \"@databricks/appkit\" {\n type DatabaseLogicalFilter<T> = T & {\n and?: readonly DatabaseLogicalFilter<T>[];\n or?: readonly DatabaseLogicalFilter<T>[];\n };\n\n interface DatabaseRegistry {\n${entries}\n }\n}\n`;\n}\n\n/** Atomically replace generated output only when its content changes. */\nasync function writeIfChanged(outFile: string, content: string): Promise<void> {\n if (\n fsSync.existsSync(outFile) &&\n (await fs.readFile(outFile, \"utf8\")) === content\n )\n return;\n await fs.mkdir(path.dirname(outFile), { recursive: true });\n const temporary = path.join(\n path.dirname(outFile),\n `.${path.basename(outFile)}.${randomUUID()}.tmp`,\n );\n try {\n await fs.writeFile(temporary, content, \"utf8\");\n await fs.rename(temporary, outFile);\n } finally {\n await fs.rm(temporary, { force: true });\n }\n}\n\n/** Disable Jiti's module cache so watch-mode runs observe schema edits. */\nasync function importSchema(schemaFile: string): Promise<unknown> {\n const { createJiti } = await import(\"jiti\");\n return createJiti(import.meta.url, { moduleCache: false }).import(schemaFile);\n}\n\n/** Generate current registry types or neutralize them when loading fails. */\nexport async function generateDatabaseTypes(\n options: GenerateDatabaseTypesOptions,\n): Promise<void> {\n if (!fsSync.existsSync(options.schemaFile)) {\n await writeIfChanged(options.outFile, NEUTRAL_DATABASE_TYPES);\n return;\n }\n try {\n const module = (await importSchema(options.schemaFile)) as {\n schema?: Schema;\n };\n if (!(\"schema\" in module)) {\n throw new DatabaseTypegenError(\n `Database schema module \"${schemaLabel(options.schemaFile)}\" must export a named \"schema\"`,\n );\n }\n try {\n assertFinalizedSchema(module.schema);\n } catch {\n throw new DatabaseTypegenError(\n `Database schema \"${schemaLabel(options.schemaFile)}\" is not a finalized AppKit schema`,\n );\n }\n await writeIfChanged(options.outFile, render(module.schema));\n } catch (error) {\n // A failed run must not leave stale entities visible to TypeScript.\n await writeIfChanged(options.outFile, NEUTRAL_DATABASE_TYPES);\n throw error instanceof DatabaseTypegenError\n ? error\n : new DatabaseTypegenError(\n `Database schema \"${schemaLabel(options.schemaFile)}\" ${importFailureReason(error)}`,\n );\n }\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YAAY,UAAU,qCAAqC;AACzD,QAAM,QAAQ;AACd,OAAK,OAAO;;;AAShB,MAAa,sBAAsB;AAEnC,SAAS,YAAY,YAA4B;AAC/C,QAAO,KAAK,SAAS,QAAQ,KAAK,EAAE,WAAW,IAAI;;AAGrD,SAAS,oBAAoB,OAAwB;AACnD,KAAI,iBAAiB,YAAa,QAAO;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,MAAM,aAAa,QAAQ,WAAW;AAGtD,MAAI,EAAE,YAAY,QAChB,OAAM,IAAI,qBACR,2BAA2B,YAAY,QAAQ,WAAW,CAAC,gCAC5D;AAEH,MAAI;AACF,yBAAsB,OAAO,OAAO;UAC9B;AACN,SAAM,IAAI,qBACR,oBAAoB,YAAY,QAAQ,WAAW,CAAC,oCACrD;;AAEH,QAAM,eAAe,QAAQ,SAAS,OAAO,OAAO,OAAO,CAAC;UACrD,OAAO;AAEd,QAAM,eAAe,QAAQ,SAAS,uBAAuB;AAC7D,QAAM,iBAAiB,uBACnB,QACA,IAAI,qBACF,oBAAoB,YAAY,QAAQ,WAAW,CAAC,IAAI,oBAAoB,MAAM,GACnF"}
@@ -2,7 +2,7 @@ import { createLogger } from "../logging/logger.js";
2
2
  import pc from "picocolors";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
- import fsSync from "node:fs";
5
+ import fs$1 from "node:fs";
6
6
 
7
7
  //#region src/type-generator/migration.ts
8
8
  const logger = createLogger("type-generator:migration");
@@ -16,7 +16,7 @@ const logger = createLogger("type-generator:migration");
16
16
  */
17
17
  function resolveProjectRoot(outFile) {
18
18
  const root = path.resolve(path.dirname(outFile), "..", "..");
19
- if (!fsSync.existsSync(path.join(root, "package.json"))) logger.warn("Resolved project root %s has no package.json — migration may target the wrong directory. Check your outFile path: %s", root, outFile);
19
+ if (!fs$1.existsSync(path.join(root, "package.json"))) logger.warn("Resolved project root %s has no package.json — migration may target the wrong directory. Check your outFile path: %s", root, outFile);
20
20
  return root;
21
21
  }
22
22
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"migration.js","names":[],"sources":["../../src/type-generator/migration.ts"],"sourcesContent":["import fsSync from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport pc from \"picocolors\";\n\nimport { createLogger } from \"../logging/logger\";\n\nconst logger = createLogger(\"type-generator:migration\");\n\n/**\n * Derive project root from an outFile path.\n * outFile is always `<projectRoot>/shared/appkit-types/<file>` — both the Vite plugins\n * and the CLI construct it this way, so going up two levels is safe.\n *\n * Validates that the resolved root contains a package.json — if not, logs a warning\n * so custom outFile paths don't silently operate on the wrong directory.\n */\nexport function resolveProjectRoot(outFile: string): string {\n const root = path.resolve(path.dirname(outFile), \"..\", \"..\");\n if (!fsSync.existsSync(path.join(root, \"package.json\"))) {\n logger.warn(\n \"Resolved project root %s has no package.json — migration may target the wrong directory. \" +\n \"Check your outFile path: %s\",\n root,\n outFile,\n );\n }\n return root;\n}\n\n/**\n * Remove old generated types from client/src/ (pre-shared/ location).\n * Best-effort: silently ignores missing files.\n */\nexport async function removeOldGeneratedTypes(\n projectRoot: string,\n filename: string,\n): Promise<void> {\n const oldFile = path.join(projectRoot, \"client\", \"src\", filename);\n try {\n await fs.unlink(oldFile);\n logger.debug(\"Removed old types at %s\", oldFile);\n } catch {\n // File doesn't exist — nothing to clean up\n }\n}\n\n// ── Project config migration ────────────────────────────────────────────\n\nconst migratedProjects = new Set<string>();\n\n/**\n * One-time config migration: update tsconfig and package.json for shared/ types output.\n * Idempotent — each sub-migration checks current file state and skips if already migrated.\n * Deduplicates per project root so monorepo builds migrate each app independently.\n * Opt-out: set `\"appkit\": { \"autoMigrate\": false }` in package.json.\n */\nexport async function migrateProjectConfig(projectRoot: string): Promise<void> {\n const resolved = path.resolve(projectRoot);\n if (migratedProjects.has(resolved)) return;\n migratedProjects.add(resolved);\n\n if (await isAutoMigrateDisabled(projectRoot)) {\n logger.debug(\"Auto-migration disabled via package.json appkit.autoMigrate\");\n return;\n }\n\n const results: Array<{ file: string; action: string }> = [];\n\n results.push(...(await migrateTsconfigClient(projectRoot)));\n results.push(...(await migrateTsconfigServer(projectRoot)));\n results.push(...(await migratePackageJsonScripts(projectRoot)));\n\n if (results.length > 0) {\n printMigrationSummary(results);\n }\n}\n\n/** Exported for testing only. */\nexport function _resetMigrationState(): void {\n migratedProjects.clear();\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────\n\nasync function isAutoMigrateDisabled(projectRoot: string): Promise<boolean> {\n try {\n const raw = await fs.readFile(\n path.join(projectRoot, \"package.json\"),\n \"utf-8\",\n );\n const parsed = JSON.parse(raw);\n return parsed.appkit?.autoMigrate === false;\n } catch {\n return false;\n }\n}\n\n/** Strip JSONC comments (block and line) so JSON.parse can handle tsconfig files. */\nfunction stripJsonComments(text: string): string {\n // Match strings (to skip them) or comments (to remove them).\n // Strings must be matched first to avoid stripping comment-like patterns inside string values\n // (e.g. \"server/**/*\" contains /* which looks like a block comment start).\n return text.replace(/\"(?:[^\"\\\\]|\\\\.)*\"|\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*/g, (match) =>\n match.startsWith('\"') ? match : \"\",\n );\n}\n\ntype MigrationResult = Array<{ file: string; action: string }>;\n\n// ── tsconfig.client.json ────────────────────────────────────────────────\n\nasync function migrateTsconfigClient(\n projectRoot: string,\n): Promise<MigrationResult> {\n const results: MigrationResult = [];\n const filePath = path.join(projectRoot, \"tsconfig.client.json\");\n\n try {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(stripJsonComments(raw));\n\n if (!Array.isArray(parsed.include)) return results;\n if (parsed.include.includes(\"shared/appkit-types\")) return results;\n\n parsed.include.push(\"shared/appkit-types\");\n await fs.writeFile(\n filePath,\n `${JSON.stringify(parsed, null, 2)}\\n`,\n \"utf-8\",\n );\n results.push({\n file: \"tsconfig.client.json\",\n action: 'added \"shared/appkit-types\" to include',\n });\n } catch (err) {\n logger.warn(\n \"Failed to migrate tsconfig.client.json: %s\",\n (err as Error).message,\n );\n }\n\n return results;\n}\n\n// ── tsconfig.server.json ────────────────────────────────────────────────\n\nasync function migrateTsconfigServer(\n projectRoot: string,\n): Promise<MigrationResult> {\n const results: MigrationResult = [];\n const filePath = path.join(projectRoot, \"tsconfig.server.json\");\n\n try {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(stripJsonComments(raw));\n const opts = parsed.compilerOptions;\n\n if (!opts || !opts.outDir) return results; // already migrated or non-standard\n\n delete opts.outDir;\n delete opts.declaration;\n delete opts.declarationMap;\n delete opts.sourceMap;\n opts.noEmit = true;\n\n await fs.writeFile(\n filePath,\n `${JSON.stringify(parsed, null, 2)}\\n`,\n \"utf-8\",\n );\n results.push({\n file: \"tsconfig.server.json\",\n action: \"switched to noEmit mode\",\n });\n } catch (err) {\n logger.warn(\n \"Failed to migrate tsconfig.server.json: %s\",\n (err as Error).message,\n );\n }\n\n return results;\n}\n\n// ── package.json ────────────────────────────────────────────────────────\n\nconst SCRIPT_MIGRATIONS: Record<string, { old: string; new: string }> = {\n \"build:server\": {\n old: \"tsdown -c tsdown.server.config.ts\",\n new: \"tsc -b tsconfig.server.json && tsdown -c tsdown.server.config.ts\",\n },\n typecheck: {\n old: \"tsc -p ./tsconfig.server.json --noEmit && tsc -p ./tsconfig.client.json --noEmit\",\n new: \"tsc -b tsconfig.server.json && tsc -b tsconfig.client.json\",\n },\n};\n\nasync function migratePackageJsonScripts(\n projectRoot: string,\n): Promise<MigrationResult> {\n const results: MigrationResult = [];\n const filePath = path.join(projectRoot, \"package.json\");\n\n try {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n const scripts = parsed.scripts;\n if (!scripts) return results;\n\n const updated: string[] = [];\n\n for (const [name, { old, new: replacement }] of Object.entries(\n SCRIPT_MIGRATIONS,\n )) {\n if (scripts[name] === old) {\n scripts[name] = replacement;\n updated.push(name);\n }\n }\n\n if (updated.length === 0) return results;\n\n const indent = raw.match(/^\\s+/m)?.[0]?.length === 4 ? 4 : 2;\n await fs.writeFile(\n filePath,\n `${JSON.stringify(parsed, null, indent)}\\n`,\n \"utf-8\",\n );\n results.push({\n file: \"package.json\",\n action: `updated ${updated.join(\" and \")} scripts`,\n });\n } catch (err) {\n logger.warn(\n \"Failed to migrate package.json scripts: %s\",\n (err as Error).message,\n );\n }\n\n return results;\n}\n\n// ── Summary ─────────────────────────────────────────────────────────────\n\nfunction printMigrationSummary(\n results: Array<{ file: string; action: string }>,\n) {\n const separator = pc.dim(\"─\".repeat(50));\n console.log(\"\");\n console.log(` ${pc.bold(\"Typegen Migration\")}`);\n console.log(` ${separator}`);\n for (const { file, action } of results) {\n console.log(` ${pc.green(\"✓\")} ${file.padEnd(24)} ${pc.dim(action)}`);\n }\n console.log(` ${separator}`);\n console.log(\"\");\n}\n"],"mappings":";;;;;;;AAQA,MAAM,SAAS,aAAa,2BAA2B;;;;;;;;;AAUvD,SAAgB,mBAAmB,SAAyB;CAC1D,MAAM,OAAO,KAAK,QAAQ,KAAK,QAAQ,QAAQ,EAAE,MAAM,KAAK;AAC5D,KAAI,CAAC,OAAO,WAAW,KAAK,KAAK,MAAM,eAAe,CAAC,CACrD,QAAO,KACL,wHAEA,MACA,QACD;AAEH,QAAO;;;;;;AAOT,eAAsB,wBACpB,aACA,UACe;CACf,MAAM,UAAU,KAAK,KAAK,aAAa,UAAU,OAAO,SAAS;AACjE,KAAI;AACF,QAAM,GAAG,OAAO,QAAQ;AACxB,SAAO,MAAM,2BAA2B,QAAQ;SAC1C;;AAOV,MAAM,mCAAmB,IAAI,KAAa;;;;;;;AAQ1C,eAAsB,qBAAqB,aAAoC;CAC7E,MAAM,WAAW,KAAK,QAAQ,YAAY;AAC1C,KAAI,iBAAiB,IAAI,SAAS,CAAE;AACpC,kBAAiB,IAAI,SAAS;AAE9B,KAAI,MAAM,sBAAsB,YAAY,EAAE;AAC5C,SAAO,MAAM,8DAA8D;AAC3E;;CAGF,MAAM,UAAmD,EAAE;AAE3D,SAAQ,KAAK,GAAI,MAAM,sBAAsB,YAAY,CAAE;AAC3D,SAAQ,KAAK,GAAI,MAAM,sBAAsB,YAAY,CAAE;AAC3D,SAAQ,KAAK,GAAI,MAAM,0BAA0B,YAAY,CAAE;AAE/D,KAAI,QAAQ,SAAS,EACnB,uBAAsB,QAAQ;;AAWlC,eAAe,sBAAsB,aAAuC;AAC1E,KAAI;EACF,MAAM,MAAM,MAAM,GA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,CAAC,GAAG,KAAK,OAAO,GAAG,CAAC,GAAG,GAAG,IAAI,OAAO,GAAG;AAExE,SAAQ,IAAI,KAAK,YAAY;AAC7B,SAAQ,IAAI,GAAG"}
1
+ {"version":3,"file":"migration.js","names":["fsSync"],"sources":["../../src/type-generator/migration.ts"],"sourcesContent":["import fsSync from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport pc from \"picocolors\";\n\nimport { createLogger } from \"../logging/logger\";\n\nconst logger = createLogger(\"type-generator:migration\");\n\n/**\n * Derive project root from an outFile path.\n * outFile is always `<projectRoot>/shared/appkit-types/<file>` — both the Vite plugins\n * and the CLI construct it this way, so going up two levels is safe.\n *\n * Validates that the resolved root contains a package.json — if not, logs a warning\n * so custom outFile paths don't silently operate on the wrong directory.\n */\nexport function resolveProjectRoot(outFile: string): string {\n const root = path.resolve(path.dirname(outFile), \"..\", \"..\");\n if (!fsSync.existsSync(path.join(root, \"package.json\"))) {\n logger.warn(\n \"Resolved project root %s has no package.json — migration may target the wrong directory. \" +\n \"Check your outFile path: %s\",\n root,\n outFile,\n );\n }\n return root;\n}\n\n/**\n * Remove old generated types from client/src/ (pre-shared/ location).\n * Best-effort: silently ignores missing files.\n */\nexport async function removeOldGeneratedTypes(\n projectRoot: string,\n filename: string,\n): Promise<void> {\n const oldFile = path.join(projectRoot, \"client\", \"src\", filename);\n try {\n await fs.unlink(oldFile);\n logger.debug(\"Removed old types at %s\", oldFile);\n } catch {\n // File doesn't exist — nothing to clean up\n }\n}\n\n// ── Project config migration ────────────────────────────────────────────\n\nconst migratedProjects = new Set<string>();\n\n/**\n * One-time config migration: update tsconfig and package.json for shared/ types output.\n * Idempotent — each sub-migration checks current file state and skips if already migrated.\n * Deduplicates per project root so monorepo builds migrate each app independently.\n * Opt-out: set `\"appkit\": { \"autoMigrate\": false }` in package.json.\n */\nexport async function migrateProjectConfig(projectRoot: string): Promise<void> {\n const resolved = path.resolve(projectRoot);\n if (migratedProjects.has(resolved)) return;\n migratedProjects.add(resolved);\n\n if (await isAutoMigrateDisabled(projectRoot)) {\n logger.debug(\"Auto-migration disabled via package.json appkit.autoMigrate\");\n return;\n }\n\n const results: Array<{ file: string; action: string }> = [];\n\n results.push(...(await migrateTsconfigClient(projectRoot)));\n results.push(...(await migrateTsconfigServer(projectRoot)));\n results.push(...(await migratePackageJsonScripts(projectRoot)));\n\n if (results.length > 0) {\n printMigrationSummary(results);\n }\n}\n\n/** Exported for testing only. */\nexport function _resetMigrationState(): void {\n migratedProjects.clear();\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────\n\nasync function isAutoMigrateDisabled(projectRoot: string): Promise<boolean> {\n try {\n const raw = await fs.readFile(\n path.join(projectRoot, \"package.json\"),\n \"utf-8\",\n );\n const parsed = JSON.parse(raw);\n return parsed.appkit?.autoMigrate === false;\n } catch {\n return false;\n }\n}\n\n/** Strip JSONC comments (block and line) so JSON.parse can handle tsconfig files. */\nfunction stripJsonComments(text: string): string {\n // Match strings (to skip them) or comments (to remove them).\n // Strings must be matched first to avoid stripping comment-like patterns inside string values\n // (e.g. \"server/**/*\" contains /* which looks like a block comment start).\n return text.replace(/\"(?:[^\"\\\\]|\\\\.)*\"|\\/\\*[\\s\\S]*?\\*\\/|\\/\\/.*/g, (match) =>\n match.startsWith('\"') ? match : \"\",\n );\n}\n\ntype MigrationResult = Array<{ file: string; action: string }>;\n\n// ── tsconfig.client.json ────────────────────────────────────────────────\n\nasync function migrateTsconfigClient(\n projectRoot: string,\n): Promise<MigrationResult> {\n const results: MigrationResult = [];\n const filePath = path.join(projectRoot, \"tsconfig.client.json\");\n\n try {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(stripJsonComments(raw));\n\n if (!Array.isArray(parsed.include)) return results;\n if (parsed.include.includes(\"shared/appkit-types\")) return results;\n\n parsed.include.push(\"shared/appkit-types\");\n await fs.writeFile(\n filePath,\n `${JSON.stringify(parsed, null, 2)}\\n`,\n \"utf-8\",\n );\n results.push({\n file: \"tsconfig.client.json\",\n action: 'added \"shared/appkit-types\" to include',\n });\n } catch (err) {\n logger.warn(\n \"Failed to migrate tsconfig.client.json: %s\",\n (err as Error).message,\n );\n }\n\n return results;\n}\n\n// ── tsconfig.server.json ────────────────────────────────────────────────\n\nasync function migrateTsconfigServer(\n projectRoot: string,\n): Promise<MigrationResult> {\n const results: MigrationResult = [];\n const filePath = path.join(projectRoot, \"tsconfig.server.json\");\n\n try {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(stripJsonComments(raw));\n const opts = parsed.compilerOptions;\n\n if (!opts || !opts.outDir) return results; // already migrated or non-standard\n\n delete opts.outDir;\n delete opts.declaration;\n delete opts.declarationMap;\n delete opts.sourceMap;\n opts.noEmit = true;\n\n await fs.writeFile(\n filePath,\n `${JSON.stringify(parsed, null, 2)}\\n`,\n \"utf-8\",\n );\n results.push({\n file: \"tsconfig.server.json\",\n action: \"switched to noEmit mode\",\n });\n } catch (err) {\n logger.warn(\n \"Failed to migrate tsconfig.server.json: %s\",\n (err as Error).message,\n );\n }\n\n return results;\n}\n\n// ── package.json ────────────────────────────────────────────────────────\n\nconst SCRIPT_MIGRATIONS: Record<string, { old: string; new: string }> = {\n \"build:server\": {\n old: \"tsdown -c tsdown.server.config.ts\",\n new: \"tsc -b tsconfig.server.json && tsdown -c tsdown.server.config.ts\",\n },\n typecheck: {\n old: \"tsc -p ./tsconfig.server.json --noEmit && tsc -p ./tsconfig.client.json --noEmit\",\n new: \"tsc -b tsconfig.server.json && tsc -b tsconfig.client.json\",\n },\n};\n\nasync function migratePackageJsonScripts(\n projectRoot: string,\n): Promise<MigrationResult> {\n const results: MigrationResult = [];\n const filePath = path.join(projectRoot, \"package.json\");\n\n try {\n const raw = await fs.readFile(filePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n const scripts = parsed.scripts;\n if (!scripts) return results;\n\n const updated: string[] = [];\n\n for (const [name, { old, new: replacement }] of Object.entries(\n SCRIPT_MIGRATIONS,\n )) {\n if (scripts[name] === old) {\n scripts[name] = replacement;\n updated.push(name);\n }\n }\n\n if (updated.length === 0) return results;\n\n const indent = raw.match(/^\\s+/m)?.[0]?.length === 4 ? 4 : 2;\n await fs.writeFile(\n filePath,\n `${JSON.stringify(parsed, null, indent)}\\n`,\n \"utf-8\",\n );\n results.push({\n file: \"package.json\",\n action: `updated ${updated.join(\" and \")} scripts`,\n });\n } catch (err) {\n logger.warn(\n \"Failed to migrate package.json scripts: %s\",\n (err as Error).message,\n );\n }\n\n return results;\n}\n\n// ── Summary ─────────────────────────────────────────────────────────────\n\nfunction printMigrationSummary(\n results: Array<{ file: string; action: string }>,\n) {\n const separator = pc.dim(\"─\".repeat(50));\n console.log(\"\");\n console.log(` ${pc.bold(\"Typegen Migration\")}`);\n console.log(` ${separator}`);\n for (const { file, action } of results) {\n console.log(` ${pc.green(\"✓\")} ${file.padEnd(24)} ${pc.dim(action)}`);\n }\n console.log(` ${separator}`);\n console.log(\"\");\n}\n"],"mappings":";;;;;;;AAQA,MAAM,SAAS,aAAa,2BAA2B;;;;;;;;;AAUvD,SAAgB,mBAAmB,SAAyB;CAC1D,MAAM,OAAO,KAAK,QAAQ,KAAK,QAAQ,QAAQ,EAAE,MAAM,KAAK;AAC5D,KAAI,CAACA,KAAO,WAAW,KAAK,KAAK,MAAM,eAAe,CAAC,CACrD,QAAO,KACL,wHAEA,MACA,QACD;AAEH,QAAO;;;;;;AAOT,eAAsB,wBACpB,aACA,UACe;CACf,MAAM,UAAU,KAAK,KAAK,aAAa,UAAU,OAAO,SAAS;AACjE,KAAI;AACF,QAAM,GAAG,OAAO,QAAQ;AACxB,SAAO,MAAM,2BAA2B,QAAQ;SAC1C;;AAOV,MAAM,mCAAmB,IAAI,KAAa;;;;;;;AAQ1C,eAAsB,qBAAqB,aAAoC;CAC7E,MAAM,WAAW,KAAK,QAAQ,YAAY;AAC1C,KAAI,iBAAiB,IAAI,SAAS,CAAE;AACpC,kBAAiB,IAAI,SAAS;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QAAQ,WAAW,QAAQ,KAAK,QAAQ,CAAC;GAC1C,CAAC;UACK,KAAK;AACZ,SAAO,KACL,8CACC,IAAc,QAChB;;AAGH,QAAO;;AAKT,SAAS,sBACP,SACA;CACA,MAAM,YAAY,GAAG,IAAI,IAAI,OAAO,GAAG,CAAC;AACxC,SAAQ,IAAI,GAAG;AACf,SAAQ,IAAI,KAAK,GAAG,KAAK,oBAAoB,GAAG;AAChD,SAAQ,IAAI,KAAK,YAAY;AAC7B,MAAK,MAAM,EAAE,MAAM,YAAY,QAC7B,SAAQ,IAAI,KAAK,GAAG,MAAM,IAAI,CAAC,GAAG,KAAK,OAAO,GAAG,CAAC,GAAG,GAAG,IAAI,OAAO,GAAG;AAExE,SAAQ,IAAI,KAAK,YAAY;AAC7B,SAAQ,IAAI,GAAG"}
@@ -1,6 +1,6 @@
1
1
  import { createLogger } from "../../logging/logger.js";
2
2
  import path from "node:path";
3
- import fsSync from "node:fs";
3
+ import fs from "node:fs";
4
4
  import { Lang, parse } from "@ast-grep/napi";
5
5
 
6
6
  //#region src/type-generator/serving/server-file-extractor.ts
@@ -20,7 +20,7 @@ const SERVER_FILE_CANDIDATES = ["server/index.ts", "server/server.ts"];
20
20
  function findServerFile(basePath) {
21
21
  for (const candidate of SERVER_FILE_CANDIDATES) {
22
22
  const fullPath = path.join(basePath, candidate);
23
- if (fsSync.existsSync(fullPath)) return fullPath;
23
+ if (fs.existsSync(fullPath)) return fullPath;
24
24
  }
25
25
  return null;
26
26
  }
@@ -35,7 +35,7 @@ function findServerFile(basePath) {
35
35
  function extractServingEndpoints(serverFilePath) {
36
36
  let content;
37
37
  try {
38
- content = fsSync.readFileSync(serverFilePath, "utf-8");
38
+ content = fs.readFileSync(serverFilePath, "utf-8");
39
39
  } catch {
40
40
  logger.debug("Could not read server file: %s", serverFilePath);
41
41
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"server-file-extractor.js","names":["fs"],"sources":["../../../src/type-generator/serving/server-file-extractor.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Lang, parse, type SgNode } from \"@ast-grep/napi\";\n\nimport { createLogger } from \"../../logging/logger\";\nimport type { EndpointConfig } from \"../../plugins/serving/types\";\n\nconst logger = createLogger(\"type-generator:serving:extractor\");\n\n/**\n * Candidate paths for the server entry file, relative to the project root.\n * Checked in order; the first that exists is used.\n * Same convention as plugin sync (sync.ts SERVER_FILE_CANDIDATES).\n */\nconst SERVER_FILE_CANDIDATES = [\"server/index.ts\", \"server/server.ts\"];\n\n/**\n * Find the server entry file by checking candidate paths in order.\n *\n * @param basePath - Project root directory to search from\n * @returns Absolute path to the server file, or null if none found\n */\nexport function findServerFile(basePath: string): string | null {\n for (const candidate of SERVER_FILE_CANDIDATES) {\n const fullPath = path.join(basePath, candidate);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Extract serving endpoint config from a server file by AST-parsing it.\n * Looks for `serving({ endpoints: { alias: { env: \"...\" }, ... } })` calls\n * and extracts the endpoint alias names and their environment variable mappings.\n *\n * @param serverFilePath - Absolute path to the server entry file\n * @returns Extracted endpoint config, or null if not found or not extractable\n */\nexport function extractServingEndpoints(\n serverFilePath: string,\n): Record<string, EndpointConfig> | null {\n let content: string;\n try {\n content = fs.readFileSync(serverFilePath, \"utf-8\");\n } catch {\n logger.debug(\"Could not read server file: %s\", serverFilePath);\n return null;\n }\n\n const lang = serverFilePath.endsWith(\".tsx\") ? Lang.Tsx : Lang.TypeScript;\n const ast = parse(lang, content);\n const root = ast.root();\n\n // Find serving(...) call expressions\n const servingCall = findServingCall(root);\n if (!servingCall) {\n logger.debug(\"No serving() call found in %s\", serverFilePath);\n return null;\n }\n\n // Get the first argument (the config object)\n const args = servingCall.field(\"arguments\");\n if (!args) {\n return null;\n }\n\n const configArg = args.children().find((child) => child.kind() === \"object\");\n if (!configArg) {\n // serving() called with no args or non-object arg\n return null;\n }\n\n // Find the \"endpoints\" property in the config object\n const endpointsPair = findProperty(configArg, \"endpoints\");\n if (!endpointsPair) {\n // Config object has no \"endpoints\" property (e.g. serving({ timeout: 5000 }))\n return null;\n }\n\n // Get the value of the endpoints property\n const endpointsValue = getPropertyValue(endpointsPair);\n if (!endpointsValue || endpointsValue.kind() !== \"object\") {\n // endpoints is a variable reference, not an inline object\n logger.debug(\n \"serving() endpoints is not an inline object literal in %s. \" +\n \"Pass endpoints explicitly via appKitServingTypesPlugin({ endpoints }) in vite.config.ts.\",\n serverFilePath,\n );\n return null;\n }\n\n // Extract each endpoint entry\n const endpoints: Record<string, EndpointConfig> = {};\n const pairs = endpointsValue\n .children()\n .filter((child) => child.kind() === \"pair\");\n\n for (const pair of pairs) {\n const entry = extractEndpointEntry(pair);\n if (entry) {\n endpoints[entry.alias] = entry.config;\n }\n }\n\n if (Object.keys(endpoints).length === 0) {\n return null;\n }\n\n logger.debug(\n \"Extracted %d endpoint(s) from %s: %s\",\n Object.keys(endpoints).length,\n serverFilePath,\n Object.keys(endpoints).join(\", \"),\n );\n\n return endpoints;\n}\n\n/**\n * Find the serving() call expression in the AST.\n * Looks for call expressions where the callee identifier is \"serving\".\n */\nfunction findServingCall(root: SgNode): SgNode | null {\n const callExpressions = root.findAll({\n rule: { kind: \"call_expression\" },\n });\n\n for (const call of callExpressions) {\n const callee = call.children()[0];\n if (callee?.kind() === \"identifier\" && callee.text() === \"serving\") {\n return call;\n }\n }\n\n return null;\n}\n\n/**\n * Find a property (pair node) with the given key name in an object expression.\n */\nfunction findProperty(objectNode: SgNode, propertyName: string): SgNode | null {\n const pairs = objectNode\n .children()\n .filter((child) => child.kind() === \"pair\");\n\n for (const pair of pairs) {\n const key = pair.children()[0];\n if (!key) continue;\n\n const keyText =\n key.kind() === \"property_identifier\"\n ? key.text()\n : key.kind() === \"string\"\n ? key.text().replace(/^['\"]|['\"]$/g, \"\")\n : null;\n\n if (keyText === propertyName) {\n return pair;\n }\n }\n\n return null;\n}\n\n/**\n * Get the value node from a pair (property: value).\n * The value is typically the last meaningful child after the colon.\n */\nfunction getPropertyValue(pairNode: SgNode): SgNode | null {\n const children = pairNode.children();\n // pair children: [key, \":\", value]\n return children.length >= 3 ? children[children.length - 1] : null;\n}\n\n/**\n * Extract a single endpoint entry from a pair node like:\n * `demo: { env: \"DATABRICKS_SERVING_ENDPOINT_NAME\", servedModel: \"my-model\" }`\n */\nfunction extractEndpointEntry(\n pair: SgNode,\n): { alias: string; config: EndpointConfig } | null {\n const children = pair.children();\n if (children.length < 3) return null;\n\n // Get alias name (the key)\n const keyNode = children[0];\n const alias =\n keyNode.kind() === \"property_identifier\"\n ? keyNode.text()\n : keyNode.kind() === \"string\"\n ? keyNode.text().replace(/^['\"]|['\"]$/g, \"\")\n : null;\n\n if (!alias) return null;\n\n // Get the value (should be an object like { env: \"...\" })\n const valueNode = children[children.length - 1];\n if (valueNode.kind() !== \"object\") return null;\n\n // Extract env field\n const envPair = findProperty(valueNode, \"env\");\n if (!envPair) return null;\n\n const envValue = getPropertyValue(envPair);\n if (!envValue || envValue.kind() !== \"string\") return null;\n\n const env = envValue.text().replace(/^['\"]|['\"]$/g, \"\");\n\n // Extract optional servedModel field\n const config: EndpointConfig = { env };\n const servedModelPair = findProperty(valueNode, \"servedModel\");\n if (servedModelPair) {\n const servedModelValue = getPropertyValue(servedModelPair);\n if (servedModelValue?.kind() === \"string\") {\n config.servedModel = servedModelValue.text().replace(/^['\"]|['\"]$/g, \"\");\n }\n }\n\n return { alias, config };\n}\n"],"mappings":";;;;;;AAQA,MAAM,SAAS,aAAa,mCAAmC;;;;;;AAO/D,MAAM,yBAAyB,CAAC,mBAAmB,mBAAmB;;;;;;;AAQtE,SAAgB,eAAe,UAAiC;AAC9D,MAAK,MAAM,aAAa,wBAAwB;EAC9C,MAAM,WAAW,KAAK,KAAK,UAAU,UAAU;AAC/C,MAAIA,OAAG,WAAW,SAAS,CACzB,QAAO;;AAGX,QAAO;;;;;;;;;;AAWT,SAAgB,wBACd,gBACuC;CACvC,IAAI;AACJ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MAAI,kBAAkB,MAAM,KAAK,SAC/B,QAAO,cAAc,iBAAiB,MAAM,CAAC,QAAQ,gBAAgB,GAAG;;AAI5E,QAAO;EAAE;EAAO;EAAQ"}
1
+ {"version":3,"file":"server-file-extractor.js","names":[],"sources":["../../../src/type-generator/serving/server-file-extractor.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Lang, parse, type SgNode } from \"@ast-grep/napi\";\n\nimport { createLogger } from \"../../logging/logger\";\nimport type { EndpointConfig } from \"../../plugins/serving/types\";\n\nconst logger = createLogger(\"type-generator:serving:extractor\");\n\n/**\n * Candidate paths for the server entry file, relative to the project root.\n * Checked in order; the first that exists is used.\n * Same convention as plugin sync (sync.ts SERVER_FILE_CANDIDATES).\n */\nconst SERVER_FILE_CANDIDATES = [\"server/index.ts\", \"server/server.ts\"];\n\n/**\n * Find the server entry file by checking candidate paths in order.\n *\n * @param basePath - Project root directory to search from\n * @returns Absolute path to the server file, or null if none found\n */\nexport function findServerFile(basePath: string): string | null {\n for (const candidate of SERVER_FILE_CANDIDATES) {\n const fullPath = path.join(basePath, candidate);\n if (fs.existsSync(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Extract serving endpoint config from a server file by AST-parsing it.\n * Looks for `serving({ endpoints: { alias: { env: \"...\" }, ... } })` calls\n * and extracts the endpoint alias names and their environment variable mappings.\n *\n * @param serverFilePath - Absolute path to the server entry file\n * @returns Extracted endpoint config, or null if not found or not extractable\n */\nexport function extractServingEndpoints(\n serverFilePath: string,\n): Record<string, EndpointConfig> | null {\n let content: string;\n try {\n content = fs.readFileSync(serverFilePath, \"utf-8\");\n } catch {\n logger.debug(\"Could not read server file: %s\", serverFilePath);\n return null;\n }\n\n const lang = serverFilePath.endsWith(\".tsx\") ? Lang.Tsx : Lang.TypeScript;\n const ast = parse(lang, content);\n const root = ast.root();\n\n // Find serving(...) call expressions\n const servingCall = findServingCall(root);\n if (!servingCall) {\n logger.debug(\"No serving() call found in %s\", serverFilePath);\n return null;\n }\n\n // Get the first argument (the config object)\n const args = servingCall.field(\"arguments\");\n if (!args) {\n return null;\n }\n\n const configArg = args.children().find((child) => child.kind() === \"object\");\n if (!configArg) {\n // serving() called with no args or non-object arg\n return null;\n }\n\n // Find the \"endpoints\" property in the config object\n const endpointsPair = findProperty(configArg, \"endpoints\");\n if (!endpointsPair) {\n // Config object has no \"endpoints\" property (e.g. serving({ timeout: 5000 }))\n return null;\n }\n\n // Get the value of the endpoints property\n const endpointsValue = getPropertyValue(endpointsPair);\n if (!endpointsValue || endpointsValue.kind() !== \"object\") {\n // endpoints is a variable reference, not an inline object\n logger.debug(\n \"serving() endpoints is not an inline object literal in %s. \" +\n \"Pass endpoints explicitly via appKitServingTypesPlugin({ endpoints }) in vite.config.ts.\",\n serverFilePath,\n );\n return null;\n }\n\n // Extract each endpoint entry\n const endpoints: Record<string, EndpointConfig> = {};\n const pairs = endpointsValue\n .children()\n .filter((child) => child.kind() === \"pair\");\n\n for (const pair of pairs) {\n const entry = extractEndpointEntry(pair);\n if (entry) {\n endpoints[entry.alias] = entry.config;\n }\n }\n\n if (Object.keys(endpoints).length === 0) {\n return null;\n }\n\n logger.debug(\n \"Extracted %d endpoint(s) from %s: %s\",\n Object.keys(endpoints).length,\n serverFilePath,\n Object.keys(endpoints).join(\", \"),\n );\n\n return endpoints;\n}\n\n/**\n * Find the serving() call expression in the AST.\n * Looks for call expressions where the callee identifier is \"serving\".\n */\nfunction findServingCall(root: SgNode): SgNode | null {\n const callExpressions = root.findAll({\n rule: { kind: \"call_expression\" },\n });\n\n for (const call of callExpressions) {\n const callee = call.children()[0];\n if (callee?.kind() === \"identifier\" && callee.text() === \"serving\") {\n return call;\n }\n }\n\n return null;\n}\n\n/**\n * Find a property (pair node) with the given key name in an object expression.\n */\nfunction findProperty(objectNode: SgNode, propertyName: string): SgNode | null {\n const pairs = objectNode\n .children()\n .filter((child) => child.kind() === \"pair\");\n\n for (const pair of pairs) {\n const key = pair.children()[0];\n if (!key) continue;\n\n const keyText =\n key.kind() === \"property_identifier\"\n ? key.text()\n : key.kind() === \"string\"\n ? key.text().replace(/^['\"]|['\"]$/g, \"\")\n : null;\n\n if (keyText === propertyName) {\n return pair;\n }\n }\n\n return null;\n}\n\n/**\n * Get the value node from a pair (property: value).\n * The value is typically the last meaningful child after the colon.\n */\nfunction getPropertyValue(pairNode: SgNode): SgNode | null {\n const children = pairNode.children();\n // pair children: [key, \":\", value]\n return children.length >= 3 ? children[children.length - 1] : null;\n}\n\n/**\n * Extract a single endpoint entry from a pair node like:\n * `demo: { env: \"DATABRICKS_SERVING_ENDPOINT_NAME\", servedModel: \"my-model\" }`\n */\nfunction extractEndpointEntry(\n pair: SgNode,\n): { alias: string; config: EndpointConfig } | null {\n const children = pair.children();\n if (children.length < 3) return null;\n\n // Get alias name (the key)\n const keyNode = children[0];\n const alias =\n keyNode.kind() === \"property_identifier\"\n ? keyNode.text()\n : keyNode.kind() === \"string\"\n ? keyNode.text().replace(/^['\"]|['\"]$/g, \"\")\n : null;\n\n if (!alias) return null;\n\n // Get the value (should be an object like { env: \"...\" })\n const valueNode = children[children.length - 1];\n if (valueNode.kind() !== \"object\") return null;\n\n // Extract env field\n const envPair = findProperty(valueNode, \"env\");\n if (!envPair) return null;\n\n const envValue = getPropertyValue(envPair);\n if (!envValue || envValue.kind() !== \"string\") return null;\n\n const env = envValue.text().replace(/^['\"]|['\"]$/g, \"\");\n\n // Extract optional servedModel field\n const config: EndpointConfig = { env };\n const servedModelPair = findProperty(valueNode, \"servedModel\");\n if (servedModelPair) {\n const servedModelValue = getPropertyValue(servedModelPair);\n if (servedModelValue?.kind() === \"string\") {\n config.servedModel = servedModelValue.text().replace(/^['\"]|['\"]$/g, \"\");\n }\n }\n\n return { alias, config };\n}\n"],"mappings":";;;;;;AAQA,MAAM,SAAS,aAAa,mCAAmC;;;;;;AAO/D,MAAM,yBAAyB,CAAC,mBAAmB,mBAAmB;;;;;;;AAQtE,SAAgB,eAA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