@tailor-platform/sdk 2.0.0-next.8 → 2.0.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 +631 -0
- package/dist/{application-GzW98_Xr.mjs → application-CM6hKnSK.mjs} +489 -118
- package/dist/application-CM6hKnSK.mjs.map +1 -0
- package/dist/application-CXNaUNhv.mjs +3 -0
- package/dist/cli/commands/deploy/aigateway.d.mts +2 -2
- package/dist/cli/commands/deploy/application.d.mts +2 -2
- package/dist/cli/commands/deploy/auth.d.mts +2 -2
- package/dist/cli/commands/deploy/deploy.d.mts +1 -0
- package/dist/cli/commands/deploy/executor.d.mts +2 -2
- package/dist/cli/commands/deploy/function-registry.d.mts +1 -2
- package/dist/cli/commands/deploy/idp.d.mts +2 -2
- package/dist/cli/commands/deploy/label.d.mts +2 -0
- package/dist/cli/commands/deploy/resolver.d.mts +2 -2
- package/dist/cli/commands/deploy/secret-manager.d.mts +1 -1
- package/dist/cli/commands/deploy/staticwebsite.d.mts +2 -2
- package/dist/cli/commands/deploy/tailordb/index.d.mts +4 -2
- package/dist/cli/commands/deploy/types.d.mts +2 -1
- package/dist/cli/commands/deploy/workflow-execution-policy.d.mts +1 -2
- package/dist/cli/commands/deploy/workflow.d.mts +2 -2
- package/dist/cli/commands/executor/get.d.mts +1 -10
- package/dist/cli/commands/executor/jobs.d.mts +1 -38
- package/dist/cli/commands/executor/trigger.d.mts +1 -11
- package/dist/cli/commands/generate/seed/bundler.d.mts +2 -1
- package/dist/cli/commands/tailordb/migrate/bundler.d.mts +3 -2
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +11 -1
- package/dist/cli/commands/tailordb/migrate/schema-checks.d.mts +5 -0
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +1 -1
- package/dist/cli/commands/workflow/executions.d.mts +1 -13
- package/dist/cli/commands/workflow/get.d.mts +1 -10
- package/dist/cli/commands/workflow/start.d.mts +2 -14
- package/dist/cli/index.mjs +12 -6552
- package/dist/cli/lib.d.mts +14 -15
- package/dist/cli/lib.mjs +203 -46
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/{index.d.mts → main.d.mts} +1 -1
- package/dist/cli/main.mjs +6777 -0
- package/dist/cli/main.mjs.map +1 -0
- package/dist/cli/services/http-adapter/bundler.d.mts +1 -0
- package/dist/cli/services/workflow/bundler.d.mts +2 -1
- package/dist/cli/shared/client.d.mts +28 -3
- package/dist/cli/shared/config-loader.d.mts +11 -4
- package/dist/cli/shared/error-json.d.mts +23 -0
- package/dist/cli/shared/script-executor.d.mts +6 -3
- package/dist/cli/shared/seed-chunker.d.mts +2 -7
- package/dist/cli/shared/seed-context.d.mts +49 -0
- package/dist/cli/shared/tailordb-namespaces.d.mts +7 -4
- package/dist/cli/shared/tsconfig-paths-plugin.d.mts +2 -0
- package/dist/cli/shared/type-generator.d.mts +4 -3
- package/dist/completion/zsh-worker.zsh +85 -22
- package/dist/configure/config/types.d.mts +29 -4
- package/dist/configure/index.d.mts +4 -3
- package/dist/configure/index.mjs +183 -6
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/executor/index.d.mts +2 -2
- package/dist/configure/services/executor/trigger/event.d.mts +245 -2
- package/dist/configure/services/executor/trigger/index.d.mts +3 -3
- package/dist/configure/services/idp/index.d.mts +2 -2
- package/dist/configure/services/idp/permission.d.mts +1 -16
- package/dist/configure/services/idp/types.d.mts +5 -1
- package/dist/configure/services/index.d.mts +4 -3
- package/dist/configure/services/resolver/index.d.mts +2 -1
- package/dist/configure/services/resolver/permission.d.mts +64 -0
- package/dist/configure/services/resolver/resolver.d.mts +14 -2
- package/dist/configure/services/tailordb/index.d.mts +0 -1
- package/dist/configure/services/tailordb/permission.d.mts +1 -16
- package/dist/configure/services/workflow/execution-policy.d.mts +3 -3
- package/dist/configure/services/workflow/execution-policy.types.d.mts +1 -1
- package/dist/configure/services/workflow/job.d.mts +11 -2
- package/dist/configure/services/workflow/workflow.d.mts +10 -0
- package/dist/configure/types/permission-operand.types.d.mts +20 -0
- package/dist/{crashreport-CxHne11E.mjs → crashreport-B5LqCTfF.mjs} +2 -2
- package/dist/{crashreport-CxHne11E.mjs.map → crashreport-B5LqCTfF.mjs.map} +1 -1
- package/dist/{crashreport-0ioNRZ4K.mjs → crashreport-eI7ty7ok.mjs} +1 -1
- package/dist/{errors-DfnF4ibq.mjs → errors-D7583Zz7.mjs} +2 -44
- package/dist/errors-D7583Zz7.mjs.map +1 -0
- package/dist/{globals-CBZ0egXT.mjs → globals-TfAVItuK.mjs} +21 -5
- package/dist/globals-TfAVItuK.mjs.map +1 -0
- package/dist/logger-BtX0suGY.mjs +48 -0
- package/dist/logger-BtX0suGY.mjs.map +1 -0
- package/dist/{logger-BwS4ppwO.mjs → logger-CXQq9YIp.mjs} +110 -13
- package/dist/logger-CXQq9YIp.mjs.map +1 -0
- package/dist/node-builtins-CmaL2Cbq.mjs +36 -0
- package/dist/node-builtins-CmaL2Cbq.mjs.map +1 -0
- package/dist/plugin/builtin/enum-constants/index.mjs +115 -2
- package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -0
- package/dist/plugin/builtin/file-utils/index.mjs +149 -2
- package/dist/plugin/builtin/file-utils/index.mjs.map +1 -0
- package/dist/plugin/builtin/kysely-type/index.mjs +274 -2
- package/dist/plugin/builtin/kysely-type/index.mjs.map +1 -0
- package/dist/plugin/builtin/seed/index.d.mts +3 -2
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/plugin/builtin/seed/seed-type-processor.d.mts +21 -0
- package/dist/plugin/builtin/seed/types.d.mts +2 -0
- package/dist/{register-ts-hook-DvEs6YsL.mjs → register-ts-hook-LYV7zH-e.mjs} +2953 -996
- package/dist/register-ts-hook-LYV7zH-e.mjs.map +1 -0
- package/dist/{registry-i7EdJ-D5.mjs → registry-BIGVUrMB.mjs} +3 -3
- package/dist/registry-BIGVUrMB.mjs.map +1 -0
- package/dist/runtime/globals.d.mts +7 -0
- package/dist/runtime/index.d.mts +3 -1
- package/dist/runtime/index.mjs +3 -2
- package/dist/runtime/logger.d.mts +98 -0
- package/dist/runtime/logger.mjs +3 -0
- package/dist/runtime/workflow.d.mts +15 -7
- package/dist/runtime/workflow.mjs +1 -1
- package/dist/seed-B-yckgQY.mjs +483 -0
- package/dist/seed-B-yckgQY.mjs.map +1 -0
- package/dist/{service-DaeJlBoH.mjs → service-B5WynBHQ.mjs} +3 -3
- package/dist/{service-DaeJlBoH.mjs.map → service-B5WynBHQ.mjs.map} +1 -1
- package/dist/service-M7OYziQP.mjs +3 -0
- package/dist/{service-Dmxa2I4i.mjs → service-k1xy_A5G.mjs} +30 -4
- package/dist/service-k1xy_A5G.mjs.map +1 -0
- package/dist/{service_pb-BoLM0X4K.mjs → service_pb-D5--My_M.mjs} +5 -5
- package/dist/service_pb-D5--My_M.mjs.map +1 -0
- package/dist/{service_pb-r1T7kpJc.mjs → service_pb-i8CmnQP4.mjs} +1 -1
- package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +106 -1
- package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +6 -1
- package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +24 -1
- package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +49 -1
- package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +89 -6
- package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +26 -1
- package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +101 -1
- package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +22 -1
- package/dist/types/auth.generated.d.mts +14 -2
- package/dist/types/executor.generated.d.mts +45 -3
- package/dist/types/http-adapter.generated.d.mts +5 -0
- package/dist/types/idp.generated.d.mts +31 -1
- package/dist/types/resolver.generated.d.mts +30 -2
- package/dist/types/tailordb.generated.d.mts +15 -3
- package/dist/utils/test/index.d.mts +1 -2
- package/dist/utils/test/index.mjs +1 -169
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +1 -1
- package/dist/vitest/index.d.mts +6 -4
- package/dist/vitest/index.mjs +112 -62
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mock.d.mts +2 -1
- package/dist/vitest/mocks/logger.d.mts +45 -0
- package/dist/vitest/mocks/workflow.d.mts +8 -8
- package/dist/vitest/setup.mjs +1 -1
- package/dist/{workflow-CsBvRE3g.mjs → workflow-Bamae_Yc.mjs} +5 -5
- package/dist/workflow-Bamae_Yc.mjs.map +1 -0
- package/dist/{workspace_resource_pb-Db3fv68L.mjs → workspace_resource_pb-DXnO2AT-.mjs} +13 -8
- package/dist/workspace_resource_pb-DXnO2AT-.mjs.map +1 -0
- package/docs/cli/application.md +5 -1
- package/docs/cli/tailordb.md +47 -13
- package/docs/cli-reference.md +38 -30
- package/docs/configuration.md +54 -2
- package/docs/github-actions.md +2 -2
- package/docs/migration/v2.md +408 -5
- package/docs/runtime.md +5 -1
- package/docs/services/executor.md +83 -3
- package/docs/services/idp.md +8 -6
- package/docs/services/resolver.md +60 -4
- package/docs/services/tailordb-migration.md +31 -7
- package/docs/services/tailordb.md +7 -5
- package/docs/services/workflow.md +33 -3
- package/docs/testing.md +34 -7
- package/package.json +31 -24
- package/dist/application-GzW98_Xr.mjs.map +0 -1
- package/dist/application-OM0taSPn.mjs +0 -3
- package/dist/cli/index.mjs.map +0 -1
- package/dist/enum-constants-j9QBF0cB.mjs +0 -116
- package/dist/enum-constants-j9QBF0cB.mjs.map +0 -1
- package/dist/errors-DfnF4ibq.mjs.map +0 -1
- package/dist/file-utils-yEiIS4nJ.mjs +0 -150
- package/dist/file-utils-yEiIS4nJ.mjs.map +0 -1
- package/dist/globals-CBZ0egXT.mjs.map +0 -1
- package/dist/kysely-type-DqIRgDYR.mjs +0 -275
- package/dist/kysely-type-DqIRgDYR.mjs.map +0 -1
- package/dist/logger-BwS4ppwO.mjs.map +0 -1
- package/dist/register-ts-hook-DvEs6YsL.mjs.map +0 -1
- package/dist/registry-i7EdJ-D5.mjs.map +0 -1
- package/dist/seed-CRSQJI_z.mjs +0 -1170
- package/dist/seed-CRSQJI_z.mjs.map +0 -1
- package/dist/service-BJAQ70e5.mjs +0 -3
- package/dist/service-Dmxa2I4i.mjs.map +0 -1
- package/dist/service_pb-BoLM0X4K.mjs.map +0 -1
- package/dist/utils/test/mock.d.mts +0 -86
- package/dist/workflow-CsBvRE3g.mjs.map +0 -1
- package/dist/workspace_resource_pb-Db3fv68L.mjs.map +0 -1
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
//#region src/plugin/builtin/enum-constants/generate-enum-constants.ts
|
|
2
|
-
/**
|
|
3
|
-
* Generate enum constant definitions from collected metadata.
|
|
4
|
-
* @param allEnums - All collected enum definitions
|
|
5
|
-
* @returns Generated enum constant definitions
|
|
6
|
-
*/
|
|
7
|
-
function generateUnifiedEnumConstants(allEnums) {
|
|
8
|
-
if (allEnums.length === 0) return "";
|
|
9
|
-
const enumMap = /* @__PURE__ */ new Map();
|
|
10
|
-
for (const enumDef of allEnums) enumMap.set(enumDef.name, enumDef);
|
|
11
|
-
const enumDefs = Array.from(enumMap.values()).map((e) => {
|
|
12
|
-
const members = e.values.map((v) => {
|
|
13
|
-
return ` "${v.value.replace(/[-\s]/g, "_")}": "${v.value}"`;
|
|
14
|
-
}).join(",\n");
|
|
15
|
-
const hasDescriptions = e.values.some((v) => v.description);
|
|
16
|
-
let jsDoc = "";
|
|
17
|
-
if (e.fieldDescription || hasDescriptions) {
|
|
18
|
-
const lines = [];
|
|
19
|
-
if (e.fieldDescription) {
|
|
20
|
-
lines.push(` * ${e.fieldDescription}`);
|
|
21
|
-
if (hasDescriptions) lines.push(" *");
|
|
22
|
-
}
|
|
23
|
-
if (hasDescriptions) {
|
|
24
|
-
const propertyDocs = e.values.map((v) => {
|
|
25
|
-
return ` * @property ${[v.value.replace(/[-\s]/g, "_"), v.description].filter(Boolean).join(" - ")}`;
|
|
26
|
-
});
|
|
27
|
-
lines.push(...propertyDocs);
|
|
28
|
-
}
|
|
29
|
-
if (lines.length > 0) jsDoc = `/**\n${lines.join("\n")}\n */\n`;
|
|
30
|
-
}
|
|
31
|
-
return `${`${jsDoc}export const ${e.name} = {\n${members}\n} as const;`}\n${`export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`}`;
|
|
32
|
-
}).join("\n\n");
|
|
33
|
-
if (!enumDefs) return "";
|
|
34
|
-
return enumDefs + "\n";
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
//#endregion
|
|
38
|
-
//#region src/plugin/builtin/enum-constants/process-enum-type.ts
|
|
39
|
-
function capitalizeFirst(str) {
|
|
40
|
-
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
41
|
-
}
|
|
42
|
-
function collectEnums(type) {
|
|
43
|
-
const enums = [];
|
|
44
|
-
for (const [fieldName, parsedField] of Object.entries(type.fields)) {
|
|
45
|
-
if (parsedField.config.type === "enum" && parsedField.config.allowedValues) {
|
|
46
|
-
const enumTypeName = `${type.name}${capitalizeFirst(fieldName)}`;
|
|
47
|
-
enums.push({
|
|
48
|
-
name: enumTypeName,
|
|
49
|
-
values: parsedField.config.allowedValues,
|
|
50
|
-
fieldDescription: parsedField.config.description
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
if (parsedField.config.type === "nested" && parsedField.config.fields) {
|
|
54
|
-
for (const [nestedFieldName, nestedFieldConfig] of Object.entries(parsedField.config.fields)) if (nestedFieldConfig.type === "enum" && nestedFieldConfig.allowedValues) {
|
|
55
|
-
const fullFieldName = `${fieldName}${capitalizeFirst(nestedFieldName)}`;
|
|
56
|
-
const enumTypeName = `${type.name}${capitalizeFirst(fullFieldName)}`;
|
|
57
|
-
enums.push({
|
|
58
|
-
name: enumTypeName,
|
|
59
|
-
values: nestedFieldConfig.allowedValues,
|
|
60
|
-
fieldDescription: nestedFieldConfig.description
|
|
61
|
-
});
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
return enums;
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* Process a TailorDB type and extract enum metadata.
|
|
69
|
-
* @param type - The parsed TailorDB type to process
|
|
70
|
-
* @returns Enum constant metadata for the type
|
|
71
|
-
*/
|
|
72
|
-
async function processEnumType(type) {
|
|
73
|
-
const enums = collectEnums(type);
|
|
74
|
-
return {
|
|
75
|
-
name: type.name,
|
|
76
|
-
enums
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
//#endregion
|
|
81
|
-
//#region src/plugin/builtin/enum-constants/index.ts
|
|
82
|
-
/** Unique identifier for the enum constants generator plugin. */
|
|
83
|
-
const EnumConstantsGeneratorID = "@tailor-platform/enum-constants";
|
|
84
|
-
/**
|
|
85
|
-
* Plugin that generates enum constants from TailorDB type definitions.
|
|
86
|
-
* @param options - Plugin options
|
|
87
|
-
* @param options.distPath - Output file path for generated constants
|
|
88
|
-
* @returns Plugin instance with onTailorDBReady hook
|
|
89
|
-
*/
|
|
90
|
-
function enumConstantsPlugin(options) {
|
|
91
|
-
return {
|
|
92
|
-
id: EnumConstantsGeneratorID,
|
|
93
|
-
description: "Generates enum constants from TailorDB type definitions",
|
|
94
|
-
pluginConfig: options,
|
|
95
|
-
async onTailorDBReady(ctx) {
|
|
96
|
-
const allEnums = [];
|
|
97
|
-
for (const ns of ctx.tailordb) for (const type of Object.values(ns.types)) {
|
|
98
|
-
const metadata = await processEnumType(type);
|
|
99
|
-
allEnums.push(...metadata.enums);
|
|
100
|
-
}
|
|
101
|
-
const files = [];
|
|
102
|
-
if (allEnums.length > 0) {
|
|
103
|
-
const content = generateUnifiedEnumConstants(allEnums);
|
|
104
|
-
files.push({
|
|
105
|
-
path: ctx.pluginConfig.distPath,
|
|
106
|
-
content
|
|
107
|
-
});
|
|
108
|
-
}
|
|
109
|
-
return { files };
|
|
110
|
-
}
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
//#endregion
|
|
115
|
-
export { enumConstantsPlugin as n, EnumConstantsGeneratorID as t };
|
|
116
|
-
//# sourceMappingURL=enum-constants-j9QBF0cB.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"enum-constants-j9QBF0cB.mjs","names":[],"sources":["../src/plugin/builtin/enum-constants/generate-enum-constants.ts","../src/plugin/builtin/enum-constants/process-enum-type.ts","../src/plugin/builtin/enum-constants/index.ts"],"sourcesContent":["import type { EnumDefinition } from \"./types\";\n\n/**\n * Generate enum constant definitions from collected metadata.\n * @param allEnums - All collected enum definitions\n * @returns Generated enum constant definitions\n */\nexport function generateUnifiedEnumConstants(allEnums: EnumDefinition[]): string {\n if (allEnums.length === 0) {\n return \"\";\n }\n\n const enumMap = new Map<string, EnumDefinition>();\n for (const enumDef of allEnums) {\n enumMap.set(enumDef.name, enumDef);\n }\n\n const enumDefs = Array.from(enumMap.values())\n .map((e) => {\n const members = e.values\n .map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` \"${key}\": \"${v.value}\"`;\n })\n .join(\",\\n\");\n\n const hasDescriptions = e.values.some((v) => v.description);\n let jsDoc = \"\";\n if (e.fieldDescription || hasDescriptions) {\n const lines: string[] = [];\n\n if (e.fieldDescription) {\n lines.push(` * ${e.fieldDescription}`);\n if (hasDescriptions) {\n lines.push(\" *\");\n }\n }\n\n if (hasDescriptions) {\n const propertyDocs = e.values.map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` * @property ${[key, v.description].filter(Boolean).join(\" - \")}`;\n });\n lines.push(...propertyDocs);\n }\n\n if (lines.length > 0) {\n jsDoc = `/**\\n${lines.join(\"\\n\")}\\n */\\n`;\n }\n }\n\n const constDef = `${jsDoc}export const ${e.name} = {\\n${members}\\n} as const;`;\n const typeDef = `export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`;\n return `${constDef}\\n${typeDef}`;\n })\n .join(\"\\n\\n\");\n\n if (!enumDefs) {\n return \"\";\n }\n\n return enumDefs + \"\\n\";\n}\n","import type { TailorDBType } from \"#/parser/service/tailordb/types\";\nimport type { EnumConstantMetadata } from \"./types\";\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nfunction collectEnums(type: TailorDBType): EnumConstantMetadata[\"enums\"] {\n const enums: EnumConstantMetadata[\"enums\"] = [];\n\n for (const [fieldName, parsedField] of Object.entries(type.fields)) {\n if (parsedField.config.type === \"enum\" && parsedField.config.allowedValues) {\n const enumTypeName = `${type.name}${capitalizeFirst(fieldName)}`;\n enums.push({\n name: enumTypeName,\n values: parsedField.config.allowedValues,\n fieldDescription: parsedField.config.description,\n });\n }\n\n // Process nested fields\n if (parsedField.config.type === \"nested\" && parsedField.config.fields) {\n for (const [nestedFieldName, nestedFieldConfig] of Object.entries(\n parsedField.config.fields,\n )) {\n if (nestedFieldConfig.type === \"enum\" && nestedFieldConfig.allowedValues) {\n const fullFieldName = `${fieldName}${capitalizeFirst(nestedFieldName)}`;\n const enumTypeName = `${type.name}${capitalizeFirst(fullFieldName)}`;\n enums.push({\n name: enumTypeName,\n values: nestedFieldConfig.allowedValues,\n fieldDescription: nestedFieldConfig.description,\n });\n }\n }\n }\n }\n\n return enums;\n}\n\n/**\n * Process a TailorDB type and extract enum metadata.\n * @param type - The parsed TailorDB type to process\n * @returns Enum constant metadata for the type\n */\nexport async function processEnumType(type: TailorDBType): Promise<EnumConstantMetadata> {\n const enums = collectEnums(type);\n\n return {\n name: type.name,\n enums,\n };\n}\n","import { generateUnifiedEnumConstants } from \"./generate-enum-constants\";\nimport { processEnumType } from \"./process-enum-type\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\nimport type { EnumDefinition } from \"./types\";\n\n/** Unique identifier for the enum constants generator plugin. */\nexport const EnumConstantsGeneratorID = \"@tailor-platform/enum-constants\";\n\ntype EnumConstantsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates enum constants from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated constants\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function enumConstantsPlugin(\n options: EnumConstantsPluginOptions,\n): Plugin<unknown, EnumConstantsPluginOptions> {\n return {\n id: EnumConstantsGeneratorID,\n description: \"Generates enum constants from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<EnumConstantsPluginOptions>,\n ): Promise<GeneratorResult> {\n const allEnums: EnumDefinition[] = [];\n\n for (const ns of ctx.tailordb) {\n for (const type of Object.values(ns.types)) {\n const metadata = await processEnumType(type);\n allEnums.push(...metadata.enums);\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allEnums.length > 0) {\n const content = generateUnifiedEnumConstants(allEnums);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;AAOA,SAAgB,6BAA6B,UAAoC;CAC/E,IAAI,SAAS,WAAW,GACtB,OAAO;CAGT,MAAM,0BAAU,IAAI,IAA4B;CAChD,KAAK,MAAM,WAAW,UACpB,QAAQ,IAAI,QAAQ,MAAM,OAAO;CAGnC,MAAM,WAAW,MAAM,KAAK,QAAQ,OAAO,CAAC,CAAC,CAC1C,KAAK,MAAM;EACV,MAAM,UAAU,EAAE,OACf,KAAK,MAAM;GAEV,OAAO,MADK,EAAE,MAAM,QAAQ,UAAU,GACvB,EAAE,MAAM,EAAE,MAAM;EACjC,CAAC,CAAC,CACD,KAAK,KAAK;EAEb,MAAM,kBAAkB,EAAE,OAAO,MAAM,MAAM,EAAE,WAAW;EAC1D,IAAI,QAAQ;EACZ,IAAI,EAAE,oBAAoB,iBAAiB;GACzC,MAAM,QAAkB,CAAC;GAEzB,IAAI,EAAE,kBAAkB;IACtB,MAAM,KAAK,MAAM,EAAE,kBAAkB;IACrC,IAAI,iBACF,MAAM,KAAK,IAAI;GAEnB;GAEA,IAAI,iBAAiB;IACnB,MAAM,eAAe,EAAE,O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kB;KAC1B,kBAAkB,kBAAkB;IACtC,CAAC;GACH;EACF;CAEJ;CAEA,OAAO;AACT;;;;;;AAOA,eAAsB,gBAAgB,MAAmD;CACvF,MAAM,QAAQ,aAAa,IAAI;CAE/B,OAAO;EACL,MAAM,KAAK;EACX;CACF;AACF;;;;;AC/CA,MAAa,2BAA2B;;;;;;;AAYxC,SAAgB,oBACd,SAC6C;CAC7C,OAAO;EACL,IAAI;EACJ,aAAa;EACb,cAAc;EAEd,MAAM,gBACJ,KAC0B;GAC1B,MAAM,WAA6B,CAAC;GAEpC,KAAK,MAAM,MAAM,IAAI,UACnB,KAAK,MAAM,QAAQ,OAAO,OAAO,GAAG,KAAK,GAAG;IAC1C,MAAM,WAAW,MAAM,gBAAgB,IAAI;IAC3C,SAAS,KAAK,GAAG,SAAS,KAAK;GACjC;GAGF,MAAM,QAAkC,CAAC;GACzC,IAAI,SAAS,SAAS,GAAG;IACvB,MAAM,UAAU,6BAA6B,QAAQ;IACrD,MAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;IACF,CAAC;GACH;GAEA,OAAO,EAAE,MAAM;EACjB;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-DfnF4ibq.mjs","names":[],"sources":["../src/cli/shared/errors.ts"],"sourcesContent":["import { Code, ConnectError } from \"@connectrpc/connect\";\nimport chalk from \"chalk\";\n\n/**\n * Options for creating a CLI error\n */\nexport interface CLIErrorOptions {\n message: string;\n details?: string;\n suggestion?: string;\n command?: string;\n code?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, unknown>>;\n}\n\nexport interface CLIErrorNextAction {\n /** Executable name, such as `tailor-sdk`. */\n command: string;\n /** Arguments passed directly to the executable. */\n args: readonly string[];\n}\n\nexport interface ErrorToJsonOptions {\n includeStack?: boolean;\n}\n\n/**\n * CLI error interface with formatted output\n */\nexport interface CLIError extends Error {\n readonly code?: string;\n readonly details?: string;\n readonly suggestion?: string;\n readonly command?: string;\n readonly next?: CLIErrorNextAction;\n readonly context?: Readonly<Record<string, unknown>>;\n format(): string;\n}\n\ntype CLIErrorInternal = Error & {\n code?: string;\n details?: string;\n suggestion?: string;\n command?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, unknown>>;\n format(): string;\n};\n\nfunction shellQuote(value: string): string {\n if (process.platform === \"win32\") {\n if (/^[A-Za-z0-9_./:=@+\\\\-]+$/.test(value)) return value;\n return `\"${value.replaceAll('\"', '\\\\\"')}\"`;\n }\n if (/^[A-Za-z0-9_./:=@+-]+$/.test(value)) return value;\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction formatNextAction(next: CLIErrorNextAction): string {\n const argv = [next.command, ...next.args];\n if (process.platform === \"win32\" && argv.some((value) => /[%$!]/.test(value))) {\n return `with argv ${JSON.stringify(argv)}`;\n }\n return `\\`${argv.map(shellQuote).join(\" \")}\\``;\n}\n\n/**\n * Format CLI error for output\n * @param error - CLIError instance to format\n * @returns Formatted error message\n */\nfunction formatError(error: CLIError): string {\n const parts: string[] = [\n chalk.red(`Error${error.code ? ` [${error.code}]` : \"\"}: ${error.message}`),\n ];\n\n if (error.details) {\n parts.push(`\\n ${chalk.gray(\"Details:\")} ${error.details}`);\n }\n\n if (error.suggestion) {\n parts.push(`\\n ${chalk.cyan(\"Suggestion:\")} ${error.suggestion}`);\n }\n\n if (error.command) {\n parts.push(\n `\\n ${chalk.gray(\"Help:\")} Run \\`tailor ${error.command} --help\\` for usage information.`,\n );\n }\n\n if (error.next) {\n parts.push(`\\n ${chalk.cyan(\"Next:\")} Run ${formatNextAction(error.next)}.`);\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Create a CLI error with formatted output\n * @param options - Options to construct a CLIError\n * @returns Constructed CLIError instance\n */\nfunction createCLIError(options: CLIErrorOptions): CLIError {\n const error = new Error(options.message) as CLIErrorInternal;\n error.name = \"CLIError\";\n error.code = options.code;\n error.details = options.details;\n error.suggestion = options.suggestion;\n error.command = options.command;\n error.next = options.next;\n error.context = options.context;\n error.format = () => formatError(error);\n return error;\n}\n\n/**\n * Type guard to check if an error is a CLIError\n * @param error - Error to check\n * @returns True if the error is a CLIError\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\n/**\n * Convert a CLI failure into the stable JSON error envelope.\n * @param error - Failure to serialize\n * @param options - JSON serialization options\n * @returns JSON-compatible error envelope\n */\nexport function errorToJson(\n error: unknown,\n options?: ErrorToJsonOptions,\n): { error: Readonly<Record<string, unknown>> } {\n if (isCLIError(error)) {\n return {\n error: {\n code: error.code ?? \"CLI_ERROR\",\n message: error.message,\n ...(error.details ? { details: error.details } : {}),\n ...(error.suggestion ? { suggestion: error.suggestion } : {}),\n ...(error.command\n ? {\n help: executableHelpAction(error.command),\n }\n : {}),\n ...(error.next ? { next: error.next } : {}),\n ...(error.context ? { context: error.context } : {}),\n ...(options?.includeStack && error.stack ? { stack: error.stack } : {}),\n },\n };\n }\n if (error instanceof ConnectError) {\n const codeName = Code[error.code];\n const stableCode =\n typeof codeName === \"string\"\n ? codeName.replaceAll(/([a-z0-9])([A-Z])/g, \"$1_$2\").toUpperCase()\n : `CODE_${error.code}`;\n return {\n error: {\n code: `RPC_${stableCode}`,\n message: error.message,\n ...(options?.includeStack && error.stack ? { stack: error.stack } : {}),\n },\n };\n }\n if (error instanceof Error) {\n return {\n error: {\n code: error.name === \"CIPromptError\" ? \"INTERACTIVE_PROMPT_REQUIRED\" : \"UNEXPECTED_ERROR\",\n message: error.message,\n ...(options?.includeStack && error.stack ? { stack: error.stack } : {}),\n },\n };\n }\n return { error: { code: \"UNKNOWN_ERROR\", message: String(error) } };\n}\n\nfunction executableHelpAction(command: string): CLIErrorNextAction {\n return {\n command: \"tailor-sdk\",\n args: [...command.split(/\\s+/).filter(Boolean), \"--help\"],\n };\n}\n\n// Re-export createCLIError as CLIError for backward compatibility\nexport { createCLIError as CLIError };\n"],"mappings":";;;;AAkDA,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;EAAE,MAAM;EAAiB,SAAS,OAAO,KAAK;CAAE,EAAE;AACpE;AAEA,SAAS,qBAAqB,SAAqC;CACjE,OAAO;EACL,SAAS;EACT,MAAM,CAAC,GAAG,QAAQ,MAAM,KAAK,CAAC,CAAC,OAAO,OAAO,GAAG,QAAQ;CAC1D;AACF"}
|
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
import { t as multiline } from "./multiline-sfHpTZZK.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/plugin/builtin/file-utils/generate-file-utils.ts
|
|
4
|
-
/**
|
|
5
|
-
* Generate unified file utility functions from collected metadata.
|
|
6
|
-
* @param namespaceData - Namespace data with file utility metadata
|
|
7
|
-
* @returns Generated file utility code
|
|
8
|
-
*/
|
|
9
|
-
function generateUnifiedFileUtils(namespaceData) {
|
|
10
|
-
if (namespaceData.length === 0) return "";
|
|
11
|
-
const typeNamespaceMap = /* @__PURE__ */ new Map();
|
|
12
|
-
const typeFieldsMap = /* @__PURE__ */ new Map();
|
|
13
|
-
for (const { namespace, types } of namespaceData) for (const type of types) {
|
|
14
|
-
typeNamespaceMap.set(type.name, namespace);
|
|
15
|
-
typeFieldsMap.set(type.name, type.fileFields);
|
|
16
|
-
}
|
|
17
|
-
if (typeNamespaceMap.size === 0) return "";
|
|
18
|
-
const interfaceFields = Array.from(typeFieldsMap.entries()).map(([typeName, fields]) => {
|
|
19
|
-
return ` ${typeName}: {\n fields: ${fields.map((field) => `"${field}"`).join(" | ")};\n };`;
|
|
20
|
-
}).join("\n");
|
|
21
|
-
return [
|
|
22
|
-
multiline`
|
|
23
|
-
import { file } from "@tailor-platform/sdk/runtime/file";
|
|
24
|
-
import type {
|
|
25
|
-
FileUploadOptions,
|
|
26
|
-
FileUploadResponse,
|
|
27
|
-
FileMetadata,
|
|
28
|
-
FileDownloadStreamResponse,
|
|
29
|
-
} from "@tailor-platform/sdk/runtime/file";
|
|
30
|
-
` + "\n",
|
|
31
|
-
multiline`
|
|
32
|
-
export interface TypeWithFiles {
|
|
33
|
-
${interfaceFields}
|
|
34
|
-
}
|
|
35
|
-
` + "\n",
|
|
36
|
-
multiline`
|
|
37
|
-
const namespaces: Record<keyof TypeWithFiles, string> = {
|
|
38
|
-
${Array.from(typeNamespaceMap.entries()).map(([typeName, namespace]) => ` ${typeName}: "${namespace}"`).join(",\n")},
|
|
39
|
-
};
|
|
40
|
-
` + "\n",
|
|
41
|
-
multiline`
|
|
42
|
-
export async function downloadFile<T extends keyof TypeWithFiles>(
|
|
43
|
-
type: T,
|
|
44
|
-
field: TypeWithFiles[T]["fields"],
|
|
45
|
-
recordId: string,
|
|
46
|
-
) {
|
|
47
|
-
return await file.download(namespaces[type], type, field, recordId);
|
|
48
|
-
}
|
|
49
|
-
` + "\n",
|
|
50
|
-
multiline`
|
|
51
|
-
export async function uploadFile<T extends keyof TypeWithFiles>(
|
|
52
|
-
type: T,
|
|
53
|
-
field: TypeWithFiles[T]["fields"],
|
|
54
|
-
recordId: string,
|
|
55
|
-
data: string | ArrayBuffer | Uint8Array<ArrayBufferLike> | number[],
|
|
56
|
-
options?: FileUploadOptions,
|
|
57
|
-
): Promise<FileUploadResponse> {
|
|
58
|
-
return await file.upload(namespaces[type], type, field, recordId, data, options);
|
|
59
|
-
}
|
|
60
|
-
` + "\n",
|
|
61
|
-
multiline`
|
|
62
|
-
export async function deleteFile<T extends keyof TypeWithFiles>(
|
|
63
|
-
type: T,
|
|
64
|
-
field: TypeWithFiles[T]["fields"],
|
|
65
|
-
recordId: string,
|
|
66
|
-
): Promise<void> {
|
|
67
|
-
return await file.delete(namespaces[type], type, field, recordId);
|
|
68
|
-
}
|
|
69
|
-
` + "\n",
|
|
70
|
-
multiline`
|
|
71
|
-
export async function getFileMetadata<T extends keyof TypeWithFiles>(
|
|
72
|
-
type: T,
|
|
73
|
-
field: TypeWithFiles[T]["fields"],
|
|
74
|
-
recordId: string,
|
|
75
|
-
): Promise<FileMetadata> {
|
|
76
|
-
return await file.getMetadata(namespaces[type], type, field, recordId);
|
|
77
|
-
}
|
|
78
|
-
` + "\n",
|
|
79
|
-
multiline`
|
|
80
|
-
export async function downloadFileStream<T extends keyof TypeWithFiles>(
|
|
81
|
-
type: T,
|
|
82
|
-
field: TypeWithFiles[T]["fields"],
|
|
83
|
-
recordId: string,
|
|
84
|
-
): Promise<FileDownloadStreamResponse> {
|
|
85
|
-
return await file.downloadStream(namespaces[type], type, field, recordId);
|
|
86
|
-
}
|
|
87
|
-
` + "\n"
|
|
88
|
-
].join("\n");
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
//#endregion
|
|
92
|
-
//#region src/plugin/builtin/file-utils/process-file-type.ts
|
|
93
|
-
/**
|
|
94
|
-
* Process a TailorDB type and extract file field metadata.
|
|
95
|
-
* @param type - The parsed TailorDB type to process
|
|
96
|
-
* @returns File utility metadata for the type
|
|
97
|
-
*/
|
|
98
|
-
async function processFileType(type) {
|
|
99
|
-
const fileFields = [];
|
|
100
|
-
if (type.files) for (const fileFieldName of Object.keys(type.files)) fileFields.push(fileFieldName);
|
|
101
|
-
return {
|
|
102
|
-
name: type.name,
|
|
103
|
-
fileFields
|
|
104
|
-
};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
//#endregion
|
|
108
|
-
//#region src/plugin/builtin/file-utils/index.ts
|
|
109
|
-
/** Unique identifier for the file utilities generator plugin. */
|
|
110
|
-
const FileUtilsGeneratorID = "@tailor-platform/file-utils";
|
|
111
|
-
/**
|
|
112
|
-
* Plugin that generates TypeWithFiles interface from TailorDB type definitions.
|
|
113
|
-
* @param options - Plugin options
|
|
114
|
-
* @param options.distPath - Output file path for generated file utilities
|
|
115
|
-
* @returns Plugin instance with onTailorDBReady hook
|
|
116
|
-
*/
|
|
117
|
-
function fileUtilsPlugin(options) {
|
|
118
|
-
return {
|
|
119
|
-
id: FileUtilsGeneratorID,
|
|
120
|
-
description: "Generates TypeWithFiles interface from TailorDB type definitions",
|
|
121
|
-
pluginConfig: options,
|
|
122
|
-
async onTailorDBReady(ctx) {
|
|
123
|
-
const namespaceData = [];
|
|
124
|
-
for (const ns of ctx.tailordb) {
|
|
125
|
-
const typesWithFiles = [];
|
|
126
|
-
for (const type of Object.values(ns.types)) {
|
|
127
|
-
const metadata = await processFileType(type);
|
|
128
|
-
if (metadata.fileFields.length > 0) typesWithFiles.push(metadata);
|
|
129
|
-
}
|
|
130
|
-
if (typesWithFiles.length > 0) namespaceData.push({
|
|
131
|
-
namespace: ns.namespace,
|
|
132
|
-
types: typesWithFiles
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
const files = [];
|
|
136
|
-
if (namespaceData.length > 0) {
|
|
137
|
-
const content = generateUnifiedFileUtils(namespaceData);
|
|
138
|
-
if (content) files.push({
|
|
139
|
-
path: ctx.pluginConfig.distPath,
|
|
140
|
-
content
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
return { files };
|
|
144
|
-
}
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
//#endregion
|
|
149
|
-
export { fileUtilsPlugin as n, FileUtilsGeneratorID as t };
|
|
150
|
-
//# sourceMappingURL=file-utils-yEiIS4nJ.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"file-utils-yEiIS4nJ.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 \"#/utils/multiline\";\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 importStatement =\n multiline /* ts */ `\n import { file } from \"@tailor-platform/sdk/runtime/file\";\n import type {\n FileUploadOptions,\n FileUploadResponse,\n FileMetadata,\n FileDownloadStreamResponse,\n } from \"@tailor-platform/sdk/runtime/file\";\n ` + \"\\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 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 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 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 file.getMetadata(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate downloadFileStream helper function\n const downloadStreamFunction =\n multiline /* ts */ `\n export async function downloadFileStream<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileDownloadStreamResponse> {\n return await file.downloadStream(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n return [\n importStatement,\n interfaceDefinition,\n namespacesDefinition,\n downloadFunction,\n uploadFunction,\n deleteFunction,\n getMetadataFunction,\n downloadStreamFunction,\n ].join(\"\\n\");\n}\n","import type { TailorDBType } from \"#/parser/service/tailordb/types\";\nimport type { FileUtilMetadata } from \"./types\";\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 { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\nimport type { FileUtilMetadata } from \"./types\";\n\n/** Unique identifier for the file utilities generator plugin. */\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;CACR,IAAI,cAAc,WAAW,GAC3B,OAAO;CAIT,MAAM,mCAAmB,IAAI,IAAoB;CACjD,MAAM,gCAAgB,IAAI,IAAsB;CAEhD,KAAK,MAAM,EAAE,WAAW,WAAW,eACjC,KAAK,MAAM,QAAQ,OAAO;EACxB,iBAAiB,IAAI,KAAK,MAAM,SAAS;EACzC,cAAc,IAAI,KAAK,MAAM,KAAK,UAAU;CAC9C;CAGF,IAAI,iBAAiB,SAAS,GAC5B,OAAO;CAIT,MAAM,kBAAkB,MAAM,KAAK,cAAc,QAAQ,CAAC,CAAC,CACxD,KAAK,CAAC,UAAU,YAAY;EAE3B,OAAO,KAAK,SAAS,mBADG,OAAO,KAAK,UAAU,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,KAC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a;IACtD,IAAI,SACF,MAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;IACF,CAAC;GAEL;GAEA,OAAO,EAAE,MAAM;EACjB;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"globals-CBZ0egXT.mjs","names":[],"sources":["../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["// Default `tailor.workflow` runner installed by the `tailor-runtime` environment.\n// Must stay free of `vitest` (`vi`): it loads via `./globals` in the environment\n// realm where `vi` is unavailable, hence relative imports only (no `@/` alias).\nimport { START_DEFAULT } from \"../configure/services/workflow/registry\";\nimport { platformSerialize } from \"../utils/test/platform-serialize\";\nimport type { StartJobFunctionOptions, StartWorkflowOptions } from \"../runtime/workflow\";\n\nexport interface DefaultWorkflowRuntime {\n startJobFunction: (name: string, args?: unknown, options?: StartJobFunctionOptions) => unknown;\n startWorkflow: (name: string, args?: unknown, options?: StartWorkflowOptions) => Promise<string>;\n resumeWorkflowExecution: (executionId: string) => Promise<string>;\n wait: (key: string, payload?: unknown) => unknown;\n resolve: (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => Promise<void>;\n}\n\nexport function createDefaultWorkflowRuntime(): DefaultWorkflowRuntime {\n const startJobFunction: DefaultWorkflowRuntime[\"startJobFunction\"] = (name) => {\n throw new Error(\n `No workflow job mock for \"${name}\". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`,\n );\n };\n const startWorkflow: DefaultWorkflowRuntime[\"startWorkflow\"] = async (_name, args) => {\n platformSerialize(args);\n return START_DEFAULT;\n };\n const resumeWorkflowExecution: DefaultWorkflowRuntime[\"resumeWorkflowExecution\"] = async (\n executionId,\n ) => executionId;\n return {\n startJobFunction,\n startWorkflow,\n resumeWorkflowExecution,\n wait: (key: string): unknown => {\n throw new Error(\n `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n );\n },\n resolve: async (): Promise<void> => {\n throw new Error(\n \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n );\n },\n };\n}\n","/**\n * Base platform globals for the tailor-runtime test environment.\n *\n * This module is intentionally free of any `vitest` (`vi`) dependency so it can\n * be imported from the Vitest *environment* module (which runs in a realm where\n * `vi` is not available). It installs only the always-present structural pieces:\n *\n * - `globalThis.tailor` / `globalThis.tailordb` container objects\n * - `globalThis.tailor.context.getInvoker` default stub\n * - the platform error classes (`TailorErrors`, `TailorErrorMessage`,\n * `TailorDBFileError`)\n * - the `__tailorRuntimeActive` sentinel flag\n *\n * The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)\n * is installed on demand by the `xMock()` factories in `./mock`, which run in\n * test context where `vi` *is* available.\n */\n\nimport { createDefaultWorkflowRuntime } from \"./workflow-runtime\";\nimport type { ContextInvoker } from \"../runtime/context\";\nimport type { TailorDBFileErrorCode } from \"../runtime/file\";\n\n// Sentinel set when the tailor-runtime environment is active. setup.ts reads it\n// to decide whether to run its blocked-globals lifecycle and config-secret\n// loading.\nexport const RUNTIME_FLAG_KEY = \"__tailorRuntimeActive\";\n\n// ---------------------------------------------------------------------------\n// Error class mocks\n// ---------------------------------------------------------------------------\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\nclass TailorErrorsMock extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n if (!Array.isArray(errors)) {\n throw new TypeError(\"TailorErrors: errors must be an array\");\n }\n const validated = errors.map((e, i) => {\n if (typeof e.message !== \"string\") {\n throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);\n }\n if (!Array.isArray(e.path)) {\n throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);\n }\n return { message: e.message, path: e.path };\n });\n // Match the PF runtime's TailorErrors serialization, which prefixes the\n // JSON payload with \"TailorErrors: \". Other SDK code (e.g. apply\n // integration fixtures) strips this prefix before JSON.parse.\n super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);\n this.name = \"TailorErrors\";\n this.errors = validated;\n }\n}\n\nclass TailorErrorMessageMock extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TailorErrorMessage\";\n }\n}\n\nclass TailorDBFileErrorMock extends Error {\n code?: TailorDBFileErrorCode;\n override cause: unknown;\n\n constructor(message: string, code?: TailorDBFileErrorCode, cause?: unknown) {\n super(message);\n this.name = \"TailorDBFileError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Base install / cleanup\n// ---------------------------------------------------------------------------\n\n// Stub-only injection. SDK consumers configure invokers at the body level\n// (resolver/executor/workflow `.body()` `invoker` arg) or, for bundled tests,\n// via `vi.spyOn(globalThis.tailor.context, \"getInvoker\")`.\nfunction defaultGetInvoker(): ContextInvoker | null {\n return null;\n}\n\n/**\n * Install the always-present base platform globals (containers, context stub,\n * error classes, runtime flag). Per-namespace mocks are layered on top by the\n * `xMock()` factories in `./mock`.\n * @param global - The global object to install into (typically `globalThis`)\n */\nexport function installPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n\n g[RUNTIME_FLAG_KEY] = true;\n\n // Containers. Namespace mocks (secretmanager, …) are added to these by the\n // corresponding `xMock()` on acquisition. `workflow` carries a default\n // runner: job/wait/resolve calls throw a helpful error, and workflow starts\n // return a placeholder execution id, unless overlaid by `mockWorkflow()` or\n // `runWorkflowLocally()`.\n g.tailor = {\n context: { getInvoker: defaultGetInvoker },\n workflow: createDefaultWorkflowRuntime(),\n };\n g.tailordb = {};\n\n g.TailorErrors = TailorErrorsMock;\n g.TailorErrorMessage = TailorErrorMessageMock;\n g.TailorDBFileError = TailorDBFileErrorMock;\n}\n\n/**\n * Remove the base platform globals (and anything the namespace mocks layered on\n * top, since they live under the same containers).\n * @param global - The global object to clean up (typically `globalThis`)\n */\nexport function cleanupPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n delete g.tailordb;\n delete g.tailor;\n delete g.TailorErrors;\n del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,OAAO;EACZ,KAAK,QAAQ;CACf;AACF;AASA,SAAS,oBAA2C;CAClD,OAAO;AACT;;;;;;;AAQA,SAAgB,uBAAuB,QAAiC;CACtE,MAAM,IAAI;CAEV,EAAE,oBAAoB;CAOtB,EAAE,SAAS;EACT,SAAS,EAAE,YAAY,kBAAkB;EACzC,UAAU,6BAA6B;CACzC;CACA,EAAE,WAAW,CAAC;CAEd,EAAE,eAAe;CACjB,EAAE,qBAAqB;CACvB,EAAE,oBAAoB;AACxB;;;;;;AAOA,SAAgB,uBAAuB,QAAiC;CACtE,MAAM,IAAI;CACV,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;CACT,OAAO,EAAE;AACX"}
|
|
@@ -1,275 +0,0 @@
|
|
|
1
|
-
import { t as multiline } from "./multiline-sfHpTZZK.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/plugin/builtin/kysely-type/type-processor.ts
|
|
4
|
-
/**
|
|
5
|
-
* Get the enum type definition.
|
|
6
|
-
* @param fieldConfig - The field configuration
|
|
7
|
-
* @returns The enum type as a string union
|
|
8
|
-
*/
|
|
9
|
-
function getEnumType(fieldConfig) {
|
|
10
|
-
const allowedValues = fieldConfig.allowedValues;
|
|
11
|
-
if (allowedValues && Array.isArray(allowedValues)) return allowedValues.map((v) => {
|
|
12
|
-
return `"${typeof v === "string" ? v : v.value}"`;
|
|
13
|
-
}).join(" | ");
|
|
14
|
-
return "string";
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Get the nested object type definition.
|
|
18
|
-
* @param fieldConfig - The field configuration
|
|
19
|
-
* @returns The nested type with used utility types
|
|
20
|
-
*/
|
|
21
|
-
function getNestedType(fieldConfig) {
|
|
22
|
-
const fields = fieldConfig.fields;
|
|
23
|
-
if (!fields || typeof fields !== "object") return {
|
|
24
|
-
type: "string",
|
|
25
|
-
usedUtilityTypes: {
|
|
26
|
-
Timestamp: false,
|
|
27
|
-
Serial: false
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
const fieldResults = Object.entries(fields).map(([fieldName, config]) => {
|
|
31
|
-
const result = generateFieldType(config);
|
|
32
|
-
return {
|
|
33
|
-
fieldType: `${fieldName}${config.required !== true ? "?" : ""}: ${result.type}`,
|
|
34
|
-
usedUtilityTypes: result.usedUtilityTypes
|
|
35
|
-
};
|
|
36
|
-
});
|
|
37
|
-
const aggregatedUtilityTypes = fieldResults.reduce((acc, result) => ({
|
|
38
|
-
Timestamp: acc.Timestamp || result.usedUtilityTypes.Timestamp,
|
|
39
|
-
Serial: acc.Serial || result.usedUtilityTypes.Serial
|
|
40
|
-
}), {
|
|
41
|
-
Timestamp: false,
|
|
42
|
-
Serial: false
|
|
43
|
-
});
|
|
44
|
-
const fieldTypes = fieldResults.map((r) => r.fieldType);
|
|
45
|
-
const obj = `{\n ${fieldTypes.join(";\n ")}${fieldTypes.length > 0 ? ";" : ""}\n}`;
|
|
46
|
-
const hasOptionalFields = Object.values(fields).some((config) => config.required !== true);
|
|
47
|
-
const hasGeneratedFields = Object.values(fields).some((config) => config.hooks?.create || config.default !== void 0);
|
|
48
|
-
if (aggregatedUtilityTypes.Timestamp || hasOptionalFields || hasGeneratedFields) return {
|
|
49
|
-
type: `ObjectColumnType<${obj}>`,
|
|
50
|
-
usedUtilityTypes: aggregatedUtilityTypes
|
|
51
|
-
};
|
|
52
|
-
return {
|
|
53
|
-
type: obj,
|
|
54
|
-
usedUtilityTypes: aggregatedUtilityTypes
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
/**
|
|
58
|
-
* Get the base Kysely type for a field (without array/null modifiers).
|
|
59
|
-
* @param fieldConfig - The field configuration
|
|
60
|
-
* @returns The base type with used utility types
|
|
61
|
-
*/
|
|
62
|
-
function getBaseType(fieldConfig) {
|
|
63
|
-
const fieldType = fieldConfig.type;
|
|
64
|
-
const usedUtilityTypes = {
|
|
65
|
-
Timestamp: false,
|
|
66
|
-
Serial: false
|
|
67
|
-
};
|
|
68
|
-
let type;
|
|
69
|
-
switch (fieldType) {
|
|
70
|
-
case "uuid":
|
|
71
|
-
case "string":
|
|
72
|
-
case "decimal":
|
|
73
|
-
type = "string";
|
|
74
|
-
break;
|
|
75
|
-
case "integer":
|
|
76
|
-
case "float":
|
|
77
|
-
type = "number";
|
|
78
|
-
break;
|
|
79
|
-
case "date":
|
|
80
|
-
case "datetime":
|
|
81
|
-
usedUtilityTypes.Timestamp = true;
|
|
82
|
-
type = "Timestamp";
|
|
83
|
-
break;
|
|
84
|
-
case "bool":
|
|
85
|
-
case "boolean":
|
|
86
|
-
type = "boolean";
|
|
87
|
-
break;
|
|
88
|
-
case "enum":
|
|
89
|
-
type = getEnumType(fieldConfig);
|
|
90
|
-
break;
|
|
91
|
-
case "nested": return getNestedType(fieldConfig);
|
|
92
|
-
default:
|
|
93
|
-
type = "string";
|
|
94
|
-
break;
|
|
95
|
-
}
|
|
96
|
-
return {
|
|
97
|
-
type,
|
|
98
|
-
usedUtilityTypes
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
/**
|
|
102
|
-
* Generate the complete field type including array and null modifiers.
|
|
103
|
-
* @param fieldConfig - The field configuration
|
|
104
|
-
* @returns The complete field type with used utility types
|
|
105
|
-
*/
|
|
106
|
-
function generateFieldType(fieldConfig) {
|
|
107
|
-
const baseTypeResult = getBaseType(fieldConfig);
|
|
108
|
-
const usedUtilityTypes = { ...baseTypeResult.usedUtilityTypes };
|
|
109
|
-
const isArray = fieldConfig.array === true;
|
|
110
|
-
const isNullable = fieldConfig.required !== true;
|
|
111
|
-
const isColumnTypeBase = (/* @__PURE__ */ new Set(["Timestamp"])).has(baseTypeResult.type);
|
|
112
|
-
let finalType = baseTypeResult.type;
|
|
113
|
-
if (isArray) if (isColumnTypeBase || finalType.startsWith("ObjectColumnType<")) finalType = `ArrayColumnType<${baseTypeResult.type}>`;
|
|
114
|
-
else finalType = fieldConfig.type === "enum" ? `(${baseTypeResult.type})[]` : `${baseTypeResult.type}[]`;
|
|
115
|
-
if (isNullable) finalType = `${finalType} | null`;
|
|
116
|
-
if (fieldConfig.serial) {
|
|
117
|
-
usedUtilityTypes.Serial = true;
|
|
118
|
-
finalType = `Serial<${finalType}>`;
|
|
119
|
-
}
|
|
120
|
-
if (fieldConfig.hooks?.create || fieldConfig.default !== void 0) finalType = `Generated<${finalType}>`;
|
|
121
|
-
return {
|
|
122
|
-
type: finalType,
|
|
123
|
-
usedUtilityTypes
|
|
124
|
-
};
|
|
125
|
-
}
|
|
126
|
-
/**
|
|
127
|
-
* Generate the table interface.
|
|
128
|
-
* @param type - The parsed TailorDB type
|
|
129
|
-
* @returns The type definition and used utility types
|
|
130
|
-
*/
|
|
131
|
-
function generateTableInterface(type) {
|
|
132
|
-
const fieldResults = Object.entries(type.fields).filter(([fieldName]) => fieldName !== "id").map(([fieldName, parsedField]) => ({
|
|
133
|
-
fieldName,
|
|
134
|
-
...generateFieldType(parsedField.config)
|
|
135
|
-
}));
|
|
136
|
-
const fields = ["id: Generated<string>;", ...fieldResults.map((result) => `${result.fieldName}: ${result.type};`)];
|
|
137
|
-
const aggregatedUtilityTypes = fieldResults.reduce((acc, result) => ({
|
|
138
|
-
Timestamp: acc.Timestamp || result.usedUtilityTypes.Timestamp,
|
|
139
|
-
Serial: acc.Serial || result.usedUtilityTypes.Serial
|
|
140
|
-
}), {
|
|
141
|
-
Timestamp: false,
|
|
142
|
-
Serial: false
|
|
143
|
-
});
|
|
144
|
-
return {
|
|
145
|
-
typeDef: multiline`
|
|
146
|
-
${type.name}: {
|
|
147
|
-
${fields.join("\n")}
|
|
148
|
-
}
|
|
149
|
-
`,
|
|
150
|
-
usedUtilityTypes: aggregatedUtilityTypes
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* Convert a TailorDBType into KyselyTypeMetadata.
|
|
155
|
-
* @param type - Parsed TailorDB type
|
|
156
|
-
* @returns Generated Kysely type metadata
|
|
157
|
-
*/
|
|
158
|
-
async function processKyselyType(type) {
|
|
159
|
-
const result = generateTableInterface(type);
|
|
160
|
-
return {
|
|
161
|
-
name: type.name,
|
|
162
|
-
typeDef: result.typeDef,
|
|
163
|
-
usedUtilityTypes: result.usedUtilityTypes
|
|
164
|
-
};
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Generate unified types file from multiple namespaces.
|
|
168
|
-
* @param namespaceData - Namespace metadata
|
|
169
|
-
* @returns Generated types file contents
|
|
170
|
-
*/
|
|
171
|
-
function generateUnifiedKyselyTypes(namespaceData) {
|
|
172
|
-
if (namespaceData.length === 0) return "";
|
|
173
|
-
const globalUsedUtilityTypes = namespaceData.reduce((acc, ns) => ({
|
|
174
|
-
Timestamp: acc.Timestamp || ns.usedUtilityTypes.Timestamp,
|
|
175
|
-
Serial: acc.Serial || ns.usedUtilityTypes.Serial
|
|
176
|
-
}), {
|
|
177
|
-
Timestamp: false,
|
|
178
|
-
Serial: false
|
|
179
|
-
});
|
|
180
|
-
const utilityTypeImports = ["type Generated"];
|
|
181
|
-
if (globalUsedUtilityTypes.Timestamp) utilityTypeImports.push("type Timestamp");
|
|
182
|
-
if (namespaceData.some((ns) => ns.types.some((t) => t.typeDef.includes("ObjectColumnType<")))) utilityTypeImports.push("type ObjectColumnType");
|
|
183
|
-
if (namespaceData.some((ns) => ns.types.some((t) => t.typeDef.includes("ArrayColumnType<")))) utilityTypeImports.push("type ArrayColumnType");
|
|
184
|
-
if (globalUsedUtilityTypes.Serial) utilityTypeImports.push("type Serial");
|
|
185
|
-
return [
|
|
186
|
-
multiline`
|
|
187
|
-
import {
|
|
188
|
-
createGetDB,
|
|
189
|
-
${utilityTypeImports.join(",\n")},
|
|
190
|
-
type NamespaceDB,
|
|
191
|
-
type NamespaceInsertable,
|
|
192
|
-
type NamespaceSelectable,
|
|
193
|
-
type NamespaceTable,
|
|
194
|
-
type NamespaceTableName,
|
|
195
|
-
type NamespaceTransaction,
|
|
196
|
-
type NamespaceUpdateable,
|
|
197
|
-
} from "@tailor-platform/sdk/kysely";
|
|
198
|
-
`,
|
|
199
|
-
`export interface Namespace {\n${namespaceData.map(({ namespace, types }) => {
|
|
200
|
-
return ` "${namespace}": {\n${types.map((type) => {
|
|
201
|
-
return type.typeDef.split("\n").map((line) => line.trim() ? ` ${line}` : "").join("\n");
|
|
202
|
-
}).join("\n\n")}\n }`;
|
|
203
|
-
}).join(",\n")}\n}`,
|
|
204
|
-
multiline`
|
|
205
|
-
export const getDB = createGetDB<Namespace>();
|
|
206
|
-
|
|
207
|
-
export type DB<N extends keyof Namespace = keyof Namespace> = NamespaceDB<Namespace, N>;
|
|
208
|
-
`,
|
|
209
|
-
multiline`
|
|
210
|
-
export type Transaction<K extends keyof Namespace | DB = keyof Namespace> =
|
|
211
|
-
NamespaceTransaction<Namespace, K>;
|
|
212
|
-
|
|
213
|
-
type TableName = NamespaceTableName<Namespace>;
|
|
214
|
-
export type Table<T extends TableName> = NamespaceTable<Namespace, T>;
|
|
215
|
-
|
|
216
|
-
export type Insertable<T extends TableName> = NamespaceInsertable<Namespace, T>;
|
|
217
|
-
export type Selectable<T extends TableName> = NamespaceSelectable<Namespace, T>;
|
|
218
|
-
export type Updateable<T extends TableName> = NamespaceUpdateable<Namespace, T>;
|
|
219
|
-
`
|
|
220
|
-
].join("\n\n") + "\n";
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
//#endregion
|
|
224
|
-
//#region src/plugin/builtin/kysely-type/index.ts
|
|
225
|
-
/** Unique identifier for the Kysely type generator plugin. */
|
|
226
|
-
const KyselyGeneratorID = "@tailor-platform/kysely-type";
|
|
227
|
-
/**
|
|
228
|
-
* Plugin that generates Kysely type definitions for TailorDB types.
|
|
229
|
-
* @param options - Plugin options
|
|
230
|
-
* @param options.distPath - Output file path for generated types
|
|
231
|
-
* @returns Plugin instance with onTailorDBReady hook
|
|
232
|
-
*/
|
|
233
|
-
function kyselyTypePlugin(options) {
|
|
234
|
-
return {
|
|
235
|
-
id: KyselyGeneratorID,
|
|
236
|
-
description: "Generates Kysely type definitions for TailorDB types",
|
|
237
|
-
pluginConfig: options,
|
|
238
|
-
async onTailorDBReady(ctx) {
|
|
239
|
-
const allNamespaceData = [];
|
|
240
|
-
for (const ns of ctx.tailordb) {
|
|
241
|
-
const typeMetadataList = [];
|
|
242
|
-
for (const type of Object.values(ns.types)) {
|
|
243
|
-
const metadata = await processKyselyType(type);
|
|
244
|
-
typeMetadataList.push(metadata);
|
|
245
|
-
}
|
|
246
|
-
if (typeMetadataList.length === 0) continue;
|
|
247
|
-
const usedUtilityTypes = typeMetadataList.reduce((acc, type) => ({
|
|
248
|
-
Timestamp: acc.Timestamp || type.usedUtilityTypes.Timestamp,
|
|
249
|
-
Serial: acc.Serial || type.usedUtilityTypes.Serial
|
|
250
|
-
}), {
|
|
251
|
-
Timestamp: false,
|
|
252
|
-
Serial: false
|
|
253
|
-
});
|
|
254
|
-
allNamespaceData.push({
|
|
255
|
-
namespace: ns.namespace,
|
|
256
|
-
types: typeMetadataList,
|
|
257
|
-
usedUtilityTypes
|
|
258
|
-
});
|
|
259
|
-
}
|
|
260
|
-
const files = [];
|
|
261
|
-
if (allNamespaceData.length > 0) {
|
|
262
|
-
const content = generateUnifiedKyselyTypes(allNamespaceData);
|
|
263
|
-
files.push({
|
|
264
|
-
path: ctx.pluginConfig.distPath,
|
|
265
|
-
content
|
|
266
|
-
});
|
|
267
|
-
}
|
|
268
|
-
return { files };
|
|
269
|
-
}
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
//#endregion
|
|
274
|
-
export { kyselyTypePlugin as n, KyselyGeneratorID as t };
|
|
275
|
-
//# sourceMappingURL=kysely-type-DqIRgDYR.mjs.map
|