@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
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
import { t as assertDefined } from "./assert-DBxo8jPo.mjs";
|
|
2
|
+
import { t as multiline } from "./multiline-sfHpTZZK.mjs";
|
|
3
|
+
import { t as isPluginGeneratedType } from "./type-source-DH_LH20p.mjs";
|
|
4
|
+
import * as path from "pathe";
|
|
5
|
+
|
|
6
|
+
//#region src/plugin/builtin/seed/idp-user-processor.ts
|
|
7
|
+
/**
|
|
8
|
+
* Processes auth configuration to generate IdP user seed metadata
|
|
9
|
+
* @param auth - Auth configuration from generator
|
|
10
|
+
* @returns IdP user metadata or undefined if not applicable
|
|
11
|
+
*/
|
|
12
|
+
function processIdpUser(auth) {
|
|
13
|
+
if (auth.idProvider?.kind !== "BuiltInIdP" || !auth.userProfile) return;
|
|
14
|
+
const { typeName, usernameField } = auth.userProfile;
|
|
15
|
+
return {
|
|
16
|
+
name: "_User",
|
|
17
|
+
dependencies: [typeName],
|
|
18
|
+
dataFile: "data/_User.jsonl",
|
|
19
|
+
idpNamespace: auth.idProvider.namespace,
|
|
20
|
+
schema: {
|
|
21
|
+
usernameField,
|
|
22
|
+
userTypeName: typeName
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Generates the server-side IDP seed script code for testExecScript execution.
|
|
28
|
+
* Uses the global tailor.idp.Client - no bundling required.
|
|
29
|
+
* @param idpNamespace - The IDP namespace name
|
|
30
|
+
* @returns Script code string
|
|
31
|
+
*/
|
|
32
|
+
function generateIdpSeedScriptCode(idpNamespace) {
|
|
33
|
+
return multiline`
|
|
34
|
+
export async function main(input) {
|
|
35
|
+
const client = new tailor.idp.Client({ namespace: "${idpNamespace}" });
|
|
36
|
+
const errors = [];
|
|
37
|
+
let processed = 0;
|
|
38
|
+
let created = 0;
|
|
39
|
+
let updated = 0;
|
|
40
|
+
let skipped = 0;
|
|
41
|
+
const upsert = input.upsert === true;
|
|
42
|
+
|
|
43
|
+
for (let i = 0; i < input.users.length; i++) {
|
|
44
|
+
try {
|
|
45
|
+
if (upsert) {
|
|
46
|
+
let existing;
|
|
47
|
+
let lookupError;
|
|
48
|
+
try {
|
|
49
|
+
existing = await client.userByName(input.users[i].name);
|
|
50
|
+
} catch (error) {
|
|
51
|
+
existing = undefined;
|
|
52
|
+
lookupError = error instanceof Error ? error.message : String(error);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (existing) {
|
|
56
|
+
const { name, ...attributes } = input.users[i];
|
|
57
|
+
if (Object.keys(attributes).length === 0) {
|
|
58
|
+
skipped++;
|
|
59
|
+
} else {
|
|
60
|
+
await client.updateUser({ id: existing.id, ...attributes });
|
|
61
|
+
updated++;
|
|
62
|
+
}
|
|
63
|
+
} else {
|
|
64
|
+
try {
|
|
65
|
+
await client.createUser(input.users[i]);
|
|
66
|
+
created++;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
69
|
+
throw new Error(
|
|
70
|
+
lookupError ? \`create failed (\${message}); lookup failed (\${lookupError})\` : message,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
} else {
|
|
75
|
+
await client.createUser(input.users[i]);
|
|
76
|
+
created++;
|
|
77
|
+
}
|
|
78
|
+
processed++;
|
|
79
|
+
console.log(\`[_User] \${i + 1}/\${input.users.length}: \${input.users[i].name}\`);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
82
|
+
errors.push(\`Row \${i} (\${input.users[i].name}): \${message}\`);
|
|
83
|
+
console.error(\`[_User] Row \${i} failed: \${message}\`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
success: errors.length === 0,
|
|
89
|
+
processed,
|
|
90
|
+
created,
|
|
91
|
+
updated,
|
|
92
|
+
skipped,
|
|
93
|
+
errors,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
`;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Generates the server-side IDP truncation script code for testExecScript execution.
|
|
100
|
+
* Lists all users with pagination and deletes each one.
|
|
101
|
+
* @param idpNamespace - The IDP namespace name
|
|
102
|
+
* @returns Script code string
|
|
103
|
+
*/
|
|
104
|
+
function generateIdpTruncateScriptCode(idpNamespace) {
|
|
105
|
+
return multiline`
|
|
106
|
+
export async function main() {
|
|
107
|
+
const client = new tailor.idp.Client({ namespace: "${idpNamespace}" });
|
|
108
|
+
const errors = [];
|
|
109
|
+
let deleted = 0;
|
|
110
|
+
|
|
111
|
+
// List all users with pagination
|
|
112
|
+
let after = undefined;
|
|
113
|
+
const allUsers = [];
|
|
114
|
+
do {
|
|
115
|
+
const response = await client.users(after ? { after } : undefined);
|
|
116
|
+
allUsers.push(...(response.users || []));
|
|
117
|
+
after = response.nextPageToken;
|
|
118
|
+
} while (after);
|
|
119
|
+
|
|
120
|
+
console.log(\`Found \${allUsers.length} IDP users to delete\`);
|
|
121
|
+
|
|
122
|
+
for (const user of allUsers) {
|
|
123
|
+
try {
|
|
124
|
+
await client.deleteUser(user.id);
|
|
125
|
+
deleted++;
|
|
126
|
+
console.log(\`[_User] Deleted \${deleted}/\${allUsers.length}: \${user.name}\`);
|
|
127
|
+
} catch (error) {
|
|
128
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
129
|
+
errors.push(\`User \${user.id} (\${user.name}): \${message}\`);
|
|
130
|
+
console.error(\`[_User] Delete failed for \${user.name}: \${message}\`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
success: errors.length === 0,
|
|
136
|
+
deleted,
|
|
137
|
+
total: allUsers.length,
|
|
138
|
+
errors,
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
`;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Generates the schema file content for IdP users. Emits the
|
|
145
|
+
* `_User.name -> <userProfile>.<usernameField>` foreign key by default; pass
|
|
146
|
+
* `includeUserProfileFK: false` to omit it (e.g. when seeding `_User` rows
|
|
147
|
+
* that do not yet have a corresponding userProfile row).
|
|
148
|
+
* @param options - Schema generation options
|
|
149
|
+
* @param options.usernameField - Username field name
|
|
150
|
+
* @param options.userTypeName - TailorDB user type name
|
|
151
|
+
* @param options.includeUserProfileFK - Whether to emit the `_User -> userProfile` foreign key (default `true`)
|
|
152
|
+
* @returns Schema file contents
|
|
153
|
+
*/
|
|
154
|
+
function generateIdpUserSchemaFile(options) {
|
|
155
|
+
const { usernameField, userTypeName, includeUserProfileFK = true } = options;
|
|
156
|
+
return multiline`
|
|
157
|
+
import { t } from "@tailor-platform/sdk";
|
|
158
|
+
import { defineSchema } from "@tailor-platform/sdk/seed";
|
|
159
|
+
import { createStandardSchema } from "@tailor-platform/sdk/test";
|
|
160
|
+
|
|
161
|
+
const schemaType = t.object({
|
|
162
|
+
name: t.string(),
|
|
163
|
+
password: t.string(),
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// Simple identity hook for _User (no TailorDB backing type)
|
|
167
|
+
const hook = <T>(data: unknown) => data as T;
|
|
168
|
+
|
|
169
|
+
export const schema = defineSchema(
|
|
170
|
+
createStandardSchema(schemaType, hook),
|
|
171
|
+
{
|
|
172
|
+
${includeUserProfileFK ? multiline`
|
|
173
|
+
primaryKey: "name",
|
|
174
|
+
indexes: [
|
|
175
|
+
{ name: "_user_name_unique_idx", columns: ["name"], unique: true },
|
|
176
|
+
],
|
|
177
|
+
foreignKeys: [
|
|
178
|
+
{
|
|
179
|
+
column: "name",
|
|
180
|
+
references: {
|
|
181
|
+
table: "${userTypeName}",
|
|
182
|
+
column: "${usernameField}",
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
],
|
|
186
|
+
` : multiline`
|
|
187
|
+
primaryKey: "name",
|
|
188
|
+
indexes: [
|
|
189
|
+
{ name: "_user_name_unique_idx", columns: ["name"], unique: true },
|
|
190
|
+
],
|
|
191
|
+
`}
|
|
192
|
+
}
|
|
193
|
+
);
|
|
194
|
+
|
|
195
|
+
`;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
//#endregion
|
|
199
|
+
//#region src/plugin/builtin/seed/lines-db-processor.ts
|
|
200
|
+
/**
|
|
201
|
+
* Processes TailorDB types to generate lines-db metadata
|
|
202
|
+
* @param type - Parsed TailorDB type
|
|
203
|
+
* @param source - Source file info
|
|
204
|
+
* @returns Generated lines-db metadata
|
|
205
|
+
*/
|
|
206
|
+
function processLinesDb(type, source) {
|
|
207
|
+
if (isPluginGeneratedType(source)) return processLinesDbForPluginType(type, source);
|
|
208
|
+
if (!source.filePath) throw new Error(`Missing source info for type ${type.name}`);
|
|
209
|
+
if (!source.exportName) throw new Error(`Missing export name for type ${type.name}`);
|
|
210
|
+
const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);
|
|
211
|
+
return {
|
|
212
|
+
typeName: type.name,
|
|
213
|
+
exportName: source.exportName,
|
|
214
|
+
importPath: source.filePath,
|
|
215
|
+
optionalFields,
|
|
216
|
+
omitFields,
|
|
217
|
+
foreignKeys,
|
|
218
|
+
indexes
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Process lines-db metadata for plugin-generated types
|
|
223
|
+
* @param type - Parsed TailorDB type
|
|
224
|
+
* @param source - Plugin-generated type source info
|
|
225
|
+
* @returns Generated lines-db metadata with plugin source
|
|
226
|
+
*/
|
|
227
|
+
function processLinesDbForPluginType(type, source) {
|
|
228
|
+
const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);
|
|
229
|
+
return {
|
|
230
|
+
typeName: type.name,
|
|
231
|
+
exportName: source.exportName,
|
|
232
|
+
importPath: "",
|
|
233
|
+
optionalFields,
|
|
234
|
+
omitFields,
|
|
235
|
+
foreignKeys,
|
|
236
|
+
indexes,
|
|
237
|
+
pluginSource: source
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Extract field metadata from TailorDB type
|
|
242
|
+
* @param type - Parsed TailorDB type
|
|
243
|
+
* @returns Field metadata including optional fields, omit fields, indexes, and foreign keys
|
|
244
|
+
*/
|
|
245
|
+
function extractFieldMetadata(type) {
|
|
246
|
+
const optionalFields = ["id"];
|
|
247
|
+
const omitFields = [];
|
|
248
|
+
const indexes = [];
|
|
249
|
+
const foreignKeys = [];
|
|
250
|
+
for (const [fieldName, field] of Object.entries(type.fields)) {
|
|
251
|
+
if (field.config.hooks?.create) optionalFields.push(fieldName);
|
|
252
|
+
if (field.config.serial) omitFields.push(fieldName);
|
|
253
|
+
if (field.config.unique) indexes.push({
|
|
254
|
+
name: `${type.name.toLowerCase()}_${fieldName}_unique_idx`,
|
|
255
|
+
columns: [fieldName],
|
|
256
|
+
unique: true
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
if (type.indexes) for (const [indexName, indexDef] of Object.entries(type.indexes)) indexes.push({
|
|
260
|
+
name: indexName,
|
|
261
|
+
columns: indexDef.fields,
|
|
262
|
+
unique: indexDef.unique
|
|
263
|
+
});
|
|
264
|
+
for (const [fieldName, field] of Object.entries(type.fields)) if (field.relation) foreignKeys.push({
|
|
265
|
+
column: fieldName,
|
|
266
|
+
references: {
|
|
267
|
+
table: field.relation.targetType,
|
|
268
|
+
column: field.relation.key
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
return {
|
|
272
|
+
optionalFields,
|
|
273
|
+
omitFields,
|
|
274
|
+
indexes,
|
|
275
|
+
foreignKeys
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Generate schema options code for lines-db
|
|
280
|
+
* @param foreignKeys - Foreign key definitions
|
|
281
|
+
* @param indexes - Index definitions
|
|
282
|
+
* @returns Schema options code string
|
|
283
|
+
*/
|
|
284
|
+
function generateSchemaOptions(foreignKeys, indexes) {
|
|
285
|
+
const schemaOptions = [];
|
|
286
|
+
if (foreignKeys.length > 0) {
|
|
287
|
+
schemaOptions.push(`foreignKeys: [`);
|
|
288
|
+
foreignKeys.forEach((fk) => {
|
|
289
|
+
schemaOptions.push(` ${JSON.stringify(fk)},`);
|
|
290
|
+
});
|
|
291
|
+
schemaOptions.push(`],`);
|
|
292
|
+
}
|
|
293
|
+
if (indexes.length > 0) {
|
|
294
|
+
schemaOptions.push(`indexes: [`);
|
|
295
|
+
indexes.forEach((index) => {
|
|
296
|
+
schemaOptions.push(` ${JSON.stringify(index)},`);
|
|
297
|
+
});
|
|
298
|
+
schemaOptions.push("],");
|
|
299
|
+
}
|
|
300
|
+
return schemaOptions.length > 0 ? [
|
|
301
|
+
"\n {",
|
|
302
|
+
...schemaOptions.map((option) => ` ${option}`),
|
|
303
|
+
" }"
|
|
304
|
+
].join("\n") : "";
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Generates the schema file content for lines-db (for user-defined types with import)
|
|
308
|
+
* @param metadata - lines-db metadata
|
|
309
|
+
* @param importPath - Import path for the TailorDB type
|
|
310
|
+
* @returns Schema file contents
|
|
311
|
+
*/
|
|
312
|
+
function generateLinesDbSchemaFile(metadata, importPath) {
|
|
313
|
+
const { exportName, optionalFields, omitFields, foreignKeys, indexes } = metadata;
|
|
314
|
+
return multiline`
|
|
315
|
+
import { t } from "@tailor-platform/sdk";
|
|
316
|
+
import { defineSchema } from "@tailor-platform/sdk/seed";
|
|
317
|
+
import { createTailorDBHook, createStandardSchema } from "@tailor-platform/sdk/test";
|
|
318
|
+
import { ${exportName} } from "${importPath}";
|
|
319
|
+
|
|
320
|
+
${multiline`
|
|
321
|
+
const schemaType = t.object({
|
|
322
|
+
...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),
|
|
323
|
+
...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),
|
|
324
|
+
});
|
|
325
|
+
`}
|
|
326
|
+
|
|
327
|
+
const hook = createTailorDBHook(${exportName});
|
|
328
|
+
|
|
329
|
+
export const schema = defineSchema(
|
|
330
|
+
createStandardSchema(schemaType, hook),${generateSchemaOptions(foreignKeys, indexes)}
|
|
331
|
+
);
|
|
332
|
+
|
|
333
|
+
`;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Generates the schema file content using getGeneratedType API
|
|
337
|
+
* (for plugin-generated types)
|
|
338
|
+
* @param metadata - lines-db metadata (must have pluginSource)
|
|
339
|
+
* @param params - Plugin import paths
|
|
340
|
+
* @returns Schema file contents
|
|
341
|
+
*/
|
|
342
|
+
function generateLinesDbSchemaFileWithPluginAPI(metadata, params) {
|
|
343
|
+
const { typeName, exportName, optionalFields, omitFields, foreignKeys, indexes, pluginSource } = metadata;
|
|
344
|
+
if (!pluginSource) throw new Error(`pluginSource is required for plugin-generated type "${typeName}"`);
|
|
345
|
+
const { configImportPath, originalImportPath } = params;
|
|
346
|
+
const schemaTypeCode = multiline`
|
|
347
|
+
const schemaType = t.object({
|
|
348
|
+
...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),
|
|
349
|
+
...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),
|
|
350
|
+
});
|
|
351
|
+
`;
|
|
352
|
+
const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);
|
|
353
|
+
if (pluginSource.originalExportName && originalImportPath && pluginSource.generatedTypeKind) return multiline`
|
|
354
|
+
import { join } from "node:path";
|
|
355
|
+
import { t } from "@tailor-platform/sdk";
|
|
356
|
+
import { getGeneratedType } from "@tailor-platform/sdk/plugin";
|
|
357
|
+
import { defineSchema } from "@tailor-platform/sdk/seed";
|
|
358
|
+
import { createTailorDBHook, createStandardSchema } from "@tailor-platform/sdk/test";
|
|
359
|
+
import { ${pluginSource.originalExportName} } from "${originalImportPath}";
|
|
360
|
+
|
|
361
|
+
const configPath = join(import.meta.dirname, "${configImportPath}");
|
|
362
|
+
const ${exportName} = await getGeneratedType(configPath, "${pluginSource.pluginId}", ${pluginSource.originalExportName}, "${pluginSource.generatedTypeKind}");
|
|
363
|
+
|
|
364
|
+
${schemaTypeCode}
|
|
365
|
+
|
|
366
|
+
const hook = createTailorDBHook(${exportName});
|
|
367
|
+
|
|
368
|
+
export const schema = defineSchema(
|
|
369
|
+
createStandardSchema(schemaType, hook),${schemaOptionsCode}
|
|
370
|
+
);
|
|
371
|
+
|
|
372
|
+
`;
|
|
373
|
+
if (!pluginSource.generatedTypeKind) throw new Error(`Namespace plugin "${pluginSource.pluginId}" must provide generatedTypeKind for type "${typeName}"`);
|
|
374
|
+
return multiline`
|
|
375
|
+
import { join } from "node:path";
|
|
376
|
+
import { t } from "@tailor-platform/sdk";
|
|
377
|
+
import { getGeneratedType } from "@tailor-platform/sdk/plugin";
|
|
378
|
+
import { defineSchema } from "@tailor-platform/sdk/seed";
|
|
379
|
+
import { createTailorDBHook, createStandardSchema } from "@tailor-platform/sdk/test";
|
|
380
|
+
|
|
381
|
+
const configPath = join(import.meta.dirname, "${configImportPath}");
|
|
382
|
+
const ${exportName} = await getGeneratedType(configPath, "${pluginSource.pluginId}", null, "${pluginSource.generatedTypeKind}");
|
|
383
|
+
|
|
384
|
+
${schemaTypeCode}
|
|
385
|
+
|
|
386
|
+
const hook = createTailorDBHook(${exportName});
|
|
387
|
+
|
|
388
|
+
export const schema = defineSchema(
|
|
389
|
+
createStandardSchema(schemaType, hook),${schemaOptionsCode}
|
|
390
|
+
);
|
|
391
|
+
|
|
392
|
+
`;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
//#endregion
|
|
396
|
+
//#region src/plugin/builtin/seed/index.ts
|
|
397
|
+
/** Unique identifier for the seed generator plugin. */
|
|
398
|
+
const SeedGeneratorID = "@tailor-platform/seed";
|
|
399
|
+
function resolveIdpUserSyncFKs(option) {
|
|
400
|
+
return {
|
|
401
|
+
emitUserToIdpFK: !(option?.userToIdp ?? false),
|
|
402
|
+
emitIdpToUserFK: !(option?.idpToUser ?? false)
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Plugin that generates seed data and schema files consumed by the
|
|
407
|
+
* `tailor seed` commands (@tailor-platform/sdk-plugin-seed).
|
|
408
|
+
* @param options - Plugin options
|
|
409
|
+
* @param options.distPath - Output directory path for generated seed files
|
|
410
|
+
* @param options.machineUserName - Default machine user name for authentication
|
|
411
|
+
* @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.
|
|
412
|
+
* @returns Plugin instance with onTailorDBReady hook
|
|
413
|
+
*/
|
|
414
|
+
function seedPlugin(options) {
|
|
415
|
+
return {
|
|
416
|
+
id: SeedGeneratorID,
|
|
417
|
+
description: "Generates seed data and schema files for the tailor seed CLI plugin",
|
|
418
|
+
pluginConfig: options,
|
|
419
|
+
async onTailorDBReady(ctx) {
|
|
420
|
+
const files = [];
|
|
421
|
+
const idpUser = ctx.auth ? processIdpUser(ctx.auth) ?? null : null;
|
|
422
|
+
const idpUserSyncFKs = resolveIdpUserSyncFKs(ctx.pluginConfig.disableIdpUserSync);
|
|
423
|
+
for (const ns of ctx.tailordb) for (const [typeName, type] of Object.entries(ns.types)) {
|
|
424
|
+
const linesDb = processLinesDb(type, assertDefined(ns.sourceInfo.get(typeName), `source info missing for type: ${typeName}`));
|
|
425
|
+
if (idpUserSyncFKs.emitUserToIdpFK && idpUser && typeName === idpUser.schema.userTypeName) linesDb.foreignKeys.push({
|
|
426
|
+
column: idpUser.schema.usernameField,
|
|
427
|
+
references: {
|
|
428
|
+
table: "_User",
|
|
429
|
+
column: "name"
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
files.push({
|
|
433
|
+
path: path.join(ctx.pluginConfig.distPath, "data", `${linesDb.typeName}.jsonl`),
|
|
434
|
+
content: "",
|
|
435
|
+
skipIfExists: true
|
|
436
|
+
});
|
|
437
|
+
const schemaOutputPath = path.join(ctx.pluginConfig.distPath, "data", `${linesDb.typeName}.schema.ts`);
|
|
438
|
+
if (linesDb.pluginSource && linesDb.pluginSource.pluginImportPath) {
|
|
439
|
+
let originalImportPath;
|
|
440
|
+
if (linesDb.pluginSource.originalFilePath && linesDb.pluginSource.originalExportName) {
|
|
441
|
+
const relativePath = path.relative(path.dirname(schemaOutputPath), linesDb.pluginSource.originalFilePath);
|
|
442
|
+
originalImportPath = relativePath.replace(/\.ts$/, "").startsWith(".") ? relativePath.replace(/\.ts$/, "") : `./${relativePath.replace(/\.ts$/, "")}`;
|
|
443
|
+
}
|
|
444
|
+
const schemaContent = generateLinesDbSchemaFileWithPluginAPI(linesDb, {
|
|
445
|
+
configImportPath: path.relative(path.dirname(schemaOutputPath), ctx.configPath),
|
|
446
|
+
originalImportPath
|
|
447
|
+
});
|
|
448
|
+
files.push({
|
|
449
|
+
path: schemaOutputPath,
|
|
450
|
+
content: schemaContent
|
|
451
|
+
});
|
|
452
|
+
} else {
|
|
453
|
+
const relativePath = path.relative(path.dirname(schemaOutputPath), linesDb.importPath);
|
|
454
|
+
const schemaContent = generateLinesDbSchemaFile(linesDb, relativePath.replace(/\.ts$/, "").startsWith(".") ? relativePath.replace(/\.ts$/, "") : `./${relativePath.replace(/\.ts$/, "")}`);
|
|
455
|
+
files.push({
|
|
456
|
+
path: schemaOutputPath,
|
|
457
|
+
content: schemaContent
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (idpUser) {
|
|
462
|
+
files.push({
|
|
463
|
+
path: path.join(ctx.pluginConfig.distPath, idpUser.dataFile),
|
|
464
|
+
content: "",
|
|
465
|
+
skipIfExists: true
|
|
466
|
+
});
|
|
467
|
+
files.push({
|
|
468
|
+
path: path.join(ctx.pluginConfig.distPath, "data", `${idpUser.name}.schema.ts`),
|
|
469
|
+
content: generateIdpUserSchemaFile({
|
|
470
|
+
usernameField: idpUser.schema.usernameField,
|
|
471
|
+
userTypeName: idpUser.schema.userTypeName,
|
|
472
|
+
includeUserProfileFK: idpUserSyncFKs.emitIdpToUserFK
|
|
473
|
+
})
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
return { files };
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
//#endregion
|
|
482
|
+
export { generateIdpTruncateScriptCode as a, generateIdpSeedScriptCode as i, seedPlugin as n, processIdpUser as o, processLinesDb as r, SeedGeneratorID as t };
|
|
483
|
+
//# sourceMappingURL=seed-B-yckgQY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"seed-B-yckgQY.mjs","names":["ml"],"sources":["../src/plugin/builtin/seed/idp-user-processor.ts","../src/plugin/builtin/seed/lines-db-processor.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 let skipped = 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 let lookupError;\n try {\n existing = await client.userByName(input.users[i].name);\n } catch (error) {\n existing = undefined;\n lookupError = error instanceof Error ? error.message : String(error);\n }\n\n if (existing) {\n const { name, ...attributes } = input.users[i];\n if (Object.keys(attributes).length === 0) {\n skipped++;\n } else {\n await client.updateUser({ id: existing.id, ...attributes });\n updated++;\n }\n } else {\n try {\n await client.createUser(input.users[i]);\n created++;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n lookupError ? \\`create failed (\\${message}); lookup failed (\\${lookupError})\\` : message,\n );\n }\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 skipped,\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 * as path from \"pathe\";\nimport { assertDefined } from \"#/utils/assert\";\nimport { processIdpUser, generateIdpUserSchemaFile } from \"./idp-user-processor\";\nimport {\n processLinesDb,\n generateLinesDbSchemaFile,\n generateLinesDbSchemaFileWithPluginAPI,\n type PluginSchemaParams,\n} from \"./lines-db-processor\";\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\nexport type 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/**\n * Plugin that generates seed data and schema files consumed by the\n * `tailor seed` commands (@tailor-platform/sdk-plugin-seed).\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 and schema files for the tailor seed CLI plugin\",\n pluginConfig: options,\n\n async onTailorDBReady(ctx: TailorDBReadyContext<SeedPluginOptions>): Promise<GeneratorResult> {\n const files: GeneratorResult[\"files\"] = [];\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 idpUserSyncFKs = resolveIdpUserSyncFKs(ctx.pluginConfig.disableIdpUserSync);\n\n for (const ns of ctx.tailordb) {\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 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 // Generate empty JSONL data file\n files.push({\n path: path.join(ctx.pluginConfig.distPath, \"data\", `${linesDb.typeName}.jsonl`),\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\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 return { files };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAgB,eAAe,MAAuD;CAEpF,IAAI,KAAK,YAAY,SAAS,gBAAgB,CAAC,KAAK,aAClD;CAGF,MAAM,EAAE,UAAU,kBAAkB,KAAK;CAEzC,OAAO;EACL,MA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,KAAK,SACxB,KAAK,QAAQ,gBAAgB,GAC7B,QAAQ,aAAa,gBACvB;MACA,qBAAqB,aAAa,QAAQ,SAAS,EAAE,CAAC,CAAC,WAAW,GAAG,IACjE,aAAa,QAAQ,SAAS,EAAE,IAChC,KAAK,aAAa,QAAQ,SAAS,EAAE;KAC3C;KAUA,MAAM,gBAAgB,uCAAuC,SAAS;MAJpE,kBAHuB,KAAK,SAAS,KAAK,QAAQ,gBAAgB,GAAG,IAAI,UAG1D;MACf;KAGyE,CAAC;KAE5E,MAAM,KAAK;MACT,MAAM;MACN,SAAS;KACX,CAAC;IACH,OAAO;KAEL,MAAM,eAAe,KAAK,SAAS,KAAK,QAAQ,gBAAgB,GAAG,QAAQ,UAAU;KAIrF,MAAM,gBAAgB,0BAA0B,SAHzB,aAAa,QAAQ,SAAS,EAAE,CAAC,CAAC,WAAW,GAAG,IACnE,aAAa,QAAQ,SAAS,EAAE,IAChC,KAAK,aAAa,QAAQ,SAAS,EAAE,GAC8B;KAEvE,MAAM,KAAK;MACT,MAAM;MACN,SAAS;KACX,CAAC;IACH;GACF;GAGF,IAAI,SAAS;IAEX,MAAM,KAAK;KACT,MAAM,KAAK,KAAK,IAAI,aAAa,UAAU,QAAQ,QAAQ;KAC3D,SAAS;KACT,cAAc;IAChB,CAAC;IAGD,MAAM,KAAK;KACT,MAAM,KAAK,KAAK,IAAI,aAAa,UAAU,QAAQ,GAAG,QAAQ,KAAK,WAAW;KAC9E,SAAS,0BAA0B;MACjC,eAAe,QAAQ,OAAO;MAC9B,cAAc,QAAQ,OAAO;MAC7B,sBAAsB,eAAe;KACvC,CAAC;IACH,CAAC;GACH;GAEA,OAAO,EAAE,MAAM;EACjB;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as logger, r as styles } from "./logger-
|
|
2
|
-
import { t as createCLIError } from "./errors-
|
|
1
|
+
import { n as logger, r as styles } from "./logger-CXQq9YIp.mjs";
|
|
2
|
+
import { t as createCLIError } from "./errors-D7583Zz7.mjs";
|
|
3
3
|
import * as path from "pathe";
|
|
4
4
|
import { readPackageJSON } from "pkg-types";
|
|
5
5
|
import { spawnSync } from "node:child_process";
|
|
@@ -128,4 +128,4 @@ async function upgrade(options) {
|
|
|
128
128
|
|
|
129
129
|
//#endregion
|
|
130
130
|
export { upgrade };
|
|
131
|
-
//# sourceMappingURL=service-
|
|
131
|
+
//# sourceMappingURL=service-B5WynBHQ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-
|
|
1
|
+
{"version":3,"file":"service-B5WynBHQ.mjs","names":["CLIError"],"sources":["../src/cli/commands/upgrade/version-detector.ts","../src/cli/commands/upgrade/service.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { readPackageJSON } from \"pkg-types\";\n\nconst SDK_PACKAGE_NAME = \"@tailor-platform/sdk\";\n\n/**\n * Detect the installed SDK version from the user's project.\n * Walks up from projectRoot to find the SDK package in node_modules,\n * matching Node's module resolution for workspace setups with hoisted deps.\n * @param projectRoot - The project root directory to search from\n * @returns The installed SDK version string, or null if not found\n */\nexport async function detectInstalledVersion(projectRoot: string): Promise<string | null> {\n let dir = path.resolve(projectRoot);\n // loop exits when a package.json is found or the root is reached\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n while (true) {\n try {\n const sdkPath = path.join(dir, \"node_modules\", SDK_PACKAGE_NAME);\n const pkg = await readPackageJSON(sdkPath);\n if (pkg.version) return pkg.version;\n } catch {\n // Not found at this level, try parent\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n","import { spawnSync } from \"node:child_process\";\nimport { CLIError } from \"#/cli/shared/errors\";\nimport { logger, styles } from \"#/cli/shared/logger\";\nimport { detectInstalledVersion } from \"./version-detector\";\nimport type { RunOutput } from \"./types\";\n\ninterface UpgradeOptions {\n from: string;\n dryRun: boolean;\n path: string;\n}\n\n/**\n * Print the upgrade summary to the terminal.\n * @param output - The parsed JSON output from sdk-codemod\n * @param dryRun - Whether this was a dry-run\n */\nfunction printUpgradeSummary(output: RunOutput, dryRun: boolean): void {\n if (dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} No files were modified.`);\n logger.log(\"\");\n }\n\n const total = output.codemodsApplied + output.codemodsSkipped + output.errors.length;\n logger.info(\n `Upgrade complete: ${styles.success(`${output.codemodsApplied} applied`)}, ${styles.dim(`${output.codemodsSkipped} skipped`)} (${total} total codemods)`,\n );\n\n if (output.filesModified.length > 0) {\n logger.log(\"\");\n logger.info(\n `${dryRun ? \"Files that would be modified\" : \"Modified files\"} (${output.filesModified.length}):`,\n );\n for (const file of output.filesModified) {\n logger.log(` ${styles.path(file)}`);\n }\n }\n\n if (output.warnings.length > 0) {\n logger.log(\"\");\n logger.warn(`Manual attention needed (${output.warnings.length}):`);\n for (const warning of output.warnings) {\n logger.log(` ${styles.warning(\"!\")} ${warning}`);\n }\n }\n\n if (output.errors.length > 0) {\n logger.log(\"\");\n logger.error(`Failed codemods (${output.errors.length}):`);\n for (const { codemodId, message } of output.errors) {\n logger.log(` ${styles.error(codemodId)}: ${message}`);\n }\n }\n}\n\n/**\n * Run the upgrade pipeline:\n * 1. Detect target SDK version from node_modules\n * 2. Invoke @tailor-platform/sdk-codemod CLI\n * 3. Parse JSON output and display results\n * @param options - Upgrade options\n */\nexport async function upgrade(options: UpgradeOptions): Promise<void> {\n const projectRoot = options.path;\n\n // Step 1: Detect target SDK version (the newly installed version)\n const targetVersion = await detectInstalledVersion(projectRoot);\n if (!targetVersion) {\n throw CLIError({\n message: `Could not detect installed @tailor-platform/sdk version in ${projectRoot}`,\n suggestion:\n \"Ensure @tailor-platform/sdk is installed. Run 'pnpm install' or 'npm install' first.\",\n command: \"upgrade\",\n });\n }\n\n logger.info(\n `Upgrading from ${styles.highlight(options.from)} → ${styles.highlight(targetVersion)}`,\n );\n\n if (options.dryRun) {\n logger.info(`${styles.bold(\"[Dry Run]\")} Changes will be previewed but not applied.`);\n }\n\n logger.log(\"\");\n\n // Step 2: Invoke sdk-codemod CLI\n // Use \"latest\" because sdk-codemod may not be published at the exact same\n // version as @tailor-platform/sdk. Version filtering is handled internally\n // by sdk-codemod's registry via the --from / --to arguments.\n const npxCommand = process.platform === \"win32\" ? \"npx.cmd\" : \"npx\";\n\n const result = spawnSync(\n npxCommand,\n [\n \"@tailor-platform/sdk-codemod@latest\",\n \"--from\",\n options.from,\n \"--to\",\n targetVersion,\n \"--target\",\n projectRoot,\n ...(options.dryRun ? [\"--dry-run\"] : []),\n ],\n {\n cwd: projectRoot,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n encoding: \"utf-8\",\n timeout: 300_000,\n },\n );\n\n if (result.error) {\n throw CLIError({\n message: `Failed to run @tailor-platform/sdk-codemod: ${result.error.message}`,\n suggestion: \"Ensure npx is available and the network is accessible.\",\n command: \"upgrade\",\n });\n }\n\n // Check for non-zero exit without a launch error (e.g. registry/auth/network failures)\n if (result.status !== 0 && !result.stdout.trim()) {\n throw CLIError({\n message: `@tailor-platform/sdk-codemod exited with code ${result.status}`,\n details: result.stderr.trim() || \"(no stderr output)\",\n suggestion:\n \"Review the error above. Common causes: invalid version arguments, network issues, or missing package registry access.\",\n command: \"upgrade\",\n });\n }\n\n // Forward captured stderr so users see dry-run diffs and progress messages\n // written by sdk-codemod. stderr is piped (not inherited) so that the error\n // path above can surface it via CLIError, but on success we still need to\n // replay it verbatim to keep the colorized unified diff output visible.\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n // Step 3: Parse JSON output\n let output: RunOutput;\n try {\n output = JSON.parse(result.stdout);\n } catch {\n throw CLIError({\n message: \"Failed to parse output from @tailor-platform/sdk-codemod\",\n details: result.stdout || \"(empty stdout)\",\n suggestion: \"This is likely a bug. Please report it.\",\n command: \"upgrade\",\n });\n }\n\n // Step 4: Display results\n // Emit structured data on stdout (honors --json via logger.out) and\n // human-readable summary on stderr (via printUpgradeSummary).\n logger.out(output);\n printUpgradeSummary(output, options.dryRun);\n\n if (output.errors.length > 0) {\n throw CLIError({\n message: `Upgrade completed with ${output.errors.length} error(s)`,\n suggestion: \"Review the errors above and re-run the upgrade after fixing the issues.\",\n command: \"upgrade\",\n });\n }\n}\n"],"mappings":";;;;;;;AAGA,MAAM,mBAAmB;;;;;;;;AASzB,eAAsB,uBAAuB,aAA6C;CACxF,IAAI,MAAM,KAAK,QAAQ,WAAW;CAGlC,OAAO,MAAM;EACX,IAAI;GAEF,MAAM,MAAM,MAAM,gBADF,KAAK,KAAK,KAAK,gBAAgB,gBACP,CAAC;GACzC,IAAI,IAAI,SAAS,OAAO,IAAI;EAC9B,QAAQ,CAER;EACA,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,WAAW,KAAK;EACpB,MAAM;CACR;CACA,OAAO;AACT;;;;;;;;;ACZA,SAAS,oBAAoB,QAAmB,QAAuB;CACrE,IAAI,QAAQ;EACV,OAAO,KAAK,GAAG,OAAO,KAAK,WAAW,EAAE,yBAAyB;EACjE,OAAO,IAAI,EAAE;CACf;CAEA,MAAM,QAAQ,OAAO,kBAAkB,OAAO,kBAAkB,OAAO,OAAO;CAC9E,OAAO,KACL,qBAAqB,OAAO,QAAQ,GAAG,OAAO,gBAAgB,SAAS,EAAE,IAAI,OAAO,IAAI,GAAG,OAAO,gBAAgB,SAAS,EAAE,IAAI,MAAM,iBACzI;CAEA,IAAI,OAAO,cAAc,SAAS,GAAG;EACnC,OAAO,IAAI,EAAE;EACb,OAAO,KACL,GAAG,SAAS,iCAAiC,iBAAiB,IAAI,OAAO,cAAc,OAAO,GAChG;EACA,KAAK,MAAM,QAAQ,OAAO,eACxB,OAAO,IAAI,KAAK,OAAO,KAAK,IAAI,GAAG;CAEvC;CAEA,IAAI,OAAO,SAAS,SAAS,GAAG;EAC9B,OAAO,IAAI,EAAE;EACb,OAAO,KAAK,4BAA4B,OAAO,SAAS,OAAO,GAAG;EAClE,KAAK,MAAM,WAAW,OAAO,UAC3B,OAAO,IAAI,KAAK,OAAO,Q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