@tailor-platform/sdk 1.83.0 → 1.85.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 +58 -0
- package/dist/application-C-zsrNjn.mjs +3 -0
- package/dist/{application-Cp0FxIm2.mjs → application-m5tYtz0-.mjs} +246 -68
- package/dist/application-m5tYtz0-.mjs.map +1 -0
- package/dist/cli/commands/deploy/tailordb/index.d.mts +2 -0
- package/dist/cli/commands/generate/seed/bundler.d.mts +2 -1
- package/dist/cli/commands/generate/service.d.mts +1 -1
- package/dist/cli/commands/generate/types.d.mts +1 -1
- 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/index.mjs +291 -29
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.d.mts +1 -1
- package/dist/cli/lib.mjs +92 -36
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/shared/client.d.mts +28 -3
- package/dist/cli/skills.d.mts +1 -1
- package/dist/completion/zsh-worker.zsh +85 -22
- package/dist/configure/index.d.mts +2 -2
- package/dist/configure/index.mjs +170 -2
- 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/index.d.mts +2 -2
- package/dist/configure/services/tailordb/index.d.mts +0 -1
- package/dist/configure/services/workflow/job.d.mts +9 -0
- package/dist/configure/services/workflow/workflow.d.mts +10 -0
- package/dist/node-builtins-CmaL2Cbq.mjs +36 -0
- package/dist/node-builtins-CmaL2Cbq.mjs.map +1 -0
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/{register-typescript-runtime-CCHyKeXO.mjs → register-typescript-runtime-nG-n9lPw.mjs} +752 -403
- package/dist/register-typescript-runtime-nG-n9lPw.mjs.map +1 -0
- package/dist/{seed-DFFigL8V.mjs → seed-6eTFj-3Q.mjs} +158 -41
- package/dist/seed-6eTFj-3Q.mjs.map +1 -0
- package/dist/{service-B0MaodSg.mjs → service-CPJWhTLn.mjs} +29 -2
- package/dist/service-CPJWhTLn.mjs.map +1 -0
- package/dist/service-Cigg_U-v.mjs +3 -0
- package/dist/{service_pb-BwZRiNug.mjs → service_pb-D5--My_M.mjs} +5 -5
- package/dist/service_pb-D5--My_M.mjs.map +1 -0
- package/dist/{service_pb-wRkxUta6.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/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/executor.generated.d.mts +23 -3
- package/dist/vitest/index.mjs +3 -35
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/{workspace_resource_pb-UGK1SSn_.mjs → workspace_resource_pb-DXnO2AT-.mjs} +7 -7
- package/dist/workspace_resource_pb-DXnO2AT-.mjs.map +1 -0
- package/docs/cli/tailordb.md +36 -12
- package/docs/cli-reference.md +16 -15
- package/docs/generator/builtin.md +7 -0
- package/docs/services/executor.md +83 -3
- package/docs/services/idp.md +3 -3
- package/docs/services/tailordb-migration.md +24 -4
- package/docs/services/workflow.md +26 -0
- package/package.json +17 -18
- package/dist/application-CP7JKG9R.mjs +0 -3
- package/dist/application-Cp0FxIm2.mjs.map +0 -1
- package/dist/register-typescript-runtime-CCHyKeXO.mjs.map +0 -1
- package/dist/seed-DFFigL8V.mjs.map +0 -1
- package/dist/service-B0MaodSg.mjs.map +0 -1
- package/dist/service-KnAiVofD.mjs +0 -3
- package/dist/service_pb-BwZRiNug.mjs.map +0 -1
- package/dist/workspace_resource_pb-UGK1SSn_.mjs.map +0 -1
|
@@ -35,10 +35,32 @@ function generateIdpSeedScriptCode(idpNamespace) {
|
|
|
35
35
|
const client = new tailor.idp.Client({ namespace: "${idpNamespace}" });
|
|
36
36
|
const errors = [];
|
|
37
37
|
let processed = 0;
|
|
38
|
+
let created = 0;
|
|
39
|
+
let updated = 0;
|
|
40
|
+
const upsert = input.upsert === true;
|
|
38
41
|
|
|
39
42
|
for (let i = 0; i < input.users.length; i++) {
|
|
40
43
|
try {
|
|
41
|
-
|
|
44
|
+
if (upsert) {
|
|
45
|
+
let existing;
|
|
46
|
+
try {
|
|
47
|
+
existing = await client.userByName(input.users[i].name);
|
|
48
|
+
} catch {
|
|
49
|
+
existing = undefined;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (existing) {
|
|
53
|
+
const { name, ...attributes } = input.users[i];
|
|
54
|
+
await client.updateUser({ id: existing.id, ...attributes });
|
|
55
|
+
updated++;
|
|
56
|
+
} else {
|
|
57
|
+
await client.createUser(input.users[i]);
|
|
58
|
+
created++;
|
|
59
|
+
}
|
|
60
|
+
} else {
|
|
61
|
+
await client.createUser(input.users[i]);
|
|
62
|
+
created++;
|
|
63
|
+
}
|
|
42
64
|
processed++;
|
|
43
65
|
console.log(\`[_User] \${i + 1}/\${input.users.length}: \${input.users[i].name}\`);
|
|
44
66
|
} catch (error) {
|
|
@@ -51,6 +73,8 @@ function generateIdpSeedScriptCode(idpNamespace) {
|
|
|
51
73
|
return {
|
|
52
74
|
success: errors.length === 0,
|
|
53
75
|
processed,
|
|
76
|
+
created,
|
|
77
|
+
updated,
|
|
54
78
|
errors,
|
|
55
79
|
};
|
|
56
80
|
}
|
|
@@ -353,6 +377,57 @@ function generateLinesDbSchemaFileWithPluginAPI(metadata, params) {
|
|
|
353
377
|
`;
|
|
354
378
|
}
|
|
355
379
|
|
|
380
|
+
//#endregion
|
|
381
|
+
//#region src/plugin/builtin/seed/seed-data-loader.ts
|
|
382
|
+
/**
|
|
383
|
+
* Generate the JSONL seed-data loader embedded in `exec.mjs`.
|
|
384
|
+
* @returns JavaScript source defining `loadSeedData`
|
|
385
|
+
*/
|
|
386
|
+
function generateSeedDataLoaderCode() {
|
|
387
|
+
return multiline`
|
|
388
|
+
const loadSeedData = (
|
|
389
|
+
dataDir,
|
|
390
|
+
typeNames,
|
|
391
|
+
{ requireId = false, requiredFieldsByType = {} } = {},
|
|
392
|
+
) => {
|
|
393
|
+
const data = {};
|
|
394
|
+
for (const typeName of typeNames) {
|
|
395
|
+
const jsonlPath = join(dataDir, \`\${typeName}.jsonl\`);
|
|
396
|
+
try {
|
|
397
|
+
const lines = readFileSync(jsonlPath, "utf-8").split("\\n");
|
|
398
|
+
const records = [];
|
|
399
|
+
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
|
|
400
|
+
if (lines[lineIndex].trim() === "") continue;
|
|
401
|
+
const record = JSON.parse(lines[lineIndex]);
|
|
402
|
+
if (requireId && (record?.id === undefined || record?.id === null)) {
|
|
403
|
+
throw new Error(
|
|
404
|
+
\`\${jsonlPath}:\${lineIndex + 1}: \\\`id\\\` is required with --upsert\`,
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
const missingRequiredField = (requiredFieldsByType[typeName] || []).find(
|
|
408
|
+
(field) => record?.[field] === undefined || record?.[field] === null,
|
|
409
|
+
);
|
|
410
|
+
if (missingRequiredField) {
|
|
411
|
+
throw new Error(
|
|
412
|
+
\`\${jsonlPath}:\${lineIndex + 1}: field \\\`\${missingRequiredField}\\\` is required with --upsert\`,
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
records.push(record);
|
|
416
|
+
}
|
|
417
|
+
data[typeName] = records;
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if (error.code === "ENOENT") {
|
|
420
|
+
data[typeName] = [];
|
|
421
|
+
} else {
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return data;
|
|
427
|
+
};
|
|
428
|
+
`;
|
|
429
|
+
}
|
|
430
|
+
|
|
356
431
|
//#endregion
|
|
357
432
|
//#region src/plugin/builtin/seed/seed-type-processor.ts
|
|
358
433
|
/**
|
|
@@ -428,7 +503,7 @@ function generateIdpUserSeedFunction(hasIdpUser, idpNamespace) {
|
|
|
428
503
|
workspaceId,
|
|
429
504
|
name: "seed-idp-user.ts",
|
|
430
505
|
code: idpSeedCode,
|
|
431
|
-
arg: JSON.stringify({ users: rows }),
|
|
506
|
+
arg: JSON.stringify({ users: rows, upsert: values.upsert }),
|
|
432
507
|
invoker: {
|
|
433
508
|
namespace: authNamespace,
|
|
434
509
|
machineUserName,
|
|
@@ -450,9 +525,15 @@ function generateIdpUserSeedFunction(hasIdpUser, idpNamespace) {
|
|
|
450
525
|
return { success: false };
|
|
451
526
|
}
|
|
452
527
|
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
528
|
+
const message = values.upsert
|
|
529
|
+
? \`\${parsed.created || 0} created, \${parsed.updated || 0} updated\`
|
|
530
|
+
: \`\${parsed.processed || 0} rows processed\`;
|
|
531
|
+
console.log(
|
|
532
|
+
styleText(
|
|
533
|
+
"green",
|
|
534
|
+
\` ✓ _User: \${message}\`,
|
|
535
|
+
),
|
|
536
|
+
);
|
|
456
537
|
|
|
457
538
|
if (!parsed.success) {
|
|
458
539
|
const errors = Array.isArray(parsed.errors) ? parsed.errors : [];
|
|
@@ -589,6 +670,7 @@ function generateExecScript(defaultMachineUserName, relativeConfigPath, namespac
|
|
|
589
670
|
const namespaceSelfRefEntries = namespaceConfigs.map(({ namespace, selfRefTypes }) => {
|
|
590
671
|
return ` "${namespace}": [${selfRefTypes.map((t) => `"${t}"`).join(", ")}]`;
|
|
591
672
|
}).join(",\n");
|
|
673
|
+
const requiredFieldsEntries = namespaceConfigs.flatMap(({ requiredFields }) => Object.entries(requiredFields)).map(([type, fields]) => ` "${type}": ${JSON.stringify(fields)}`).join(",\n");
|
|
592
674
|
return multiline`
|
|
593
675
|
/**
|
|
594
676
|
* @generated
|
|
@@ -596,7 +678,7 @@ function generateExecScript(defaultMachineUserName, relativeConfigPath, namespac
|
|
|
596
678
|
* Do not edit by hand: changes will be overwritten on the next \`sdk generate\`.
|
|
597
679
|
*/
|
|
598
680
|
import { readFileSync } from "node:fs";
|
|
599
|
-
import { join, isAbsolute } from "node:path";
|
|
681
|
+
import { dirname, join, isAbsolute } from "node:path";
|
|
600
682
|
import { parseArgs, styleText } from "node:util";
|
|
601
683
|
import { createInterface } from "node:readline";
|
|
602
684
|
import {
|
|
@@ -669,6 +751,7 @@ function generateExecScript(defaultMachineUserName, relativeConfigPath, namespac
|
|
|
669
751
|
namespace: { type: "string", short: "n" },
|
|
670
752
|
"skip-idp": { type: "boolean", default: false },
|
|
671
753
|
truncate: { type: "boolean", default: false },
|
|
754
|
+
upsert: { type: "boolean", default: false },
|
|
672
755
|
yes: { type: "boolean", default: false },
|
|
673
756
|
profile: { type: "string", short: "p" },
|
|
674
757
|
help: { type: "boolean", short: "h", default: false },
|
|
@@ -688,6 +771,7 @@ function generateExecScript(defaultMachineUserName, relativeConfigPath, namespac
|
|
|
688
771
|
-n, --namespace <ns> Process all types in specified namespace (excludes _User)
|
|
689
772
|
--skip-idp Skip IdP user (_User) entity
|
|
690
773
|
--truncate Truncate tables before seeding
|
|
774
|
+
--upsert Update existing rows instead of failing on duplicate ids
|
|
691
775
|
--yes Skip confirmation prompts (for truncate)
|
|
692
776
|
-p, --profile <name> Workspace profile name
|
|
693
777
|
-h, --help Show help
|
|
@@ -701,6 +785,7 @@ function generateExecScript(defaultMachineUserName, relativeConfigPath, namespac
|
|
|
701
785
|
node exec.mjs --truncate --yes # Truncate all tables without confirmation, then seed all
|
|
702
786
|
node exec.mjs --truncate --namespace <namespace> # Truncate tailordb, then seed tailordb
|
|
703
787
|
node exec.mjs --truncate User Order # Truncate User and Order, then seed them
|
|
788
|
+
node exec.mjs --upsert # Seed all, updating rows whose id already exists
|
|
704
789
|
node exec.mjs validate # Validate all seed data
|
|
705
790
|
node exec.mjs validate ./data/User.jsonl # Validate specific file
|
|
706
791
|
\`);
|
|
@@ -725,6 +810,8 @@ function generateExecScript(defaultMachineUserName, relativeConfigPath, namespac
|
|
|
725
810
|
const configDir = import.meta.dirname;
|
|
726
811
|
const configPath = join(configDir, "${relativeConfigPath}");
|
|
727
812
|
|
|
813
|
+
${generateSeedDataLoaderCode().replace(/^/gm, " ")}
|
|
814
|
+
|
|
728
815
|
// Determine machine user name (CLI argument takes precedence over config default)
|
|
729
816
|
const defaultMachineUser = ${defaultMachineUserName ? `"${defaultMachineUserName}"` : "undefined"};
|
|
730
817
|
const machineUserName = values["machine-user"] || defaultMachineUser;
|
|
@@ -744,6 +831,9 @@ ${namespaceDepsEntries}
|
|
|
744
831
|
};
|
|
745
832
|
const namespaceSelfRefTypes = {
|
|
746
833
|
${namespaceSelfRefEntries}
|
|
834
|
+
};
|
|
835
|
+
const requiredFieldsByType = {
|
|
836
|
+
${requiredFieldsEntries}
|
|
747
837
|
};
|
|
748
838
|
const entities = Object.values(namespaceEntities).flat();
|
|
749
839
|
const hasIdpUser = ${String(hasIdpUser)};
|
|
@@ -814,6 +904,25 @@ ${namespaceSelfRefEntries}
|
|
|
814
904
|
}
|
|
815
905
|
}
|
|
816
906
|
|
|
907
|
+
const selectedTailorDbTypes = entities.filter(
|
|
908
|
+
(entity) => !entitiesToProcess || entitiesToProcess.includes(entity),
|
|
909
|
+
);
|
|
910
|
+
const loadSelectedTailorDbSeedData = () =>
|
|
911
|
+
loadSeedData(join(configDir, "data"), selectedTailorDbTypes, {
|
|
912
|
+
requireId: values.upsert,
|
|
913
|
+
requiredFieldsByType: values.upsert ? requiredFieldsByType : {},
|
|
914
|
+
});
|
|
915
|
+
let tailorDbSeedData;
|
|
916
|
+
if (values.upsert) {
|
|
917
|
+
try {
|
|
918
|
+
tailorDbSeedData = loadSelectedTailorDbSeedData();
|
|
919
|
+
} catch (error) {
|
|
920
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
921
|
+
console.error(styleText("red", \`\\n✗ Seed data generation failed: \${message}\`));
|
|
922
|
+
process.exit(1);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
817
926
|
// Get application info
|
|
818
927
|
const appInfo = await show({ configPath, profile: values.profile });
|
|
819
928
|
const authNamespace = appInfo.auth;
|
|
@@ -875,29 +984,6 @@ ${namespaceSelfRefEntries}
|
|
|
875
984
|
console.log(styleText("dim", \` Skipping IdP user (_User)\`));
|
|
876
985
|
}
|
|
877
986
|
|
|
878
|
-
// Load seed data from JSONL files
|
|
879
|
-
const loadSeedData = (dataDir, typeNames) => {
|
|
880
|
-
const data = {};
|
|
881
|
-
for (const typeName of typeNames) {
|
|
882
|
-
const jsonlPath = join(dataDir, \`\${typeName}.jsonl\`);
|
|
883
|
-
try {
|
|
884
|
-
const content = readFileSync(jsonlPath, "utf-8").trim();
|
|
885
|
-
if (content) {
|
|
886
|
-
data[typeName] = content.split("\\n").map((line) => JSON.parse(line));
|
|
887
|
-
} else {
|
|
888
|
-
data[typeName] = [];
|
|
889
|
-
}
|
|
890
|
-
} catch (error) {
|
|
891
|
-
if (error.code === "ENOENT") {
|
|
892
|
-
data[typeName] = [];
|
|
893
|
-
} else {
|
|
894
|
-
throw error;
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
return data;
|
|
899
|
-
};
|
|
900
|
-
|
|
901
987
|
// Topological sort for dependency order
|
|
902
988
|
const topologicalSort = (types, deps) => {
|
|
903
989
|
const visited = new Set();
|
|
@@ -922,10 +1008,17 @@ ${namespaceSelfRefEntries}
|
|
|
922
1008
|
};
|
|
923
1009
|
|
|
924
1010
|
// Seed TailorDB types via testExecScript
|
|
925
|
-
const seedViaTestExecScript = async (
|
|
926
|
-
|
|
1011
|
+
const seedViaTestExecScript = async (
|
|
1012
|
+
namespace,
|
|
1013
|
+
typesToSeed,
|
|
1014
|
+
deps,
|
|
1015
|
+
selfRefTypes,
|
|
1016
|
+
seedDataByType,
|
|
1017
|
+
) => {
|
|
927
1018
|
const sortedTypes = topologicalSort(typesToSeed, deps);
|
|
928
|
-
const data =
|
|
1019
|
+
const data = Object.fromEntries(
|
|
1020
|
+
sortedTypes.map((type) => [type, seedDataByType[type] || []]),
|
|
1021
|
+
);
|
|
929
1022
|
|
|
930
1023
|
// Skip if no data
|
|
931
1024
|
const typesWithData = sortedTypes.filter((t) => data[t] && data[t].length > 0);
|
|
@@ -934,10 +1027,10 @@ ${namespaceSelfRefEntries}
|
|
|
934
1027
|
return { success: true, processed: {} };
|
|
935
1028
|
}
|
|
936
1029
|
|
|
937
|
-
console.log(styleText("cyan", \` [\${namespace}] Seeding \${typesWithData.length} types via Kysely batch insert...\`));
|
|
1030
|
+
console.log(styleText("cyan", \` [\${namespace}] Seeding \${typesWithData.length} types via Kysely batch \${values.upsert ? "upsert" : "insert"}...\`));
|
|
938
1031
|
|
|
939
1032
|
// Bundle seed script
|
|
940
|
-
const bundled = await bundleSeedScript(namespace, typesWithData);
|
|
1033
|
+
const bundled = await bundleSeedScript(namespace, typesWithData, dirname(configPath));
|
|
941
1034
|
|
|
942
1035
|
// Chunk seed data to fit within gRPC message size limits
|
|
943
1036
|
const chunks = chunkSeedData({
|
|
@@ -970,7 +1063,7 @@ ${namespaceSelfRefEntries}
|
|
|
970
1063
|
workspaceId,
|
|
971
1064
|
name: \`seed-\${namespace}.ts\`,
|
|
972
1065
|
code: bundled.bundledCode,
|
|
973
|
-
arg: JSON.stringify({ data: chunk.data, order: chunk.order, selfRefTypes }),
|
|
1066
|
+
arg: JSON.stringify({ data: chunk.data, order: chunk.order, selfRefTypes, upsert: values.upsert }),
|
|
974
1067
|
invoker: {
|
|
975
1068
|
namespace: authNamespace,
|
|
976
1069
|
machineUserName,
|
|
@@ -998,9 +1091,23 @@ ${namespaceSelfRefEntries}
|
|
|
998
1091
|
}
|
|
999
1092
|
|
|
1000
1093
|
const processed = parsed.processed || {};
|
|
1001
|
-
for (const [type,
|
|
1002
|
-
|
|
1003
|
-
|
|
1094
|
+
for (const [type, counts] of Object.entries(processed)) {
|
|
1095
|
+
const previous = allProcessed[type] || { inserted: 0, updated: 0, skipped: 0 };
|
|
1096
|
+
const current = {
|
|
1097
|
+
inserted: Number(counts.inserted) || 0,
|
|
1098
|
+
updated: Number(counts.updated) || 0,
|
|
1099
|
+
skipped: Number(counts.skipped) || 0,
|
|
1100
|
+
};
|
|
1101
|
+
allProcessed[type] = {
|
|
1102
|
+
inserted: previous.inserted + current.inserted,
|
|
1103
|
+
updated: previous.updated + current.updated,
|
|
1104
|
+
skipped: previous.skipped + current.skipped,
|
|
1105
|
+
};
|
|
1106
|
+
const skipped = current.skipped > 0 ? \`, \${current.skipped} skipped\` : "";
|
|
1107
|
+
const message = values.upsert
|
|
1108
|
+
? \`\${current.inserted} inserted, \${current.updated} updated\${skipped}\`
|
|
1109
|
+
: \`\${current.inserted} rows inserted\`;
|
|
1110
|
+
console.log(styleText("green", \` ✓ \${type}: \${message}\`));
|
|
1004
1111
|
}
|
|
1005
1112
|
|
|
1006
1113
|
if (!parsed.success) {
|
|
@@ -1029,6 +1136,7 @@ ${namespaceSelfRefEntries}
|
|
|
1029
1136
|
// Main execution
|
|
1030
1137
|
try {
|
|
1031
1138
|
let allSuccess = true;
|
|
1139
|
+
tailorDbSeedData ??= loadSelectedTailorDbSeedData();
|
|
1032
1140
|
|
|
1033
1141
|
// Determine which namespaces and types to process
|
|
1034
1142
|
const namespacesToProcess = hasNamespace
|
|
@@ -1047,7 +1155,13 @@ ${namespaceSelfRefEntries}
|
|
|
1047
1155
|
|
|
1048
1156
|
if (typesToSeed.length === 0) continue;
|
|
1049
1157
|
|
|
1050
|
-
const result = await seedViaTestExecScript(
|
|
1158
|
+
const result = await seedViaTestExecScript(
|
|
1159
|
+
namespace,
|
|
1160
|
+
typesToSeed,
|
|
1161
|
+
nsDeps,
|
|
1162
|
+
nsSelfRefTypes,
|
|
1163
|
+
tailorDbSeedData,
|
|
1164
|
+
);
|
|
1051
1165
|
if (!result.success) {
|
|
1052
1166
|
allSuccess = false;
|
|
1053
1167
|
}
|
|
@@ -1091,6 +1205,7 @@ function seedPlugin(options) {
|
|
|
1091
1205
|
const types = [];
|
|
1092
1206
|
const dependencies = {};
|
|
1093
1207
|
const selfRefTypes = [];
|
|
1208
|
+
const requiredFields = {};
|
|
1094
1209
|
for (const [typeName, type] of Object.entries(ns.types)) {
|
|
1095
1210
|
const source = assertDefined(ns.sourceInfo.get(typeName), `source info missing for type: ${typeName}`);
|
|
1096
1211
|
const typeInfo = processSeedTypeInfo(type, ns.namespace);
|
|
@@ -1104,6 +1219,7 @@ function seedPlugin(options) {
|
|
|
1104
1219
|
});
|
|
1105
1220
|
types.push(typeInfo.name);
|
|
1106
1221
|
dependencies[typeInfo.name] = typeInfo.dependencies;
|
|
1222
|
+
requiredFields[typeInfo.name] = Object.entries(type.fields).filter(([fieldName, field]) => field.config.required !== false && !linesDb.optionalFields.includes(fieldName) && !linesDb.omitFields.includes(fieldName)).map(([fieldName]) => fieldName);
|
|
1107
1223
|
if (typeInfo.selfRefFields.length > 0) selfRefTypes.push(typeInfo.name);
|
|
1108
1224
|
files.push({
|
|
1109
1225
|
path: path.join(ctx.pluginConfig.distPath, typeInfo.dataFile),
|
|
@@ -1138,7 +1254,8 @@ function seedPlugin(options) {
|
|
|
1138
1254
|
namespace: ns.namespace,
|
|
1139
1255
|
types,
|
|
1140
1256
|
dependencies,
|
|
1141
|
-
selfRefTypes
|
|
1257
|
+
selfRefTypes,
|
|
1258
|
+
requiredFields
|
|
1142
1259
|
});
|
|
1143
1260
|
}
|
|
1144
1261
|
if (idpUser) {
|
|
@@ -1168,4 +1285,4 @@ function seedPlugin(options) {
|
|
|
1168
1285
|
|
|
1169
1286
|
//#endregion
|
|
1170
1287
|
export { seedPlugin as n, SeedGeneratorID as t };
|
|
1171
|
-
//# sourceMappingURL=seed-
|
|
1288
|
+
//# sourceMappingURL=seed-6eTFj-3Q.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"seed-6eTFj-3Q.mjs","names":["ml"],"sources":["../src/plugin/builtin/seed/idp-user-processor.ts","../src/plugin/builtin/seed/lines-db-processor.ts","../src/plugin/builtin/seed/seed-data-loader.ts","../src/plugin/builtin/seed/seed-type-processor.ts","../src/plugin/builtin/seed/template-literal.ts","../src/plugin/builtin/seed/index.ts"],"sourcesContent":["import ml from \"#/utils/multiline\";\nimport type { GeneratorAuthInput } from \"#/plugin/types\";\n\nexport interface IdpUserMetadata {\n name: \"_User\";\n dependencies: string[];\n dataFile: string;\n idpNamespace: string;\n schema: {\n usernameField: string;\n userTypeName: string;\n };\n}\n\n/**\n * Processes auth configuration to generate IdP user seed metadata\n * @param auth - Auth configuration from generator\n * @returns IdP user metadata or undefined if not applicable\n */\nexport function processIdpUser(auth: GeneratorAuthInput): IdpUserMetadata | undefined {\n // Only process if idProvider is BuiltInIdP and userProfile is defined\n if (auth.idProvider?.kind !== \"BuiltInIdP\" || !auth.userProfile) {\n return undefined;\n }\n\n const { typeName, usernameField } = auth.userProfile;\n\n return {\n name: \"_User\",\n dependencies: [typeName],\n dataFile: \"data/_User.jsonl\",\n idpNamespace: auth.idProvider.namespace,\n schema: {\n usernameField,\n userTypeName: typeName,\n },\n };\n}\n\n/**\n * Generates the server-side IDP seed script code for testExecScript execution.\n * Uses the global tailor.idp.Client - no bundling required.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpSeedScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n export async function main(input) {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const errors = [];\n let processed = 0;\n let created = 0;\n let updated = 0;\n const upsert = input.upsert === true;\n\n for (let i = 0; i < input.users.length; i++) {\n try {\n if (upsert) {\n let existing;\n try {\n existing = await client.userByName(input.users[i].name);\n } catch {\n existing = undefined;\n }\n\n if (existing) {\n const { name, ...attributes } = input.users[i];\n await client.updateUser({ id: existing.id, ...attributes });\n updated++;\n } else {\n await client.createUser(input.users[i]);\n created++;\n }\n } else {\n await client.createUser(input.users[i]);\n created++;\n }\n processed++;\n console.log(\\`[_User] \\${i + 1}/\\${input.users.length}: \\${input.users[i].name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`Row \\${i} (\\${input.users[i].name}): \\${message}\\`);\n console.error(\\`[_User] Row \\${i} failed: \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n processed,\n created,\n updated,\n errors,\n };\n }\n `;\n}\n\n/**\n * Generates the server-side IDP truncation script code for testExecScript execution.\n * Lists all users with pagination and deletes each one.\n * @param idpNamespace - The IDP namespace name\n * @returns Script code string\n */\nexport function generateIdpTruncateScriptCode(idpNamespace: string): string {\n return ml /* ts */ `\n export async function main() {\n const client = new tailor.idp.Client({ namespace: \"${idpNamespace}\" });\n const errors = [];\n let deleted = 0;\n\n // List all users with pagination\n let after = undefined;\n const allUsers = [];\n do {\n const response = await client.users(after ? { after } : undefined);\n allUsers.push(...(response.users || []));\n after = response.nextPageToken;\n } while (after);\n\n console.log(\\`Found \\${allUsers.length} IDP users to delete\\`);\n\n for (const user of allUsers) {\n try {\n await client.deleteUser(user.id);\n deleted++;\n console.log(\\`[_User] Deleted \\${deleted}/\\${allUsers.length}: \\${user.name}\\`);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`User \\${user.id} (\\${user.name}): \\${message}\\`);\n console.error(\\`[_User] Delete failed for \\${user.name}: \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n deleted,\n total: allUsers.length,\n errors,\n };\n }\n `;\n}\n\ntype GenerateIdpUserSchemaFileOptions = {\n usernameField: string;\n userTypeName: string;\n /**\n * When `true` (default), emit a foreign key from `_User.name` to the\n * userProfile type's username field so that seed validation rejects `_User`\n * rows without a matching userProfile row. Set to `false` to seed `_User`\n * rows that do not yet have a corresponding userProfile row.\n */\n includeUserProfileFK?: boolean;\n};\n\n/**\n * Generates the schema file content for IdP users. Emits the\n * `_User.name -> <userProfile>.<usernameField>` foreign key by default; pass\n * `includeUserProfileFK: false` to omit it (e.g. when seeding `_User` rows\n * that do not yet have a corresponding userProfile row).\n * @param options - Schema generation options\n * @param options.usernameField - Username field name\n * @param options.userTypeName - TailorDB user type name\n * @param options.includeUserProfileFK - Whether to emit the `_User -> userProfile` foreign key (default `true`)\n * @returns Schema file contents\n */\nexport function generateIdpUserSchemaFile(options: GenerateIdpUserSchemaFileOptions): string {\n const { usernameField, userTypeName, includeUserProfileFK = true } = options;\n const schemaBody = includeUserProfileFK\n ? ml`\n primaryKey: \"name\",\n indexes: [\n { name: \"_user_name_unique_idx\", columns: [\"name\"], unique: true },\n ],\n foreignKeys: [\n {\n column: \"name\",\n references: {\n table: \"${userTypeName}\",\n column: \"${usernameField}\",\n },\n },\n ],\n `\n : ml`\n primaryKey: \"name\",\n indexes: [\n { name: \"_user_name_unique_idx\", columns: [\"name\"], unique: true },\n ],\n `;\n\n return ml /* ts */ `\n import { t } from \"@tailor-platform/sdk\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createStandardSchema } from \"@tailor-platform/sdk/test\";\n\n const schemaType = t.object({\n name: t.string(),\n password: t.string(),\n });\n\n // Simple identity hook for _User (no TailorDB backing type)\n const hook = <T>(data: unknown) => data as T;\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook),\n {\n ${schemaBody}\n }\n );\n\n `;\n}\n","import { isPluginGeneratedType } from \"#/parser/service/tailordb/type-source\";\nimport ml from \"#/utils/multiline\";\nimport type {\n PluginGeneratedTypeSource,\n TailorDBType,\n TypeSourceInfoEntry,\n} from \"#/parser/service/tailordb/types\";\nimport type { LinesDbMetadata } from \"./types\";\nimport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\n/**\n * Processes TailorDB types to generate lines-db metadata\n * @param type - Parsed TailorDB type\n * @param source - Source file info\n * @returns Generated lines-db metadata\n */\nexport function processLinesDb(type: TailorDBType, source: TypeSourceInfoEntry): LinesDbMetadata {\n if (isPluginGeneratedType(source)) {\n // Plugin-generated type\n return processLinesDbForPluginType(type, source);\n }\n\n // User-defined type\n if (!source.filePath) {\n throw new Error(`Missing source info for type ${type.name}`);\n }\n if (!source.exportName) {\n throw new Error(`Missing export name for type ${type.name}`);\n }\n\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n typeName: type.name,\n exportName: source.exportName,\n importPath: source.filePath,\n optionalFields,\n omitFields,\n foreignKeys,\n indexes,\n };\n}\n\n/**\n * Process lines-db metadata for plugin-generated types\n * @param type - Parsed TailorDB type\n * @param source - Plugin-generated type source info\n * @returns Generated lines-db metadata with plugin source\n */\nfunction processLinesDbForPluginType(\n type: TailorDBType,\n source: PluginGeneratedTypeSource,\n): LinesDbMetadata {\n const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);\n\n return {\n typeName: type.name,\n exportName: source.exportName,\n importPath: \"\",\n optionalFields,\n omitFields,\n foreignKeys,\n indexes,\n pluginSource: source,\n };\n}\n\n/**\n * Extract field metadata from TailorDB type\n * @param type - Parsed TailorDB type\n * @returns Field metadata including optional fields, omit fields, indexes, and foreign keys\n */\nfunction extractFieldMetadata(type: TailorDBType): {\n optionalFields: string[];\n omitFields: string[];\n indexes: IndexDefinition[];\n foreignKeys: ForeignKeyDefinition[];\n} {\n const optionalFields = [\"id\"]; // id is always optional\n const omitFields: string[] = [];\n const indexes: IndexDefinition[] = [];\n const foreignKeys: ForeignKeyDefinition[] = [];\n\n // Find fields with hooks.create or serial\n for (const [fieldName, field] of Object.entries(type.fields)) {\n if (field.config.hooks?.create) {\n optionalFields.push(fieldName);\n }\n // Serial fields are auto-generated, so they should be optional in seed data\n if (field.config.serial) {\n omitFields.push(fieldName);\n }\n if (field.config.unique) {\n indexes.push({\n name: `${type.name.toLowerCase()}_${fieldName}_unique_idx`,\n columns: [fieldName],\n unique: true,\n });\n }\n }\n\n // Extract indexes\n if (type.indexes) {\n for (const [indexName, indexDef] of Object.entries(type.indexes)) {\n indexes.push({\n name: indexName,\n columns: indexDef.fields,\n unique: indexDef.unique,\n });\n }\n }\n\n // Extract foreign keys from relations\n for (const [fieldName, field] of Object.entries(type.fields)) {\n if (field.relation) {\n foreignKeys.push({\n column: fieldName,\n references: {\n table: field.relation.targetType,\n column: field.relation.key,\n },\n });\n }\n }\n\n return { optionalFields, omitFields, indexes, foreignKeys };\n}\n\n/**\n * Generate schema options code for lines-db\n * @param foreignKeys - Foreign key definitions\n * @param indexes - Index definitions\n * @returns Schema options code string\n */\nfunction generateSchemaOptions(\n foreignKeys: ForeignKeyDefinition[],\n indexes: IndexDefinition[],\n): string {\n const schemaOptions: string[] = [];\n\n if (foreignKeys.length > 0) {\n schemaOptions.push(`foreignKeys: [`);\n foreignKeys.forEach((fk) => {\n schemaOptions.push(` ${JSON.stringify(fk)},`);\n });\n schemaOptions.push(`],`);\n }\n\n if (indexes.length > 0) {\n schemaOptions.push(`indexes: [`);\n indexes.forEach((index) => {\n schemaOptions.push(` ${JSON.stringify(index)},`);\n });\n schemaOptions.push(\"],\");\n }\n\n return schemaOptions.length > 0\n ? [\"\\n {\", ...schemaOptions.map((option) => ` ${option}`), \" }\"].join(\"\\n\")\n : \"\";\n}\n\n/**\n * Generates the schema file content for lines-db (for user-defined types with import)\n * @param metadata - lines-db metadata\n * @param importPath - Import path for the TailorDB type\n * @returns Schema file contents\n */\nexport function generateLinesDbSchemaFile(metadata: LinesDbMetadata, importPath: string): string {\n const { exportName, optionalFields, omitFields, foreignKeys, indexes } = metadata;\n\n const schemaTypeCode = ml /* ts */ `\n const schemaType = t.object({\n ...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),\n ...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),\n });\n `;\n\n const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);\n\n return ml /* ts */ `\n import { t } from \"@tailor-platform/sdk\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n import { ${exportName} } from \"${importPath}\";\n\n ${schemaTypeCode}\n\n const hook = createTailorDBHook(${exportName});\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook),${schemaOptionsCode}\n );\n\n `;\n}\n\n/**\n * Parameters for generating plugin-type schema file\n */\nexport interface PluginSchemaParams {\n /** Relative path from schema output to tailor.config.ts */\n configImportPath: string;\n /** Relative import path to the original type file (for type-attached plugins) */\n originalImportPath?: string;\n}\n\n/**\n * Generates the schema file content using getGeneratedType API\n * (for plugin-generated types)\n * @param metadata - lines-db metadata (must have pluginSource)\n * @param params - Plugin import paths\n * @returns Schema file contents\n */\nexport function generateLinesDbSchemaFileWithPluginAPI(\n metadata: LinesDbMetadata,\n params: PluginSchemaParams,\n): string {\n const { typeName, exportName, optionalFields, omitFields, foreignKeys, indexes, pluginSource } =\n metadata;\n\n if (!pluginSource) {\n throw new Error(`pluginSource is required for plugin-generated type \"${typeName}\"`);\n }\n\n const { configImportPath, originalImportPath } = params;\n\n const schemaTypeCode = ml /* ts */ `\n const schemaType = t.object({\n ...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),\n ...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),\n });\n `;\n\n const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);\n\n // Type-attached plugin (e.g., changeset): import original type and use getGeneratedType(configPath, pluginId, type, kind)\n if (pluginSource.originalExportName && originalImportPath && pluginSource.generatedTypeKind) {\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedType } from \"@tailor-platform/sdk/plugin\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n import { ${pluginSource.originalExportName} } from \"${originalImportPath}\";\n\n const configPath = join(import.meta.dirname, \"${configImportPath}\");\n const ${exportName} = await getGeneratedType(configPath, \"${pluginSource.pluginId}\", ${pluginSource.originalExportName}, \"${pluginSource.generatedTypeKind}\");\n\n ${schemaTypeCode}\n\n const hook = createTailorDBHook(${exportName});\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook),${schemaOptionsCode}\n );\n\n `;\n }\n\n // Namespace plugin (e.g., audit-log): use getGeneratedType(configPath, pluginId, null, kind)\n // For namespace plugins, generatedTypeKind is required\n if (!pluginSource.generatedTypeKind) {\n throw new Error(\n `Namespace plugin \"${pluginSource.pluginId}\" must provide generatedTypeKind for type \"${typeName}\"`,\n );\n }\n\n return ml /* ts */ `\n import { join } from \"node:path\";\n import { t } from \"@tailor-platform/sdk\";\n import { getGeneratedType } from \"@tailor-platform/sdk/plugin\";\n import { defineSchema } from \"@tailor-platform/sdk/seed\";\n import { createTailorDBHook, createStandardSchema } from \"@tailor-platform/sdk/test\";\n\n const configPath = join(import.meta.dirname, \"${configImportPath}\");\n const ${exportName} = await getGeneratedType(configPath, \"${pluginSource.pluginId}\", null, \"${pluginSource.generatedTypeKind}\");\n\n ${schemaTypeCode}\n\n const hook = createTailorDBHook(${exportName});\n\n export const schema = defineSchema(\n createStandardSchema(schemaType, hook),${schemaOptionsCode}\n );\n\n `;\n}\n","import ml from \"#/utils/multiline\";\n\n/**\n * Generate the JSONL seed-data loader embedded in `exec.mjs`.\n * @returns JavaScript source defining `loadSeedData`\n */\nexport function generateSeedDataLoaderCode(): string {\n return ml /* js */ `\n const loadSeedData = (\n dataDir,\n typeNames,\n { requireId = false, requiredFieldsByType = {} } = {},\n ) => {\n const data = {};\n for (const typeName of typeNames) {\n const jsonlPath = join(dataDir, \\`\\${typeName}.jsonl\\`);\n try {\n const lines = readFileSync(jsonlPath, \"utf-8\").split(\"\\\\n\");\n const records = [];\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n if (lines[lineIndex].trim() === \"\") continue;\n const record = JSON.parse(lines[lineIndex]);\n if (requireId && (record?.id === undefined || record?.id === null)) {\n throw new Error(\n \\`\\${jsonlPath}:\\${lineIndex + 1}: \\\\\\`id\\\\\\` is required with --upsert\\`,\n );\n }\n const missingRequiredField = (requiredFieldsByType[typeName] || []).find(\n (field) => record?.[field] === undefined || record?.[field] === null,\n );\n if (missingRequiredField) {\n throw new Error(\n \\`\\${jsonlPath}:\\${lineIndex + 1}: field \\\\\\`\\${missingRequiredField}\\\\\\` is required with --upsert\\`,\n );\n }\n records.push(record);\n }\n data[typeName] = records;\n } catch (error) {\n if (error.code === \"ENOENT\") {\n data[typeName] = [];\n } else {\n throw error;\n }\n }\n }\n return data;\n };\n `;\n}\n","import type { TailorDBType } from \"#/parser/service/tailordb/types\";\nimport type { SeedTypeInfo } from \"./types\";\n\n/**\n * Processes TailorDB types to extract seed type information\n * @param type - Parsed TailorDB type\n * @param namespace - Namespace of the type\n * @returns Seed type information\n */\nexport function processSeedTypeInfo(type: TailorDBType, namespace: string): SeedTypeInfo {\n // Extract dependencies from relations (including keyOnly which only sets foreignKeyType)\n const dependencies: Set<string> = new Set();\n const selfRefFields: string[] = [];\n\n for (const [fieldName, field] of Object.entries(type.fields)) {\n const targetType = field.relation?.targetType ?? field.config.foreignKeyType;\n if (!targetType) continue;\n\n if (targetType === type.name) {\n selfRefFields.push(fieldName);\n } else {\n dependencies.add(targetType);\n }\n }\n\n return {\n name: type.name,\n namespace,\n dependencies: Array.from(dependencies),\n selfRefFields,\n dataFile: `data/${type.name}.jsonl`,\n };\n}\n","/**\n * Escape generated script source before embedding it in a template literal.\n * @param scriptCode - Generated script source to embed.\n * @returns Escaped template literal content.\n */\nexport function escapeSeedScriptCodeForTemplateLiteral(scriptCode: string): string {\n return scriptCode.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\").replace(/\\$/g, \"\\\\$\");\n}\n","import * as path from \"pathe\";\nimport { assertDefined } from \"#/utils/assert\";\nimport ml from \"#/utils/multiline\";\nimport {\n processIdpUser,\n generateIdpUserSchemaFile,\n generateIdpSeedScriptCode,\n generateIdpTruncateScriptCode,\n} from \"./idp-user-processor\";\nimport {\n processLinesDb,\n generateLinesDbSchemaFile,\n generateLinesDbSchemaFileWithPluginAPI,\n type PluginSchemaParams,\n} from \"./lines-db-processor\";\nimport { generateSeedDataLoaderCode } from \"./seed-data-loader\";\nimport { processSeedTypeInfo } from \"./seed-type-processor\";\nimport { escapeSeedScriptCodeForTemplateLiteral } from \"./template-literal\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\n\n/** Unique identifier for the seed generator plugin. */\nexport const SeedGeneratorID = \"@tailor-platform/seed\";\n\ntype DisableIdpUserSyncDirections = {\n /**\n * Skip emitting the foreign key from `<userProfile>.<usernameField>` to\n * `_User.name`. Defaults to `false` (FK emitted).\n *\n * Set to `true` to seed pre-registration states such as\n * invited-but-not-registered users.\n */\n userToIdp?: boolean;\n /**\n * Skip emitting the foreign key from `_User.name` to\n * `<userProfile>.<usernameField>`. Defaults to `false` (FK emitted).\n *\n * Set to `true` to seed `_User` rows that do not yet have a corresponding\n * userProfile row.\n */\n idpToUser?: boolean;\n};\n\ntype SeedPluginOptions = {\n distPath: string;\n machineUserName?: string;\n /**\n * Disable individual `_User <-> userProfile` foreign keys emitted into\n * the generated seed schema. Both directions are emitted by default.\n *\n * Set a direction to `true` to relax it — for example to seed invited\n * users that do not yet have an IdP credential.\n */\n disableIdpUserSync?: DisableIdpUserSyncDirections;\n};\n\nfunction resolveIdpUserSyncFKs(option: SeedPluginOptions[\"disableIdpUserSync\"]): {\n emitUserToIdpFK: boolean;\n emitIdpToUserFK: boolean;\n} {\n return {\n emitUserToIdpFK: !(option?.userToIdp ?? false),\n emitIdpToUserFK: !(option?.idpToUser ?? false),\n };\n}\n\ntype NamespaceConfig = {\n namespace: string;\n types: string[];\n dependencies: Record<string, string[]>;\n selfRefTypes: string[];\n requiredFields: Record<string, string[]>;\n};\n\n/**\n * Generate the IdP user seed function code using tailor.idp.Client via testExecScript\n * @param hasIdpUser - Whether IdP user is included\n * @param idpNamespace - The IDP namespace name\n * @returns JavaScript code for IdP user seeding function\n */\nfunction generateIdpUserSeedFunction(hasIdpUser: boolean, idpNamespace: string | null): string {\n if (!hasIdpUser || !idpNamespace) return \"\";\n\n const scriptCode = generateIdpSeedScriptCode(idpNamespace);\n\n return ml`\n // Seed _User via tailor.idp.Client (server-side)\n const seedIdpUser = async () => {\n console.log(styleText(\"cyan\", \" Seeding _User via tailor.idp.Client...\"));\n const dataDir = join(configDir, \"data\");\n const data = loadSeedData(dataDir, [\"_User\"]);\n const rows = data[\"_User\"] || [];\n if (rows.length === 0) {\n console.log(styleText(\"dim\", \" No _User data to seed\"));\n return { success: true };\n }\n console.log(styleText(\"dim\", \\` Processing \\${rows.length} _User records...\\`));\n\n const idpSeedCode = \\/* js *\\/\\`${escapeSeedScriptCodeForTemplateLiteral(scriptCode)}\\`;\n\n const result = await executeScript({\n client: operatorClient,\n workspaceId,\n name: \"seed-idp-user.ts\",\n code: idpSeedCode,\n arg: JSON.stringify({ users: rows, upsert: values.upsert }),\n invoker: {\n namespace: authNamespace,\n machineUserName,\n },\n });\n\n if (result.logs) {\n for (const line of result.logs.split(\"\\\\n\").filter(Boolean)) {\n console.log(styleText(\"dim\", \\` \\${line}\\`));\n }\n }\n\n if (result.success) {\n let parsed;\n try {\n parsed = JSON.parse(result.result || \"{}\");\n } catch (e) {\n console.error(styleText(\"red\", \\` ✗ Failed to parse seed result: \\${e.message}\\`));\n return { success: false };\n }\n\n const message = values.upsert\n ? \\`\\${parsed.created || 0} created, \\${parsed.updated || 0} updated\\`\n : \\`\\${parsed.processed || 0} rows processed\\`;\n console.log(\n styleText(\n \"green\",\n \\` ✓ _User: \\${message}\\`,\n ),\n );\n\n if (!parsed.success) {\n const errors = Array.isArray(parsed.errors) ? parsed.errors : [];\n for (const err of errors) {\n console.error(styleText(\"red\", \\` ✗ \\${err}\\`));\n }\n return { success: false };\n }\n\n return { success: true };\n } else {\n console.error(styleText(\"red\", \\` ✗ Seed failed: \\${result.error}\\`));\n return { success: false };\n }\n };\n `;\n}\n\n/**\n * Generate the IdP user seed call code\n * @param hasIdpUser - Whether IdP user is included\n * @returns JavaScript code for calling IdP user seeding\n */\nfunction generateIdpUserSeedCall(hasIdpUser: boolean): string {\n if (!hasIdpUser) return \"\";\n\n return ml`\n // Seed _User if included and not skipped\n const shouldSeedUser = !skipIdp && (!entitiesToProcess || entitiesToProcess.includes(\"_User\"));\n if (hasIdpUser && shouldSeedUser) {\n const result = await seedIdpUser();\n if (!result.success) {\n allSuccess = false;\n }\n }\n `;\n}\n\n/**\n * Generate the IdP user truncation function code using tailor.idp.Client via testExecScript\n * @param hasIdpUser - Whether IdP user is included\n * @param idpNamespace - The IDP namespace name\n * @returns JavaScript code for IdP user truncation function\n */\nfunction generateIdpUserTruncateFunction(hasIdpUser: boolean, idpNamespace: string | null): string {\n if (!hasIdpUser || !idpNamespace) return \"\";\n\n const scriptCode = generateIdpTruncateScriptCode(idpNamespace);\n\n return ml`\n // Truncate _User via tailor.idp.Client (server-side)\n const truncateIdpUser = async () => {\n console.log(styleText(\"cyan\", \"Truncating _User via tailor.idp.Client...\"));\n\n const idpTruncateCode = \\/* js *\\/\\`${escapeSeedScriptCodeForTemplateLiteral(scriptCode)}\\`;\n\n const result = await executeScript({\n client: operatorClient,\n workspaceId,\n name: \"truncate-idp-user.ts\",\n code: idpTruncateCode,\n arg: JSON.stringify({}),\n invoker: {\n namespace: authNamespace,\n machineUserName,\n },\n });\n\n if (result.logs) {\n for (const line of result.logs.split(\"\\\\n\").filter(Boolean)) {\n console.log(styleText(\"dim\", \\` \\${line}\\`));\n }\n }\n\n if (result.success) {\n let parsed;\n try {\n parsed = JSON.parse(result.result || \"{}\");\n } catch (e) {\n console.error(styleText(\"red\", \\` ✗ Failed to parse truncation result: \\${e.message}\\`));\n return { success: false };\n }\n\n if (parsed.deleted !== undefined) {\n console.log(styleText(\"green\", \\` ✓ _User: \\${parsed.deleted} users deleted\\`));\n }\n\n if (!parsed.success) {\n const errors = Array.isArray(parsed.errors) ? parsed.errors : [];\n for (const err of errors) {\n console.error(styleText(\"red\", \\` ✗ \\${err}\\`));\n }\n return { success: false };\n }\n\n return { success: true };\n } else {\n console.error(styleText(\"red\", \\` ✗ Truncation failed: \\${result.error}\\`));\n return { success: false };\n }\n };\n `;\n}\n\n/**\n * Generate the IdP user truncation call code within the truncate block\n * @param hasIdpUser - Whether IdP user is included\n * @returns JavaScript code for calling IdP user truncation\n */\nfunction generateIdpUserTruncateCall(hasIdpUser: boolean): string {\n if (!hasIdpUser) return \"\";\n\n return ml`\n // Truncate _User if applicable\n const shouldTruncateUser = !skipIdp && !hasNamespace && (!hasTypes || entitiesToProcess.includes(\"_User\"));\n if (hasIdpUser && shouldTruncateUser) {\n const truncResult = await truncateIdpUser();\n if (!truncResult.success) {\n console.error(styleText(\"red\", \"IDP user truncation failed.\"));\n process.exit(1);\n }\n }\n `;\n}\n\n/**\n * Generates the exec.mjs script content using testExecScript API for TailorDB types\n * and tailor.idp.Client for _User (IdP managed)\n * @param defaultMachineUserName - Default machine user name from generator config (can be overridden at runtime)\n * @param relativeConfigPath - Config path relative to exec script\n * @param namespaceConfigs - Namespace configurations with types and dependencies\n * @param hasIdpUser - Whether _User is included\n * @param idpNamespace - The IDP namespace name, or null if not applicable\n * @returns exec.mjs file contents\n */\nfunction generateExecScript(\n defaultMachineUserName: string | undefined,\n relativeConfigPath: string,\n namespaceConfigs: NamespaceConfig[],\n hasIdpUser: boolean,\n idpNamespace: string | null,\n): string {\n // Generate namespaceEntities object\n const namespaceEntitiesEntries = namespaceConfigs\n .map(({ namespace, types }) => {\n const entitiesFormatted = types.map((e) => ` \"${e}\",`).join(\"\\n\");\n return ` \"${namespace}\": [\\n${entitiesFormatted}\\n ]`;\n })\n .join(\",\\n\");\n\n // Generate dependency map for each namespace\n const namespaceDepsEntries = namespaceConfigs\n .map(({ namespace, dependencies }) => {\n const depsObj = Object.entries(dependencies)\n .map(([type, deps]) => ` \"${type}\": [${deps.map((d) => `\"${d}\"`).join(\", \")}]`)\n .join(\",\\n\");\n return ` \"${namespace}\": {\\n${depsObj}\\n }`;\n })\n .join(\",\\n\");\n\n // Generate self-referencing types map for each namespace\n const namespaceSelfRefEntries = namespaceConfigs\n .map(({ namespace, selfRefTypes }) => {\n const formatted = selfRefTypes.map((t) => `\"${t}\"`).join(\", \");\n return ` \"${namespace}\": [${formatted}]`;\n })\n .join(\",\\n\");\n const requiredFieldsEntries = namespaceConfigs\n .flatMap(({ requiredFields }) => Object.entries(requiredFields))\n .map(([type, fields]) => ` \"${type}\": ${JSON.stringify(fields)}`)\n .join(\",\\n\");\n const seedDataLoaderCode = generateSeedDataLoaderCode().replace(/^/gm, \" \");\n\n return ml /* js */ `\n /**\n * @generated\n * This file is auto-generated by @tailor-platform/sdk's seedPlugin.\n * Do not edit by hand: changes will be overwritten on the next \\`sdk generate\\`.\n */\n import { readFileSync } from \"node:fs\";\n import { dirname, join, isAbsolute } from \"node:path\";\n import { parseArgs, styleText } from \"node:util\";\n import { createInterface } from \"node:readline\";\n import {\n show,\n truncate,\n bundleSeedScript,\n chunkSeedData,\n executeScript,\n initOperatorClient,\n loadAccessToken,\n loadWorkspaceId,\n } from \"@tailor-platform/sdk/cli\";\n\n // Handle \"validate\" subcommand before parseArgs\n const subcommand = process.argv[2];\n if (subcommand === \"validate\") {\n const { validateSeedData } = await import(\"@tailor-platform/sdk/seed\");\n const validateArgs = parseArgs({\n args: process.argv.slice(3),\n options: {\n verbose: { type: \"boolean\", short: \"v\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n allowPositionals: true,\n });\n\n if (validateArgs.values.help) {\n console.log(\\`\n Usage: node exec.mjs validate [options] [path]\n\n Validate JSONL seed data against schema definitions.\n\n Arguments:\n path File or directory to validate (default: ./data)\n\n Options:\n -v, --verbose Show verbose error output\n -h, --help Show help\n\n Examples:\n node exec.mjs validate # Validate all seed data\n node exec.mjs validate ./data/User.jsonl # Validate specific file\n node exec.mjs validate -v # Verbose error output\n \\`);\n process.exit(0);\n }\n\n const configDir = import.meta.dirname;\n const targetPath = validateArgs.positionals[0] || join(configDir, \"data\");\n const resolvedPath = isAbsolute(targetPath) ? targetPath : join(process.cwd(), targetPath);\n\n try {\n const result = await validateSeedData({ path: resolvedPath, verbose: validateArgs.values.verbose });\n if (result.output) console.log(result.output);\n if (!result.valid) {\n console.error(result.error);\n process.exit(1);\n }\n process.exit(0);\n } catch (error) {\n console.error(styleText(\"red\", \\`Error: \\${error instanceof Error ? error.message : String(error)}\\`));\n process.exit(1);\n }\n }\n\n // Parse command-line arguments\n const { values, positionals } = parseArgs({\n options: {\n \"machine-user\": { type: \"string\", short: \"m\" },\n namespace: { type: \"string\", short: \"n\" },\n \"skip-idp\": { type: \"boolean\", default: false },\n truncate: { type: \"boolean\", default: false },\n upsert: { type: \"boolean\", default: false },\n yes: { type: \"boolean\", default: false },\n profile: { type: \"string\", short: \"p\" },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n allowPositionals: true,\n });\n\n if (values.help) {\n console.log(\\`\n Usage: node exec.mjs [command] [options] [types...]\n\n Commands:\n validate [path] Validate seed data against schema (default: ./data)\n\n Options:\n -m, --machine-user <name> Machine user name for authentication (required if not configured)\n -n, --namespace <ns> Process all types in specified namespace (excludes _User)\n --skip-idp Skip IdP user (_User) entity\n --truncate Truncate tables before seeding\n --upsert Update existing rows instead of failing on duplicate ids\n --yes Skip confirmation prompts (for truncate)\n -p, --profile <name> Workspace profile name\n -h, --help Show help\n\n Examples:\n node exec.mjs -m admin # Process all types with machine user\n node exec.mjs --namespace <namespace> # Process tailordb namespace only (no _User)\n node exec.mjs User Order # Process specific types only\n node exec.mjs --skip-idp # Process all except _User\n node exec.mjs --truncate # Truncate all tables, then seed all\n node exec.mjs --truncate --yes # Truncate all tables without confirmation, then seed all\n node exec.mjs --truncate --namespace <namespace> # Truncate tailordb, then seed tailordb\n node exec.mjs --truncate User Order # Truncate User and Order, then seed them\n node exec.mjs --upsert # Seed all, updating rows whose id already exists\n node exec.mjs validate # Validate all seed data\n node exec.mjs validate ./data/User.jsonl # Validate specific file\n \\`);\n process.exit(0);\n }\n\n // Helper function to prompt for y/n confirmation\n const promptConfirmation = (question) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(styleText(\"yellow\", question), (answer) => {\n rl.close();\n resolve(answer.toLowerCase().trim());\n });\n });\n };\n\n const configDir = import.meta.dirname;\n const configPath = join(configDir, \"${relativeConfigPath}\");\n\n${seedDataLoaderCode}\n\n // Determine machine user name (CLI argument takes precedence over config default)\n const defaultMachineUser = ${defaultMachineUserName ? `\"${defaultMachineUserName}\"` : \"undefined\"};\n const machineUserName = values[\"machine-user\"] || defaultMachineUser;\n\n if (!machineUserName) {\n console.error(styleText(\"red\", \"Error: Machine user name is required.\"));\n console.error(styleText(\"yellow\", \"Specify --machine-user <name> or configure machineUserName in generator options.\"));\n process.exit(1);\n }\n\n // Entity configuration\n const namespaceEntities = {\n${namespaceEntitiesEntries}\n };\n const namespaceDeps = {\n${namespaceDepsEntries}\n };\n const namespaceSelfRefTypes = {\n${namespaceSelfRefEntries}\n };\n const requiredFieldsByType = {\n${requiredFieldsEntries}\n };\n const entities = Object.values(namespaceEntities).flat();\n const hasIdpUser = ${String(hasIdpUser)};\n\n // Determine which entities to process\n let entitiesToProcess = null;\n\n const hasNamespace = !!values.namespace;\n const hasTypes = positionals.length > 0;\n const skipIdp = values[\"skip-idp\"];\n\n // Validate mutually exclusive options\n const optionCount = [hasNamespace, hasTypes].filter(Boolean).length;\n if (optionCount > 1) {\n console.error(styleText(\"red\", \"Error: Options --namespace and type names are mutually exclusive.\"));\n process.exit(1);\n }\n\n // --skip-idp and --namespace are redundant (namespace already excludes _User)\n if (skipIdp && hasNamespace) {\n console.warn(styleText(\"yellow\", \"Warning: --skip-idp is redundant with --namespace (namespace filtering already excludes _User).\"));\n }\n\n // Filter by namespace (automatically excludes _User as it has no namespace)\n if (hasNamespace) {\n const namespace = values.namespace;\n entitiesToProcess = namespaceEntities[namespace];\n\n if (!entitiesToProcess || entitiesToProcess.length === 0) {\n console.error(styleText(\"red\", \\`Error: No entities found in namespace \"\\${namespace}\"\\`));\n console.error(styleText(\"yellow\", \\`Available namespaces: \\${Object.keys(namespaceEntities).join(\", \")}\\`));\n process.exit(1);\n }\n\n console.log(styleText(\"cyan\", \\`Filtering by namespace: \\${namespace}\\`));\n console.log(styleText(\"dim\", \\`Entities: \\${entitiesToProcess.join(\", \")}\\`));\n }\n\n // Filter by specific types\n if (hasTypes) {\n const requestedTypes = positionals;\n const notFoundTypes = [];\n const allTypes = hasIdpUser ? [...entities, \"_User\"] : entities;\n\n entitiesToProcess = requestedTypes.filter((type) => {\n if (!allTypes.includes(type)) {\n notFoundTypes.push(type);\n return false;\n }\n return true;\n });\n\n if (notFoundTypes.length > 0) {\n console.error(styleText(\"red\", \\`Error: The following types were not found: \\${notFoundTypes.join(\", \")}\\`));\n console.error(styleText(\"yellow\", \\`Available types: \\${allTypes.join(\", \")}\\`));\n process.exit(1);\n }\n\n console.log(styleText(\"cyan\", \\`Filtering by types: \\${entitiesToProcess.join(\", \")}\\`));\n }\n\n // Apply --skip-idp filter\n if (skipIdp) {\n if (entitiesToProcess) {\n entitiesToProcess = entitiesToProcess.filter((entity) => entity !== \"_User\");\n } else {\n entitiesToProcess = entities.filter((entity) => entity !== \"_User\");\n }\n }\n\n const selectedTailorDbTypes = entities.filter(\n (entity) => !entitiesToProcess || entitiesToProcess.includes(entity),\n );\n const loadSelectedTailorDbSeedData = () =>\n loadSeedData(join(configDir, \"data\"), selectedTailorDbTypes, {\n requireId: values.upsert,\n requiredFieldsByType: values.upsert ? requiredFieldsByType : {},\n });\n let tailorDbSeedData;\n if (values.upsert) {\n try {\n tailorDbSeedData = loadSelectedTailorDbSeedData();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(styleText(\"red\", \\`\\\\n✗ Seed data generation failed: \\${message}\\`));\n process.exit(1);\n }\n }\n\n // Get application info\n const appInfo = await show({ configPath, profile: values.profile });\n const authNamespace = appInfo.auth;\n\n // Initialize operator client (once for all namespaces)\n const accessToken = await loadAccessToken({ profile: values.profile });\n const workspaceId = await loadWorkspaceId({ profile: values.profile });\n const operatorClient = await initOperatorClient(accessToken);\n\n ${generateIdpUserTruncateFunction(hasIdpUser, idpNamespace)}\n\n // Truncate tables if requested\n if (values.truncate) {\n const answer = values.yes ? \"y\" : await promptConfirmation(\"Are you sure you want to truncate? (y/n): \");\n if (answer !== \"y\") {\n console.log(styleText(\"yellow\", \"Truncate cancelled.\"));\n process.exit(0);\n }\n\n console.log(styleText(\"cyan\", \"Truncating tables...\"));\n\n try {\n if (hasNamespace) {\n await truncate({\n configPath,\n profile: values.profile,\n namespace: values.namespace,\n });\n } else if (hasTypes) {\n const typesToTruncate = entitiesToProcess.filter((t) => t !== \"_User\");\n if (typesToTruncate.length > 0) {\n await truncate({\n configPath,\n profile: values.profile,\n types: typesToTruncate,\n });\n } else {\n console.log(styleText(\"dim\", \"No TailorDB types to truncate (only _User was specified).\"));\n }\n } else {\n await truncate({\n configPath,\n profile: values.profile,\n all: true,\n });\n }\n } catch (error) {\n console.error(styleText(\"red\", \\`Truncate failed: \\${error.message}\\`));\n process.exit(1);\n }\n\n ${generateIdpUserTruncateCall(hasIdpUser)}\n\n console.log(styleText(\"green\", \"Truncate completed.\"));\n }\n\n console.log(styleText(\"cyan\", \"\\\\nStarting seed data generation...\"));\n if (skipIdp) {\n console.log(styleText(\"dim\", \\` Skipping IdP user (_User)\\`));\n }\n\n // Topological sort for dependency order\n const topologicalSort = (types, deps) => {\n const visited = new Set();\n const result = [];\n\n const visit = (type) => {\n if (visited.has(type)) return;\n visited.add(type);\n const typeDeps = deps[type] || [];\n for (const dep of typeDeps) {\n if (types.includes(dep)) {\n visit(dep);\n }\n }\n result.push(type);\n };\n\n for (const type of types) {\n visit(type);\n }\n return result;\n };\n\n // Seed TailorDB types via testExecScript\n const seedViaTestExecScript = async (\n namespace,\n typesToSeed,\n deps,\n selfRefTypes,\n seedDataByType,\n ) => {\n const sortedTypes = topologicalSort(typesToSeed, deps);\n const data = Object.fromEntries(\n sortedTypes.map((type) => [type, seedDataByType[type] || []]),\n );\n\n // Skip if no data\n const typesWithData = sortedTypes.filter((t) => data[t] && data[t].length > 0);\n if (typesWithData.length === 0) {\n console.log(styleText(\"dim\", \\` [\\${namespace}] No data to seed\\`));\n return { success: true, processed: {} };\n }\n\n console.log(styleText(\"cyan\", \\` [\\${namespace}] Seeding \\${typesWithData.length} types via Kysely batch \\${values.upsert ? \"upsert\" : \"insert\"}...\\`));\n\n // Bundle seed script\n const bundled = await bundleSeedScript(namespace, typesWithData, dirname(configPath));\n\n // Chunk seed data to fit within gRPC message size limits\n const chunks = chunkSeedData({\n data,\n order: sortedTypes,\n codeByteSize: new TextEncoder().encode(bundled.bundledCode).length,\n });\n\n if (chunks.length === 0) {\n console.log(styleText(\"dim\", \\` [\\${namespace}] No data to seed\\`));\n return { success: true, processed: {} };\n }\n\n if (chunks.length > 1) {\n console.log(styleText(\"dim\", \\` Split into \\${chunks.length} chunks\\`));\n }\n\n const allProcessed = {};\n let hasError = false;\n const allErrors = [];\n\n for (const chunk of chunks) {\n if (chunks.length > 1) {\n console.log(styleText(\"dim\", \\` Chunk \\${chunk.index + 1}/\\${chunk.total}: \\${chunk.order.join(\", \")}\\`));\n }\n\n // Execute seed script for this chunk\n const result = await executeScript({\n client: operatorClient,\n workspaceId,\n name: \\`seed-\\${namespace}.ts\\`,\n code: bundled.bundledCode,\n arg: JSON.stringify({ data: chunk.data, order: chunk.order, selfRefTypes, upsert: values.upsert }),\n invoker: {\n namespace: authNamespace,\n machineUserName,\n },\n });\n\n // Parse result and display logs\n if (result.logs) {\n for (const line of result.logs.split(\"\\\\n\").filter(Boolean)) {\n console.log(styleText(\"dim\", \\` \\${line}\\`));\n }\n }\n\n if (result.success) {\n let parsed;\n try {\n const parsedResult = JSON.parse(result.result || \"{}\");\n parsed = parsedResult && typeof parsedResult === \"object\" ? parsedResult : {};\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(styleText(\"red\", \\` ✗ Failed to parse seed result: \\${message}\\`));\n hasError = true;\n allErrors.push(message);\n continue;\n }\n\n const processed = parsed.processed || {};\n for (const [type, counts] of Object.entries(processed)) {\n const previous = allProcessed[type] || { inserted: 0, updated: 0, skipped: 0 };\n const current = {\n inserted: Number(counts.inserted) || 0,\n updated: Number(counts.updated) || 0,\n skipped: Number(counts.skipped) || 0,\n };\n allProcessed[type] = {\n inserted: previous.inserted + current.inserted,\n updated: previous.updated + current.updated,\n skipped: previous.skipped + current.skipped,\n };\n const skipped = current.skipped > 0 ? \\`, \\${current.skipped} skipped\\` : \"\";\n const message = values.upsert\n ? \\`\\${current.inserted} inserted, \\${current.updated} updated\\${skipped}\\`\n : \\`\\${current.inserted} rows inserted\\`;\n console.log(styleText(\"green\", \\` ✓ \\${type}: \\${message}\\`));\n }\n\n if (!parsed.success) {\n const errors = Array.isArray(parsed.errors) ? parsed.errors : [];\n const errorMessage =\n errors.length > 0 ? errors.join(\"\\\\n \") : \"Seed script reported failure\";\n console.error(styleText(\"red\", \\` ✗ Seed failed:\\\\n \\${errorMessage}\\`));\n hasError = true;\n allErrors.push(errorMessage);\n }\n } else {\n console.error(styleText(\"red\", \\` ✗ Seed failed: \\${result.error}\\`));\n hasError = true;\n allErrors.push(result.error);\n }\n }\n\n if (hasError) {\n return { success: false, error: allErrors.join(\"\\\\n\") };\n }\n return { success: true, processed: allProcessed };\n };\n\n ${generateIdpUserSeedFunction(hasIdpUser, idpNamespace)}\n\n // Main execution\n try {\n let allSuccess = true;\n tailorDbSeedData ??= loadSelectedTailorDbSeedData();\n\n // Determine which namespaces and types to process\n const namespacesToProcess = hasNamespace\n ? [values.namespace]\n : Object.keys(namespaceEntities);\n\n for (const namespace of namespacesToProcess) {\n const nsTypes = namespaceEntities[namespace] || [];\n const nsDeps = namespaceDeps[namespace] || {};\n const nsSelfRefTypes = namespaceSelfRefTypes[namespace] || [];\n\n // Filter types if specific types requested\n let typesToSeed = entitiesToProcess\n ? nsTypes.filter((t) => entitiesToProcess.includes(t))\n : nsTypes;\n\n if (typesToSeed.length === 0) continue;\n\n const result = await seedViaTestExecScript(\n namespace,\n typesToSeed,\n nsDeps,\n nsSelfRefTypes,\n tailorDbSeedData,\n );\n if (!result.success) {\n allSuccess = false;\n }\n }\n\n ${generateIdpUserSeedCall(hasIdpUser)}\n\n if (allSuccess) {\n console.log(styleText(\"green\", \"\\\\n✓ Seed data generation completed successfully\"));\n } else {\n console.error(styleText(\"red\", \"\\\\n✗ Seed data generation completed with errors\"));\n process.exit(1);\n }\n } catch (error) {\n console.error(styleText(\"red\", \\`\\\\n✗ Seed data generation failed: \\${error.message}\\`));\n process.exit(1);\n }\n\n `;\n}\n\n/**\n * Plugin that generates seed data files with Kysely batch insert and tailor.idp.Client for _User.\n * @param options - Plugin options\n * @param options.distPath - Output directory path for generated seed files\n * @param options.machineUserName - Default machine user name for authentication\n * @param options.disableIdpUserSync - Skip emitting individual `_User <-> userProfile` foreign keys. Both directions are emitted by default; set a direction to `true` to relax that side.\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function seedPlugin(options: SeedPluginOptions): Plugin<unknown, SeedPluginOptions> {\n return {\n id: SeedGeneratorID,\n description: \"Generates seed data files (Kysely batch insert + tailor.idp.Client for _User)\",\n pluginConfig: options,\n\n async onTailorDBReady(ctx: TailorDBReadyContext<SeedPluginOptions>): Promise<GeneratorResult> {\n const files: GeneratorResult[\"files\"] = [];\n const namespaceConfigs: NamespaceConfig[] = [];\n\n // Process IdP user early so we can add reverse FK to the user profile type\n const idpUser = ctx.auth ? (processIdpUser(ctx.auth) ?? null) : null;\n const hasIdpUser = idpUser !== null;\n const idpUserSyncFKs = resolveIdpUserSyncFKs(ctx.pluginConfig.disableIdpUserSync);\n\n for (const ns of ctx.tailordb) {\n const types: string[] = [];\n const dependencies: Record<string, string[]> = {};\n const selfRefTypes: string[] = [];\n const requiredFields: Record<string, string[]> = {};\n\n for (const [typeName, type] of Object.entries(ns.types)) {\n const source = assertDefined(\n ns.sourceInfo.get(typeName),\n `source info missing for type: ${typeName}`,\n );\n const typeInfo = processSeedTypeInfo(type, ns.namespace);\n const linesDb = processLinesDb(type, source);\n\n // Add reverse FK from userProfile type to _User (opt-out via disableIdpUserSync.userToIdp: true)\n if (\n idpUserSyncFKs.emitUserToIdpFK &&\n idpUser &&\n typeName === idpUser.schema.userTypeName\n ) {\n linesDb.foreignKeys.push({\n column: idpUser.schema.usernameField,\n references: {\n table: \"_User\",\n column: \"name\",\n },\n });\n }\n\n types.push(typeInfo.name);\n dependencies[typeInfo.name] = typeInfo.dependencies;\n requiredFields[typeInfo.name] = Object.entries(type.fields)\n .filter(\n ([fieldName, field]) =>\n field.config.required !== false &&\n !linesDb.optionalFields.includes(fieldName) &&\n !linesDb.omitFields.includes(fieldName),\n )\n .map(([fieldName]) => fieldName);\n if (typeInfo.selfRefFields.length > 0) {\n selfRefTypes.push(typeInfo.name);\n }\n\n // Generate empty JSONL data file\n files.push({\n path: path.join(ctx.pluginConfig.distPath, typeInfo.dataFile),\n content: \"\",\n skipIfExists: true,\n });\n\n const schemaOutputPath = path.join(\n ctx.pluginConfig.distPath,\n \"data\",\n `${linesDb.typeName}.schema.ts`,\n );\n\n // Plugin-generated type: use getGeneratedType API\n if (linesDb.pluginSource && linesDb.pluginSource.pluginImportPath) {\n // Build original type import path\n let originalImportPath: string | undefined;\n if (linesDb.pluginSource.originalFilePath && linesDb.pluginSource.originalExportName) {\n const relativePath = path.relative(\n path.dirname(schemaOutputPath),\n linesDb.pluginSource.originalFilePath,\n );\n originalImportPath = relativePath.replace(/\\.ts$/, \"\").startsWith(\".\")\n ? relativePath.replace(/\\.ts$/, \"\")\n : `./${relativePath.replace(/\\.ts$/, \"\")}`;\n }\n\n // Compute relative path from schema output to config file\n const configImportPath = path.relative(path.dirname(schemaOutputPath), ctx.configPath);\n\n const params: PluginSchemaParams = {\n configImportPath,\n originalImportPath,\n };\n\n const schemaContent = generateLinesDbSchemaFileWithPluginAPI(linesDb, params);\n\n files.push({\n path: schemaOutputPath,\n content: schemaContent,\n });\n } else {\n // User-defined type: import from source file\n const relativePath = path.relative(path.dirname(schemaOutputPath), linesDb.importPath);\n const typeImportPath = relativePath.replace(/\\.ts$/, \"\").startsWith(\".\")\n ? relativePath.replace(/\\.ts$/, \"\")\n : `./${relativePath.replace(/\\.ts$/, \"\")}`;\n const schemaContent = generateLinesDbSchemaFile(linesDb, typeImportPath);\n\n files.push({\n path: schemaOutputPath,\n content: schemaContent,\n });\n }\n }\n\n namespaceConfigs.push({\n namespace: ns.namespace,\n types,\n dependencies,\n selfRefTypes,\n requiredFields,\n });\n }\n\n if (idpUser) {\n // Generate empty JSONL data file\n files.push({\n path: path.join(ctx.pluginConfig.distPath, idpUser.dataFile),\n content: \"\",\n skipIfExists: true,\n });\n\n // Generate schema file with foreign key (opt-out via disableIdpUserSync.idpToUser: true)\n files.push({\n path: path.join(ctx.pluginConfig.distPath, \"data\", `${idpUser.name}.schema.ts`),\n content: generateIdpUserSchemaFile({\n usernameField: idpUser.schema.usernameField,\n userTypeName: idpUser.schema.userTypeName,\n includeUserProfileFK: idpUserSyncFKs.emitIdpToUserFK,\n }),\n });\n }\n\n // Generate exec.mjs (machineUserName can be provided at runtime if not configured)\n const relativeConfigPath = path.relative(ctx.pluginConfig.distPath, ctx.configPath);\n files.push({\n path: path.join(ctx.pluginConfig.distPath, \"exec.mjs\"),\n content: generateExecScript(\n ctx.pluginConfig.machineUserName,\n relativeConfigPath,\n namespaceConfigs,\n hasIdpUser,\n idpUser?.idpNamespace ?? null,\n ),\n });\n\n return { files };\n },\n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O;MAC9B,cAAc,QAAQ,OAAO;MAC7B,sBAAsB,eAAe;KACvC,CAAC;IACH,CAAC;GACH;GAGA,MAAM,qBAAqB,KAAK,SAAS,IAAI,aAAa,UAAU,IAAI,UAAU;GAClF,MAAM,KAAK;IACT,MAAM,KAAK,KAAK,IAAI,aAAa,UAAU,UAAU;IACrD,SAAS,mBACP,IAAI,aAAa,iBACjB,oBACA,kBACA,YACA,SAAS,gBAAgB,IAC3B;GACF,CAAC;GAED,OAAO,EAAE,MAAM;EACjB;CACF;AACF"}
|
|
@@ -347,13 +347,40 @@ const AuthAccessTokenTriggerSchema = z.object({
|
|
|
347
347
|
"auth.access_token.revoked"
|
|
348
348
|
])).min(1).transform((arr) => [...new Set(arr)]).describe("Auth access token event types to trigger on")
|
|
349
349
|
});
|
|
350
|
+
const workflowNameSchema = z.string().refine((value) => value.trim().length > 0, "Workflow name cannot be blank").describe("Workflow name to subscribe to.");
|
|
351
|
+
const WorkflowExecutionTriggerSchema = z.object({
|
|
352
|
+
kind: z.literal("workflowExecution").describe("Workflow execution event trigger"),
|
|
353
|
+
events: z.array(z.enum([
|
|
354
|
+
"workflow.workflow_execution.started",
|
|
355
|
+
"workflow.workflow_execution.completed",
|
|
356
|
+
"workflow.workflow_execution.retried",
|
|
357
|
+
"workflow.workflow_execution.resumed",
|
|
358
|
+
"workflow.workflow_execution.wait_started",
|
|
359
|
+
"workflow.workflow_execution.wait_resolved"
|
|
360
|
+
])).min(1).transform((arr) => [...new Set(arr)]).describe("Workflow execution event types to trigger on"),
|
|
361
|
+
workflowName: workflowNameSchema,
|
|
362
|
+
condition: functionSchema.optional().describe("Condition function to filter events")
|
|
363
|
+
});
|
|
364
|
+
const WorkflowJobExecutionTriggerSchema = z.object({
|
|
365
|
+
kind: z.literal("workflowJobExecution").describe("Workflow job execution event trigger"),
|
|
366
|
+
events: z.array(z.enum([
|
|
367
|
+
"workflow.workflow_execution.job_execution.started",
|
|
368
|
+
"workflow.workflow_execution.job_execution.completed",
|
|
369
|
+
"workflow.workflow_execution.job_execution.wait_started",
|
|
370
|
+
"workflow.workflow_execution.job_execution.wait_resolved"
|
|
371
|
+
])).min(1).transform((arr) => [...new Set(arr)]).describe("Workflow job execution event types to trigger on"),
|
|
372
|
+
workflowName: workflowNameSchema,
|
|
373
|
+
condition: functionSchema.optional().describe("Condition function to filter events")
|
|
374
|
+
});
|
|
350
375
|
const TriggerSchema = z.discriminatedUnion("kind", [
|
|
351
376
|
TailorDBTriggerSchema,
|
|
352
377
|
ResolverExecutedTriggerSchema,
|
|
353
378
|
ScheduleTriggerSchema,
|
|
354
379
|
IncomingWebhookTriggerSchema,
|
|
355
380
|
IdpUserTriggerSchema,
|
|
356
|
-
AuthAccessTokenTriggerSchema
|
|
381
|
+
AuthAccessTokenTriggerSchema,
|
|
382
|
+
WorkflowExecutionTriggerSchema,
|
|
383
|
+
WorkflowJobExecutionTriggerSchema
|
|
357
384
|
]);
|
|
358
385
|
const FunctionOperationSchema = z.object({
|
|
359
386
|
kind: z.enum(["function", "jobFunction"]),
|
|
@@ -487,4 +514,4 @@ function assertUniqueExecutorNames(executors) {
|
|
|
487
514
|
|
|
488
515
|
//#endregion
|
|
489
516
|
export { TailorFieldSchema as a, AuthInvokerSchema as i, ExecutorSchema as n, loadFilesWithIgnores as o, AuthConfigSchema as r, functionSchema as s, createExecutorService as t };
|
|
490
|
-
//# sourceMappingURL=service-
|
|
517
|
+
//# sourceMappingURL=service-CPJWhTLn.mjs.map
|