@tailor-platform/sdk 1.22.0 → 1.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +74 -0
- package/dist/app-config-BNKHurwr.d.mts +174 -0
- package/dist/{application-CTQe2HSB.mjs → application-DThE2HW7.mjs} +200 -215
- package/dist/application-DThE2HW7.mjs.map +1 -0
- package/dist/application-P1by1htu.mjs +8 -0
- package/dist/{brand-DyPrAzpM.mjs → brand-64NrPh_e.mjs} +1 -1
- package/dist/{brand-DyPrAzpM.mjs.map → brand-64NrPh_e.mjs.map} +1 -1
- package/dist/cli/index.d.mts +0 -1
- package/dist/cli/index.mjs +7 -7
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.d.mts +8 -9
- package/dist/cli/lib.mjs +7 -7
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/skills.d.mts +0 -1
- package/dist/configure/index.d.mts +5 -5
- package/dist/configure/index.mjs +3 -3
- package/dist/configure/index.mjs.map +1 -1
- package/dist/enum-constants-B5Nl-yzx.mjs.map +1 -1
- package/dist/env-CHwmMyfF.d.mts +32 -0
- package/dist/file-utils-sEOwAdJ4.mjs.map +1 -1
- package/dist/{index-Cwi86SUR.d.mts → index-BrIZ1rm2.d.mts} +2 -3
- package/dist/{index-BiutQT7m.d.mts → index-Df0aH5zp.d.mts} +55 -5
- package/dist/{index-DPN_P0w3.d.mts → index-DhtKJmgi.d.mts} +2 -3
- package/dist/{index-ClS0NClx.d.mts → index-DkRJwNw2.d.mts} +2 -3
- package/dist/{index-BGPX26_D.d.mts → index-zZUL7_2B.d.mts} +2 -3
- package/dist/{interceptor-DiARwPfw.mjs → interceptor-B-0OmiDZ.mjs} +1 -1
- package/dist/{interceptor-DiARwPfw.mjs.map → interceptor-B-0OmiDZ.mjs.map} +1 -1
- package/dist/{job-CRavYLLk.mjs → job-CnqcfVTI.mjs} +2 -2
- package/dist/{job-CRavYLLk.mjs.map → job-CnqcfVTI.mjs.map} +1 -1
- package/dist/kysely/index.d.mts +0 -1
- package/dist/kysely-type-CSlcwNFH.mjs.map +1 -1
- package/dist/{package-json-iVBhE5Ef.mjs → package-json-4G3gLWMd.mjs} +1 -1
- package/dist/{package-json-iVBhE5Ef.mjs.map → package-json-4G3gLWMd.mjs.map} +1 -1
- package/dist/package-json-BqvUKPBM.mjs +3 -0
- package/dist/plugin/builtin/enum-constants/index.d.mts +2 -3
- package/dist/plugin/builtin/file-utils/index.d.mts +2 -3
- package/dist/plugin/builtin/kysely-type/index.d.mts +2 -3
- package/dist/plugin/builtin/seed/index.d.mts +2 -3
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/plugin/index.d.mts +2 -2
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/{types-bcuNRo1Y.d.mts → plugin-CE-BZZgX.d.mts} +1069 -1763
- package/dist/{query-Bz2oDGhw.mjs → query-CV5n7DRd.mjs} +496 -115
- package/dist/query-CV5n7DRd.mjs.map +1 -0
- package/dist/{schema-Cjm-OvPF.mjs → schema-0ByCZ2Ym.mjs} +2 -2
- package/dist/schema-0ByCZ2Ym.mjs.map +1 -0
- package/dist/{seed-CXvCW3Xc.mjs → seed-Cl5QXYsL.mjs} +13 -3
- package/dist/seed-Cl5QXYsL.mjs.map +1 -0
- package/dist/{telemetry-C46fds1l.mjs → telemetry-BPviAbME.mjs} +2 -2
- package/dist/{telemetry-C46fds1l.mjs.map → telemetry-BPviAbME.mjs.map} +1 -1
- package/dist/telemetry-Dq5FZUH0.mjs +3 -0
- package/dist/utils/test/index.d.mts +3 -4
- package/dist/utils/test/index.mjs +2 -2
- package/docs/cli/tailordb.md +1 -1
- package/docs/cli-reference.md +8 -8
- package/docs/services/auth.md +2 -2
- package/package.json +27 -25
- package/postinstall.mjs +4 -14
- package/dist/application-CTQe2HSB.mjs.map +0 -1
- package/dist/application-DdSu3baZ.mjs +0 -8
- package/dist/package-json-BI0ng3_5.mjs +0 -3
- package/dist/query-Bz2oDGhw.mjs.map +0 -1
- package/dist/schema-Cjm-OvPF.mjs.map +0 -1
- package/dist/seed-CXvCW3Xc.mjs.map +0 -1
- package/dist/telemetry-BAxP8-PR.mjs +0 -3
- package/dist/types-CBTSg-LK.mjs +0 -13
- package/dist/types-CBTSg-LK.mjs.map +0 -1
- package/dist/types-DVMQNdTs.d.mts +0 -246
- package/dist/user-defined.d.ts +0 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-utils-sEOwAdJ4.mjs","names":[],"sources":["../src/plugin/builtin/file-utils/generate-file-utils.ts","../src/plugin/builtin/file-utils/process-file-type.ts","../src/plugin/builtin/file-utils/index.ts"],"sourcesContent":["import multiline from \"multiline-ts\";\nimport type { FileUtilMetadata } from \"./types\";\n\n/**\n * Generate unified file utility functions from collected metadata.\n * @param namespaceData - Namespace data with file utility metadata\n * @returns Generated file utility code\n */\nexport function generateUnifiedFileUtils(\n namespaceData: { namespace: string; types: FileUtilMetadata[] }[],\n): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Collect all types with their namespace\n const typeNamespaceMap = new Map<string, string>();\n const typeFieldsMap = new Map<string, string[]>();\n\n for (const { namespace, types } of namespaceData) {\n for (const type of types) {\n typeNamespaceMap.set(type.name, namespace);\n typeFieldsMap.set(type.name, type.fileFields);\n }\n }\n\n if (typeNamespaceMap.size === 0) {\n return \"\";\n }\n\n // Generate interface fields\n const interfaceFields = Array.from(typeFieldsMap.entries())\n .map(([typeName, fields]) => {\n const fieldNamesUnion = fields.map((field) => `\"${field}\"`).join(\" | \");\n return ` ${typeName}: {\\n fields: ${fieldNamesUnion};\\n };`;\n })\n .join(\"\\n\");\n\n const interfaceDefinition =\n multiline /* ts */ `\n export interface TypeWithFiles {\n ${interfaceFields}\n }\n ` + \"\\n\";\n\n // Generate namespaces object\n const namespaceEntries = Array.from(typeNamespaceMap.entries())\n .map(([typeName, namespace]) => ` ${typeName}: \"${namespace}\"`)\n .join(\",\\n\");\n\n const namespacesDefinition =\n multiline /* ts */ `\n const namespaces: Record<keyof TypeWithFiles, string> = {\n ${namespaceEntries},\n };\n ` + \"\\n\";\n\n // Generate downloadFile helper function\n const downloadFunction =\n multiline /* ts */ `\n export async function downloadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ) {\n return await tailordb.file.download(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate uploadFile helper function\n const uploadFunction =\n multiline /* ts */ `\n export async function uploadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n data: string | ArrayBuffer | Uint8Array<ArrayBufferLike> | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse> {\n return await tailordb.file.upload(namespaces[type], type, field, recordId, data, options);\n }\n ` + \"\\n\";\n\n // Generate deleteFile helper function\n const deleteFunction =\n multiline /* ts */ `\n export async function deleteFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<void> {\n return await tailordb.file.delete(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate getFileMetadata helper function\n const getMetadataFunction =\n multiline /* ts */ `\n export async function getFileMetadata<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileMetadata> {\n return await tailordb.file.getMetadata(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate openFileDownloadStream helper function\n const openDownloadStreamFunction =\n multiline /* ts */ `\n export async function openFileDownloadStream<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileStreamIterator> {\n return await tailordb.file.openDownloadStream(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n return [\n interfaceDefinition,\n namespacesDefinition,\n downloadFunction,\n uploadFunction,\n deleteFunction,\n getMetadataFunction,\n openDownloadStreamFunction,\n ].join(\"\\n\");\n}\n","import type { FileUtilMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/
|
|
1
|
+
{"version":3,"file":"file-utils-sEOwAdJ4.mjs","names":[],"sources":["../src/plugin/builtin/file-utils/generate-file-utils.ts","../src/plugin/builtin/file-utils/process-file-type.ts","../src/plugin/builtin/file-utils/index.ts"],"sourcesContent":["import multiline from \"multiline-ts\";\nimport type { FileUtilMetadata } from \"./types\";\n\n/**\n * Generate unified file utility functions from collected metadata.\n * @param namespaceData - Namespace data with file utility metadata\n * @returns Generated file utility code\n */\nexport function generateUnifiedFileUtils(\n namespaceData: { namespace: string; types: FileUtilMetadata[] }[],\n): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Collect all types with their namespace\n const typeNamespaceMap = new Map<string, string>();\n const typeFieldsMap = new Map<string, string[]>();\n\n for (const { namespace, types } of namespaceData) {\n for (const type of types) {\n typeNamespaceMap.set(type.name, namespace);\n typeFieldsMap.set(type.name, type.fileFields);\n }\n }\n\n if (typeNamespaceMap.size === 0) {\n return \"\";\n }\n\n // Generate interface fields\n const interfaceFields = Array.from(typeFieldsMap.entries())\n .map(([typeName, fields]) => {\n const fieldNamesUnion = fields.map((field) => `\"${field}\"`).join(\" | \");\n return ` ${typeName}: {\\n fields: ${fieldNamesUnion};\\n };`;\n })\n .join(\"\\n\");\n\n const interfaceDefinition =\n multiline /* ts */ `\n export interface TypeWithFiles {\n ${interfaceFields}\n }\n ` + \"\\n\";\n\n // Generate namespaces object\n const namespaceEntries = Array.from(typeNamespaceMap.entries())\n .map(([typeName, namespace]) => ` ${typeName}: \"${namespace}\"`)\n .join(\",\\n\");\n\n const namespacesDefinition =\n multiline /* ts */ `\n const namespaces: Record<keyof TypeWithFiles, string> = {\n ${namespaceEntries},\n };\n ` + \"\\n\";\n\n // Generate downloadFile helper function\n const downloadFunction =\n multiline /* ts */ `\n export async function downloadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ) {\n return await tailordb.file.download(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate uploadFile helper function\n const uploadFunction =\n multiline /* ts */ `\n export async function uploadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n data: string | ArrayBuffer | Uint8Array<ArrayBufferLike> | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse> {\n return await tailordb.file.upload(namespaces[type], type, field, recordId, data, options);\n }\n ` + \"\\n\";\n\n // Generate deleteFile helper function\n const deleteFunction =\n multiline /* ts */ `\n export async function deleteFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<void> {\n return await tailordb.file.delete(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate getFileMetadata helper function\n const getMetadataFunction =\n multiline /* ts */ `\n export async function getFileMetadata<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileMetadata> {\n return await tailordb.file.getMetadata(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate openFileDownloadStream helper function\n const openDownloadStreamFunction =\n multiline /* ts */ `\n export async function openFileDownloadStream<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileStreamIterator> {\n return await tailordb.file.openDownloadStream(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n return [\n interfaceDefinition,\n namespacesDefinition,\n downloadFunction,\n uploadFunction,\n deleteFunction,\n getMetadataFunction,\n openDownloadStreamFunction,\n ].join(\"\\n\");\n}\n","import type { FileUtilMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/types/tailordb\";\n\n/**\n * Process a TailorDB type and extract file field metadata.\n * @param type - The parsed TailorDB type to process\n * @returns File utility metadata for the type\n */\nexport async function processFileType(type: TailorDBType): Promise<FileUtilMetadata> {\n const fileFields: string[] = [];\n\n if (type.files) {\n for (const fileFieldName of Object.keys(type.files)) {\n fileFields.push(fileFieldName);\n }\n }\n\n return {\n name: type.name,\n fileFields,\n };\n}\n","import { generateUnifiedFileUtils } from \"./generate-file-utils\";\nimport { processFileType } from \"./process-file-type\";\nimport type { FileUtilMetadata } from \"./types\";\nimport type { Plugin } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\nexport const FileUtilsGeneratorID = \"@tailor-platform/file-utils\";\n\ntype FileUtilsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates TypeWithFiles interface from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated file utilities\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function fileUtilsPlugin(\n options: FileUtilsPluginOptions,\n): Plugin<unknown, FileUtilsPluginOptions> {\n return {\n id: FileUtilsGeneratorID,\n description: \"Generates TypeWithFiles interface from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<FileUtilsPluginOptions>,\n ): Promise<GeneratorResult> {\n const namespaceData: { namespace: string; types: FileUtilMetadata[] }[] = [];\n\n for (const ns of ctx.tailordb) {\n const typesWithFiles: FileUtilMetadata[] = [];\n\n for (const type of Object.values(ns.types)) {\n const metadata = await processFileType(type);\n if (metadata.fileFields.length > 0) {\n typesWithFiles.push(metadata);\n }\n }\n\n if (typesWithFiles.length > 0) {\n namespaceData.push({\n namespace: ns.namespace,\n types: typesWithFiles,\n });\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (namespaceData.length > 0) {\n const content = generateUnifiedFileUtils(namespaceData);\n if (content) {\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,yBACd,eACQ;AACR,KAAI,cAAc,WAAW,EAC3B,QAAO;CAIT,MAAM,mCAAmB,IAAI,K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O,GAAG,MAAM,EAAE;KAC1C,MAAM,WAAW,MAAM,gBAAgB,KAAK;AAC5C,SAAI,SAAS,WAAW,SAAS,EAC/B,gBAAe,KAAK,SAAS;;AAIjC,QAAI,eAAe,SAAS,EAC1B,eAAc,KAAK;KACjB,WAAW,GAAG;KACd,OAAO;KACR,CAAC;;GAIN,MAAM,QAAkC,EAAE;AAC1C,OAAI,cAAc,SAAS,GAAG;IAC5B,MAAM,UAAU,yBAAyB,cAAc;AACvD,QAAI,QACF,OAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAIN,UAAO,EAAE,OAAO;;EAEnB"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { u as Plugin } from "./types-bcuNRo1Y.mjs";
|
|
1
|
+
import { n as Plugin } from "./plugin-CE-BZZgX.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/plugin/builtin/enum-constants/index.d.ts
|
|
5
4
|
declare const EnumConstantsGeneratorID = "@tailor-platform/enum-constants";
|
|
@@ -15,4 +14,4 @@ type EnumConstantsPluginOptions = {
|
|
|
15
14
|
declare function enumConstantsPlugin(options: EnumConstantsPluginOptions): Plugin<unknown, EnumConstantsPluginOptions>;
|
|
16
15
|
//#endregion
|
|
17
16
|
export { enumConstantsPlugin as n, EnumConstantsGeneratorID as t };
|
|
18
|
-
//# sourceMappingURL=index-
|
|
17
|
+
//# sourceMappingURL=index-BrIZ1rm2.d.mts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { t as AppConfig } from "./
|
|
1
|
+
import { $ as TailorFieldType, B as TailorDBInstance, Ct as RecordTrigger$1, Dt as WorkflowOperation$1, Et as WebhookOperation$1, J as ArrayFieldOutput, N as UserAttributeListKey, O as AuthServiceInput, Ot as AuthInvoker$1, P as UserAttributeMap, Q as FieldOutput, St as IncomingWebhookTrigger$1, Tt as ScheduleTriggerInput, V as TailorDBType, X as FieldMetadata, Y as DefinedFieldMetadata, Z as FieldOptions, bt as GqlOperation$1, dt as AllowedValues, et as TailorAnyField, ft as AllowedValuesOutput, gt as AuthAccessTokenTrigger$1, ht as GeneratorConfig, it as output$1, k as DefinedAuth, lt as TailorUser, mt as ResolverInput, n as Plugin, nt as InferFieldsOutput, pt as Resolver, rt as JsonCompatible, tt as TailorField, vt as ExecutorInput, wt as ResolverExecutedTrigger$1, xt as IdpUserTrigger$1, yt as FunctionOperation$1 } from "./plugin-CE-BZZgX.mjs";
|
|
2
|
+
import { n as TailorEnv, r as TailorActor } from "./env-CHwmMyfF.mjs";
|
|
3
|
+
import { g as IdPInput, p as IdpDefinitionBrand, t as AppConfig } from "./app-config-BNKHurwr.mjs";
|
|
4
4
|
import * as zod0 from "zod";
|
|
5
5
|
import { JsonPrimitive, Jsonifiable, Jsonify } from "type-fest";
|
|
6
6
|
import { Client } from "@urql/core";
|
|
@@ -109,6 +109,9 @@ declare function createResolver<Input extends Record<string, TailorAnyField> | u
|
|
|
109
109
|
}>): ResolverReturn<Input, Output>;
|
|
110
110
|
type ResolverConfig = ReturnType<typeof createResolver<any, any>>;
|
|
111
111
|
//#endregion
|
|
112
|
+
//#region src/types/resolver.d.ts
|
|
113
|
+
type QueryType = Resolver["operation"];
|
|
114
|
+
//#endregion
|
|
112
115
|
//#region src/configure/services/workflow/job.d.ts
|
|
113
116
|
/**
|
|
114
117
|
* Context object passed as the second argument to workflow job body functions.
|
|
@@ -583,6 +586,53 @@ declare function createExecutor<Args, O extends Operation<Args> | {
|
|
|
583
586
|
workflow: Workflow;
|
|
584
587
|
}>(config: Executor<Trigger<Args>, O>): Executor<Trigger<Args>, O>;
|
|
585
588
|
//#endregion
|
|
589
|
+
//#region src/configure/services/idp/index.d.ts
|
|
590
|
+
/**
|
|
591
|
+
* Define an IdP service configuration for the Tailor SDK.
|
|
592
|
+
* @template TClients
|
|
593
|
+
* @param name - IdP service name
|
|
594
|
+
* @param config - IdP configuration
|
|
595
|
+
* @returns Defined IdP service
|
|
596
|
+
*/
|
|
597
|
+
declare function defineIdp<const TClients extends string[]>(name: string, config: Omit<IdPInput, "name" | "clients"> & {
|
|
598
|
+
clients: TClients;
|
|
599
|
+
}): {
|
|
600
|
+
readonly name: string;
|
|
601
|
+
readonly provider: (providerName: string, clientName: TClients[number]) => {
|
|
602
|
+
readonly name: string;
|
|
603
|
+
readonly kind: "BuiltInIdP";
|
|
604
|
+
readonly namespace: string;
|
|
605
|
+
readonly clientName: TClients[number];
|
|
606
|
+
};
|
|
607
|
+
readonly authorization: "insecure" | "loggedIn" | {
|
|
608
|
+
cel: string;
|
|
609
|
+
};
|
|
610
|
+
readonly lang?: "en" | "ja" | undefined;
|
|
611
|
+
readonly userAuthPolicy?: {
|
|
612
|
+
useNonEmailIdentifier?: boolean | undefined;
|
|
613
|
+
allowSelfPasswordReset?: boolean | undefined;
|
|
614
|
+
passwordRequireUppercase?: boolean | undefined;
|
|
615
|
+
passwordRequireLowercase?: boolean | undefined;
|
|
616
|
+
passwordRequireNonAlphanumeric?: boolean | undefined;
|
|
617
|
+
passwordRequireNumeric?: boolean | undefined;
|
|
618
|
+
passwordMinLength?: number | undefined;
|
|
619
|
+
passwordMaxLength?: number | undefined;
|
|
620
|
+
allowedEmailDomains?: string[] | undefined;
|
|
621
|
+
allowGoogleOauth?: boolean | undefined;
|
|
622
|
+
allowMicrosoftOauth?: boolean | undefined;
|
|
623
|
+
disablePasswordAuth?: boolean | undefined;
|
|
624
|
+
} | undefined;
|
|
625
|
+
readonly publishUserEvents?: boolean | undefined;
|
|
626
|
+
readonly gqlOperations?: "query" | {
|
|
627
|
+
create?: boolean | undefined;
|
|
628
|
+
update?: boolean | undefined;
|
|
629
|
+
delete?: boolean | undefined;
|
|
630
|
+
read?: boolean | undefined;
|
|
631
|
+
sendPasswordResetEmail?: boolean | undefined;
|
|
632
|
+
} | undefined;
|
|
633
|
+
readonly clients: TClients;
|
|
634
|
+
} & IdpDefinitionBrand;
|
|
635
|
+
//#endregion
|
|
586
636
|
//#region src/configure/config.d.ts
|
|
587
637
|
/**
|
|
588
638
|
* Define a Tailor SDK application configuration with shallow exactness.
|
|
@@ -703,5 +753,5 @@ declare namespace t {
|
|
|
703
753
|
type infer<T> = TailorOutput<T>;
|
|
704
754
|
}
|
|
705
755
|
//#endregion
|
|
706
|
-
export {
|
|
707
|
-
//# sourceMappingURL=index-
|
|
756
|
+
export { AuthInvoker as $, idpUserCreatedTrigger as A, WebhookOperation as B, RecordTrigger as C, authAccessTokenIssuedTrigger as D, ResolverExecutedTrigger as E, recordUpdatedTrigger as F, WORKFLOW_TEST_ENV_KEY as G, Workflow as H, resolverExecutedTrigger as I, WorkflowJobInput as J, WorkflowJob as K, FunctionOperation as L, idpUserUpdatedTrigger as M, recordCreatedTrigger as N, authAccessTokenRefreshedTrigger as O, recordDeletedTrigger as P, createResolver as Q, GqlOperation as R, RecordDeletedArgs as S, ResolverExecutedArgs as T, WorkflowConfig as U, WorkflowOperation as V, createWorkflow as W, createWorkflowJob as X, WorkflowJobOutput as Y, QueryType as Z, AuthAccessTokenArgs as _, defineGenerators as a, IdpUserTrigger as b, createExecutor as c, IncomingWebhookRequest as d, defineAuth as et, IncomingWebhookTrigger as f, scheduleTrigger as g, ScheduleTrigger as h, defineConfig as i, idpUserDeletedTrigger as j, authAccessTokenRevokedTrigger as k, Trigger as l, ScheduleArgs as m, output as n, definePlugins as o, incomingWebhookTrigger as p, WorkflowJobContext as q, t as r, defineIdp as s, infer as t, IncomingWebhookArgs as u, AuthAccessTokenTrigger as v, RecordUpdatedArgs as w, RecordCreatedArgs as x, IdpUserArgs as y, Operation as z };
|
|
757
|
+
//# sourceMappingURL=index-Df0aH5zp.d.mts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { u as Plugin } from "./types-bcuNRo1Y.mjs";
|
|
1
|
+
import { n as Plugin } from "./plugin-CE-BZZgX.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/plugin/builtin/kysely-type/index.d.ts
|
|
5
4
|
declare const KyselyGeneratorID = "@tailor-platform/kysely-type";
|
|
@@ -15,4 +14,4 @@ type KyselyTypePluginOptions = {
|
|
|
15
14
|
declare function kyselyTypePlugin(options: KyselyTypePluginOptions): Plugin<unknown, KyselyTypePluginOptions>;
|
|
16
15
|
//#endregion
|
|
17
16
|
export { kyselyTypePlugin as n, KyselyGeneratorID as t };
|
|
18
|
-
//# sourceMappingURL=index-
|
|
17
|
+
//# sourceMappingURL=index-DhtKJmgi.d.mts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { u as Plugin } from "./types-bcuNRo1Y.mjs";
|
|
1
|
+
import { n as Plugin } from "./plugin-CE-BZZgX.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/plugin/builtin/seed/index.d.ts
|
|
5
4
|
declare const SeedGeneratorID = "@tailor-platform/seed";
|
|
@@ -17,4 +16,4 @@ type SeedPluginOptions = {
|
|
|
17
16
|
declare function seedPlugin(options: SeedPluginOptions): Plugin<unknown, SeedPluginOptions>;
|
|
18
17
|
//#endregion
|
|
19
18
|
export { seedPlugin as n, SeedGeneratorID as t };
|
|
20
|
-
//# sourceMappingURL=index-
|
|
19
|
+
//# sourceMappingURL=index-DkRJwNw2.d.mts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { u as Plugin } from "./types-bcuNRo1Y.mjs";
|
|
1
|
+
import { n as Plugin } from "./plugin-CE-BZZgX.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/plugin/builtin/file-utils/index.d.ts
|
|
5
4
|
declare const FileUtilsGeneratorID = "@tailor-platform/file-utils";
|
|
@@ -15,4 +14,4 @@ type FileUtilsPluginOptions = {
|
|
|
15
14
|
declare function fileUtilsPlugin(options: FileUtilsPluginOptions): Plugin<unknown, FileUtilsPluginOptions>;
|
|
16
15
|
//#endregion
|
|
17
16
|
export { fileUtilsPlugin as n, FileUtilsGeneratorID as t };
|
|
18
|
-
//# sourceMappingURL=index-
|
|
17
|
+
//# sourceMappingURL=index-zZUL7_2B.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"interceptor-
|
|
1
|
+
{"version":3,"file":"interceptor-B-0OmiDZ.mjs","names":[],"sources":["../src/cli/telemetry/interceptor.ts"],"sourcesContent":["import { trace, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Interceptor } from \"@connectrpc/connect\";\n\n/**\n * Create a Connect-RPC interceptor that records OTLP spans for each RPC call.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @returns Tracing interceptor\n */\nexport function createTracingInterceptor(): Interceptor {\n return (next) => async (req) => {\n const tracer = trace.getTracer(\"tailor-sdk\");\n\n return tracer.startActiveSpan(`rpc.${req.method.name}`, async (span) => {\n span.setAttribute(\"rpc.method\", req.method.name);\n span.setAttribute(\"rpc.service\", \"OperatorService\");\n span.setAttribute(\"rpc.system\", \"connect-rpc\");\n\n try {\n const response = await next(req);\n span.setStatus({ code: SpanStatusCode.OK });\n return response;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;AASA,SAAgB,2BAAwC;AACtD,SAAQ,SAAS,OAAO,QAAQ;AAG9B,SAFe,MAAM,UAAU,aAAa,CAE9B,gBAAgB,OAAO,IAAI,OAAO,QAAQ,OAAO,SAAS;AACtE,QAAK,aAAa,cAAc,IAAI,OAAO,KAAK;AAChD,QAAK,aAAa,eAAe,kBAAkB;AACnD,QAAK,aAAa,cAAc,cAAc;AAE9C,OAAI;IACF,MAAM,WAAW,MAAM,KAAK,IAAI;AAChC,SAAK,UAAU,EAAE,MAAM,eAAe,IAAI,CAAC;AAC3C,WAAO;YACA,OAAO;AACd,SAAK,UAAU,EAAE,MAAM,eAAe,OAAO,CAAC;AAC9C,QAAI,iBAAiB,MACnB,MAAK,gBAAgB,MAAM;AAE7B,UAAM;aACE;AACR,SAAK,KAAK;;IAEZ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as brandValue } from "./brand-
|
|
1
|
+
import { t as brandValue } from "./brand-64NrPh_e.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/configure/services/workflow/job.ts
|
|
4
4
|
/**
|
|
@@ -50,4 +50,4 @@ const createWorkflowJob = (config) => {
|
|
|
50
50
|
|
|
51
51
|
//#endregion
|
|
52
52
|
export { createWorkflowJob as n, WORKFLOW_TEST_ENV_KEY as t };
|
|
53
|
-
//# sourceMappingURL=job-
|
|
53
|
+
//# sourceMappingURL=job-CnqcfVTI.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"job-
|
|
1
|
+
{"version":3,"file":"job-CnqcfVTI.mjs","names":[],"sources":["../src/configure/services/workflow/job.ts"],"sourcesContent":["import { brandValue } from \"@/utils/brand\";\nimport type { TailorEnv } from \"@/configure/types/env\";\nimport type { JsonCompatible } from \"@/configure/types/helpers\";\nimport type { Jsonifiable, Jsonify, JsonPrimitive } from \"type-fest\";\n\n/**\n * Context object passed as the second argument to workflow job body functions.\n */\nexport type WorkflowJobContext = {\n env: TailorEnv;\n};\n\n/**\n * Allowed output types for workflow job body functions.\n * Includes Jsonifiable (JSON-serializable values including objects with toJSON like Date),\n * undefined, and void.\n */\nexport type WorkflowJobOutput = Jsonifiable | undefined | void;\n\n/**\n * Convert output type to what trigger returns after JSON serialization.\n * - Jsonifiable values are converted via Jsonify (Date -> string, etc.)\n * - undefined remains undefined\n * - void becomes void\n */\ntype JsonifyOutput<T> = T extends Jsonifiable ? Jsonify<T> : T;\n\n/**\n * Input type constraint for workflow jobs.\n * Accepts any type that is JSON-compatible (primitives, arrays, objects with JSON-compatible values).\n * Excludes objects with toJSON method (like Date) since they won't be serialized in input.\n */\nexport type WorkflowJobInput = undefined | JsonCompatible<unknown>;\n\n/**\n * WorkflowJob represents a job that can be triggered in a workflow.\n *\n * Type constraints:\n * - Input: Must be JSON-compatible (no Date/toJSON objects) or undefined. Interfaces are allowed.\n * - Output: Must be Jsonifiable, undefined, or void\n * - Trigger returns Jsonify<Output> (Date becomes string after JSON.stringify)\n */\nexport interface WorkflowJob<Name extends string = string, Input = undefined, Output = undefined> {\n name: Name;\n /**\n * Trigger this job with the given input.\n * At runtime, this is a placeholder that calls the body function.\n * During bundling, calls to .trigger() are transformed to\n * tailor.workflow.triggerJobFunction(\"<job-name>\", args).\n *\n * Returns Jsonify<Output> because the value passes through JSON.stringify.\n *\n * Inside a workflow job body, .trigger() calls are transformed by the bundler\n * into synchronous `triggerJobFunction` calls. You may use `await` for\n * readability — the bundler strips it automatically at build time.\n * @example\n * // Both styles work — await is stripped by the bundler:\n * body: async (input) => {\n * const a = await jobA.trigger({ id: input.id });\n * const b = await jobB.trigger({ id: input.id });\n * return { a, b };\n * }\n */\n trigger: [Input] extends [undefined]\n ? () => Promise<JsonifyOutput<Awaited<Output>>>\n : (input: Input) => Promise<JsonifyOutput<Awaited<Output>>>;\n body: (input: Input, context: WorkflowJobContext) => Output | Promise<Output>;\n}\n\n/**\n * Helper type to check if all property types are valid.\n * Uses -? to remove optional modifiers so all properties are treated uniformly.\n */\ntype AllPropertiesValid<T> = {\n [K in keyof T]-?: IsValidInput<T[K]> extends true ? true : false;\n}[keyof T] extends true\n ? true\n : false;\n\n/**\n * Check if a type contains any non-JSON-compatible values.\n * Returns `true` if the type is valid for input, `false` otherwise.\n *\n * Accepts:\n * - JSON primitives (string, number, boolean, null)\n * - undefined\n * - Optional primitives (e.g., string | undefined)\n * - Arrays of valid types\n * - Objects with valid field types\n *\n * Rejects:\n * - Objects with toJSON methods (like Date)\n * - Other non-JSON-serializable types\n */\ntype IsValidInput<T> = T extends undefined\n ? true\n : T extends JsonPrimitive\n ? true\n : T extends readonly (infer U)[]\n ? IsValidInput<U>\n : T extends object\n ? T extends { toJSON: () => unknown }\n ? false\n : AllPropertiesValid<T>\n : false;\n\n/**\n * Helper type to check if all property types are valid for output.\n * Uses -? to remove optional modifiers so all properties are treated uniformly.\n */\ntype AllPropertiesValidOutput<T> = {\n [K in keyof T]-?: IsValidOutput<T[K]> extends true ? true : false;\n}[keyof T] extends true\n ? true\n : false;\n\n/**\n * Check if a type is valid for output.\n * Returns `true` if the type is valid, `false` otherwise.\n *\n * Accepts:\n * - JSON primitives (string, number, boolean, null)\n * - undefined and void\n * - Optional primitives (e.g., string | undefined)\n * - Jsonifiable types (Date, objects with toJSON)\n * - Arrays of valid types\n * - Objects with valid field types\n */\ntype IsValidOutput<T> = T extends undefined | void\n ? true\n : T extends JsonPrimitive\n ? true\n : T extends readonly (infer U)[]\n ? IsValidOutput<U>\n : T extends object\n ? AllPropertiesValidOutput<T>\n : false;\n\n/**\n * Body function type with conditional constraint.\n * If input contains invalid types (like Date), the body type becomes `never` to cause an error.\n */\ntype WorkflowJobBody<I, O> =\n IsValidInput<I> extends true\n ? IsValidOutput<O> extends true\n ? (input: I, context: WorkflowJobContext) => O | Promise<O>\n : never\n : never;\n\n/**\n * Environment variable key for workflow testing.\n * Contains JSON-serialized TailorEnv object.\n */\nexport const WORKFLOW_TEST_ENV_KEY = \"TAILOR_TEST_WORKFLOW_ENV\";\n\n/**\n * Create a workflow job definition.\n *\n * All jobs must be named exports from the workflow file.\n * Job names must be unique across the entire project.\n * @param config - Job configuration with name and body function\n * @param config.name - Unique job name across the project\n * @param config.body - Async function that processes the job input\n * @returns A WorkflowJob that can be triggered from other jobs\n * @example\n * // Simple job with async body:\n * export const fetchData = createWorkflowJob({\n * name: \"fetch-data\",\n * body: async (input: { id: string }) => {\n * const db = getDB(\"tailordb\");\n * return await db.selectFrom(\"Table\").selectAll().where(\"id\", \"=\", input.id).executeTakeFirst();\n * },\n * });\n * @example\n * // Orchestrator job that fans out to other jobs.\n * // await is optional — the bundler strips it at build time.\n * export const orchestrate = createWorkflowJob({\n * name: \"orchestrate\",\n * body: async (input: { orderId: string }) => {\n * const inventory = await checkInventory.trigger({ orderId: input.orderId });\n * const payment = await processPayment.trigger({ orderId: input.orderId });\n * return { inventory, payment };\n * },\n * });\n */\nexport const createWorkflowJob = <const Name extends string, I = undefined, O = undefined>(config: {\n readonly name: Name;\n readonly body: WorkflowJobBody<I, O>;\n}): WorkflowJob<Name, I, Awaited<O>> => {\n return brandValue({\n name: config.name,\n // JSON.parse(JSON.stringify(...)) ensures the return value matches Jsonify<Output> type.\n // This converts Date objects to strings, matching actual runtime behavior.\n // In production, bundler transforms .trigger() calls to tailor.workflow.triggerJobFunction().\n trigger: async (args?: unknown) => {\n const env: TailorEnv = JSON.parse(process.env[WORKFLOW_TEST_ENV_KEY] || \"{}\");\n const result = await config.body(args as I, { env });\n return result ? JSON.parse(JSON.stringify(result)) : result;\n },\n body: config.body,\n } as WorkflowJob<Name, I, Awaited<O>>);\n};\n"],"mappings":";;;;;;;AAyJA,MAAa,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCrC,MAAa,qBAA8E,WAGnD;AACtC,QAAO,WAAW;EAChB,MAAM,OAAO;EAIb,SAAS,OAAO,SAAmB;GACjC,MAAM,MAAiB,KAAK,MAAM,QAAQ,IAAI,0BAA0B,KAAK;GAC7E,MAAM,SAAS,MAAM,OAAO,KAAK,MAAW,EAAE,KAAK,CAAC;AACpD,UAAO,SAAS,KAAK,MAAM,KAAK,UAAU,OAAO,CAAC,GAAG;;EAEvD,MAAM,OAAO;EACd,CAAqC"}
|
package/dist/kysely/index.d.mts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/// <reference path="./../user-defined.d.ts" />
|
|
2
1
|
import { TailordbDialect } from "@tailor-platform/function-kysely-tailordb";
|
|
3
2
|
import { ColumnType, ColumnType as ColumnType$1, Insertable, Insertable as Insertable$1, Kysely, Kysely as Kysely$1, KyselyConfig, KyselyConfig as KyselyConfig$1, Selectable, Selectable as Selectable$1, Transaction, Transaction as Transaction$1, Updateable, Updateable as Updateable$1, sql } from "kysely";
|
|
4
3
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-type-CSlcwNFH.mjs","names":[],"sources":["../src/plugin/builtin/kysely-type/type-processor.ts","../src/plugin/builtin/kysely-type/index.ts"],"sourcesContent":["import multiline from \"multiline-ts\";\nimport { type KyselyNamespaceMetadata, type KyselyTypeMetadata } from \"./types\";\nimport type { OperatorFieldConfig, TailorDBType } from \"@/parser/service/tailordb/types\";\n\ntype UsedUtilityTypes = { Timestamp: boolean; Serial: boolean };\n\ntype FieldTypeResult = {\n type: string;\n usedUtilityTypes: UsedUtilityTypes;\n};\n\n/**\n * Get the enum type definition.\n * @param fieldConfig - The field configuration\n * @returns The enum type as a string union\n */\nfunction getEnumType(fieldConfig: OperatorFieldConfig): string {\n const allowedValues = fieldConfig.allowedValues;\n\n if (allowedValues && Array.isArray(allowedValues)) {\n return allowedValues\n .map((v: string | { value: string }) => {\n const value = typeof v === \"string\" ? v : v.value;\n return `\"${value}\"`;\n })\n .join(\" | \");\n }\n return \"string\";\n}\n\n/**\n * Get the nested object type definition.\n * @param fieldConfig - The field configuration\n * @returns The nested type with used utility types\n */\nfunction getNestedType(fieldConfig: OperatorFieldConfig): FieldTypeResult {\n const fields = fieldConfig.fields;\n if (!fields || typeof fields !== \"object\") {\n return {\n type: \"string\",\n usedUtilityTypes: { Timestamp: false, Serial: false },\n };\n }\n\n const fieldResults = Object.entries(fields).map(([fieldName, nestedOperatorFieldConfig]) => ({\n fieldName,\n ...generateFieldType(nestedOperatorFieldConfig),\n }));\n\n const fieldTypes = fieldResults.map((result) => `${result.fieldName}: ${result.type}`);\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => ({\n Timestamp: acc.Timestamp || result.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || result.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n const type = `{\\n ${fieldTypes.join(\";\\n \")}${fieldTypes.length > 0 ? \";\" : \"\"}\\n}`;\n return { type, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Get the base Kysely type for a field (without array/null modifiers).\n * @param fieldConfig - The field configuration\n * @returns The base type with used utility types\n */\nfunction getBaseType(fieldConfig: OperatorFieldConfig): FieldTypeResult {\n const fieldType = fieldConfig.type;\n const usedUtilityTypes = { Timestamp: false, Serial: false };\n\n let type: string;\n switch (fieldType) {\n case \"uuid\":\n case \"string\":\n case \"decimal\":\n type = \"string\";\n break;\n case \"integer\":\n case \"float\":\n type = \"number\";\n break;\n case \"date\":\n case \"datetime\":\n usedUtilityTypes.Timestamp = true;\n type = \"Timestamp\";\n break;\n case \"bool\":\n case \"boolean\":\n type = \"boolean\";\n break;\n case \"enum\":\n type = getEnumType(fieldConfig);\n break;\n case \"nested\": {\n const nestedResult = getNestedType(fieldConfig);\n return nestedResult;\n }\n default:\n type = \"string\";\n break;\n }\n\n return { type, usedUtilityTypes };\n}\n\n/**\n * Generate the complete field type including array and null modifiers.\n * @param fieldConfig - The field configuration\n * @returns The complete field type with used utility types\n */\nfunction generateFieldType(fieldConfig: OperatorFieldConfig): FieldTypeResult {\n const baseTypeResult = getBaseType(fieldConfig);\n const usedUtilityTypes = { ...baseTypeResult.usedUtilityTypes };\n\n const isArray = fieldConfig.array === true;\n const isNullable = fieldConfig.required !== true;\n\n let finalType = baseTypeResult.type;\n if (isArray) {\n // Wrap enum types in parentheses before adding array suffix\n const needsParens = fieldConfig.type === \"enum\";\n finalType = needsParens ? `(${baseTypeResult.type})[]` : `${baseTypeResult.type}[]`;\n }\n if (isNullable) {\n finalType = `${finalType} | null`;\n }\n\n if (fieldConfig.serial) {\n usedUtilityTypes.Serial = true;\n finalType = `Serial<${finalType}>`;\n }\n if (fieldConfig.hooks?.create) {\n finalType = `Generated<${finalType}>`;\n }\n\n return { type: finalType, usedUtilityTypes };\n}\n\n/**\n * Generate the table interface.\n * @param type - The parsed TailorDB type\n * @returns The type definition and used utility types\n */\nfunction generateTableInterface(type: TailorDBType): {\n typeDef: string;\n usedUtilityTypes: UsedUtilityTypes;\n} {\n const fieldEntries = Object.entries(type.fields).filter(([fieldName]) => fieldName !== \"id\");\n\n const fieldResults = fieldEntries.map(([fieldName, parsedField]) => ({\n fieldName,\n ...generateFieldType(parsedField.config),\n }));\n\n const fields = [\n \"id: Generated<string>;\",\n ...fieldResults.map((result) => `${result.fieldName}: ${result.type};`),\n ];\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => ({\n Timestamp: acc.Timestamp || result.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || result.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n const typeDef = multiline /* ts */ `\n ${type.name}: {\n ${fields.join(\"\\n\")}\n }\n `;\n\n return { typeDef, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Convert a TailorDBType into KyselyTypeMetadata.\n * @param type - Parsed TailorDB type\n * @returns Generated Kysely type metadata\n */\nexport async function processKyselyType(type: TailorDBType): Promise<KyselyTypeMetadata> {\n const result = generateTableInterface(type);\n\n return {\n name: type.name,\n typeDef: result.typeDef,\n usedUtilityTypes: result.usedUtilityTypes,\n };\n}\n\n/**\n * Generate unified types file from multiple namespaces.\n * @param namespaceData - Namespace metadata\n * @returns Generated types file contents\n */\nexport function generateUnifiedKyselyTypes(namespaceData: KyselyNamespaceMetadata[]): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Aggregate used utility types from all namespaces\n const globalUsedUtilityTypes = namespaceData.reduce(\n (acc, ns) => ({\n Timestamp: acc.Timestamp || ns.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || ns.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n const utilityTypeImports: string[] = [\"type Generated\"];\n if (globalUsedUtilityTypes.Timestamp) {\n utilityTypeImports.push(\"type Timestamp\");\n }\n if (globalUsedUtilityTypes.Serial) {\n utilityTypeImports.push(\"type Serial\");\n }\n\n const importsSection = multiline /* ts */ `\n import {\n createGetDB,\n ${utilityTypeImports.join(\",\\n\")},\n type NamespaceDB,\n type NamespaceInsertable,\n type NamespaceSelectable,\n type NamespaceTable,\n type NamespaceTableName,\n type NamespaceTransaction,\n type NamespaceUpdateable,\n } from \"@tailor-platform/sdk/kysely\";\n `;\n\n // Generate Namespace interface with multiple namespaces\n const namespaceInterfaces = namespaceData\n .map(({ namespace, types }) => {\n const typeDefsWithIndent = types\n .map((type) => {\n return type.typeDef\n .split(\"\\n\")\n .map((line) => (line.trim() ? ` ${line}` : \"\"))\n .join(\"\\n\");\n })\n .join(\"\\n\\n\");\n\n return ` \"${namespace}\": {\\n${typeDefsWithIndent}\\n }`;\n })\n .join(\",\\n\");\n\n const namespaceInterface = `export interface Namespace {\\n${namespaceInterfaces}\\n}`;\n\n const getDBFunction = multiline /* ts */ `\n export const getDB = createGetDB<Namespace>();\n\n export type DB<N extends keyof Namespace = keyof Namespace> = NamespaceDB<Namespace, N>;\n `;\n\n const utilityTypeExports = multiline /* ts */ `\n export type Transaction<K extends keyof Namespace | DB = keyof Namespace> =\n NamespaceTransaction<Namespace, K>;\n\n type TableName = NamespaceTableName<Namespace>;\n export type Table<T extends TableName> = NamespaceTable<Namespace, T>;\n\n export type Insertable<T extends TableName> = NamespaceInsertable<Namespace, T>;\n export type Selectable<T extends TableName> = NamespaceSelectable<Namespace, T>;\n export type Updateable<T extends TableName> = NamespaceUpdateable<Namespace, T>;\n `;\n\n return (\n [importsSection, namespaceInterface, getDBFunction, utilityTypeExports].join(\"\\n\\n\") + \"\\n\"\n );\n}\n","import { processKyselyType, generateUnifiedKyselyTypes } from \"./type-processor\";\nimport type { KyselyTypeMetadata, KyselyNamespaceMetadata } from \"./types\";\nimport type {\n GeneratorResult,\n TailorDBReadyContext,\n} from \"@/parser/plugin-config/generation-types\";\nimport type { Plugin } from \"@/parser/plugin-config/types\";\n\nexport const KyselyGeneratorID = \"@tailor-platform/kysely-type\";\n\ntype KyselyTypePluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates Kysely type definitions for TailorDB types.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated types\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function kyselyTypePlugin(\n options: KyselyTypePluginOptions,\n): Plugin<unknown, KyselyTypePluginOptions> {\n return {\n id: KyselyGeneratorID,\n description: \"Generates Kysely type definitions for TailorDB types\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<KyselyTypePluginOptions>,\n ): Promise<GeneratorResult> {\n const allNamespaceData: KyselyNamespaceMetadata[] = [];\n\n for (const ns of ctx.tailordb) {\n const typeMetadataList: KyselyTypeMetadata[] = [];\n\n for (const type of Object.values(ns.types)) {\n const metadata = await processKyselyType(type);\n typeMetadataList.push(metadata);\n }\n\n if (typeMetadataList.length === 0) continue;\n\n const usedUtilityTypes = typeMetadataList.reduce(\n (acc, type) => ({\n Timestamp: acc.Timestamp || type.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || type.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n allNamespaceData.push({\n namespace: ns.namespace,\n types: typeMetadataList,\n usedUtilityTypes,\n });\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allNamespaceData.length > 0) {\n const content = generateUnifiedKyselyTypes(allNamespaceData);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;;AAgBA,SAAS,YAAY,aAA0C;CAC7D,MAAM,gBAAgB,YAAY;AAElC,KAAI,iBAAiB,MAAM,QAAQ,cAAc,CAC/C,QAAO,cACJ,KAAK,MAAkC;AAEtC,SAAO,IADO,OAAO,MAAM,WAAW,IAAI,EAAE,MAC3B;GACjB,CACD,KAAK,MAAM;AAEhB,QAAO;;;;;;;AAQT,SAAS,cAAc,aAAmD;CACxE,MAAM,SAAS,YAAY;AAC3B,KAAI,CAAC,UAAU,OAAO,WAAW,SAC/B,QAAO;EACL,MAAM;E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C5D,UAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAGJ,UAAO,EAAE,OAAO;;EAEnB"}
|
|
1
|
+
{"version":3,"file":"kysely-type-CSlcwNFH.mjs","names":[],"sources":["../src/plugin/builtin/kysely-type/type-processor.ts","../src/plugin/builtin/kysely-type/index.ts"],"sourcesContent":["import multiline from \"multiline-ts\";\nimport { type KyselyNamespaceMetadata, type KyselyTypeMetadata } from \"./types\";\nimport type { OperatorFieldConfig, TailorDBType } from \"@/types/tailordb\";\n\ntype UsedUtilityTypes = { Timestamp: boolean; Serial: boolean };\n\ntype FieldTypeResult = {\n type: string;\n usedUtilityTypes: UsedUtilityTypes;\n};\n\n/**\n * Get the enum type definition.\n * @param fieldConfig - The field configuration\n * @returns The enum type as a string union\n */\nfunction getEnumType(fieldConfig: OperatorFieldConfig): string {\n const allowedValues = fieldConfig.allowedValues;\n\n if (allowedValues && Array.isArray(allowedValues)) {\n return allowedValues\n .map((v: string | { value: string }) => {\n const value = typeof v === \"string\" ? v : v.value;\n return `\"${value}\"`;\n })\n .join(\" | \");\n }\n return \"string\";\n}\n\n/**\n * Get the nested object type definition.\n * @param fieldConfig - The field configuration\n * @returns The nested type with used utility types\n */\nfunction getNestedType(fieldConfig: OperatorFieldConfig): FieldTypeResult {\n const fields = fieldConfig.fields;\n if (!fields || typeof fields !== \"object\") {\n return {\n type: \"string\",\n usedUtilityTypes: { Timestamp: false, Serial: false },\n };\n }\n\n const fieldResults = Object.entries(fields).map(([fieldName, nestedOperatorFieldConfig]) => ({\n fieldName,\n ...generateFieldType(nestedOperatorFieldConfig),\n }));\n\n const fieldTypes = fieldResults.map((result) => `${result.fieldName}: ${result.type}`);\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => ({\n Timestamp: acc.Timestamp || result.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || result.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n const type = `{\\n ${fieldTypes.join(\";\\n \")}${fieldTypes.length > 0 ? \";\" : \"\"}\\n}`;\n return { type, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Get the base Kysely type for a field (without array/null modifiers).\n * @param fieldConfig - The field configuration\n * @returns The base type with used utility types\n */\nfunction getBaseType(fieldConfig: OperatorFieldConfig): FieldTypeResult {\n const fieldType = fieldConfig.type;\n const usedUtilityTypes = { Timestamp: false, Serial: false };\n\n let type: string;\n switch (fieldType) {\n case \"uuid\":\n case \"string\":\n case \"decimal\":\n type = \"string\";\n break;\n case \"integer\":\n case \"float\":\n type = \"number\";\n break;\n case \"date\":\n case \"datetime\":\n usedUtilityTypes.Timestamp = true;\n type = \"Timestamp\";\n break;\n case \"bool\":\n case \"boolean\":\n type = \"boolean\";\n break;\n case \"enum\":\n type = getEnumType(fieldConfig);\n break;\n case \"nested\": {\n const nestedResult = getNestedType(fieldConfig);\n return nestedResult;\n }\n default:\n type = \"string\";\n break;\n }\n\n return { type, usedUtilityTypes };\n}\n\n/**\n * Generate the complete field type including array and null modifiers.\n * @param fieldConfig - The field configuration\n * @returns The complete field type with used utility types\n */\nfunction generateFieldType(fieldConfig: OperatorFieldConfig): FieldTypeResult {\n const baseTypeResult = getBaseType(fieldConfig);\n const usedUtilityTypes = { ...baseTypeResult.usedUtilityTypes };\n\n const isArray = fieldConfig.array === true;\n const isNullable = fieldConfig.required !== true;\n\n let finalType = baseTypeResult.type;\n if (isArray) {\n // Wrap enum types in parentheses before adding array suffix\n const needsParens = fieldConfig.type === \"enum\";\n finalType = needsParens ? `(${baseTypeResult.type})[]` : `${baseTypeResult.type}[]`;\n }\n if (isNullable) {\n finalType = `${finalType} | null`;\n }\n\n if (fieldConfig.serial) {\n usedUtilityTypes.Serial = true;\n finalType = `Serial<${finalType}>`;\n }\n if (fieldConfig.hooks?.create) {\n finalType = `Generated<${finalType}>`;\n }\n\n return { type: finalType, usedUtilityTypes };\n}\n\n/**\n * Generate the table interface.\n * @param type - The parsed TailorDB type\n * @returns The type definition and used utility types\n */\nfunction generateTableInterface(type: TailorDBType): {\n typeDef: string;\n usedUtilityTypes: UsedUtilityTypes;\n} {\n const fieldEntries = Object.entries(type.fields).filter(([fieldName]) => fieldName !== \"id\");\n\n const fieldResults = fieldEntries.map(([fieldName, parsedField]) => ({\n fieldName,\n ...generateFieldType(parsedField.config),\n }));\n\n const fields = [\n \"id: Generated<string>;\",\n ...fieldResults.map((result) => `${result.fieldName}: ${result.type};`),\n ];\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => ({\n Timestamp: acc.Timestamp || result.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || result.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n const typeDef = multiline /* ts */ `\n ${type.name}: {\n ${fields.join(\"\\n\")}\n }\n `;\n\n return { typeDef, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Convert a TailorDBType into KyselyTypeMetadata.\n * @param type - Parsed TailorDB type\n * @returns Generated Kysely type metadata\n */\nexport async function processKyselyType(type: TailorDBType): Promise<KyselyTypeMetadata> {\n const result = generateTableInterface(type);\n\n return {\n name: type.name,\n typeDef: result.typeDef,\n usedUtilityTypes: result.usedUtilityTypes,\n };\n}\n\n/**\n * Generate unified types file from multiple namespaces.\n * @param namespaceData - Namespace metadata\n * @returns Generated types file contents\n */\nexport function generateUnifiedKyselyTypes(namespaceData: KyselyNamespaceMetadata[]): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Aggregate used utility types from all namespaces\n const globalUsedUtilityTypes = namespaceData.reduce(\n (acc, ns) => ({\n Timestamp: acc.Timestamp || ns.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || ns.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n const utilityTypeImports: string[] = [\"type Generated\"];\n if (globalUsedUtilityTypes.Timestamp) {\n utilityTypeImports.push(\"type Timestamp\");\n }\n if (globalUsedUtilityTypes.Serial) {\n utilityTypeImports.push(\"type Serial\");\n }\n\n const importsSection = multiline /* ts */ `\n import {\n createGetDB,\n ${utilityTypeImports.join(\",\\n\")},\n type NamespaceDB,\n type NamespaceInsertable,\n type NamespaceSelectable,\n type NamespaceTable,\n type NamespaceTableName,\n type NamespaceTransaction,\n type NamespaceUpdateable,\n } from \"@tailor-platform/sdk/kysely\";\n `;\n\n // Generate Namespace interface with multiple namespaces\n const namespaceInterfaces = namespaceData\n .map(({ namespace, types }) => {\n const typeDefsWithIndent = types\n .map((type) => {\n return type.typeDef\n .split(\"\\n\")\n .map((line) => (line.trim() ? ` ${line}` : \"\"))\n .join(\"\\n\");\n })\n .join(\"\\n\\n\");\n\n return ` \"${namespace}\": {\\n${typeDefsWithIndent}\\n }`;\n })\n .join(\",\\n\");\n\n const namespaceInterface = `export interface Namespace {\\n${namespaceInterfaces}\\n}`;\n\n const getDBFunction = multiline /* ts */ `\n export const getDB = createGetDB<Namespace>();\n\n export type DB<N extends keyof Namespace = keyof Namespace> = NamespaceDB<Namespace, N>;\n `;\n\n const utilityTypeExports = multiline /* ts */ `\n export type Transaction<K extends keyof Namespace | DB = keyof Namespace> =\n NamespaceTransaction<Namespace, K>;\n\n type TableName = NamespaceTableName<Namespace>;\n export type Table<T extends TableName> = NamespaceTable<Namespace, T>;\n\n export type Insertable<T extends TableName> = NamespaceInsertable<Namespace, T>;\n export type Selectable<T extends TableName> = NamespaceSelectable<Namespace, T>;\n export type Updateable<T extends TableName> = NamespaceUpdateable<Namespace, T>;\n `;\n\n return (\n [importsSection, namespaceInterface, getDBFunction, utilityTypeExports].join(\"\\n\\n\") + \"\\n\"\n );\n}\n","import { processKyselyType, generateUnifiedKyselyTypes } from \"./type-processor\";\nimport type { KyselyTypeMetadata, KyselyNamespaceMetadata } from \"./types\";\nimport type { Plugin } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\nexport const KyselyGeneratorID = \"@tailor-platform/kysely-type\";\n\ntype KyselyTypePluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates Kysely type definitions for TailorDB types.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated types\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function kyselyTypePlugin(\n options: KyselyTypePluginOptions,\n): Plugin<unknown, KyselyTypePluginOptions> {\n return {\n id: KyselyGeneratorID,\n description: \"Generates Kysely type definitions for TailorDB types\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<KyselyTypePluginOptions>,\n ): Promise<GeneratorResult> {\n const allNamespaceData: KyselyNamespaceMetadata[] = [];\n\n for (const ns of ctx.tailordb) {\n const typeMetadataList: KyselyTypeMetadata[] = [];\n\n for (const type of Object.values(ns.types)) {\n const metadata = await processKyselyType(type);\n typeMetadataList.push(metadata);\n }\n\n if (typeMetadataList.length === 0) continue;\n\n const usedUtilityTypes = typeMetadataList.reduce(\n (acc, type) => ({\n Timestamp: acc.Timestamp || type.usedUtilityTypes.Timestamp,\n Serial: acc.Serial || type.usedUtilityTypes.Serial,\n }),\n { Timestamp: false, Serial: false },\n );\n\n allNamespaceData.push({\n namespace: ns.namespace,\n types: typeMetadataList,\n usedUtilityTypes,\n });\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allNamespaceData.length > 0) {\n const content = generateUnifiedKyselyTypes(allNamespaceData);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;;AAgBA,SAAS,YAAY,aAA0C;CAC7D,MAAM,gBAAgB,YAAY;AAElC,KAAI,iBAAiB,MAAM,QAAQ,cAAc,CAC/C,QAAO,cACJ,KAAK,MAAkC;AAEtC,SAAO,IADO,OAAO,MAAM,WAAW,IAAI,EAAE,MAC3B;GACjB,CACD,KAAK,MAAM;AAEhB,QAAO;;;;;;;AAQT,SAAS,cAAc,aAAmD;CACxE,MAAM,SAAS,YAAY;AAC3B,KAAI,CAAC,UAAU,OAAO,WAAW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,UAAU,2BAA2B,iBAAiB;AAC5D,UAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAGJ,UAAO,EAAE,OAAO;;EAEnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package-json-
|
|
1
|
+
{"version":3,"file":"package-json-4G3gLWMd.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;AACtC,KAAI,YACF,QAAO;AAET,eAAc,MAAM,gBAAgB,OAAO,KAAK,IAAI;AACpD,QAAO"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
import "../../../
|
|
3
|
-
import { n as enumConstantsPlugin, t as EnumConstantsGeneratorID } from "../../../index-Cwi86SUR.mjs";
|
|
1
|
+
import "../../../plugin-CE-BZZgX.mjs";
|
|
2
|
+
import { n as enumConstantsPlugin, t as EnumConstantsGeneratorID } from "../../../index-BrIZ1rm2.mjs";
|
|
4
3
|
export { EnumConstantsGeneratorID, enumConstantsPlugin };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
import "../../../
|
|
3
|
-
import { n as fileUtilsPlugin, t as FileUtilsGeneratorID } from "../../../index-BGPX26_D.mjs";
|
|
1
|
+
import "../../../plugin-CE-BZZgX.mjs";
|
|
2
|
+
import { n as fileUtilsPlugin, t as FileUtilsGeneratorID } from "../../../index-zZUL7_2B.mjs";
|
|
4
3
|
export { FileUtilsGeneratorID, fileUtilsPlugin };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
import "../../../
|
|
3
|
-
import { n as kyselyTypePlugin, t as KyselyGeneratorID } from "../../../index-DPN_P0w3.mjs";
|
|
1
|
+
import "../../../plugin-CE-BZZgX.mjs";
|
|
2
|
+
import { n as kyselyTypePlugin, t as KyselyGeneratorID } from "../../../index-DhtKJmgi.mjs";
|
|
4
3
|
export { KyselyGeneratorID, kyselyTypePlugin };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
import "../../../
|
|
3
|
-
import { n as seedPlugin, t as SeedGeneratorID } from "../../../index-ClS0NClx.mjs";
|
|
1
|
+
import "../../../plugin-CE-BZZgX.mjs";
|
|
2
|
+
import { n as seedPlugin, t as SeedGeneratorID } from "../../../index-DkRJwNw2.mjs";
|
|
4
3
|
export { SeedGeneratorID, seedPlugin };
|
package/dist/plugin/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
1
|
+
import { R as TailorAnyDBType } from "../plugin-CE-BZZgX.mjs";
|
|
2
|
+
import { n as TailorEnv, r as TailorActor } from "../env-CHwmMyfF.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/plugin/with-context.d.ts
|
|
5
5
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["namespace","cacheKey"],"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 \"@/parser/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 { Plugin, PluginOutput, TypePluginOutput } from \"@/parser/plugin-config/types\";\nimport type { TailorAnyDBType } from \"@/parser/service/tailordb/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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA,SAAgB,kBACd,SAC4B;AAC5B,QAAO;;;;;;AC9FT,MAAM,iCAAiB,IAAI,KAA0B;;;;;;AAOrD,SAAS,SAAS,OAAiC;AACjD,QACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAkC,OAAO,YACjD,OAAQ,MAAkC,gBAAgB;;;;;;;;;AAW9D,eAAe,mBAAmB,YAAiD;CACjF,MAAM,eAAe,KAAK,QAAQ,WAAW;CAE7C,MAAM,SAAS,eAAe,IAAI,aAAa;AAC/C,KAAI,OAAQ,QAAO;AAGnB,KAAI,CAAC,GAAG,WAAW,aAAa,CAC9B,QAAO;CAGT,MAAM,eAAe,MAAM,OAAO,cAAc,aAAa,CAAC;AAC9D,KAAI,CAAC,cAAc,QACjB,OAAM,IAAI,MAAM,6BAA6B,aAAa,6BAA6B;CAGzF,MAAM,SAAS,aAAa;CAC5B,MAAM,YAAY,KAAK,QAAQ,aAAa;CAC5C,MAAM,0BAAU,IAAI,KAA0B;AAG9C,MAAK,MAAM,SAAS,OAAO,OAAO,aAAa,EAAE;AAC/C,MAAI,CAAC,MAAM,QAAQ,MAAM,CAAE;AAE3B,OAAK,MAAM,QAAQ,MACjB,KAAI,SAAS,KAAK,CAChB,SAAQ,IAAI,KAAK,IAAI;GAAE,QAAQ;GAAM,cAAc,KAAK;GAAc,CAAC;;CAK7E,MAAM,SAAsB;EAAE;EAAQ;EAAS;EAAW;AAC1D,gBAAe,IAAI,cAAc,OAAO;AACxC,QAAO;;;;;;;;;;;AAqBT,eAAe,wBACb,QACA,WACA,YACiB;AACjB,KAAI,CAAC,OAAO,GACV,OAAM,IA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ACA,QACA,MACA,cAC0B;AAC1B,KAAI,CAAC,OAAO,kBACV,OAAM,IAAI,MAAM,WAAW,OAAO,GAAG,8CAA8C;CAIrF,IAAI,cAAc,sBAAsB,IAAI,OAAO;AACnD,KAAI,CAAC,aAAa;AAChB,gCAAc,IAAI,KAAK;AACvB,wBAAsB,IAAI,QAAQ,YAAY;;AAIhD,KAAI,OAAO,GACT,MAAK,MAAMA,eAAa,OAAO,KAAK,OAAO,GAAG,EAAE;AAE9C,MADiB,OAAO,GAAGA,aACd,SAAU;EAEvB,MAAMC,aAAW,YAAY,gBAAgBD,eAAa,aAAa;EACvE,MAAM,SAAS,YAAY,IAAIC,WAAS;AACxC,MAAI,QAAQ,QAAQ,MAClB,QAAO,OAAO,MAAM;;CAM1B,MAAM,EAAE,WAAW,WAAW,MAAM,mCAClC,QACA,QACA,MACA,aACD;CAED,MAAM,WAAW,YAAY,gBAAgB,aAAa,aAAa;AACvE,aAAY,IAAI,UAAU,OAAO;CAEjC,MAAM,gBAAgB,OAAO,QAAQ;AACrC,KAAI,CAAC,cACH,OAAM,IAAI,MAAM,oCAAoC,OAAO,GAAG,SAAS,OAAO;AAGhF,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["namespace","cacheKey"],"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;AAC5B,QAAO;;;;;;AC9FT,MAAM,iCAAiB,IAAI,KAA0B;;;;;;AAOrD,SAAS,SAAS,OAAiC;AACjD,QACE,OAAO,UAAU,YACjB,UAAU,QACV,OAAQ,MAAkC,OAAO,YACjD,OAAQ,MAAkC,gBAAgB;;;;;;;;;AAW9D,eAAe,mBAAmB,YAAiD;CACjF,MAAM,eAAe,KAAK,QAAQ,WAAW;CAE7C,MAAM,SAAS,eAAe,IAAI,aAAa;AAC/C,KAAI,OAAQ,QAAO;AAGnB,KAAI,CAAC,GAAG,WAAW,aAAa,CAC9B,QAAO;CAGT,MAAM,eAAe,MAAM,OAAO,cAAc,aAAa,CAAC;AAC9D,KAAI,CAAC,cAAc,QACjB,OAAM,IAAI,MAAM,6BAA6B,aAAa,6BAA6B;CAGzF,MAAM,SAAS,aAAa;CAC5B,MAAM,YAAY,KAAK,QAAQ,aAAa;CAC5C,MAAM,0BAAU,IAAI,KAA0B;AAG9C,MAAK,MAAM,SAAS,OAAO,OAAO,aAAa,EAAE;AAC/C,MAAI,CAAC,MAAM,QAAQ,MAAM,CAAE;AAE3B,OAAK,MAAM,QAAQ,MACjB,KAAI,SAAS,KAAK,CAChB,SAAQ,IAAI,KAAK,IAAI;GAAE,QAAQ;GAAM,cAAc,KAAK;GAAc,CAAC;;CAK7E,MAAM,SAAsB;EAAE;EAAQ;EAAS;EAAW;AAC1D,gBAAe,IAAI,cAAc,OAAO;AACxC,QAAO;;;;;;;;;;;AAqBT,eAAe,wBACb,QACA,WACA,YACiB;AACjB,KAAI,CAAC,OAAO,GACV,OAAM,IAAI,MAAM,sCAAsC;AAGxD,MAAK,MAAM,CA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