@tailor-platform/sdk 2.0.0-next.0 → 2.0.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +105 -0
- package/dist/application-DB2r36Et.mjs +3 -0
- package/dist/{application-76hhIhnJ.mjs → application-DqS1yBg3.mjs} +217 -131
- package/dist/application-DqS1yBg3.mjs.map +1 -0
- package/dist/{assert-CKfwrmCV.mjs → assert-DBxo8jPo.mjs} +1 -2
- package/dist/{assert-CKfwrmCV.mjs.map → assert-DBxo8jPo.mjs.map} +1 -1
- package/dist/{authconnection-D8SJGMpj.mjs → authconnection-D2MhtTN5.mjs} +2 -3
- package/dist/{authconnection-D8SJGMpj.mjs.map → authconnection-D2MhtTN5.mjs.map} +1 -1
- package/dist/{authconnection-BIYzEh2p.d.mts → authconnection-DvUQAjQS.d.mts} +1 -1
- package/dist/{brand-DlnJ375c.mjs → brand-Eo4pLXPJ.mjs} +1 -2
- package/dist/{brand-DlnJ375c.mjs.map → brand-Eo4pLXPJ.mjs.map} +1 -1
- package/dist/cli/index.mjs +78 -131
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.d.mts +619 -751
- package/dist/cli/lib.mjs +9 -10
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/{client-C68VWo4g.mjs → client-Dbohmtkv.mjs} +1 -2
- package/dist/{client-CobIRHl-.mjs → client-z_oHGVNy.mjs} +10 -7
- package/dist/client-z_oHGVNy.mjs.map +1 -0
- package/dist/completion/zsh-worker.zsh +4029 -0
- package/dist/configure/index.d.mts +8 -7
- package/dist/configure/index.mjs +27 -28
- package/dist/configure/index.mjs.map +1 -1
- package/dist/{context-s0lxhu8_.mjs → context-Bd266-ru.mjs} +2 -3
- package/dist/{context-s0lxhu8_.mjs.map → context-Bd266-ru.mjs.map} +1 -1
- package/dist/{context-CUBwSBq4.d.mts → context-BuuIb8CC.d.mts} +1 -1
- package/dist/{crashreport-BhD0y14F.mjs → crashreport-BsjAkFWw.mjs} +19 -10
- package/dist/{crashreport-BhD0y14F.mjs.map → crashreport-BsjAkFWw.mjs.map} +1 -1
- package/dist/{crashreport-D1wKBJ8N.mjs → crashreport-pr6Rhvza.mjs} +1 -2
- package/dist/{enum-constants-C7DaWeQo.mjs → enum-constants-j9QBF0cB.mjs} +1 -2
- package/dist/enum-constants-j9QBF0cB.mjs.map +1 -0
- package/dist/{errors-EsY4XO6O.mjs → errors-Dtf2WPaW.mjs} +1 -2
- package/dist/{errors-EsY4XO6O.mjs.map → errors-Dtf2WPaW.mjs.map} +1 -1
- package/dist/{field-C4zdJLW5.mjs → field-DOsJCPFa.mjs} +1 -2
- package/dist/field-DOsJCPFa.mjs.map +1 -0
- package/dist/{file-BzK8z3X-.d.mts → file-BB8Vs9O_.d.mts} +1 -1
- package/dist/{file-B58Dm-2P.mjs → file-_oUZo76X.mjs} +2 -3
- package/dist/{file-B58Dm-2P.mjs.map → file-_oUZo76X.mjs.map} +1 -1
- package/dist/{file-utils-BHPxPXmn.mjs → file-utils-DcyIPFQh.mjs} +2 -3
- package/dist/{file-utils-BHPxPXmn.mjs.map → file-utils-DcyIPFQh.mjs.map} +1 -1
- package/dist/{globals-ByrCoDip.mjs → globals-Crz8o65k.mjs} +53 -5
- package/dist/globals-Crz8o65k.mjs.map +1 -0
- package/dist/http-adapter.generated-WgMnb7Sb.d.mts +580 -0
- package/dist/{iconv-kwrmd1U_.d.mts → iconv-Co-TOPuH.d.mts} +1 -1
- package/dist/{iconv-DreIffeM.mjs → iconv-D2vi8G36.mjs} +2 -3
- package/dist/{iconv-DreIffeM.mjs.map → iconv-D2vi8G36.mjs.map} +1 -1
- package/dist/{idp-Ch95ag8h.mjs → idp-BDbK5gjm.mjs} +2 -3
- package/dist/{idp-Ch95ag8h.mjs.map → idp-BDbK5gjm.mjs.map} +1 -1
- package/dist/{idp-BlBPtXJ-.d.mts → idp-DrhVrLmV.d.mts} +1 -1
- package/dist/{index-CQZVJ5SX.d.mts → index-5vPyRu1y.d.mts} +2 -2
- package/dist/{index-CfRFkXIO.d.mts → index-B7AKc18V.d.mts} +2 -2
- package/dist/{index-CLxubakC.d.mts → index-BlpzXncY.d.mts} +38 -247
- package/dist/{index-DRhMpdnA.d.mts → index-CK7u9isy.d.mts} +8 -8
- package/dist/{index-DUupuPhZ.d.mts → index-CNYe5lnW.d.mts} +2 -2
- package/dist/{index-CPRnOjjt.d.mts → index-DjUdWlzf.d.mts} +2 -2
- package/dist/index-ZePLwxw7.d.mts +208 -0
- package/dist/{interceptor-DOqRkCya.mjs → interceptor-D-q1rvRl.mjs} +1 -2
- package/dist/{interceptor-DOqRkCya.mjs.map → interceptor-D-q1rvRl.mjs.map} +1 -1
- package/dist/{job-BpsFXPbi.mjs → job-fuc3j1Ma.mjs} +9 -10
- package/dist/job-fuc3j1Ma.mjs.map +1 -0
- package/dist/kysely/index.mjs +0 -1
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/{kysely-type-D1e0Vwkd.mjs → kysely-type-DR8uzZTA.mjs} +2 -3
- package/dist/kysely-type-DR8uzZTA.mjs.map +1 -0
- package/dist/{logger-DpJyJvNz.mjs → logger-CxF-Ex5d.mjs} +1 -2
- package/dist/{logger-DpJyJvNz.mjs.map → logger-CxF-Ex5d.mjs.map} +1 -1
- package/dist/{mock-DMgIygjE.mjs → mock-BjFj5o1I.mjs} +9 -11
- package/dist/mock-BjFj5o1I.mjs.map +1 -0
- package/dist/{multiline-Cf9ODpr1.mjs → multiline-sfHpTZZK.mjs} +1 -2
- package/dist/{multiline-Cf9ODpr1.mjs.map → multiline-sfHpTZZK.mjs.map} +1 -1
- package/dist/{package-json-DcQApfPQ.mjs → package-json-8b0O9TlX.mjs} +1 -2
- package/dist/{package-json-DcQApfPQ.mjs.map → package-json-8b0O9TlX.mjs.map} +1 -1
- package/dist/package-json-Cv2Z-TqQ.mjs +3 -0
- package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +1 -2
- package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +1 -2
- package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -2
- package/dist/plugin/builtin/seed/index.d.mts +1 -1
- package/dist/plugin/builtin/seed/index.mjs +1 -2
- package/dist/plugin/index.d.mts +1 -3
- package/dist/plugin/index.mjs +0 -1
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/registry-DdsYlL_P.mjs +51 -0
- package/dist/registry-DdsYlL_P.mjs.map +1 -0
- package/dist/{repl-editor-CJG3sz7A.mjs → repl-editor-DmGr9zMw.mjs} +2 -3
- package/dist/{repl-editor-CJG3sz7A.mjs.map → repl-editor-DmGr9zMw.mjs.map} +1 -1
- package/dist/{chunk-BkoGK1jX.mjs → rolldown-runtime-DXywRVcq.mjs} +0 -1
- package/dist/runtime/authconnection.d.mts +1 -1
- package/dist/runtime/authconnection.mjs +1 -2
- package/dist/runtime/context.d.mts +1 -1
- package/dist/runtime/context.mjs +1 -2
- package/dist/runtime/file.d.mts +1 -1
- package/dist/runtime/file.mjs +1 -2
- package/dist/runtime/globals.d.mts +6 -39
- package/dist/runtime/globals.mjs +0 -1
- package/dist/runtime/iconv.d.mts +1 -1
- package/dist/runtime/iconv.mjs +1 -2
- package/dist/runtime/idp.d.mts +1 -1
- package/dist/runtime/idp.mjs +1 -2
- package/dist/runtime/index.d.mts +8 -8
- package/dist/runtime/index.mjs +7 -8
- package/dist/runtime/secretmanager.d.mts +1 -1
- package/dist/runtime/secretmanager.mjs +1 -2
- package/dist/runtime/workflow.d.mts +1 -1
- package/dist/runtime/workflow.mjs +1 -2
- package/dist/{runtime-C7qTBDD2.mjs → runtime-n9NCkjee.mjs} +301 -317
- package/dist/runtime-n9NCkjee.mjs.map +1 -0
- package/dist/{schema-1msIhXwA.mjs → schema-BhkpP5Hw.mjs} +3 -4
- package/dist/schema-BhkpP5Hw.mjs.map +1 -0
- package/dist/{secret-file-CWzF8rry.mjs → secret-file-DBqZhjFQ.mjs} +1 -2
- package/dist/{secret-file-CWzF8rry.mjs.map → secret-file-DBqZhjFQ.mjs.map} +1 -1
- package/dist/{secretmanager-CKLB3wAQ.d.mts → secretmanager-B3n4KHfm.d.mts} +1 -1
- package/dist/{secretmanager-B9h-U_8U.mjs → secretmanager-BVxw3ih_.mjs} +2 -3
- package/dist/{secretmanager-B9h-U_8U.mjs.map → secretmanager-BVxw3ih_.mjs.map} +1 -1
- package/dist/seed/index.mjs +0 -1
- package/dist/seed/index.mjs.map +1 -1
- package/dist/{seed-BH2FbrPV.mjs → seed-jf3008-h.mjs} +5 -16
- package/dist/seed-jf3008-h.mjs.map +1 -0
- package/dist/{service-wI3Hvrgx.mjs → service-CCL8ruDf.mjs} +3 -4
- package/dist/service-CCL8ruDf.mjs.map +1 -0
- package/dist/service-D6yonf2I.mjs +3 -0
- package/dist/{service-DMohAx8a2.mjs → service-DU1mVzri.mjs} +3 -4
- package/dist/service-DU1mVzri.mjs.map +1 -0
- package/dist/{telemetry-BQbbVo2t.mjs → telemetry-CdqJEzkj.mjs} +2 -3
- package/dist/{telemetry-BQbbVo2t.mjs.map → telemetry-CdqJEzkj.mjs.map} +1 -1
- package/dist/telemetry-ClwW5ohF.mjs +3 -0
- package/dist/test-env-key-D9kM6ETE.mjs +49 -0
- package/dist/test-env-key-D9kM6ETE.mjs.map +1 -0
- package/dist/type-source-DH_LH20p.mjs +13 -0
- package/dist/type-source-DH_LH20p.mjs.map +1 -0
- package/dist/{types-CmzfQP_m.mjs → types-B2RpYyA_.mjs} +2 -3
- package/dist/types-B2RpYyA_.mjs.map +1 -0
- package/dist/types-ClhIrW_C.mjs +4 -0
- package/dist/{tailordb-BlBGmQK-.d.mts → types-DCUhgpyI.d.mts} +142 -221
- package/dist/{plugin-C_FyVSdl.d.mts → types-DhO_VEZd.d.mts} +119 -179
- package/dist/types-DwDgacni.d.mts +338 -0
- package/dist/utils/test/index.d.mts +4 -3
- package/dist/utils/test/index.mjs +1 -2
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +1 -2
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.d.mts +42 -5
- package/dist/vitest/index.mjs +133 -4
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/setup.mjs +2 -3
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/{workflow-CMamswkK.d.mts → workflow-BbKvGLQg.d.mts} +1 -1
- package/dist/{workflow--aPbA8Uq.mjs → workflow-DgemCAz3.mjs} +2 -3
- package/dist/{workflow--aPbA8Uq.mjs.map → workflow-DgemCAz3.mjs.map} +1 -1
- package/dist/workflow.generated-DtQwEo-x.d.mts +671 -0
- package/docs/cli/application.md +0 -2
- package/docs/cli/completion.md +3 -0
- package/docs/cli/crashreport.md +0 -2
- package/docs/cli/function.md +1 -1
- package/docs/cli/user.md +3 -3
- package/docs/cli/workspace.md +3 -3
- package/docs/configuration.md +0 -2
- package/docs/plugin/custom.md +2 -2
- package/docs/plugin/index.md +1 -1
- package/docs/runtime.md +3 -3
- package/docs/services/aigateway.md +97 -0
- package/docs/services/auth.md +19 -2
- package/docs/services/executor.md +0 -2
- package/docs/services/resolver.md +2 -4
- package/docs/services/tailordb.md +1 -1
- package/docs/services/workflow.md +13 -15
- package/docs/testing.md +18 -11
- package/package.json +13 -12
- package/dist/actor-J2gJ0eK5.d.mts +0 -24
- package/dist/application-76hhIhnJ.mjs.map +0 -1
- package/dist/application-av2raLs6.mjs +0 -4
- package/dist/cli/skills.d.mts +0 -1
- package/dist/cli/skills.mjs +0 -22
- package/dist/cli/skills.mjs.map +0 -1
- package/dist/client-CobIRHl-.mjs.map +0 -1
- package/dist/enum-constants-C7DaWeQo.mjs.map +0 -1
- package/dist/env-B-g-qgE4.d.mts +0 -7
- package/dist/field-C4zdJLW5.mjs.map +0 -1
- package/dist/globals-ByrCoDip.mjs.map +0 -1
- package/dist/job-BpsFXPbi.mjs.map +0 -1
- package/dist/kysely-type-D1e0Vwkd.mjs.map +0 -1
- package/dist/mock-DMgIygjE.mjs.map +0 -1
- package/dist/package-json-wzO6nV9O.mjs +0 -4
- package/dist/registry-D0uB0OrK.mjs +0 -178
- package/dist/registry-D0uB0OrK.mjs.map +0 -1
- package/dist/runtime-C7qTBDD2.mjs.map +0 -1
- package/dist/schema-1msIhXwA.mjs.map +0 -1
- package/dist/seed-BH2FbrPV.mjs.map +0 -1
- package/dist/service-BHQIerYh.mjs +0 -4
- package/dist/service-DMohAx8a2.mjs.map +0 -1
- package/dist/service-wI3Hvrgx.mjs.map +0 -1
- package/dist/telemetry-w92bvGdC.mjs +0 -4
- package/dist/types-2Be3wSMc.mjs +0 -5
- package/dist/types-CmzfQP_m.mjs.map +0 -1
- package/dist/workflow.generated-Bf1tWylx.d.mts +0 -1416
- package/docs/generator/builtin.md +0 -257
- package/docs/generator/custom.md +0 -147
- package/docs/generator/index.md +0 -66
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mock-BjFj5o1I.mjs","names":["#fromEncoding","#toEncoding"],"sources":["../src/vitest/mock.ts"],"sourcesContent":["/**\n * Mock controls for Tailor Platform APIs (vitest).\n *\n * Each `xMock()` factory installs `vi.fn()`-backed mocks for one platform\n * namespace onto `globalThis` when acquired, and restores the previous value\n * when the `using` scope exits. State lives in the per-acquisition vi.fns /\n * closures — there is no shared global state bag — so nested/sequential scopes\n * are isolated and namespaces never interfere with each other.\n *\n * Acquire a mock with a `using` declaration:\n *\n * ```ts\n * test(\"...\", () => {\n * using wf = mockWorkflow();\n * wf.setJobHandler(() => ({ ok: true }));\n * }); // previous workflow mock restored here\n * ```\n *\n * The friendly helpers (`setJobHandler`, `enqueueResult`, `triggeredJobs`, …)\n * are thin wrappers over the underlying vi.fns, which are also exposed directly\n * (`wf.triggerJobFunction`) for native matchers like\n * `expect(wf.triggerJobFunction).toHaveBeenCalledWith(...)`.\n */\n\nimport { type Mock, vi } from \"vitest\";\nimport { TRIGGER_DEFAULT } from \"@/configure/services/workflow/registry\";\nimport { assertDefined } from \"@/utils/assert\";\nimport { platformSerialize } from \"@/utils/test/platform-serialize\";\nimport {\n clearWorkflowTestEnv,\n writeWorkflowTestEnv,\n} from \"../configure/services/workflow/test-env-key\";\nimport type { User as IdpUser } from \"../runtime/idp\";\nimport type { TailorEnv } from \"@/runtime/types\";\n\nexport { RUNTIME_FLAG_KEY } from \"./globals\";\n\n// Re-export the base globals install/cleanup under their historical names so\n// non-environment tests (which run in the plain `node` environment) can set up\n// the base platform surface — `globalThis.tailor`, error classes — themselves.\nexport {\n installPlatformGlobals as injectMocks,\n cleanupPlatformGlobals as cleanupMocks,\n} from \"./globals\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\ntype QueryResolver = (query: string, params: unknown[]) => unknown[];\ntype JobHandler = (jobName: string, args: unknown) => unknown;\ntype IdpResolver = (method: string, args: unknown[], namespace: string) => unknown;\ntype FileResolver = (method: string, call: FileCall) => unknown;\ntype IconvResolver = (method: string, args: unknown[]) => unknown;\n\ntype TriggerWorkflowOptions = {\n authInvoker?: { namespace: string; machineUserName: string };\n};\ntype TriggerHandlerFn = (\n workflowName: string,\n args: unknown,\n options?: TriggerWorkflowOptions,\n) => string;\ntype WaitHandlerFn = (key: string, payload: unknown) => unknown;\ntype ResolveHandler = (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n) => unknown | Promise<unknown>;\n\n// Overloaded so TypeScript narrows to WaitHandlerFn first (giving inferred\n// `(key: string, payload: unknown) => …` for callers) before falling back\n// to the static-value form. A union type would let `unknown` swallow the\n// function variant and break inference.\ntype SetWaitHandler = {\n (handler: WaitHandlerFn): void;\n (handler: unknown): void;\n};\n\ninterface ExecutedQuery {\n query: string;\n params: unknown[];\n}\n\ninterface CreatedClient {\n namespace: string | undefined;\n ended: boolean;\n}\n\ninterface TriggeredJob {\n jobName: string;\n args: unknown;\n}\n\ninterface SecretCall {\n method: \"getSecret\" | \"getSecrets\";\n vault: string;\n name?: string;\n names?: readonly string[];\n}\n\ninterface AuthConnectionCall {\n connectionName: string;\n}\n\ninterface IdpCall {\n method: string;\n args: unknown[];\n namespace: string;\n}\n\ninterface FileCall {\n method: string;\n namespace: string;\n typeName: string;\n fieldName: string;\n recordId: string;\n}\n\ninterface IconvCall {\n method: string;\n args: unknown[];\n}\n\n// ---------------------------------------------------------------------------\n// Shared helpers\n// ---------------------------------------------------------------------------\n\n// Attach a non-enumerable `Symbol.dispose` to a facade so it works with `using`.\nfunction withDispose<T extends object>(facade: T, dispose: () => void): T & Disposable {\n Object.defineProperty(facade, Symbol.dispose, {\n value: dispose,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n return facade as T & Disposable;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction tailorRoot(): Record<string, any> {\n const g = globalThis as Record<string, unknown>;\n if (!g.tailor) {\n // Ensure the container (and the always-present context stub) exists even if\n // the base globals were not installed (e.g. a unit test that only acquires\n // a single mock without the tailor-runtime environment).\n g.tailor = { context: { getInvoker: () => null } };\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return g.tailor as Record<string, any>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction tailordbRoot(): Record<string, any> {\n const g = globalThis as Record<string, unknown>;\n if (!g.tailordb) {\n g.tailordb = {};\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return g.tailordb as Record<string, any>;\n}\n\nclass MockQueryResult {\n command: string;\n rowCount: number;\n rows: unknown[];\n\n constructor(rows: unknown[]) {\n this.command = \"\";\n this.rowCount = rows.length;\n this.rows = rows;\n }\n}\n\n// ---------------------------------------------------------------------------\n// TailorDB Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for TailorDB operations. Installs a mock\n * `tailordb.Client` whose `queryObject` is a shared `vi.fn()` (so query\n * responses can be staged before the client is constructed). Restored on\n * dispose.\n * @returns Disposable TailorDB mock control object\n * @example\n * ```typescript\n * import { mockTailordb } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"order-based\", async () => {\n * using db = mockTailordb();\n * db.enqueueResults([], [{ age: 30 }], []); // BEGIN / SELECT / COMMIT\n * // …\n * expect(db.queryObject).toHaveBeenCalledTimes(3);\n * expect(db.Client).toHaveBeenCalledWith({ namespace: \"tailordb\" });\n * });\n * ```\n */\nexport function mockTailordb() {\n const root = tailordbRoot();\n const prevClient = root.Client;\n\n const queryObject = vi.fn(\n async (_query: string, _params: unknown[] = []): Promise<MockQueryResult> =>\n new MockQueryResult([]),\n );\n const connect = vi.fn(async (): Promise<void> => {});\n const createdClients: CreatedClient[] = [];\n\n const Client = vi.fn(function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n config?: { namespace?: string },\n ) {\n const record: CreatedClient = { namespace: config?.namespace, ended: false };\n createdClients.push(record);\n this.connect = connect;\n this.end = vi.fn(async (): Promise<void> => {\n record.ended = true;\n });\n this.queryObject = queryObject;\n this.createTransaction = (name: string) => {\n if (!name) {\n throw new Error(\"Transaction name must be a non-empty string\");\n }\n return {\n begin: async (): Promise<void> => {},\n commit: async (): Promise<void> => {},\n rollback: async (): Promise<void> => {},\n queryObject,\n };\n };\n });\n\n root.Client = Client;\n\n const facade = {\n /** The mock `tailordb.Client` constructor (`vi.fn`). */\n Client,\n /** The shared `queryObject` `vi.fn` used by every client and transaction. */\n queryObject,\n\n /**\n * Set a fallback query resolver. Called when the enqueue queue is empty.\n * @param resolver - Function that returns rows for a given query and params\n */\n setQueryResolver(resolver: QueryResolver): void {\n queryObject.mockImplementation(\n async (query: string, params: unknown[] = []) =>\n // user resolvers may return undefined\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n new MockQueryResult(resolver(query, params) ?? []),\n );\n },\n\n /**\n * Enqueue rows for the next `queryObject` call (FIFO; takes priority over\n * `setQueryResolver`). Call with no arguments for an empty result.\n * @param rows - Row objects to return from the next `queryObject` call\n */\n enqueueResult(...rows: unknown[]): void {\n queryObject.mockImplementationOnce(async () => new MockQueryResult(rows));\n },\n\n /**\n * Enqueue rows for multiple subsequent `queryObject` calls (FIFO).\n * @param rowsList - Rows arrays, one per upcoming query\n */\n enqueueResults(...rowsList: unknown[][]): void {\n for (const rows of rowsList) {\n queryObject.mockImplementationOnce(async () => new MockQueryResult(rows));\n }\n },\n\n /**\n * All queries executed via `queryObject`, in order, derived from the vi.fn\n * call records.\n * @returns Executed queries array\n */\n get executedQueries(): ExecutedQuery[] {\n return queryObject.mock.calls.map(([query, params]) => ({\n query: query as string,\n // vitest records an omitted argument as undefined\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n params: (params as unknown[]) ?? [],\n }));\n },\n\n /**\n * All TailorDB clients created, with their namespace and end state.\n * @returns Created clients array\n */\n get createdClients(): CreatedClient[] {\n return createdClients;\n },\n\n /** Reset query responses and recorded calls (keeps the mock installed). */\n reset(): void {\n queryObject.mockReset();\n queryObject.mockImplementation(async () => new MockQueryResult([]));\n connect.mockClear();\n Client.mockClear();\n createdClients.length = 0;\n },\n };\n\n return withDispose(facade, () => {\n root.Client = prevClient;\n });\n}\n\n// ---------------------------------------------------------------------------\n// Workflow Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for workflow operations (`tailor.workflow`).\n * Restored on dispose.\n * @returns Disposable workflow mock control object\n * @example\n * ```typescript\n * import { mockWorkflow } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"job handler\", async () => {\n * using wf = mockWorkflow();\n * wf.setJobHandler((name) => (name === \"validate\" ? { valid: true } : null));\n * await runWorkflowUnderTest(); // calls tailor.workflow.triggerJobFunction(\"validate\", {})\n * expect(wf.triggerJobFunction).toHaveBeenCalledWith(\"validate\", {});\n * });\n * ```\n */\nexport function mockWorkflow() {\n const root = tailorRoot();\n const prev = root.workflow;\n\n const defaultTriggerJob = (jobName: string, _args?: unknown): unknown => {\n throw new Error(\n `No workflow job mock for \"${jobName}\". Call mockWorkflow().setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`,\n );\n };\n const defaultTriggerWorkflow = async (\n _workflowName: string,\n _args?: unknown,\n _options?: TriggerWorkflowOptions,\n ): Promise<string> => {\n return TRIGGER_DEFAULT;\n };\n\n // Inner vi.fns hold the overridable behavior + call recording; the installed\n // shims below cross the platform JSON boundary (serialize args + results) once.\n const triggerJobFunction = vi.fn(defaultTriggerJob);\n const triggerWorkflow = vi.fn(defaultTriggerWorkflow);\n const wait = vi.fn((_key: string, _payload?: unknown): unknown => null);\n const resolve = vi.fn(\n async (\n _executionId: string,\n _key: string,\n _callback: (payload: unknown) => unknown,\n ): Promise<void> => {},\n );\n\n const installedTriggerJobFunction = (jobName: string, args?: unknown): unknown => {\n const out = triggerJobFunction(jobName, platformSerialize(args));\n return out instanceof Promise ? out.then((v) => platformSerialize(v)) : platformSerialize(out);\n };\n\n root.workflow = {\n triggerJobFunction: installedTriggerJobFunction,\n // Preserve arity so a forwarded third `options` arg — even `undefined` — is\n // recorded, matching the real `.trigger(args, options)` call shape.\n triggerWorkflow: (...call: [string, unknown?, TriggerWorkflowOptions?]) =>\n call.length >= 3\n ? triggerWorkflow(call[0], platformSerialize(call[1]), call[2])\n : triggerWorkflow(call[0], platformSerialize(call[1])),\n wait: (key: string, payload?: unknown) => wait(key, platformSerialize(payload)),\n resolve: (executionId: string, key: string, callback: (payload: unknown) => unknown) =>\n resolve(executionId, key, (payload: unknown) => {\n const out = callback(payload);\n return out instanceof Promise\n ? out.then((v) => platformSerialize(v))\n : platformSerialize(out);\n }),\n };\n\n const facade = {\n /** The `triggerJobFunction` `vi.fn`. */\n triggerJobFunction,\n /** The `triggerWorkflow` `vi.fn`. */\n triggerWorkflow,\n /** The `wait` `vi.fn`. */\n wait,\n /** The `resolve` `vi.fn`. */\n resolve,\n\n /**\n * Set a fallback job handler. Called when the enqueue queue is empty.\n * @param handler - Function returning a result for a job name and args\n */\n setJobHandler(handler: JobHandler): void {\n triggerJobFunction.mockImplementation((name, args) => handler(name, args));\n },\n\n /**\n * Enqueue a single result for the next `triggerJobFunction` call (FIFO;\n * takes priority over `setJobHandler`).\n * @param result - Result to return from the next call\n */\n enqueueResult(result: unknown): void {\n triggerJobFunction.mockImplementationOnce(() => result);\n },\n\n /**\n * Enqueue results for multiple subsequent `triggerJobFunction` calls (FIFO).\n * @param results - Results to enqueue, one per upcoming call\n */\n enqueueResults(...results: unknown[]): void {\n for (const result of results) {\n triggerJobFunction.mockImplementationOnce(() => result);\n }\n },\n\n /**\n * All jobs triggered via `triggerJobFunction`, in order.\n * @returns Triggered jobs array\n */\n get triggeredJobs(): TriggeredJob[] {\n return triggerJobFunction.mock.calls.map(([jobName, args]) => ({\n jobName: jobName as string,\n args,\n }));\n },\n\n /**\n * Configure what `triggerWorkflow` returns. Pass a string (same id every\n * call) or `(name, args, options) => string`. Default: a placeholder UUID.\n * @param handler - Static execution ID or a function returning one\n */\n setTriggerHandler(handler: string | TriggerHandlerFn): void {\n triggerWorkflow.mockImplementation(\n typeof handler === \"function\"\n ? async (name, args, options) => handler(name, args, options)\n : async () => handler,\n );\n },\n\n /**\n * Configure what `wait` returns. Pass `(key, payload) => unknown` or any\n * other value to return it for every call. Default: `null`.\n * @param handler - Static value or a function returning one\n */\n setWaitHandler: ((handler: unknown) => {\n wait.mockImplementation(\n typeof handler === \"function\"\n ? (key, payload) => (handler as WaitHandlerFn)(key, payload)\n : () => handler,\n );\n }) as SetWaitHandler,\n\n /**\n * Set the `env` passed to job bodies invoked via `runWorkflowLocally()`.\n * Cleared on dispose / reset.\n * @param env - Env passed to job bodies.\n */\n setEnv(env: TailorEnv): void {\n writeWorkflowTestEnv({ ...env });\n },\n\n /**\n * Configure how `resolve` runs the user-supplied callback. Default: callback\n * is not invoked (records the call only).\n * @param handler - Function invoked per `resolve` call\n */\n setResolveHandler(handler: ResolveHandler): void {\n resolve.mockImplementation(async (executionId, key, callback) => {\n await handler(executionId, key, callback);\n });\n },\n\n /**\n * `wait` calls reshaped as `{ key, payload }` for assertions.\n * @returns Wait call records\n */\n get waitCalls(): { key: string; payload: unknown }[] {\n return wait.mock.calls.map(([key, payload]) => ({ key: key as string, payload }));\n },\n\n /**\n * `resolve` calls reshaped as `{ executionId, key }` for assertions.\n * @returns Resolve call records\n */\n get resolveCalls(): { executionId: string; key: string }[] {\n return resolve.mock.calls.map(([executionId, key]) => ({\n executionId: executionId as string,\n key: key as string,\n }));\n },\n\n /** Reset all workflow responses and recorded calls (keeps the mock installed). */\n reset(): void {\n triggerJobFunction.mockReset();\n triggerJobFunction.mockImplementation(defaultTriggerJob);\n triggerWorkflow.mockReset();\n triggerWorkflow.mockImplementation(defaultTriggerWorkflow);\n wait.mockReset();\n wait.mockImplementation(() => null);\n resolve.mockReset();\n resolve.mockImplementation(async () => {});\n clearWorkflowTestEnv();\n },\n };\n\n return withDispose(facade, () => {\n root.workflow = prev;\n clearWorkflowTestEnv();\n });\n}\n\n// ---------------------------------------------------------------------------\n// SecretManager Mock\n// ---------------------------------------------------------------------------\n\n// Hidden accessor key used to inherit the previous scope's secret store on\n// acquisition (so secrets seeded once outside tests — e.g. from tailor.config.ts\n// via setup.ts — remain visible) while still isolating per-test overrides.\nconst SECRET_STORE = Symbol(\"tailorSecretStore\");\n\n/**\n * Acquire a disposable mock for `tailor.secretmanager`. The secret store is\n * inherited (cloned) from the currently-installed mock on acquisition and\n * restored on dispose, so secrets seeded outside the test survive across\n * `using` scopes while per-test `setSecrets()` overrides stay isolated.\n * @returns Disposable SecretManager mock control object\n * @example\n * ```typescript\n * import { mockSecretmanager } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"reads secrets from vault\", async () => {\n * using sm = mockSecretmanager();\n * sm.setSecrets({ \"my-vault\": { API_KEY: \"sk-123\" } });\n * // …\n * });\n * ```\n */\nexport function mockSecretmanager() {\n const root = tailorRoot();\n const prev = root.secretmanager;\n\n const holder: { store: Record<string, Record<string, string>> } = {\n // prior mock state may be absent\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n store: structuredClone((prev?.[SECRET_STORE]?.store as typeof holder.store) ?? {}),\n };\n\n const getSecret = vi.fn(\n async (vault: string, name: string): Promise<string | undefined> => holder.store[vault]?.[name],\n );\n const getSecrets = vi.fn(\n async <const T extends readonly string[]>(\n vault: string,\n names: T,\n ): Promise<Partial<Record<T[number], string>>> => {\n const vaultData = holder.store[vault] ?? {};\n const result: Record<string, string> = {};\n for (const name of names) {\n if (name in vaultData) {\n result[name] = assertDefined(vaultData[name], `vault entry missing for: ${name}`);\n }\n }\n return result as Partial<Record<T[number], string>>;\n },\n );\n\n root.secretmanager = { getSecret, getSecrets, [SECRET_STORE]: holder };\n\n const facade = {\n /** The `getSecret` `vi.fn`. */\n getSecret,\n /** The `getSecrets` `vi.fn`. */\n getSecrets,\n\n setSecrets(secrets: Record<string, Record<string, string>>): void {\n holder.store = secrets;\n },\n\n get calls(): SecretCall[] {\n // Merge both methods' calls back into chronological order via vi.fn's\n // global invocationCallOrder, so a test mixing getSecret/getSecrets sees\n // them in the order they actually ran (not all getSecret, then all getSecrets).\n const entries: { order: number; call: SecretCall }[] = [\n ...getSecret.mock.calls.map((args, i) => ({\n order: getSecret.mock.invocationCallOrder[i] ?? 0,\n call: { method: \"getSecret\" as const, vault: args[0] as string, name: args[1] as string },\n })),\n ...getSecrets.mock.calls.map((args, i) => ({\n order: getSecrets.mock.invocationCallOrder[i] ?? 0,\n call: {\n method: \"getSecrets\" as const,\n vault: args[0] as string,\n names: args[1] as readonly string[],\n },\n })),\n ];\n return entries.toSorted((a, b) => a.order - b.order).map((e) => e.call);\n },\n\n reset(): void {\n holder.store = {};\n getSecret.mockClear();\n getSecrets.mockClear();\n },\n };\n\n return withDispose(facade, () => {\n root.secretmanager = prev;\n });\n}\n\n// ---------------------------------------------------------------------------\n// AuthConnection Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for `tailor.authconnection`. Restored on dispose.\n * @returns Disposable AuthConnection mock control object\n * @example\n * ```typescript\n * import { mockAuthconnection } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"returns configured token\", async () => {\n * using ac = mockAuthconnection();\n * ac.setTokens({ google: { access_token: \"ya29.xxx\" } });\n * // …\n * });\n * ```\n */\nexport function mockAuthconnection() {\n const root = tailorRoot();\n const prev = root.authconnection;\n\n let tokens: Record<string, unknown> = {};\n const getConnectionToken = vi.fn(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async (connectionName: string): Promise<any> =>\n tokens[connectionName] ?? { access_token: \"mock-token\" },\n );\n\n root.authconnection = { getConnectionToken };\n\n const facade = {\n /** The `getConnectionToken` `vi.fn`. */\n getConnectionToken,\n\n setTokens(value: Record<string, unknown>): void {\n tokens = value;\n },\n\n get calls(): AuthConnectionCall[] {\n return getConnectionToken.mock.calls.map(([connectionName]) => ({\n connectionName: connectionName as string,\n }));\n },\n\n reset(): void {\n tokens = {};\n getConnectionToken.mockClear();\n },\n };\n\n return withDispose(facade, () => {\n root.authconnection = prev;\n });\n}\n\n// ---------------------------------------------------------------------------\n// IDP Mock\n// ---------------------------------------------------------------------------\n\nconst IDP_DEFAULTS: Record<string, unknown> = {\n users: { users: [], nextPageToken: null, totalCount: 0 },\n user: { id: \"mock-id\", name: \"mock-user\", disabled: false },\n userByName: { id: \"mock-id\", name: \"mock-user\", disabled: false },\n createUser: { id: \"mock-id\", name: \"mock-user\", disabled: false },\n updateUser: { id: \"mock-id\", name: \"mock-user\", disabled: false },\n deleteUser: true,\n sendPasswordResetEmail: true,\n};\n\n/**\n * Acquire a disposable mock for `tailor.idp`. Restored on dispose.\n * @returns Disposable IDP mock control object\n * @example\n * ```typescript\n * import { mockIdp } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"resolver-based\", async () => {\n * using idp = mockIdp();\n * idp.setResolver((method) =>\n * method === \"user\" ? { id: \"u-1\", name: \"alice\", disabled: false } : null,\n * );\n * // …\n * });\n * ```\n */\nexport function mockIdp() {\n const root = tailorRoot();\n const prev = root.idp;\n\n const queue: unknown[] = [];\n let resolver: IdpResolver = () => null;\n const calls: IdpCall[] = [];\n\n function handle(method: string, args: unknown[], namespace: string): unknown {\n calls.push({ method, args, namespace });\n if (queue.length > 0) return queue.shift();\n const resolved = resolver(method, args, namespace);\n // Treat null and undefined alike as \"no override\".\n if (resolved != null) return resolved;\n // Clone the default so a test mutating the returned value cannot corrupt\n // the shared module-level object for subsequent tests.\n const fallback = IDP_DEFAULTS[method];\n return fallback === undefined ? undefined : structuredClone(fallback);\n }\n\n const Client = vi.fn(function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this: any,\n config: { namespace: string },\n ) {\n const namespace = config.namespace;\n this.users = async (options?: unknown) => handle(\"users\", [options], namespace);\n this.user = async (userId: string) => handle(\"user\", [userId], namespace);\n this.userByName = async (name: string) => handle(\"userByName\", [name], namespace);\n this.createUser = async (input: unknown) => handle(\"createUser\", [input], namespace);\n this.updateUser = async (input: unknown) => handle(\"updateUser\", [input], namespace);\n this.deleteUser = async (userId: string) => handle(\"deleteUser\", [userId], namespace);\n this.sendPasswordResetEmail = async (input: unknown) =>\n handle(\"sendPasswordResetEmail\", [input], namespace);\n }) as unknown as new (config: { namespace: string }) => {\n users(options?: {\n first?: number;\n after?: string;\n query?: { ids?: string[]; names?: string[] };\n }): Promise<{ users: IdpUser[]; nextPageToken: string | null; totalCount: number }>;\n user(userId: string): Promise<IdpUser>;\n userByName(name: string): Promise<IdpUser>;\n createUser(input: { name: string; password?: string; disabled?: boolean }): Promise<IdpUser>;\n updateUser(input: {\n id: string;\n name?: string;\n password?: string;\n clearPassword?: boolean;\n disabled?: boolean;\n }): Promise<IdpUser>;\n deleteUser(userId: string): Promise<boolean>;\n sendPasswordResetEmail(input: { userId: string; redirectUri: string }): Promise<boolean>;\n };\n\n root.idp = { Client };\n\n const facade = {\n /** The mock IDP `Client` constructor (`vi.fn`). */\n Client: Client as unknown as Mock,\n\n setResolver(value: IdpResolver): void {\n resolver = value;\n },\n\n /**\n * Enqueue a single result for the next IDP call (FIFO; falls back to\n * `setResolver` when exhausted).\n * @param result - Result to return from the next IDP call\n */\n enqueueResult(result: unknown): void {\n queue.push(result);\n },\n\n /**\n * Enqueue results for multiple subsequent IDP calls.\n * @param results - Results to enqueue, one per upcoming call\n */\n enqueueResults(...results: unknown[]): void {\n queue.push(...results);\n },\n\n get calls(): IdpCall[] {\n return calls;\n },\n\n reset(): void {\n queue.length = 0;\n resolver = () => null;\n calls.length = 0;\n },\n };\n\n return withDispose(facade, () => {\n root.idp = prev;\n });\n}\n\n// ---------------------------------------------------------------------------\n// Iconv Mock\n// ---------------------------------------------------------------------------\n\n// Iconv methods return `string` for UTF-8 target encodings and `Uint8Array`\n// for any other byte-producing encoding (the platform API mirrors this).\nfunction isUtf8(encoding: unknown): boolean {\n return encoding === \"UTF8\" || encoding === \"UTF-8\";\n}\n\nfunction defaultIconvResult(method: string, args: unknown[]): unknown {\n switch (method) {\n case \"convert\":\n case \"convertBuffer\":\n return isUtf8(args[2]) ? \"\" : new Uint8Array();\n case \"decode\":\n return \"\";\n case \"encode\":\n return isUtf8(args[1]) ? \"\" : new Uint8Array();\n case \"encodings\":\n return [];\n default:\n return undefined;\n }\n}\n\n/**\n * Acquire a disposable mock for `tailor.iconv`. Restored on dispose.\n * @returns Disposable Iconv mock control object\n * @example\n * ```typescript\n * import { mockIconv } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"mock encoding conversion\", () => {\n * using iconv = mockIconv();\n * iconv.setResolver((method) => (method === \"decode\" ? \"decoded-text\" : null));\n * // …\n * });\n * ```\n */\nexport function mockIconv() {\n const root = tailorRoot();\n const prev = root.iconv;\n\n let resolver: IconvResolver | null = null;\n const calls: IconvCall[] = [];\n\n function handle(method: string, args: unknown[]): unknown {\n calls.push({ method, args: [...args] });\n if (resolver) {\n const result = resolver(method, args);\n if (result != null) return result;\n }\n return defaultIconvResult(method, args);\n }\n\n class MockIconv {\n #fromEncoding: string;\n #toEncoding: string;\n constructor(fromEncoding: string, toEncoding: string) {\n this.#fromEncoding = fromEncoding;\n this.#toEncoding = toEncoding;\n }\n convert(input: string | Uint8Array | ArrayBuffer): string | Uint8Array {\n return handle(\"convert\", [input, this.#fromEncoding, this.#toEncoding]) as\n | string\n | Uint8Array;\n }\n }\n\n root.iconv = {\n convert: (str: unknown, from: string, to: string) => handle(\"convert\", [str, from, to]),\n convertBuffer: (buf: unknown, from: string, to: string) =>\n handle(\"convertBuffer\", [buf, from, to]),\n decode: (buf: unknown, encoding: string) => handle(\"decode\", [buf, encoding]),\n encode: (str: string, encoding: string) => handle(\"encode\", [str, encoding]),\n encodings: () => handle(\"encodings\", []),\n Iconv: MockIconv,\n };\n\n const facade = {\n setResolver(value: IconvResolver): void {\n resolver = value;\n },\n\n get calls(): IconvCall[] {\n return calls;\n },\n\n reset(): void {\n resolver = null;\n calls.length = 0;\n },\n };\n\n return withDispose(facade, () => {\n root.iconv = prev;\n });\n}\n\n// ---------------------------------------------------------------------------\n// File Mock (tailordb.file)\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst FILE_DEFAULTS: Record<string, any> = {\n upload: { metadata: { fileSize: 0, sha256sum: \"\" } },\n download: {\n data: new Uint8Array(),\n metadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", lastUploadedAt: \"\" },\n },\n downloadAsBase64: {\n data: \"\",\n metadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", lastUploadedAt: \"\" },\n },\n delete: undefined,\n getMetadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", urlPath: \"\" },\n downloadStream: null,\n uploadStream: { metadata: { fileSize: 0, sha256sum: \"\" } },\n};\n\ntype FileStream = AsyncIterableIterator<unknown> & { close(): Promise<void> };\n\nfunction toFileStream(value: unknown): FileStream {\n if (\n value !== null &&\n typeof value === \"object\" &&\n Symbol.asyncIterator in value &&\n typeof (value as { close?: unknown }).close === \"function\"\n ) {\n return value as FileStream;\n }\n if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) {\n throw new TypeError(\n \"openDownloadStream expects an iterable of StreamValue items \" +\n '(e.g. [{ type: \"chunk\", data, position }, { type: \"complete\" }]); ' +\n \"got raw bytes. Wrap the bytes in a structured chunk first.\",\n );\n }\n if (\n value !== null &&\n typeof value === \"object\" &&\n (Symbol.iterator in value || Symbol.asyncIterator in value)\n ) {\n const source = value as Iterable<unknown> | AsyncIterable<unknown>;\n const inner =\n Symbol.asyncIterator in source\n ? (source as AsyncIterable<unknown>)[Symbol.asyncIterator]()\n : (source as Iterable<unknown>)[Symbol.iterator]();\n const stream: FileStream = {\n async next() {\n const r = await inner.next();\n if (!r.done) {\n assertStreamValue(r.value);\n }\n return r.done ? { done: true as const, value: undefined } : r;\n },\n async close() {},\n [Symbol.asyncIterator]() {\n return stream;\n },\n };\n return stream;\n }\n const empty: FileStream = {\n async next() {\n return { done: true as const, value: undefined };\n },\n async close() {},\n [Symbol.asyncIterator]() {\n return empty;\n },\n };\n return empty;\n}\n\nfunction assertStreamValue(v: unknown): void {\n if (v === null || typeof v !== \"object\") {\n throw new TypeError(\n 'openDownloadStream expected a StreamValue item ({ type: \"metadata\" | \"chunk\" | \"complete\", ... }); ' +\n `got ${typeof v === \"object\" ? \"null\" : typeof v}.`,\n );\n }\n if (v instanceof ArrayBuffer || ArrayBuffer.isView(v)) {\n throw new TypeError(\n \"openDownloadStream expected a StreamValue item, got raw bytes. \" +\n 'Wrap the bytes in a structured chunk first (e.g. { type: \"chunk\", data, position }).',\n );\n }\n const type = (v as { type?: unknown }).type;\n if (type !== \"metadata\" && type !== \"chunk\" && type !== \"complete\") {\n throw new TypeError(\n 'openDownloadStream expected a StreamValue item with type \"metadata\" | \"chunk\" | \"complete\"; ' +\n `got ${JSON.stringify(type)}.`,\n );\n }\n}\n\n/**\n * Acquire a disposable mock for `tailordb.file`. Restored on dispose.\n * @returns Disposable File mock control object\n * @example\n * ```typescript\n * import { mockFile } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"mock file download\", async () => {\n * using file = mockFile();\n * file.enqueueResult({ data: new Uint8Array([1, 2, 3]), metadata: { ... } });\n * // …\n * });\n * ```\n */\nexport function mockFile() {\n const root = tailordbRoot();\n const prev = root.file;\n\n const queue: unknown[] = [];\n let resolver: FileResolver = () => null;\n const calls: FileCall[] = [];\n\n function handle(\n method: string,\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): unknown {\n const call: FileCall = { method, namespace, typeName, fieldName, recordId };\n calls.push(call);\n if (queue.length > 0) return queue.shift();\n const resolved = resolver(method, call);\n if (resolved != null) return resolved;\n const fallback = FILE_DEFAULTS[method];\n return fallback === undefined ? undefined : structuredClone(fallback);\n }\n\n root.file = {\n async upload(namespace: string, typeName: string, fieldName: string, recordId: string) {\n return handle(\"upload\", namespace, typeName, fieldName, recordId);\n },\n async download(namespace: string, typeName: string, fieldName: string, recordId: string) {\n return handle(\"download\", namespace, typeName, fieldName, recordId);\n },\n async downloadAsBase64(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ) {\n return handle(\"downloadAsBase64\", namespace, typeName, fieldName, recordId);\n },\n async delete(namespace: string, typeName: string, fieldName: string, recordId: string) {\n handle(\"delete\", namespace, typeName, fieldName, recordId);\n },\n async getMetadata(namespace: string, typeName: string, fieldName: string, recordId: string) {\n return handle(\"getMetadata\", namespace, typeName, fieldName, recordId);\n },\n async openDownloadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ) {\n return toFileStream(handle(\"openDownloadStream\", namespace, typeName, fieldName, recordId));\n },\n async downloadStream(namespace: string, typeName: string, fieldName: string, recordId: string) {\n const resolved = handle(\"downloadStream\", namespace, typeName, fieldName, recordId);\n if (resolved != null) return resolved;\n return {\n body: new ReadableStream({\n start(c) {\n c.close();\n },\n }),\n metadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", lastUploadedAt: \"\" },\n };\n },\n async uploadStream(namespace: string, typeName: string, fieldName: string, recordId: string) {\n return handle(\"uploadStream\", namespace, typeName, fieldName, recordId);\n },\n };\n\n const facade = {\n setResolver(value: FileResolver): void {\n resolver = value;\n },\n\n /**\n * Enqueue a single result for the next `tailordb.file` call (FIFO; falls\n * back to `setResolver` when exhausted).\n * @param result - Result to return from the next file call\n */\n enqueueResult(result: unknown): void {\n queue.push(result);\n },\n\n /**\n * Enqueue results for multiple subsequent `tailordb.file` calls.\n * @param results - Results to enqueue, one per upcoming call\n */\n enqueueResults(...results: unknown[]): void {\n queue.push(...results);\n },\n\n get calls(): FileCall[] {\n return calls;\n },\n\n reset(): void {\n queue.length = 0;\n resolver = () => null;\n calls.length = 0;\n },\n };\n\n return withDispose(facade, () => {\n root.file = prev;\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiIA,SAAS,YAA8B,QAAW,SAAqC;CACrF,OAAO,eAAe,QAAQ,OAAO,SAAS;EAC5C,OAAO;EACP,YAAY;EACZ,UAAU;EACV,cAAc;CAChB,CAAC;CACD,OAAO;AACT;AAGA,SAAS,aAAkC;CACzC,MAAM,IAAI;CACV,IAAI,CAAC,EAAE,QAIL,EAAE,SAAS,EAAE,SAAS,EAAE,kBAAkB,KAAK,EAAE;CAGnD,OAAO,EAAE;AACX;AAGA,SAAS,eAAoC;CAC3C,MAAM,IAAI;CACV,IAAI,CAAC,EAAE,UACL,EAAE,WAAW,CAAC;CAGhB,OAAO,EAAE;AACX;AAEA,IAAM,kBAAN,MAAsB;CACpB;CACA;CACA;CAEA,YAAY,MAAiB;EAC3B,KAAK,UAAU;EACf,KAAK,WAAW,KAAK;EACrB,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,eAAe;CAC7B,MAAM,OAAO,aAAa;CAC1B,MAAM,aAAa,KAAK;CAExB,MAAM,cAAc,GAAG,GACrB,OAAO,QAAgB,UAAqB,CAAC,MAC3C,IAAI,gBAAgB,CAAC,CAAC,CAC1B;CACA,MAAM,UAAU,GAAG,GAAG,YAA2B,CAAC,CA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AAkB,WAAmB,UAAkB;GAC1F,OAAO,OAAO,eAAe,WAAW,UAAU,WAAW,QAAQ;EACvE;EACA,MAAM,mBACJ,WACA,UACA,WACA,UACA;GACA,OAAO,aAAa,OAAO,sBAAsB,WAAW,UAAU,WAAW,QAAQ,CAAC;EAC5F;EACA,MAAM,eAAe,WAAmB,UAAkB,WAAmB,UAAkB;GAC7F,MAAM,WAAW,OAAO,kBAAkB,WAAW,UAAU,WAAW,QAAQ;GAClF,IAAI,YAAY,MAAM,OAAO;GAC7B,OAAO;IACL,MAAM,IAAI,eAAe,EACvB,MAAM,GAAG;KACP,EAAE,MAAM;IACV,EACF,CAAC;IACD,UAAU;KAAE,aAAa;KAAI,UAAU;KAAG,WAAW;KAAI,gBAAgB;IAAG;GAC9E;EACF;EACA,MAAM,aAAa,WAAmB,UAAkB,WAAmB,UAAkB;GAC3F,OAAO,OAAO,gBAAgB,WAAW,UAAU,WAAW,QAAQ;EACxE;CACF;CAmCA,OAAO,YAAY;EAhCjB,YAAY,OAA2B;GACrC,WAAW;EACb;;;;;;EAOA,cAAc,QAAuB;GACnC,MAAM,KAAK,MAAM;EACnB;;;;;EAMA,eAAe,GAAG,SAA0B;GAC1C,MAAM,KAAK,GAAG,OAAO;EACvB;EAEA,IAAI,QAAoB;GACtB,OAAO;EACT;EAEA,QAAc;GACZ,MAAM,SAAS;GACf,iBAAiB;GACjB,MAAM,SAAS;EACjB;CAGsB,SAAS;EAC/B,KAAK,OAAO;CACd,CAAC;AACH"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
//#region src/utils/multiline.ts
|
|
3
2
|
/**
|
|
4
3
|
* Tag function which strips the common leading indent from a multi-line
|
|
@@ -36,4 +35,4 @@ function getFinalIndent(value) {
|
|
|
36
35
|
|
|
37
36
|
//#endregion
|
|
38
37
|
export { multiline as t };
|
|
39
|
-
//# sourceMappingURL=multiline-
|
|
38
|
+
//# sourceMappingURL=multiline-sfHpTZZK.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multiline-
|
|
1
|
+
{"version":3,"file":"multiline-sfHpTZZK.mjs","names":[],"sources":["../src/utils/multiline.ts"],"sourcesContent":["/**\n * Tag function which strips the common leading indent from a multi-line\n * template literal and trims surrounding blank lines, while indenting each\n * line of interpolated values to match the placeholder's indent.\n *\n * Mirrors the behaviour of the `multiline-ts` package, which we used to\n * depend on. We replaced it with this in-tree implementation because the\n * upstream package ships a `preinstall: npx only-allow pnpm` hook that\n * makes `npx create-tailor-sdk@latest` (and any other npm-based install\n * path that resolves a fresh copy) abort with `ECOMPROMISED`.\n * @param value - Template strings array, or a plain string for non-tagged usage\n * @param inputs - Interpolated values\n * @returns The dedented and trimmed string\n */\nexport default function multiline(\n value: TemplateStringsArray | string,\n ...inputs: string[]\n): string {\n const strings = typeof value === \"string\" ? value.split(/(?=\\r\\n|\\r|\\n)/) : Array.from(value);\n\n let currentIndent = \"\";\n const joined = strings\n .map((segment, i) => {\n if (/\\r\\n|\\r|\\n/.test(segment)) {\n currentIndent = getFinalIndent(segment) || currentIndent;\n }\n const input = inputs[i] ?? \"\";\n return segment + input.replace(/\\r\\n|\\r|\\n/g, `\\n${currentIndent}`);\n })\n .join(\"\");\n\n const lines = joined.split(/\\r\\n|\\r|\\n/);\n const indents = lines.filter((line) => /[^ \\t]/.test(line)).map((line) => getIndent(line).length);\n const minIndent = indents.length === 0 ? 0 : Math.min(...indents);\n return lines\n .map((line) => line.slice(minIndent))\n .join(\"\\n\")\n .replace(/^\\n|\\n[ \\t]*$/g, \"\");\n}\n\nfunction getIndent(line: string): string {\n const match = line.match(/^[ \\t]+/);\n return match ? match[0] : \"\";\n}\n\nfunction getFinalIndent(value: string): string {\n const match = value.match(/(?<=(\\r\\n|\\r|\\n))[ \\t]+$/);\n return match ? match[0] : \"\";\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAwB,UACtB,OACA,GAAG,QACK;CACR,MAAM,UAAU,OAAO,UAAU,WAAW,MAAM,MAAM,gBAAgB,IAAI,MAAM,KAAK,KAAK;CAE5F,IAAI,gBAAgB;CAWpB,MAAM,QAVS,QACZ,KAAK,SAAS,MAAM;EACnB,IAAI,aAAa,KAAK,OAAO,GAC3B,gBAAgB,eAAe,OAAO,KAAK;EAG7C,OAAO,WADO,OAAO,MAAM,GACL,CAAC,QAAQ,eAAe,KAAK,eAAe;CACpE,CAAC,CAAC,CACD,KAAK,EAEW,CAAC,CAAC,MAAM,YAAY;CACvC,MAAM,UAAU,MAAM,QAAQ,SAAS,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK,SAAS,UAAU,IAAI,CAAC,CAAC,MAAM;CAChG,MAAM,YAAY,QAAQ,WAAW,IAAI,IAAI,KAAK,IAAI,GAAG,OAAO;CAChE,OAAO,MACJ,KAAK,SAAS,KAAK,MAAM,SAAS,CAAC,CAAC,CACpC,KAAK,IAAI,CAAC,CACV,QAAQ,kBAAkB,EAAE;AACjC;AAEA,SAAS,UAAU,MAAsB;CACvC,MAAM,QAAQ,KAAK,MAAM,SAAS;CAClC,OAAO,QAAQ,MAAM,KAAK;AAC5B;AAEA,SAAS,eAAe,OAAuB;CAC7C,MAAM,QAAQ,MAAM,MAAM,0BAA0B;CACpD,OAAO,QAAQ,MAAM,KAAK;AAC5B"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
import { readPackageJSON } from "pkg-types";
|
|
3
2
|
|
|
4
3
|
//#region src/cli/shared/package-json.ts
|
|
@@ -15,4 +14,4 @@ async function readPackageJson() {
|
|
|
15
14
|
|
|
16
15
|
//#endregion
|
|
17
16
|
export { readPackageJson as t };
|
|
18
|
-
//# sourceMappingURL=package-json-
|
|
17
|
+
//# sourceMappingURL=package-json-8b0O9TlX.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package-json-
|
|
1
|
+
{"version":3,"file":"package-json-8b0O9TlX.mjs","names":[],"sources":["../src/cli/shared/package-json.ts"],"sourcesContent":["import { readPackageJSON, type PackageJson } from \"pkg-types\";\n\nlet packageJson: PackageJson | null = null;\n\n/**\n * Read and cache the package.json of the SDK package.\n * @returns Parsed package.json contents\n */\nexport async function readPackageJson() {\n if (packageJson) {\n return packageJson;\n }\n packageJson = await readPackageJSON(import.meta.url);\n return packageJson;\n}\n"],"mappings":";;;AAEA,IAAI,cAAkC;;;;;AAMtC,eAAsB,kBAAkB;CACtC,IAAI,aACF,OAAO;CAET,cAAc,MAAM,gBAAgB,OAAO,KAAK,GAAG;CACnD,OAAO;AACT"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as enumConstantsPlugin, t as EnumConstantsGeneratorID } from "../../../index-
|
|
1
|
+
import { n as enumConstantsPlugin, t as EnumConstantsGeneratorID } from "../../../index-DjUdWlzf.mjs";
|
|
2
2
|
export { EnumConstantsGeneratorID, enumConstantsPlugin };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
import { n as enumConstantsPlugin, t as EnumConstantsGeneratorID } from "../../../enum-constants-C7DaWeQo.mjs";
|
|
1
|
+
import { n as enumConstantsPlugin, t as EnumConstantsGeneratorID } from "../../../enum-constants-j9QBF0cB.mjs";
|
|
3
2
|
|
|
4
3
|
export { EnumConstantsGeneratorID, enumConstantsPlugin };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as fileUtilsPlugin, t as FileUtilsGeneratorID } from "../../../index-
|
|
1
|
+
import { n as fileUtilsPlugin, t as FileUtilsGeneratorID } from "../../../index-CNYe5lnW.mjs";
|
|
2
2
|
export { FileUtilsGeneratorID, fileUtilsPlugin };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as kyselyTypePlugin, t as KyselyGeneratorID } from "../../../index-
|
|
1
|
+
import { n as kyselyTypePlugin, t as KyselyGeneratorID } from "../../../index-5vPyRu1y.mjs";
|
|
2
2
|
export { KyselyGeneratorID, kyselyTypePlugin };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as seedPlugin, t as SeedGeneratorID } from "../../../index-
|
|
1
|
+
import { n as seedPlugin, t as SeedGeneratorID } from "../../../index-B7AKc18V.mjs";
|
|
2
2
|
export { SeedGeneratorID, seedPlugin };
|
package/dist/plugin/index.d.mts
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as TailorEnv } from "../env-B-g-qgE4.mjs";
|
|
3
|
-
import { t as TailorActor } from "../actor-J2gJ0eK5.mjs";
|
|
1
|
+
import { B as TailorActor, V as TailorEnv, f as TailorAnyDBType } from "../types-DCUhgpyI.mjs";
|
|
4
2
|
|
|
5
3
|
//#region src/plugin/with-context.d.ts
|
|
6
4
|
/**
|
package/dist/plugin/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/with-context.ts","../../src/plugin/get-generated-type.ts"],"sourcesContent":["/**\n * Plugin executor context support for defining plugin executors in separate files.\n * This module provides utilities for creating type-safe plugin executors that receive\n * context (like type references and namespace) at runtime.\n */\n\nimport type { TailorActor, TailorEnv } from \"@/types/runtime\";\n\n/**\n * Plugin executor factory function type.\n * Takes context and returns an executor configuration.\n * Returns unknown since the exact return type depends on createExecutor's generic params.\n */\nexport type PluginExecutorFactory<Ctx> = (ctx: Ctx) => unknown;\n\n// ============================================================================\n// Plugin Executor Args Types\n// ============================================================================\n\n/**\n * Base args for plugin executor function operations.\n * Provides typed access to runtime context without requiring specific record types.\n */\nexport interface PluginFunctionArgs {\n /** Workspace ID where the executor runs */\n workspaceId: string;\n /** Application namespace */\n appNamespace: string;\n /** Environment variables */\n env: TailorEnv;\n /** Actor (user) who triggered the event, null for system events */\n actor: TailorActor | null;\n /** Name of the TailorDB type */\n typeName: string;\n /** TailorDB connections by namespace */\n tailordb: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record creation.\n */\nexport interface PluginRecordCreatedArgs extends PluginFunctionArgs {\n /** The newly created record */\n newRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record update.\n */\nexport interface PluginRecordUpdatedArgs extends PluginFunctionArgs {\n /** The record after update */\n newRecord: Record<string, unknown>;\n /** The record before update */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record deletion.\n */\nexport interface PluginRecordDeletedArgs extends PluginFunctionArgs {\n /** The deleted record */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Database schema type for plugins.\n * Since plugins work with dynamic types, the schema uses Record types.\n */\nexport type PluginDBSchema = Record<string, Record<string, unknown>>;\n\n/**\n * Base record type for TailorDB records.\n * All records have an id field.\n */\nexport type PluginRecord = { id: string } & Record<string, unknown>;\n\n/**\n * Define a plugin executor that receives context at runtime.\n * This allows executor definitions to be in separate files while\n * still receiving dynamic values like typeName, generated types, and namespace.\n * @param factory - Function that takes context and returns executor configuration\n * @returns The same factory function (for type inference)\n * @example\n * ```typescript\n * // executors/on-create.ts\n * import { withPluginContext } from \"@tailor-platform/sdk/plugin\";\n * import { createExecutor, recordCreatedTrigger } from \"@tailor-platform/sdk\";\n * import { getDB } from \"@tailor-platform/function-kysely-tailordb\";\n *\n * interface MyContext {\n * sourceType: TailorAnyDBType;\n * historyType: TailorAnyDBType;\n * namespace: string;\n * }\n *\n * export default withPluginContext<MyContext>((ctx) =>\n * createExecutor({\n * name: `${ctx.sourceType.name.toLowerCase()}-on-create`,\n * trigger: recordCreatedTrigger({ type: ctx.sourceType }),\n * operation: {\n * kind: \"function\",\n * body: async (args) => {\n * const db = getDB(ctx.namespace);\n * await db.insertInto(ctx.historyType.name).values({\n * recordId: args.newRecord.id,\n * // ...\n * }).execute();\n * },\n * },\n * })\n * );\n * ```\n */\nexport function withPluginContext<Ctx>(\n factory: PluginExecutorFactory<Ctx>,\n): PluginExecutorFactory<Ctx> {\n return factory;\n}\n","import * as fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport type { Plugin, PluginOutput, TypePluginOutput } from \"@/types/plugin\";\nimport type { TailorAnyDBType } from \"@/types/tailordb\";\n\n// ========================================\n// Config loading and caching\n// ========================================\n\ninterface PluginEntry {\n plugin: Plugin;\n pluginConfig: unknown;\n}\n\ninterface ConfigCache {\n config: { db?: Record<string, unknown> };\n plugins: Map<string, PluginEntry>;\n configDir: string;\n}\n\n/** Cache: resolved config path -> loaded config data */\nconst configCacheMap = new Map<string, ConfigCache>();\n\n/**\n * Check if a value is a Plugin instance.\n * @param value - Value to check\n * @returns True if value has the shape of Plugin\n */\nfunction isPlugin(value: unknown): value is Plugin {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).id === \"string\" &&\n typeof (value as Record<string, unknown>).description === \"string\"\n );\n}\n\n/**\n * Load and cache config module from the given path.\n * Extracts plugins from all array exports using definePlugins() format.\n * Returns null if the config file does not exist (e.g., in bundled executor on platform server).\n * @param configPath - Absolute or relative path to tailor.config.ts\n * @returns Cached config data with plugins map, or null if config file is not available\n */\nasync function loadAndCacheConfig(configPath: string): Promise<ConfigCache | null> {\n const resolvedPath = path.resolve(configPath);\n\n const cached = configCacheMap.get(resolvedPath);\n if (cached) return cached;\n\n // Config file may not exist in bundled environments (e.g., platform server)\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n\n const configModule = await import(pathToFileURL(resolvedPath).href);\n if (!configModule?.default) {\n throw new Error(`Invalid config module at \"${resolvedPath}\": default export not found`);\n }\n\n const config = configModule.default as { db?: Record<string, unknown> };\n const configDir = path.dirname(resolvedPath);\n const plugins = new Map<string, PluginEntry>();\n\n // Find plugin arrays from exports (definePlugins returns PluginConfig[])\n for (const value of Object.values(configModule)) {\n if (!Array.isArray(value)) continue;\n\n for (const item of value) {\n if (isPlugin(item)) {\n plugins.set(item.id, { plugin: item, pluginConfig: item.pluginConfig });\n }\n }\n }\n\n const result: ConfigCache = { config, plugins, configDir };\n configCacheMap.set(resolvedPath, result);\n return result;\n}\n\n// ========================================\n// Namespace resolution\n// ========================================\n\ninterface DbNamespaceConfig {\n files?: string[];\n external?: boolean;\n}\n\n/**\n * Resolve the namespace for a type-attached sourceType by checking config.db file patterns.\n * Uses ESM module cache identity: same file path yields same object references.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param configDir - Directory containing the config file\n * @param sourceType - The TailorDB type to look up\n * @returns The namespace name\n */\nasync function resolveNamespaceForType(\n config: { db?: Record<string, unknown> },\n configDir: string,\n sourceType: TailorAnyDBType,\n): Promise<string> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n for (const [namespace, nsConfig] of Object.entries(config.db)) {\n const dbConfig = nsConfig as DbNamespaceConfig;\n // Skip external namespaces (no files to resolve)\n if (dbConfig.external || !dbConfig.files) continue;\n\n for (const pattern of dbConfig.files) {\n const absolutePattern = path.resolve(configDir, pattern);\n let matchedFiles: string[];\n try {\n matchedFiles = fs.globSync(absolutePattern);\n } catch {\n continue;\n }\n\n for (const file of matchedFiles) {\n const mod = await import(pathToFileURL(file).href);\n for (const exported of Object.values(mod)) {\n if (exported === sourceType) {\n return namespace;\n }\n }\n }\n }\n }\n\n throw new Error(\n `Could not resolve namespace for type \"${sourceType.name}\". ` +\n `Ensure the type file is included in a db namespace's files pattern.`,\n );\n}\n\n/**\n * Resolve the namespace for a namespace plugin by trying each namespace.\n * Calls onNamespaceLoaded() for each and returns the first whose output contains the requested kind.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - Plugin instance\n * @param kind - The generated type kind to look for\n * @param pluginConfig - Plugin-level configuration\n * @returns The namespace name\n */\nasync function resolveNamespaceForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<{ namespace: string; output: PluginOutput }> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const output = await plugin.onNamespaceLoaded({\n pluginConfig,\n namespace,\n });\n\n if (output.types?.[kind]) {\n return { namespace, output };\n }\n }\n\n throw new Error(\n `Could not resolve namespace for plugin \"${plugin.id}\" with kind \"${kind}\". ` +\n `No namespace produced a type with that kind.`,\n );\n}\n\n// ========================================\n// Process caching\n// ========================================\n\n// Cache: plugin -> cacheKey -> TypePluginOutput\nconst processCache = new WeakMap<Plugin, Map<string, TypePluginOutput>>();\n\n// Cache for namespace plugins: plugin -> cacheKey -> PluginOutput\nconst namespaceProcessCache = new WeakMap<Plugin, Map<string, PluginOutput>>();\n\n/**\n * Generate a cache key that includes pluginConfig.\n * @param baseKey - Base key for the cache\n * @param pluginConfig - Plugin configuration to include in the key\n * @returns Cache key string\n */\nfunction getCacheKey(baseKey: string, pluginConfig: unknown): string {\n if (pluginConfig === undefined) {\n return baseKey;\n }\n try {\n return `${baseKey}:${JSON.stringify(pluginConfig)}`;\n } catch {\n throw new Error(\n `pluginConfig must be JSON-serializable for caching. Received non-serializable value.`,\n );\n }\n}\n\n// ========================================\n// Main API\n// ========================================\n\n/**\n * Get a generated type from a plugin by loading the config and resolving everything automatically.\n * For type-attached plugins, calls onTypeLoaded() with the sourceType.\n * For namespace plugins, calls onNamespaceLoaded() with auto-resolved namespace.\n * Results are cached per config path, plugin, namespace, and pluginConfig to avoid redundant processing.\n * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)\n * @param pluginId - The plugin's unique identifier\n * @param sourceType - The source TailorDB type (null for namespace plugins)\n * @param kind - The generated type kind (e.g., \"request\", \"step\")\n * @returns The generated TailorDB type\n */\nexport async function getGeneratedType(\n configPath: string,\n pluginId: string,\n sourceType: TailorAnyDBType | null,\n kind: string,\n): Promise<TailorAnyDBType> {\n const cache = await loadAndCacheConfig(configPath);\n\n if (!cache) {\n // Config not available (e.g., running in bundled executor on platform server).\n // Return a placeholder. The actual type is resolved at generate/apply time.\n return { name: `__placeholder_${kind}__`, fields: {} } as TailorAnyDBType;\n }\n\n const { config, configDir, plugins } = cache;\n\n const pluginEntry = plugins.get(pluginId);\n if (!pluginEntry) {\n throw new Error(\n `Plugin \"${pluginId}\" not found in config at \"${configPath}\". ` +\n `Ensure the plugin is registered via definePlugins().`,\n );\n }\n\n const { plugin, pluginConfig } = pluginEntry;\n\n if (sourceType === null) {\n return getGeneratedTypeForNamespacePlugin(config, plugin, kind, pluginConfig);\n }\n\n const namespace = await resolveNamespaceForType(config, configDir, sourceType);\n return getGeneratedTypeForTypeAttachedPlugin(plugin, sourceType, kind, pluginConfig, namespace);\n}\n\n/**\n * Get a generated type from a type-attached plugin.\n * @param plugin - The plugin instance (must have onTypeLoaded() method)\n * @param sourceType - The source TailorDB type\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @param namespace - Resolved namespace\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForTypeAttachedPlugin(\n plugin: Plugin,\n sourceType: TailorAnyDBType,\n kind: string,\n pluginConfig: unknown,\n namespace: string,\n): Promise<TailorAnyDBType> {\n if (!plugin.onTypeLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onTypeLoaded() method`);\n }\n\n // Check cache first\n let pluginCache = processCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n processCache.set(plugin, pluginCache);\n }\n\n const cacheKey = getCacheKey(`${sourceType.name}:ns=${namespace}`, pluginConfig);\n let output = pluginCache.get(cacheKey);\n\n if (!output) {\n const typeConfig = sourceType.plugins.find((p) => p.pluginId === plugin.id)?.config;\n output = await plugin.onTypeLoaded({\n type: sourceType,\n typeConfig: typeConfig ?? {},\n pluginConfig,\n namespace,\n });\n pluginCache.set(cacheKey, output);\n }\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(\n `Generated type not found: plugin=${plugin.id}, sourceType=${sourceType.name}, kind=${kind}`,\n );\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Get a generated type from a namespace plugin.\n * Auto-resolves the namespace by trying each one.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - The plugin instance (must have onNamespaceLoaded() method)\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<TailorAnyDBType> {\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n // Check cache first - try all namespaces\n let pluginCache = namespaceProcessCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n namespaceProcessCache.set(plugin, pluginCache);\n }\n\n // Try cached results first\n if (config.db) {\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n const cached = pluginCache.get(cacheKey);\n if (cached?.types?.[kind]) {\n return cached.types[kind] as TailorAnyDBType;\n }\n }\n }\n\n // Not in cache - resolve namespace and process\n const { namespace, output } = await resolveNamespaceForNamespacePlugin(\n config,\n plugin,\n kind,\n pluginConfig,\n );\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n pluginCache.set(cacheKey, output);\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(`Generated type not found: plugin=${plugin.id}, kind=${kind}`);\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Clear all internal caches. For testing only.\n */\nexport function _clearCacheForTesting(): void {\n configCacheMap.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,SAAgB,kBACd,SAC4B;CAC5B,OAAO;AACT;;;;;AC/F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EACtB,sBAAsB,IAAI,QAAQ,WAAW;CAC/C;CAGA,IAAI,OAAO,IACT,KAAK,MAAM,aAAa,OAAO,KAAK,OAAO,EAAE,GAAG;EAE9C,IADiB,OAAO,GAAG,UACf,CAAC,UAAU;EAEvB,MAAM,WAAW,YAAY,gBAAgB,aAAa,YAAY;EACtE,MAAM,SAAS,YAAY,IAAI,QAAQ;EACvC,IAAI,QAAQ,QAAQ,OAClB,OAAO,OAAO,MAAM;CAExB;CAIF,MAAM,EAAE,WAAW,WAAW,MAAM,mCAClC,QACA,QACA,MACA,YACF;CAEA,MAAM,WAAW,YAAY,gBAAgB,aAAa,YAAY;CACtE,YAAY,IAAI,UAAU,MAAM;CAEhC,MAAM,gBAAgB,OAAO,QAAQ;CACrC,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,oCAAoC,OAAO,GAAG,SAAS,MAAM;CAG/E,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/with-context.ts","../../src/plugin/get-generated-type.ts"],"sourcesContent":["/**\n * Plugin executor context support for defining plugin executors in separate files.\n * This module provides utilities for creating type-safe plugin executors that receive\n * context (like type references and namespace) at runtime.\n */\n\nimport type { TailorActor, TailorEnv } from \"@/runtime/types\";\n\n/**\n * Plugin executor factory function type.\n * Takes context and returns an executor configuration.\n * Returns unknown since the exact return type depends on createExecutor's generic params.\n */\nexport type PluginExecutorFactory<Ctx> = (ctx: Ctx) => unknown;\n\n// ============================================================================\n// Plugin Executor Args Types\n// ============================================================================\n\n/**\n * Base args for plugin executor function operations.\n * Provides typed access to runtime context without requiring specific record types.\n */\nexport interface PluginFunctionArgs {\n /** Workspace ID where the executor runs */\n workspaceId: string;\n /** Application namespace */\n appNamespace: string;\n /** Environment variables */\n env: TailorEnv;\n /** Actor (user) who triggered the event, null for system events */\n actor: TailorActor | null;\n /** Name of the TailorDB type */\n typeName: string;\n /** TailorDB connections by namespace */\n tailordb: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record creation.\n */\nexport interface PluginRecordCreatedArgs extends PluginFunctionArgs {\n /** The newly created record */\n newRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record update.\n */\nexport interface PluginRecordUpdatedArgs extends PluginFunctionArgs {\n /** The record after update */\n newRecord: Record<string, unknown>;\n /** The record before update */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record deletion.\n */\nexport interface PluginRecordDeletedArgs extends PluginFunctionArgs {\n /** The deleted record */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Database schema type for plugins.\n * Since plugins work with dynamic types, the schema uses Record types.\n */\nexport type PluginDBSchema = Record<string, Record<string, unknown>>;\n\n/**\n * Base record type for TailorDB records.\n * All records have an id field.\n */\nexport type PluginRecord = { id: string } & Record<string, unknown>;\n\n/**\n * Define a plugin executor that receives context at runtime.\n * This allows executor definitions to be in separate files while\n * still receiving dynamic values like typeName, generated types, and namespace.\n * @param factory - Function that takes context and returns executor configuration\n * @returns The same factory function (for type inference)\n * @example\n * ```typescript\n * // executors/on-create.ts\n * import { withPluginContext } from \"@tailor-platform/sdk/plugin\";\n * import { createExecutor, recordCreatedTrigger } from \"@tailor-platform/sdk\";\n * import { getDB } from \"@tailor-platform/function-kysely-tailordb\";\n *\n * interface MyContext {\n * sourceType: TailorAnyDBType;\n * historyType: TailorAnyDBType;\n * namespace: string;\n * }\n *\n * export default withPluginContext<MyContext>((ctx) =>\n * createExecutor({\n * name: `${ctx.sourceType.name.toLowerCase()}-on-create`,\n * trigger: recordCreatedTrigger({ type: ctx.sourceType }),\n * operation: {\n * kind: \"function\",\n * body: async (args) => {\n * const db = getDB(ctx.namespace);\n * await db.insertInto(ctx.historyType.name).values({\n * recordId: args.newRecord.id,\n * // ...\n * }).execute();\n * },\n * },\n * })\n * );\n * ```\n */\nexport function withPluginContext<Ctx>(\n factory: PluginExecutorFactory<Ctx>,\n): PluginExecutorFactory<Ctx> {\n return factory;\n}\n","import * as fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport type { TailorAnyDBType } from \"@/configure/services/tailordb/types\";\nimport type { Plugin, PluginOutput, TypePluginOutput } from \"@/plugin/types\";\n\n// ========================================\n// Config loading and caching\n// ========================================\n\ninterface PluginEntry {\n plugin: Plugin;\n pluginConfig: unknown;\n}\n\ninterface ConfigCache {\n config: { db?: Record<string, unknown> };\n plugins: Map<string, PluginEntry>;\n configDir: string;\n}\n\n/** Cache: resolved config path -> loaded config data */\nconst configCacheMap = new Map<string, ConfigCache>();\n\n/**\n * Check if a value is a Plugin instance.\n * @param value - Value to check\n * @returns True if value has the shape of Plugin\n */\nfunction isPlugin(value: unknown): value is Plugin {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).id === \"string\" &&\n typeof (value as Record<string, unknown>).description === \"string\"\n );\n}\n\n/**\n * Load and cache config module from the given path.\n * Extracts plugins from all array exports using definePlugins() format.\n * Returns null if the config file does not exist (e.g., in bundled executor on platform server).\n * @param configPath - Absolute or relative path to tailor.config.ts\n * @returns Cached config data with plugins map, or null if config file is not available\n */\nasync function loadAndCacheConfig(configPath: string): Promise<ConfigCache | null> {\n const resolvedPath = path.resolve(configPath);\n\n const cached = configCacheMap.get(resolvedPath);\n if (cached) return cached;\n\n // Config file may not exist in bundled environments (e.g., platform server)\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n\n const configModule = await import(pathToFileURL(resolvedPath).href);\n if (!configModule?.default) {\n throw new Error(`Invalid config module at \"${resolvedPath}\": default export not found`);\n }\n\n const config = configModule.default as { db?: Record<string, unknown> };\n const configDir = path.dirname(resolvedPath);\n const plugins = new Map<string, PluginEntry>();\n\n // Find plugin arrays from exports (definePlugins returns PluginConfig[])\n for (const value of Object.values(configModule)) {\n if (!Array.isArray(value)) continue;\n\n for (const item of value) {\n if (isPlugin(item)) {\n plugins.set(item.id, { plugin: item, pluginConfig: item.pluginConfig });\n }\n }\n }\n\n const result: ConfigCache = { config, plugins, configDir };\n configCacheMap.set(resolvedPath, result);\n return result;\n}\n\n// ========================================\n// Namespace resolution\n// ========================================\n\ninterface DbNamespaceConfig {\n files?: string[];\n external?: boolean;\n}\n\n/**\n * Resolve the namespace for a type-attached sourceType by checking config.db file patterns.\n * Uses ESM module cache identity: same file path yields same object references.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param configDir - Directory containing the config file\n * @param sourceType - The TailorDB type to look up\n * @returns The namespace name\n */\nasync function resolveNamespaceForType(\n config: { db?: Record<string, unknown> },\n configDir: string,\n sourceType: TailorAnyDBType,\n): Promise<string> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n for (const [namespace, nsConfig] of Object.entries(config.db)) {\n const dbConfig = nsConfig as DbNamespaceConfig;\n // Skip external namespaces (no files to resolve)\n if (dbConfig.external || !dbConfig.files) continue;\n\n for (const pattern of dbConfig.files) {\n const absolutePattern = path.resolve(configDir, pattern);\n let matchedFiles: string[];\n try {\n matchedFiles = fs.globSync(absolutePattern);\n } catch {\n continue;\n }\n\n for (const file of matchedFiles) {\n const mod = await import(pathToFileURL(file).href);\n for (const exported of Object.values(mod)) {\n if (exported === sourceType) {\n return namespace;\n }\n }\n }\n }\n }\n\n throw new Error(\n `Could not resolve namespace for type \"${sourceType.name}\". ` +\n `Ensure the type file is included in a db namespace's files pattern.`,\n );\n}\n\n/**\n * Resolve the namespace for a namespace plugin by trying each namespace.\n * Calls onNamespaceLoaded() for each and returns the first whose output contains the requested kind.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - Plugin instance\n * @param kind - The generated type kind to look for\n * @param pluginConfig - Plugin-level configuration\n * @returns The namespace name\n */\nasync function resolveNamespaceForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<{ namespace: string; output: PluginOutput }> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const output = await plugin.onNamespaceLoaded({\n pluginConfig,\n namespace,\n });\n\n if (output.types?.[kind]) {\n return { namespace, output };\n }\n }\n\n throw new Error(\n `Could not resolve namespace for plugin \"${plugin.id}\" with kind \"${kind}\". ` +\n `No namespace produced a type with that kind.`,\n );\n}\n\n// ========================================\n// Process caching\n// ========================================\n\n// Cache: plugin -> cacheKey -> TypePluginOutput\nconst processCache = new WeakMap<Plugin, Map<string, TypePluginOutput>>();\n\n// Cache for namespace plugins: plugin -> cacheKey -> PluginOutput\nconst namespaceProcessCache = new WeakMap<Plugin, Map<string, PluginOutput>>();\n\n/**\n * Generate a cache key that includes pluginConfig.\n * @param baseKey - Base key for the cache\n * @param pluginConfig - Plugin configuration to include in the key\n * @returns Cache key string\n */\nfunction getCacheKey(baseKey: string, pluginConfig: unknown): string {\n if (pluginConfig === undefined) {\n return baseKey;\n }\n try {\n return `${baseKey}:${JSON.stringify(pluginConfig)}`;\n } catch {\n throw new Error(\n `pluginConfig must be JSON-serializable for caching. Received non-serializable value.`,\n );\n }\n}\n\n// ========================================\n// Main API\n// ========================================\n\n/**\n * Get a generated type from a plugin by loading the config and resolving everything automatically.\n * For type-attached plugins, calls onTypeLoaded() with the sourceType.\n * For namespace plugins, calls onNamespaceLoaded() with auto-resolved namespace.\n * Results are cached per config path, plugin, namespace, and pluginConfig to avoid redundant processing.\n * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)\n * @param pluginId - The plugin's unique identifier\n * @param sourceType - The source TailorDB type (null for namespace plugins)\n * @param kind - The generated type kind (e.g., \"request\", \"step\")\n * @returns The generated TailorDB type\n */\nexport async function getGeneratedType(\n configPath: string,\n pluginId: string,\n sourceType: TailorAnyDBType | null,\n kind: string,\n): Promise<TailorAnyDBType> {\n const cache = await loadAndCacheConfig(configPath);\n\n if (!cache) {\n // Config not available (e.g., running in bundled executor on platform server).\n // Return a placeholder. The actual type is resolved at generate/apply time.\n return { name: `__placeholder_${kind}__`, fields: {} } as TailorAnyDBType;\n }\n\n const { config, configDir, plugins } = cache;\n\n const pluginEntry = plugins.get(pluginId);\n if (!pluginEntry) {\n throw new Error(\n `Plugin \"${pluginId}\" not found in config at \"${configPath}\". ` +\n `Ensure the plugin is registered via definePlugins().`,\n );\n }\n\n const { plugin, pluginConfig } = pluginEntry;\n\n if (sourceType === null) {\n return getGeneratedTypeForNamespacePlugin(config, plugin, kind, pluginConfig);\n }\n\n const namespace = await resolveNamespaceForType(config, configDir, sourceType);\n return getGeneratedTypeForTypeAttachedPlugin(plugin, sourceType, kind, pluginConfig, namespace);\n}\n\n/**\n * Get a generated type from a type-attached plugin.\n * @param plugin - The plugin instance (must have onTypeLoaded() method)\n * @param sourceType - The source TailorDB type\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @param namespace - Resolved namespace\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForTypeAttachedPlugin(\n plugin: Plugin,\n sourceType: TailorAnyDBType,\n kind: string,\n pluginConfig: unknown,\n namespace: string,\n): Promise<TailorAnyDBType> {\n if (!plugin.onTypeLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onTypeLoaded() method`);\n }\n\n // Check cache first\n let pluginCache = processCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n processCache.set(plugin, pluginCache);\n }\n\n const cacheKey = getCacheKey(`${sourceType.name}:ns=${namespace}`, pluginConfig);\n let output = pluginCache.get(cacheKey);\n\n if (!output) {\n const typeConfig = sourceType.plugins.find((p) => p.pluginId === plugin.id)?.config;\n output = await plugin.onTypeLoaded({\n type: sourceType,\n typeConfig: typeConfig ?? {},\n pluginConfig,\n namespace,\n });\n pluginCache.set(cacheKey, output);\n }\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(\n `Generated type not found: plugin=${plugin.id}, sourceType=${sourceType.name}, kind=${kind}`,\n );\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Get a generated type from a namespace plugin.\n * Auto-resolves the namespace by trying each one.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - The plugin instance (must have onNamespaceLoaded() method)\n * @param kind - The generated type kind\n * @param pluginConfig - Plugin-level configuration\n * @returns The generated TailorDB type\n */\nasync function getGeneratedTypeForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<TailorAnyDBType> {\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n // Check cache first - try all namespaces\n let pluginCache = namespaceProcessCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n namespaceProcessCache.set(plugin, pluginCache);\n }\n\n // Try cached results first\n if (config.db) {\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n const cached = pluginCache.get(cacheKey);\n if (cached?.types?.[kind]) {\n return cached.types[kind] as TailorAnyDBType;\n }\n }\n }\n\n // Not in cache - resolve namespace and process\n const { namespace, output } = await resolveNamespaceForNamespacePlugin(\n config,\n plugin,\n kind,\n pluginConfig,\n );\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n pluginCache.set(cacheKey, output);\n\n const generatedType = output.types?.[kind];\n if (!generatedType) {\n throw new Error(`Generated type not found: plugin=${plugin.id}, kind=${kind}`);\n }\n\n return generatedType as TailorAnyDBType;\n}\n\n/**\n * Clear all internal caches. For testing only.\n */\nexport function _clearCacheForTesting(): void {\n configCacheMap.clear();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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sB,IAAI,MAAM;CAClD,IAAI,CAAC,aAAa;EAChB,8BAAc,IAAI,IAAI;EACtB,sBAAsB,IAAI,QAAQ,WAAW;CAC/C;CAGA,IAAI,OAAO,IACT,KAAK,MAAM,aAAa,OAAO,KAAK,OAAO,EAAE,GAAG;EAE9C,IADiB,OAAO,GAAG,UACf,CAAC,UAAU;EAEvB,MAAM,WAAW,YAAY,gBAAgB,aAAa,YAAY;EACtE,MAAM,SAAS,YAAY,IAAI,QAAQ;EACvC,IAAI,QAAQ,QAAQ,OAClB,OAAO,OAAO,MAAM;CAExB;CAIF,MAAM,EAAE,WAAW,WAAW,MAAM,mCAClC,QACA,QACA,MACA,YACF;CAEA,MAAM,WAAW,YAAY,gBAAgB,aAAa,YAAY;CACtE,YAAY,IAAI,UAAU,MAAM;CAEhC,MAAM,gBAAgB,OAAO,QAAQ;CACrC,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,oCAAoC,OAAO,GAAG,SAAS,MAAM;CAG/E,OAAO;AACT"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
//#region src/configure/services/workflow/registry.ts
|
|
2
|
+
const JOB_REGISTRY_KEY = Symbol.for("tailor-platform/sdk:job-registry");
|
|
3
|
+
function jobs() {
|
|
4
|
+
const g = globalThis;
|
|
5
|
+
let map = g[JOB_REGISTRY_KEY];
|
|
6
|
+
if (!map) {
|
|
7
|
+
map = /* @__PURE__ */ new Map();
|
|
8
|
+
g[JOB_REGISTRY_KEY] = map;
|
|
9
|
+
}
|
|
10
|
+
return map;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Register a job body keyed by job name. Called as a side effect by
|
|
14
|
+
* `createWorkflowJob` so `runWorkflowLocally()` can execute dependent job
|
|
15
|
+
* bodies when `globalThis.tailor.workflow.triggerJobFunction(name, args)` is invoked.
|
|
16
|
+
*
|
|
17
|
+
* In production builds the bundler rewrites `.trigger()` calls so this registry
|
|
18
|
+
* is never read; the gated write is dropped as dead code.
|
|
19
|
+
* @param name - Job name
|
|
20
|
+
* @param body - Job body function
|
|
21
|
+
*/
|
|
22
|
+
function registerJob(name, body) {
|
|
23
|
+
jobs().set(name, body);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Look up a registered job body by name.
|
|
27
|
+
* @param name - Job name
|
|
28
|
+
* @returns The registered body, or undefined when no job is registered
|
|
29
|
+
*/
|
|
30
|
+
function getRegisteredJob(name) {
|
|
31
|
+
return jobs().get(name);
|
|
32
|
+
}
|
|
33
|
+
function currentPlatformWorkflow() {
|
|
34
|
+
return globalThis.tailor?.workflow;
|
|
35
|
+
}
|
|
36
|
+
function requirePlatformWorkflow() {
|
|
37
|
+
const workflow = currentPlatformWorkflow();
|
|
38
|
+
if (!workflow) throw new Error("tailor.workflow is not available. Run tests in the `tailor-runtime` Vitest environment and use mockWorkflow(), or use runWorkflowLocally() from @tailor-platform/sdk/vitest for local workflow execution.");
|
|
39
|
+
return workflow;
|
|
40
|
+
}
|
|
41
|
+
const TRIGGER_DEFAULT = "00000000-0000-4000-8000-000000000000";
|
|
42
|
+
function dispatchTriggerJob(name, args) {
|
|
43
|
+
return requirePlatformWorkflow().triggerJobFunction(name, args);
|
|
44
|
+
}
|
|
45
|
+
function dispatchTriggerWorkflow(name, args, options) {
|
|
46
|
+
return requirePlatformWorkflow().triggerWorkflow(name, args, options);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
//#endregion
|
|
50
|
+
export { registerJob as a, getRegisteredJob as i, dispatchTriggerJob as n, dispatchTriggerWorkflow as r, TRIGGER_DEFAULT as t };
|
|
51
|
+
//# sourceMappingURL=registry-DdsYlL_P.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"registry-DdsYlL_P.mjs","names":[],"sources":["../src/configure/services/workflow/registry.ts"],"sourcesContent":["import type { TailorEnv, TailorInvoker } from \"@/runtime/types\";\n\n/**\n * Body signature shared by workflow jobs at registry-write time.\n * The user's `createWorkflowJob`/`createWorkflow` body uses concrete types,\n * but the registry erases them for storage.\n */\nexport type RegisteredJobBody = (\n args: unknown,\n context: { env: TailorEnv; invoker?: TailorInvoker },\n) => unknown | Promise<unknown>;\n\nconst JOB_REGISTRY_KEY: unique symbol = Symbol.for(\"tailor-platform/sdk:job-registry\");\n\ntype PlatformWorkflow = {\n triggerWorkflow: (name: string, args?: unknown, options?: unknown) => Promise<string>;\n triggerJobFunction: (name: string, args?: unknown) => unknown;\n};\n\ntype GlobalWithRegistry = typeof globalThis & {\n [JOB_REGISTRY_KEY]?: Map<string, RegisteredJobBody>;\n tailor?: { workflow?: PlatformWorkflow };\n};\n\nfunction jobs(): Map<string, RegisteredJobBody> {\n const g = globalThis as GlobalWithRegistry;\n let map = g[JOB_REGISTRY_KEY];\n if (!map) {\n map = new Map();\n g[JOB_REGISTRY_KEY] = map;\n }\n return map;\n}\n\n/**\n * Register a job body keyed by job name. Called as a side effect by\n * `createWorkflowJob` so `runWorkflowLocally()` can execute dependent job\n * bodies when `globalThis.tailor.workflow.triggerJobFunction(name, args)` is invoked.\n *\n * In production builds the bundler rewrites `.trigger()` calls so this registry\n * is never read; the gated write is dropped as dead code.\n * @param name - Job name\n * @param body - Job body function\n */\nexport function registerJob(name: string, body: RegisteredJobBody): void {\n jobs().set(name, body);\n}\n\n/**\n * Look up a registered job body by name.\n * @param name - Job name\n * @returns The registered body, or undefined when no job is registered\n */\nexport function getRegisteredJob(name: string): RegisteredJobBody | undefined {\n return jobs().get(name);\n}\n\nfunction currentPlatformWorkflow(): PlatformWorkflow | undefined {\n // globalThis may not have the tailor property at runtime\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n return (globalThis as GlobalWithRegistry).tailor?.workflow;\n}\n\nfunction requirePlatformWorkflow(): PlatformWorkflow {\n const workflow = currentPlatformWorkflow();\n if (!workflow) {\n throw new Error(\n \"tailor.workflow is not available. Run tests in the `tailor-runtime` Vitest environment and use mockWorkflow(), or use runWorkflowLocally() from @tailor-platform/sdk/vitest for local workflow execution.\",\n );\n }\n return workflow;\n}\n\n// A valid placeholder UUID, so callers that validate the execution id behave the\n// same locally as against the platform.\nexport const TRIGGER_DEFAULT = \"00000000-0000-4000-8000-000000000000\";\n\n// `.trigger()` routes through the installed `tailor.workflow` shim. Local body\n// execution is intentionally available only through `runWorkflowLocally()`.\nexport function dispatchTriggerJob(name: string, args?: unknown): unknown {\n return requirePlatformWorkflow().triggerJobFunction(name, args);\n}\n\nexport function dispatchTriggerWorkflow(\n name: string,\n args?: unknown,\n options?: unknown,\n): Promise<string> {\n return requirePlatformWorkflow().triggerWorkflow(name, args, options);\n}\n"],"mappings":";AAYA,MAAM,mBAAkC,OAAO,IAAI,kCAAkC;AAYrF,SAAS,OAAuC;CAC9C,MAAM,IAAI;CACV,IAAI,MAAM,EAAE;CACZ,IAAI,CAAC,KAAK;EACR,sBAAM,IAAI,IAAI;EACd,EAAE,oBAAoB;CACxB;CACA,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,YAAY,MAAc,MAA+B;CACvE,KAAK,CAAC,CAAC,IAAI,MAAM,IAAI;AACvB;;;;;;AAOA,SAAgB,iBAAiB,MAA6C;CAC5E,OAAO,KAAK,CAAC,CAAC,IAAI,IAAI;AACxB;AAEA,SAAS,0BAAwD;CAG/D,OAAQ,WAAkC,QAAQ;AACpD;AAEA,SAAS,0BAA4C;CACnD,MAAM,WAAW,wBAAwB;CACzC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,2MACF;CAEF,OAAO;AACT;AAIA,MAAa,kBAAkB;AAI/B,SAAgB,mBAAmB,MAAc,MAAyB;CACxE,OAAO,wBAAwB,CAAC,CAAC,mBAAmB,MAAM,IAAI;AAChE;AAEA,SAAgB,wBACd,MACA,MACA,SACiB;CACjB,OAAO,wBAAwB,CAAC,CAAC,gBAAgB,MAAM,MAAM,OAAO;AACtE"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { t as assertDefined } from "./assert-CKfwrmCV.mjs";
|
|
1
|
+
import { t as assertDefined } from "./assert-DBxo8jPo.mjs";
|
|
3
2
|
import { GraphQLError, Lexer, Source, TokenKind } from "graphql";
|
|
4
3
|
import { getSegments } from "sql-highlight";
|
|
5
4
|
|
|
@@ -248,4 +247,4 @@ function replTransform(state, event) {
|
|
|
248
247
|
|
|
249
248
|
//#endregion
|
|
250
249
|
export { highlightGraphqlLine, highlightSqlLine, replTransform };
|
|
251
|
-
//# sourceMappingURL=repl-editor-
|
|
250
|
+
//# sourceMappingURL=repl-editor-DmGr9zMw.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repl-editor-CJG3sz7A.mjs","names":[],"sources":["../src/cli/query/repl-editor.ts"],"sourcesContent":["import { GraphQLError, Lexer, Source, TokenKind } from \"graphql\";\nimport { getSegments } from \"sql-highlight\";\nimport { assertDefined } from \"@/utils/assert\";\nimport type { TransformEvent, TransformState } from \"@toiroakr/read-multiline\";\n\n// ANSI colour sequences. Kept inline (rather than going through `node:util`\n// styleText) so that tests running outside a TTY still produce deterministic\n// escape sequences regardless of detected colour support.\nconst RESET = \"\\x1b[0m\";\nconst BLUE = \"\\x1b[34m\";\nconst MAGENTA = \"\\x1b[35m\";\nconst YELLOW = \"\\x1b[33m\";\nconst BRIGHT_GREEN = \"\\x1b[92m\";\nconst CYAN = \"\\x1b[36m\";\nconst BRIGHT_BLUE = \"\\x1b[94m\";\nconst BOLD_CYAN = \"\\x1b[1;36m\";\nconst BOLD_MAGENTA = \"\\x1b[1;35m\";\nconst ITALIC_YELLOW = \"\\x1b[3;33m\";\nconst GREEN = \"\\x1b[32m\";\nconst DIM = \"\\x1b[90m\";\nconst DIM_YELLOW = \"\\x1b[2;33m\";\n\nconst SQL_STYLE_MAP: Record<string, string> = {\n keyword: BLUE,\n function: MAGENTA,\n identifier: YELLOW,\n string: BRIGHT_GREEN,\n number: CYAN,\n bracket: DIM_YELLOW,\n special: DIM,\n};\n\n/**\n * Highlight a single SQL line using the `sql-highlight` tokenizer.\n * @param line - SQL text for a single editor line\n * @returns ANSI-decorated line safe for terminal output\n */\nexport function highlightSqlLine(line: string): string {\n const segments = getSegments(line);\n let result = \"\";\n for (const seg of segments) {\n const style = SQL_STYLE_MAP[seg.name];\n result += style ? style + seg.content + RESET : seg.content;\n }\n return result;\n}\n\nconst GQL_KEYWORDS = new Set([\n \"query\",\n \"mutation\",\n \"subscription\",\n \"fragment\",\n \"on\",\n \"type\",\n \"input\",\n \"enum\",\n \"interface\",\n \"union\",\n \"scalar\",\n \"extend\",\n \"schema\",\n \"directive\",\n \"implements\",\n]);\n\n// Keywords that introduce a definition name (next NAME token is the def).\nconst GQL_DEF_KEYWORDS = new Set([\"query\", \"mutation\", \"subscription\", \"fragment\"]);\n\nconst GQL_BUILTINS = new Set([\"true\", \"false\", \"null\"]);\n\n/**\n * Highlight a single GraphQL line using the official `graphql` Lexer. Tracks\n * paren depth and the previous token to provide semantic-level colouring\n * (field names vs argument names vs types).\n * @param line - GraphQL text for a single editor line\n * @returns ANSI-decorated line, or the input unchanged when the lexer rejects it\n */\nexport function highlightGraphqlLine(line: string): string {\n if (line.trimStart().startsWith(\"#\")) {\n return `${DIM}${line}${RESET}`;\n }\n\n try {\n const source = new Source(line);\n const lexer = new Lexer(source);\n let result = \"\";\n let pos = 0;\n\n let parenDepth = 0;\n let prevKind: string = \"\";\n let prevText = \"\";\n let afterColon = false;\n\n let token = lexer.advance();\n while (token.kind !== TokenKind.EOF) {\n if (token.start > pos) {\n result += line.slice(pos, token.start);\n }\n\n const text = line.slice(token.start, token.end);\n switch (token.kind) {\n case TokenKind.NAME: {\n if (prevKind === TokenKind.DOLLAR) {\n result += `${MAGENTA}${text}${RESET}`;\n } else if (prevKind === TokenKind.AT) {\n result += `${BOLD_MAGENTA}${text}${RESET}`;\n } else if (GQL_BUILTINS.has(text) || GQL_KEYWORDS.has(text)) {\n result += `${BLUE}${text}${RESET}`;\n } else if (GQL_DEF_KEYWORDS.has(prevText)) {\n result += `${BOLD_CYAN}${text}${RESET}`;\n } else if (afterColon) {\n result += `${CYAN}${text}${RESET}`;\n } else if (parenDepth > 0) {\n result += `${ITALIC_YELLOW}${text}${RESET}`;\n } else {\n result += `${BRIGHT_BLUE}${text}${RESET}`;\n }\n afterColon = false;\n break;\n }\n case TokenKind.INT:\n case TokenKind.FLOAT:\n result += `${BLUE}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.STRING:\n case TokenKind.BLOCK_STRING:\n result += `${GREEN}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.DOLLAR:\n result += `${MAGENTA}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.AT:\n result += `${BOLD_MAGENTA}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.BRACE_L:\n case TokenKind.BRACE_R:\n result += `${YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.PAREN_L:\n parenDepth += 1;\n result += `${DIM_YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.PAREN_R:\n parenDepth = Math.max(0, parenDepth - 1);\n result += `${DIM_YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.BRACKET_L:\n case TokenKind.BRACKET_R:\n result += `${DIM_YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.COLON:\n result += `${DIM}${text}${RESET}`;\n afterColon = true;\n break;\n case TokenKind.BANG:\n case TokenKind.EQUALS:\n case TokenKind.PIPE:\n case TokenKind.AMP:\n case TokenKind.SPREAD:\n result += `${DIM}${text}${RESET}`;\n afterColon = false;\n break;\n default:\n result += text;\n afterColon = false;\n }\n\n prevKind = token.kind;\n prevText = text;\n pos = token.end;\n token = lexer.advance();\n }\n\n if (pos < line.length) {\n result += line.slice(pos);\n }\n return result;\n } catch (error) {\n // The lexer throws GraphQLError on partial or invalid input (e.g. an\n // unterminated string while the user is still typing). Fall back to the\n // raw line so the editor keeps rendering without colour until the input\n // is valid. Any other error is a real bug and should surface.\n if (error instanceof GraphQLError) {\n return line;\n }\n throw error;\n }\n}\n\nconst BRACKET_PAIRS: Record<string, string> = { \"(\": \")\", \"[\": \"]\", \"{\": \"}\" };\nconst CLOSE_BRACKETS = new Set(Object.values(BRACKET_PAIRS));\n\n/**\n * Apply auto-close brackets and auto-indent on newline. Works for both SQL\n * and GraphQL because both languages share the `()`, `[]`, `{}` bracket set.\n * @param state - Editor state after the last edit\n * @param event - Event describing the edit that just occurred\n * @returns A new editor state to apply, or `undefined` to leave the state unchanged\n */\nexport function replTransform(\n state: TransformState,\n event: TransformEvent,\n): TransformState | undefined {\n const { lines, row, col } = state;\n\n if (event.type === \"insert\" && event.char in BRACKET_PAIRS) {\n const close = BRACKET_PAIRS[event.char];\n const line = assertDefined(lines[row], `line at row ${row} missing`);\n const newLine = line.slice(0, col) + close + line.slice(col);\n return { lines: lines.with(row, newLine), row, col };\n }\n\n if (event.type === \"insert\" && CLOSE_BRACKETS.has(event.char)) {\n const line = assertDefined(lines[row], `line at row ${row} missing`);\n if (line[col] === event.char) {\n const newLine = line.slice(0, col) + line.slice(col + 1);\n return { lines: lines.with(row, newLine), row, col };\n }\n }\n\n if (event.type === \"backspace\") {\n const line = assertDefined(lines[row], `line at row ${row} missing`);\n const beforeCursor = line.slice(0, col);\n if (beforeCursor.length >= 1 && /^ +$/.test(beforeCursor)) {\n const newIndent = beforeCursor.slice(0, -1);\n const newLine = newIndent + line.slice(col);\n return { lines: lines.with(row, newLine), row, col: newIndent.length };\n }\n }\n\n if (event.type === \"newline\" && row > 0) {\n const prevLine = assertDefined(lines[row - 1], `line at row ${row - 1} missing`);\n const baseIndent = prevLine.match(/^(\\s*)/)?.[1] ?? \"\";\n const endsWithOpen = /[{([]$/.test(prevLine.trimEnd());\n const currentLine = assertDefined(lines[row], `line at row ${row} missing`);\n const startsWithClose = /^[}\\])]/.test(currentLine.trimStart());\n\n if (endsWithOpen && startsWithClose) {\n // Bracket expansion: the cursor sits between a matching open/close\n // pair (e.g. `{|}`). Expand into a three-line block with the cursor\n // on an indented middle line.\n const innerIndent = baseIndent + \" \";\n const newLines = lines\n .with(row, innerIndent)\n .toSpliced(row + 1, 0, baseIndent + currentLine.trimStart());\n return { lines: newLines, row, col: innerIndent.length };\n }\n if (endsWithOpen) {\n // A lone open bracket on the previous line: drop an extra indent for\n // the new line and auto-insert the matching closing bracket below.\n const openChar = prevLine.trimEnd().slice(-1);\n const closeChar = BRACKET_PAIRS[openChar] ?? \"}\";\n const indent = baseIndent + \" \";\n const newLines = lines\n .with(row, indent + currentLine)\n .toSpliced(row + 1, 0, baseIndent + closeChar);\n return { lines: newLines, row, col: indent.length };\n }\n if (baseIndent && col === 0) {\n return { lines: lines.with(row, baseIndent + currentLine), row, col: baseIndent.length };\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;AAQA,MAAM,QAAQ;AACd,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,eAAe;AACrB,MAAM,OAAO;AACb,MAAM,cAAc;AACpB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,aAAa;AAEnB,MAAM,gBAAwC;CAC5C,SAAS;CACT,UAAU;CACV,YAAY;CACZ,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;AACX;;;;;;AAOA,SAAgB,iBAAiB,MAAsB;CACrD,MAAM,WAAW,YAAY,IAAI;CACjC,IAAI,SAAS;CACb,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,QAAQ,cAAc,IAAI;EAChC,UAAU,QAAQ,QAAQ,IAAI,UAAU,QAAQ,IAAI;CACtD;CACA,OAAO;AACT;AAEA,MAAM,eAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,mBAAmB,IAAI,IAAI;CAAC;CAAS;CAAY;CAAgB;AAAU,CAAC;AA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K,YAAY;GAAO;EACzD;EACA,IAAI,cAAc;GAIhB,MAAM,YAAY,cADD,SAAS,QAAQ,CAAC,CAAC,MAAM,EACH,MAAM;GAC7C,MAAM,SAAS,aAAa;GAI5B,OAAO;IAAE,OAHQ,MACd,KAAK,KAAK,SAAS,WAAW,CAAC,CAC/B,UAAU,MAAM,GAAG,GAAG,aAAa,SACf;IAAG;IAAK,KAAK,OAAO;GAAO;EACpD;EACA,IAAI,cAAc,QAAQ,GACxB,OAAO;GAAE,OAAO,MAAM,KAAK,KAAK,aAAa,WAAW;GAAG;GAAK,KAAK,WAAW;EAAO;CAE3F;AAGF"}
|
|
1
|
+
{"version":3,"file":"repl-editor-DmGr9zMw.mjs","names":[],"sources":["../src/cli/query/repl-editor.ts"],"sourcesContent":["import { GraphQLError, Lexer, Source, TokenKind } from \"graphql\";\nimport { getSegments } from \"sql-highlight\";\nimport { assertDefined } from \"@/utils/assert\";\nimport type { TransformEvent, TransformState } from \"@toiroakr/read-multiline\";\n\n// ANSI colour sequences. Kept inline (rather than going through `node:util`\n// styleText) so that tests running outside a TTY still produce deterministic\n// escape sequences regardless of detected colour support.\nconst RESET = \"\\x1b[0m\";\nconst BLUE = \"\\x1b[34m\";\nconst MAGENTA = \"\\x1b[35m\";\nconst YELLOW = \"\\x1b[33m\";\nconst BRIGHT_GREEN = \"\\x1b[92m\";\nconst CYAN = \"\\x1b[36m\";\nconst BRIGHT_BLUE = \"\\x1b[94m\";\nconst BOLD_CYAN = \"\\x1b[1;36m\";\nconst BOLD_MAGENTA = \"\\x1b[1;35m\";\nconst ITALIC_YELLOW = \"\\x1b[3;33m\";\nconst GREEN = \"\\x1b[32m\";\nconst DIM = \"\\x1b[90m\";\nconst DIM_YELLOW = \"\\x1b[2;33m\";\n\nconst SQL_STYLE_MAP: Record<string, string> = {\n keyword: BLUE,\n function: MAGENTA,\n identifier: YELLOW,\n string: BRIGHT_GREEN,\n number: CYAN,\n bracket: DIM_YELLOW,\n special: DIM,\n};\n\n/**\n * Highlight a single SQL line using the `sql-highlight` tokenizer.\n * @param line - SQL text for a single editor line\n * @returns ANSI-decorated line safe for terminal output\n */\nexport function highlightSqlLine(line: string): string {\n const segments = getSegments(line);\n let result = \"\";\n for (const seg of segments) {\n const style = SQL_STYLE_MAP[seg.name];\n result += style ? style + seg.content + RESET : seg.content;\n }\n return result;\n}\n\nconst GQL_KEYWORDS = new Set([\n \"query\",\n \"mutation\",\n \"subscription\",\n \"fragment\",\n \"on\",\n \"type\",\n \"input\",\n \"enum\",\n \"interface\",\n \"union\",\n \"scalar\",\n \"extend\",\n \"schema\",\n \"directive\",\n \"implements\",\n]);\n\n// Keywords that introduce a definition name (next NAME token is the def).\nconst GQL_DEF_KEYWORDS = new Set([\"query\", \"mutation\", \"subscription\", \"fragment\"]);\n\nconst GQL_BUILTINS = new Set([\"true\", \"false\", \"null\"]);\n\n/**\n * Highlight a single GraphQL line using the official `graphql` Lexer. Tracks\n * paren depth and the previous token to provide semantic-level colouring\n * (field names vs argument names vs types).\n * @param line - GraphQL text for a single editor line\n * @returns ANSI-decorated line, or the input unchanged when the lexer rejects it\n */\nexport function highlightGraphqlLine(line: string): string {\n if (line.trimStart().startsWith(\"#\")) {\n return `${DIM}${line}${RESET}`;\n }\n\n try {\n const source = new Source(line);\n const lexer = new Lexer(source);\n let result = \"\";\n let pos = 0;\n\n let parenDepth = 0;\n let prevKind: string = \"\";\n let prevText = \"\";\n let afterColon = false;\n\n let token = lexer.advance();\n while (token.kind !== TokenKind.EOF) {\n if (token.start > pos) {\n result += line.slice(pos, token.start);\n }\n\n const text = line.slice(token.start, token.end);\n switch (token.kind) {\n case TokenKind.NAME: {\n if (prevKind === TokenKind.DOLLAR) {\n result += `${MAGENTA}${text}${RESET}`;\n } else if (prevKind === TokenKind.AT) {\n result += `${BOLD_MAGENTA}${text}${RESET}`;\n } else if (GQL_BUILTINS.has(text) || GQL_KEYWORDS.has(text)) {\n result += `${BLUE}${text}${RESET}`;\n } else if (GQL_DEF_KEYWORDS.has(prevText)) {\n result += `${BOLD_CYAN}${text}${RESET}`;\n } else if (afterColon) {\n result += `${CYAN}${text}${RESET}`;\n } else if (parenDepth > 0) {\n result += `${ITALIC_YELLOW}${text}${RESET}`;\n } else {\n result += `${BRIGHT_BLUE}${text}${RESET}`;\n }\n afterColon = false;\n break;\n }\n case TokenKind.INT:\n case TokenKind.FLOAT:\n result += `${BLUE}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.STRING:\n case TokenKind.BLOCK_STRING:\n result += `${GREEN}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.DOLLAR:\n result += `${MAGENTA}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.AT:\n result += `${BOLD_MAGENTA}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.BRACE_L:\n case TokenKind.BRACE_R:\n result += `${YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.PAREN_L:\n parenDepth += 1;\n result += `${DIM_YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.PAREN_R:\n parenDepth = Math.max(0, parenDepth - 1);\n result += `${DIM_YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.BRACKET_L:\n case TokenKind.BRACKET_R:\n result += `${DIM_YELLOW}${text}${RESET}`;\n afterColon = false;\n break;\n case TokenKind.COLON:\n result += `${DIM}${text}${RESET}`;\n afterColon = true;\n break;\n case TokenKind.BANG:\n case TokenKind.EQUALS:\n case TokenKind.PIPE:\n case TokenKind.AMP:\n case TokenKind.SPREAD:\n result += `${DIM}${text}${RESET}`;\n afterColon = false;\n break;\n default:\n result += text;\n afterColon = false;\n }\n\n prevKind = token.kind;\n prevText = text;\n pos = token.end;\n token = lexer.advance();\n }\n\n if (pos < line.length) {\n result += line.slice(pos);\n }\n return result;\n } catch (error) {\n // The lexer throws GraphQLError on partial or invalid input (e.g. an\n // unterminated string while the user is still typing). Fall back to the\n // raw line so the editor keeps rendering without colour until the input\n // is valid. Any other error is a real bug and should surface.\n if (error instanceof GraphQLError) {\n return line;\n }\n throw error;\n }\n}\n\nconst BRACKET_PAIRS: Record<string, string> = { \"(\": \")\", \"[\": \"]\", \"{\": \"}\" };\nconst CLOSE_BRACKETS = new Set(Object.values(BRACKET_PAIRS));\n\n/**\n * Apply auto-close brackets and auto-indent on newline. Works for both SQL\n * and GraphQL because both languages share the `()`, `[]`, `{}` bracket set.\n * @param state - Editor state after the last edit\n * @param event - Event describing the edit that just occurred\n * @returns A new editor state to apply, or `undefined` to leave the state unchanged\n */\nexport function replTransform(\n state: TransformState,\n event: TransformEvent,\n): TransformState | undefined {\n const { lines, row, col } = state;\n\n if (event.type === \"insert\" && event.char in BRACKET_PAIRS) {\n const close = BRACKET_PAIRS[event.char];\n const line = assertDefined(lines[row], `line at row ${row} missing`);\n const newLine = line.slice(0, col) + close + line.slice(col);\n return { lines: lines.with(row, newLine), row, col };\n }\n\n if (event.type === \"insert\" && CLOSE_BRACKETS.has(event.char)) {\n const line = assertDefined(lines[row], `line at row ${row} missing`);\n if (line[col] === event.char) {\n const newLine = line.slice(0, col) + line.slice(col + 1);\n return { lines: lines.with(row, newLine), row, col };\n }\n }\n\n if (event.type === \"backspace\") {\n const line = assertDefined(lines[row], `line at row ${row} missing`);\n const beforeCursor = line.slice(0, col);\n if (beforeCursor.length >= 1 && /^ +$/.test(beforeCursor)) {\n const newIndent = beforeCursor.slice(0, -1);\n const newLine = newIndent + line.slice(col);\n return { lines: lines.with(row, newLine), row, col: newIndent.length };\n }\n }\n\n if (event.type === \"newline\" && row > 0) {\n const prevLine = assertDefined(lines[row - 1], `line at row ${row - 1} missing`);\n const baseIndent = prevLine.match(/^(\\s*)/)?.[1] ?? \"\";\n const endsWithOpen = /[{([]$/.test(prevLine.trimEnd());\n const currentLine = assertDefined(lines[row], `line at row ${row} missing`);\n const startsWithClose = /^[}\\])]/.test(currentLine.trimStart());\n\n if (endsWithOpen && startsWithClose) {\n // Bracket expansion: the cursor sits between a matching open/close\n // pair (e.g. `{|}`). Expand into a three-line block with the cursor\n // on an indented middle line.\n const innerIndent = baseIndent + \" \";\n const newLines = lines\n .with(row, innerIndent)\n .toSpliced(row + 1, 0, baseIndent + currentLine.trimStart());\n return { lines: newLines, row, col: innerIndent.length };\n }\n if (endsWithOpen) {\n // A lone open bracket on the previous line: drop an extra indent for\n // the new line and auto-insert the matching closing bracket below.\n const openChar = prevLine.trimEnd().slice(-1);\n const closeChar = BRACKET_PAIRS[openChar] ?? \"}\";\n const indent = baseIndent + \" \";\n const newLines = lines\n .with(row, indent + currentLine)\n .toSpliced(row + 1, 0, baseIndent + closeChar);\n return { lines: newLines, row, col: indent.length };\n }\n if (baseIndent && col === 0) {\n return { lines: lines.with(row, baseIndent + currentLine), row, col: baseIndent.length };\n }\n }\n\n return undefined;\n}\n"],"mappings":";;;;;AAQA,MAAM,QAAQ;AACd,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,eAAe;AACrB,MAAM,OAAO;AACb,MAAM,cAAc;AACpB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,QAAQ;AACd,MAAM,MAAM;AACZ,MAAM,aAAa;AAEnB,MAAM,gBAAwC;CAC5C,SAAS;CACT,UAAU;CACV,YAAY;CACZ,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;AACX;;;;;;AAOA,SAAgB,iBAAiB,MAAsB;CACrD,MAAM,WAAW,YAAY,IAAI;CACjC,IAAI,SAAS;CACb,KAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,QAAQ,cAAc,IAAI;EAChC,UAAU,QAAQ,QAAQ,IAAI,UAAU,QAAQ,IAAI;CACtD;CACA,OAAO;AACT;AAEA,MAAM,eAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAGD,MAAM,mBAAmB,IAAI,IAAI;CA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Aa,YAAY,UAAU,CACrC;IAAG;IAAK,KAAK,YAAY;GAAO;EACzD;EACA,IAAI,cAAc;GAIhB,MAAM,YAAY,cADD,SAAS,QAAQ,CAAC,CAAC,MAAM,EACH,MAAM;GAC7C,MAAM,SAAS,aAAa;GAI5B,OAAO;IAAE,OAHQ,MACd,KAAK,KAAK,SAAS,WAAW,CAAC,CAC/B,UAAU,MAAM,GAAG,GAAG,aAAa,SACf;IAAG;IAAK,KAAK,OAAO;GAAO;EACpD;EACA,IAAI,cAAc,QAAQ,GACxB,OAAO;GAAE,OAAO,MAAM,KAAK,KAAK,aAAa,WAAW;GAAG;GAAK,KAAK,WAAW;EAAO;CAE3F;AAGF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { r as getConnectionToken, t as TailorAuthconnectionAPI } from "../authconnection-
|
|
1
|
+
import { r as getConnectionToken, t as TailorAuthconnectionAPI } from "../authconnection-DvUQAjQS.mjs";
|
|
2
2
|
export { TailorAuthconnectionAPI, getConnectionToken };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as getInvoker, n as Invoker, r as TailorContextAPI, t as ContextInvoker } from "../context-
|
|
1
|
+
import { a as getInvoker, n as Invoker, r as TailorContextAPI, t as ContextInvoker } from "../context-BuuIb8CC.mjs";
|
|
2
2
|
export { ContextInvoker, Invoker, TailorContextAPI, getInvoker };
|
package/dist/runtime/context.mjs
CHANGED
package/dist/runtime/file.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as upload, S as openDownloadStream, _ as download, a as FileMetadata, c as FileUploadResponse, d as StreamValue, f as TailorDBFileAPI, g as deleteFile, h as UploadMetadata, i as FileDownloadStreamResponse, l as FileUploadStreamOptions, m as TailorDBFileErrorCode, n as FileDownloadAsBase64Response, o as FileStreamIterator, p as TailorDBFileError, r as FileDownloadResponse, s as FileUploadOptions, t as DownloadMetadata, u as StreamMetadata, v as downloadAsBase64, w as uploadStream, x as getMetadata, y as downloadStream } from "../file-
|
|
1
|
+
import { C as upload, S as openDownloadStream, _ as download, a as FileMetadata, c as FileUploadResponse, d as StreamValue, f as TailorDBFileAPI, g as deleteFile, h as UploadMetadata, i as FileDownloadStreamResponse, l as FileUploadStreamOptions, m as TailorDBFileErrorCode, n as FileDownloadAsBase64Response, o as FileStreamIterator, p as TailorDBFileError, r as FileDownloadResponse, s as FileUploadOptions, t as DownloadMetadata, u as StreamMetadata, v as downloadAsBase64, w as uploadStream, x as getMetadata, y as downloadStream } from "../file-BB8Vs9O_.mjs";
|
|
2
2
|
export { DownloadMetadata, FileDownloadAsBase64Response, FileDownloadResponse, FileDownloadStreamResponse, FileMetadata, FileStreamIterator, FileUploadOptions, FileUploadResponse, FileUploadStreamOptions, StreamMetadata, StreamValue, TailorDBFileAPI, TailorDBFileError, TailorDBFileErrorCode, UploadMetadata, deleteFile as delete, deleteFile, download, downloadAsBase64, downloadStream, getMetadata, openDownloadStream, upload, uploadStream };
|
package/dist/runtime/file.mjs
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
import { c as upload, i as downloadStream, l as uploadStream, n as download, o as getMetadata, r as downloadAsBase64, s as openDownloadStream, t as deleteFile } from "../file-B58Dm-2P.mjs";
|
|
1
|
+
import { c as upload, i as downloadStream, l as uploadStream, n as download, o as getMetadata, r as downloadAsBase64, s as openDownloadStream, t as deleteFile } from "../file-_oUZo76X.mjs";
|
|
3
2
|
|
|
4
3
|
export { deleteFile as delete, deleteFile, download, downloadAsBase64, downloadStream, getMetadata, openDownloadStream, upload, uploadStream };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { t as ContextInvoker } from "../context-
|
|
2
|
-
import { m as TailorDBFileErrorCode } from "../file-
|
|
3
|
-
import { r as IconvInstance } from "../iconv-
|
|
4
|
-
import { a as IdpClientInstance, c as SendPasswordResetEmailInput, d as User, f as UserQuery, n as ClientConfig, o as ListUsersOptions, r as CreateUserInput, s as ListUsersResponse, u as UpdateUserInput } from "../idp-
|
|
5
|
-
import { r as TriggerWorkflowOptions, t as AuthInvoker } from "../workflow-
|
|
6
|
-
import { a as TailordbQueryResult, i as TailordbCommandType, o as TailordbRuntime, r as TailordbClientInstance, t as TailorRuntime } from "../index-
|
|
1
|
+
import { t as ContextInvoker } from "../context-BuuIb8CC.mjs";
|
|
2
|
+
import { m as TailorDBFileErrorCode } from "../file-BB8Vs9O_.mjs";
|
|
3
|
+
import { r as IconvInstance } from "../iconv-Co-TOPuH.mjs";
|
|
4
|
+
import { a as IdpClientInstance, c as SendPasswordResetEmailInput, d as User, f as UserQuery, n as ClientConfig, o as ListUsersOptions, r as CreateUserInput, s as ListUsersResponse, u as UpdateUserInput } from "../idp-DrhVrLmV.mjs";
|
|
5
|
+
import { r as TriggerWorkflowOptions, t as AuthInvoker } from "../workflow-BbKvGLQg.mjs";
|
|
6
|
+
import { a as TailordbQueryResult, i as TailordbCommandType, o as TailordbRuntime, r as TailordbClientInstance, t as TailorRuntime } from "../index-CK7u9isy.mjs";
|
|
7
7
|
|
|
8
8
|
//#region src/runtime/globals.d.ts
|
|
9
9
|
declare global {
|
|
@@ -13,39 +13,6 @@ declare global {
|
|
|
13
13
|
type Client = TailordbClientInstance;
|
|
14
14
|
}
|
|
15
15
|
var tailordb: TailordbRuntime;
|
|
16
|
-
/**
|
|
17
|
-
* @deprecated Use the lowercase `tailordb.*` namespace instead (e.g.
|
|
18
|
-
* `tailordb.QueryResult`, `tailordb.CommandType`,
|
|
19
|
-
* `typeof tailordb.Client`). This capital-cased namespace is retained
|
|
20
|
-
* only for backwards compatibility with `@tailor-platform/function-types`
|
|
21
|
-
* and will be removed in v2. Run
|
|
22
|
-
* `pnpm dlx @tailor-platform/sdk-codemod v2/tailordb-namespace`
|
|
23
|
-
* to migrate.
|
|
24
|
-
*/
|
|
25
|
-
namespace Tailordb {
|
|
26
|
-
/**
|
|
27
|
-
* @deprecated Use `tailordb.Client` (lowercase) instead.
|
|
28
|
-
* Will be removed in v2.
|
|
29
|
-
*/
|
|
30
|
-
class Client {
|
|
31
|
-
constructor(config: {
|
|
32
|
-
namespace: string;
|
|
33
|
-
});
|
|
34
|
-
connect(): Promise<void>;
|
|
35
|
-
end(): Promise<void>;
|
|
36
|
-
queryObject<O>(sql: string, args?: readonly unknown[]): Promise<TailordbQueryResult<O>>;
|
|
37
|
-
}
|
|
38
|
-
/**
|
|
39
|
-
* @deprecated Use `tailordb.QueryResult<T>` (lowercase) instead.
|
|
40
|
-
* Will be removed in v2.
|
|
41
|
-
*/
|
|
42
|
-
type QueryResult<T> = TailordbQueryResult<T>;
|
|
43
|
-
/**
|
|
44
|
-
* @deprecated Use `tailordb.CommandType` (lowercase) instead.
|
|
45
|
-
* Will be removed in v2.
|
|
46
|
-
*/
|
|
47
|
-
type CommandType = TailordbCommandType;
|
|
48
|
-
}
|
|
49
16
|
namespace tailor {
|
|
50
17
|
namespace iconv {
|
|
51
18
|
type Iconv = IconvInstance;
|
package/dist/runtime/globals.mjs
CHANGED