@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.
Files changed (180) hide show
  1. package/CHANGELOG.md +631 -0
  2. package/dist/{application-GzW98_Xr.mjs → application-CM6hKnSK.mjs} +489 -118
  3. package/dist/application-CM6hKnSK.mjs.map +1 -0
  4. package/dist/application-CXNaUNhv.mjs +3 -0
  5. package/dist/cli/commands/deploy/aigateway.d.mts +2 -2
  6. package/dist/cli/commands/deploy/application.d.mts +2 -2
  7. package/dist/cli/commands/deploy/auth.d.mts +2 -2
  8. package/dist/cli/commands/deploy/deploy.d.mts +1 -0
  9. package/dist/cli/commands/deploy/executor.d.mts +2 -2
  10. package/dist/cli/commands/deploy/function-registry.d.mts +1 -2
  11. package/dist/cli/commands/deploy/idp.d.mts +2 -2
  12. package/dist/cli/commands/deploy/label.d.mts +2 -0
  13. package/dist/cli/commands/deploy/resolver.d.mts +2 -2
  14. package/dist/cli/commands/deploy/secret-manager.d.mts +1 -1
  15. package/dist/cli/commands/deploy/staticwebsite.d.mts +2 -2
  16. package/dist/cli/commands/deploy/tailordb/index.d.mts +4 -2
  17. package/dist/cli/commands/deploy/types.d.mts +2 -1
  18. package/dist/cli/commands/deploy/workflow-execution-policy.d.mts +1 -2
  19. package/dist/cli/commands/deploy/workflow.d.mts +2 -2
  20. package/dist/cli/commands/executor/get.d.mts +1 -10
  21. package/dist/cli/commands/executor/jobs.d.mts +1 -38
  22. package/dist/cli/commands/executor/trigger.d.mts +1 -11
  23. package/dist/cli/commands/generate/seed/bundler.d.mts +2 -1
  24. package/dist/cli/commands/tailordb/migrate/bundler.d.mts +3 -2
  25. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +11 -1
  26. package/dist/cli/commands/tailordb/migrate/schema-checks.d.mts +5 -0
  27. package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +1 -1
  28. package/dist/cli/commands/workflow/executions.d.mts +1 -13
  29. package/dist/cli/commands/workflow/get.d.mts +1 -10
  30. package/dist/cli/commands/workflow/start.d.mts +2 -14
  31. package/dist/cli/index.mjs +12 -6552
  32. package/dist/cli/lib.d.mts +14 -15
  33. package/dist/cli/lib.mjs +203 -46
  34. package/dist/cli/lib.mjs.map +1 -1
  35. package/dist/cli/{index.d.mts → main.d.mts} +1 -1
  36. package/dist/cli/main.mjs +6777 -0
  37. package/dist/cli/main.mjs.map +1 -0
  38. package/dist/cli/services/http-adapter/bundler.d.mts +1 -0
  39. package/dist/cli/services/workflow/bundler.d.mts +2 -1
  40. package/dist/cli/shared/client.d.mts +28 -3
  41. package/dist/cli/shared/config-loader.d.mts +11 -4
  42. package/dist/cli/shared/error-json.d.mts +23 -0
  43. package/dist/cli/shared/script-executor.d.mts +6 -3
  44. package/dist/cli/shared/seed-chunker.d.mts +2 -7
  45. package/dist/cli/shared/seed-context.d.mts +49 -0
  46. package/dist/cli/shared/tailordb-namespaces.d.mts +7 -4
  47. package/dist/cli/shared/tsconfig-paths-plugin.d.mts +2 -0
  48. package/dist/cli/shared/type-generator.d.mts +4 -3
  49. package/dist/completion/zsh-worker.zsh +85 -22
  50. package/dist/configure/config/types.d.mts +29 -4
  51. package/dist/configure/index.d.mts +4 -3
  52. package/dist/configure/index.mjs +183 -6
  53. package/dist/configure/index.mjs.map +1 -1
  54. package/dist/configure/services/executor/index.d.mts +2 -2
  55. package/dist/configure/services/executor/trigger/event.d.mts +245 -2
  56. package/dist/configure/services/executor/trigger/index.d.mts +3 -3
  57. package/dist/configure/services/idp/index.d.mts +2 -2
  58. package/dist/configure/services/idp/permission.d.mts +1 -16
  59. package/dist/configure/services/idp/types.d.mts +5 -1
  60. package/dist/configure/services/index.d.mts +4 -3
  61. package/dist/configure/services/resolver/index.d.mts +2 -1
  62. package/dist/configure/services/resolver/permission.d.mts +64 -0
  63. package/dist/configure/services/resolver/resolver.d.mts +14 -2
  64. package/dist/configure/services/tailordb/index.d.mts +0 -1
  65. package/dist/configure/services/tailordb/permission.d.mts +1 -16
  66. package/dist/configure/services/workflow/execution-policy.d.mts +3 -3
  67. package/dist/configure/services/workflow/execution-policy.types.d.mts +1 -1
  68. package/dist/configure/services/workflow/job.d.mts +11 -2
  69. package/dist/configure/services/workflow/workflow.d.mts +10 -0
  70. package/dist/configure/types/permission-operand.types.d.mts +20 -0
  71. package/dist/{crashreport-CxHne11E.mjs → crashreport-B5LqCTfF.mjs} +2 -2
  72. package/dist/{crashreport-CxHne11E.mjs.map → crashreport-B5LqCTfF.mjs.map} +1 -1
  73. package/dist/{crashreport-0ioNRZ4K.mjs → crashreport-eI7ty7ok.mjs} +1 -1
  74. package/dist/{errors-DfnF4ibq.mjs → errors-D7583Zz7.mjs} +2 -44
  75. package/dist/errors-D7583Zz7.mjs.map +1 -0
  76. package/dist/{globals-CBZ0egXT.mjs → globals-TfAVItuK.mjs} +21 -5
  77. package/dist/globals-TfAVItuK.mjs.map +1 -0
  78. package/dist/logger-BtX0suGY.mjs +48 -0
  79. package/dist/logger-BtX0suGY.mjs.map +1 -0
  80. package/dist/{logger-BwS4ppwO.mjs → logger-CXQq9YIp.mjs} +110 -13
  81. package/dist/logger-CXQq9YIp.mjs.map +1 -0
  82. package/dist/node-builtins-CmaL2Cbq.mjs +36 -0
  83. package/dist/node-builtins-CmaL2Cbq.mjs.map +1 -0
  84. package/dist/plugin/builtin/enum-constants/index.mjs +115 -2
  85. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -0
  86. package/dist/plugin/builtin/file-utils/index.mjs +149 -2
  87. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -0
  88. package/dist/plugin/builtin/kysely-type/index.mjs +274 -2
  89. package/dist/plugin/builtin/kysely-type/index.mjs.map +1 -0
  90. package/dist/plugin/builtin/seed/index.d.mts +3 -2
  91. package/dist/plugin/builtin/seed/index.mjs +1 -1
  92. package/dist/plugin/builtin/seed/seed-type-processor.d.mts +21 -0
  93. package/dist/plugin/builtin/seed/types.d.mts +2 -0
  94. package/dist/{register-ts-hook-DvEs6YsL.mjs → register-ts-hook-LYV7zH-e.mjs} +2953 -996
  95. package/dist/register-ts-hook-LYV7zH-e.mjs.map +1 -0
  96. package/dist/{registry-i7EdJ-D5.mjs → registry-BIGVUrMB.mjs} +3 -3
  97. package/dist/registry-BIGVUrMB.mjs.map +1 -0
  98. package/dist/runtime/globals.d.mts +7 -0
  99. package/dist/runtime/index.d.mts +3 -1
  100. package/dist/runtime/index.mjs +3 -2
  101. package/dist/runtime/logger.d.mts +98 -0
  102. package/dist/runtime/logger.mjs +3 -0
  103. package/dist/runtime/workflow.d.mts +15 -7
  104. package/dist/runtime/workflow.mjs +1 -1
  105. package/dist/seed-B-yckgQY.mjs +483 -0
  106. package/dist/seed-B-yckgQY.mjs.map +1 -0
  107. package/dist/{service-DaeJlBoH.mjs → service-B5WynBHQ.mjs} +3 -3
  108. package/dist/{service-DaeJlBoH.mjs.map → service-B5WynBHQ.mjs.map} +1 -1
  109. package/dist/service-M7OYziQP.mjs +3 -0
  110. package/dist/{service-Dmxa2I4i.mjs → service-k1xy_A5G.mjs} +30 -4
  111. package/dist/service-k1xy_A5G.mjs.map +1 -0
  112. package/dist/{service_pb-BoLM0X4K.mjs → service_pb-D5--My_M.mjs} +5 -5
  113. package/dist/service_pb-D5--My_M.mjs.map +1 -0
  114. package/dist/{service_pb-r1T7kpJc.mjs → service_pb-i8CmnQP4.mjs} +1 -1
  115. package/dist/tailor-proto/src/tailor/v1/application_pb.d.mts +106 -1
  116. package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +6 -1
  117. package/dist/tailor-proto/src/tailor/v1/executor_resource_pb.d.mts +24 -1
  118. package/dist/tailor-proto/src/tailor/v1/function_pb.d.mts +49 -1
  119. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +89 -6
  120. package/dist/tailor-proto/src/tailor/v1/telemetryrouter_resource_pb.d.mts +26 -1
  121. package/dist/tailor-proto/src/tailor/v1/workflow_pb.d.mts +101 -1
  122. package/dist/tailor-proto/src/tailor/v1/workflow_resource_pb.d.mts +22 -1
  123. package/dist/types/auth.generated.d.mts +14 -2
  124. package/dist/types/executor.generated.d.mts +45 -3
  125. package/dist/types/http-adapter.generated.d.mts +5 -0
  126. package/dist/types/idp.generated.d.mts +31 -1
  127. package/dist/types/resolver.generated.d.mts +30 -2
  128. package/dist/types/tailordb.generated.d.mts +15 -3
  129. package/dist/utils/test/index.d.mts +1 -2
  130. package/dist/utils/test/index.mjs +1 -169
  131. package/dist/utils/test/index.mjs.map +1 -1
  132. package/dist/vitest/environment.mjs +1 -1
  133. package/dist/vitest/index.d.mts +6 -4
  134. package/dist/vitest/index.mjs +112 -62
  135. package/dist/vitest/index.mjs.map +1 -1
  136. package/dist/vitest/mock.d.mts +2 -1
  137. package/dist/vitest/mocks/logger.d.mts +45 -0
  138. package/dist/vitest/mocks/workflow.d.mts +8 -8
  139. package/dist/vitest/setup.mjs +1 -1
  140. package/dist/{workflow-CsBvRE3g.mjs → workflow-Bamae_Yc.mjs} +5 -5
  141. package/dist/workflow-Bamae_Yc.mjs.map +1 -0
  142. package/dist/{workspace_resource_pb-Db3fv68L.mjs → workspace_resource_pb-DXnO2AT-.mjs} +13 -8
  143. package/dist/workspace_resource_pb-DXnO2AT-.mjs.map +1 -0
  144. package/docs/cli/application.md +5 -1
  145. package/docs/cli/tailordb.md +47 -13
  146. package/docs/cli-reference.md +38 -30
  147. package/docs/configuration.md +54 -2
  148. package/docs/github-actions.md +2 -2
  149. package/docs/migration/v2.md +408 -5
  150. package/docs/runtime.md +5 -1
  151. package/docs/services/executor.md +83 -3
  152. package/docs/services/idp.md +8 -6
  153. package/docs/services/resolver.md +60 -4
  154. package/docs/services/tailordb-migration.md +31 -7
  155. package/docs/services/tailordb.md +7 -5
  156. package/docs/services/workflow.md +33 -3
  157. package/docs/testing.md +34 -7
  158. package/package.json +31 -24
  159. package/dist/application-GzW98_Xr.mjs.map +0 -1
  160. package/dist/application-OM0taSPn.mjs +0 -3
  161. package/dist/cli/index.mjs.map +0 -1
  162. package/dist/enum-constants-j9QBF0cB.mjs +0 -116
  163. package/dist/enum-constants-j9QBF0cB.mjs.map +0 -1
  164. package/dist/errors-DfnF4ibq.mjs.map +0 -1
  165. package/dist/file-utils-yEiIS4nJ.mjs +0 -150
  166. package/dist/file-utils-yEiIS4nJ.mjs.map +0 -1
  167. package/dist/globals-CBZ0egXT.mjs.map +0 -1
  168. package/dist/kysely-type-DqIRgDYR.mjs +0 -275
  169. package/dist/kysely-type-DqIRgDYR.mjs.map +0 -1
  170. package/dist/logger-BwS4ppwO.mjs.map +0 -1
  171. package/dist/register-ts-hook-DvEs6YsL.mjs.map +0 -1
  172. package/dist/registry-i7EdJ-D5.mjs.map +0 -1
  173. package/dist/seed-CRSQJI_z.mjs +0 -1170
  174. package/dist/seed-CRSQJI_z.mjs.map +0 -1
  175. package/dist/service-BJAQ70e5.mjs +0 -3
  176. package/dist/service-Dmxa2I4i.mjs.map +0 -1
  177. package/dist/service_pb-BoLM0X4K.mjs.map +0 -1
  178. package/dist/utils/test/mock.d.mts +0 -86
  179. package/dist/workflow-CsBvRE3g.mjs.map +0 -1
  180. package/dist/workspace_resource_pb-Db3fv68L.mjs.map +0 -1
@@ -1,1170 +0,0 @@
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
-
39
- for (let i = 0; i < input.users.length; i++) {
40
- try {
41
- await client.createUser(input.users[i]);
42
- processed++;
43
- console.log(\`[_User] \${i + 1}/\${input.users.length}: \${input.users[i].name}\`);
44
- } catch (error) {
45
- const message = error instanceof Error ? error.message : String(error);
46
- errors.push(\`Row \${i} (\${input.users[i].name}): \${message}\`);
47
- console.error(\`[_User] Row \${i} failed: \${message}\`);
48
- }
49
- }
50
-
51
- return {
52
- success: errors.length === 0,
53
- processed,
54
- errors,
55
- };
56
- }
57
- `;
58
- }
59
- /**
60
- * Generates the server-side IDP truncation script code for testExecScript execution.
61
- * Lists all users with pagination and deletes each one.
62
- * @param idpNamespace - The IDP namespace name
63
- * @returns Script code string
64
- */
65
- function generateIdpTruncateScriptCode(idpNamespace) {
66
- return multiline`
67
- export async function main() {
68
- const client = new tailor.idp.Client({ namespace: "${idpNamespace}" });
69
- const errors = [];
70
- let deleted = 0;
71
-
72
- // List all users with pagination
73
- let after = undefined;
74
- const allUsers = [];
75
- do {
76
- const response = await client.users(after ? { after } : undefined);
77
- allUsers.push(...(response.users || []));
78
- after = response.nextPageToken;
79
- } while (after);
80
-
81
- console.log(\`Found \${allUsers.length} IDP users to delete\`);
82
-
83
- for (const user of allUsers) {
84
- try {
85
- await client.deleteUser(user.id);
86
- deleted++;
87
- console.log(\`[_User] Deleted \${deleted}/\${allUsers.length}: \${user.name}\`);
88
- } catch (error) {
89
- const message = error instanceof Error ? error.message : String(error);
90
- errors.push(\`User \${user.id} (\${user.name}): \${message}\`);
91
- console.error(\`[_User] Delete failed for \${user.name}: \${message}\`);
92
- }
93
- }
94
-
95
- return {
96
- success: errors.length === 0,
97
- deleted,
98
- total: allUsers.length,
99
- errors,
100
- };
101
- }
102
- `;
103
- }
104
- /**
105
- * Generates the schema file content for IdP users. Emits the
106
- * `_User.name -> <userProfile>.<usernameField>` foreign key by default; pass
107
- * `includeUserProfileFK: false` to omit it (e.g. when seeding `_User` rows
108
- * that do not yet have a corresponding userProfile row).
109
- * @param options - Schema generation options
110
- * @param options.usernameField - Username field name
111
- * @param options.userTypeName - TailorDB user type name
112
- * @param options.includeUserProfileFK - Whether to emit the `_User -> userProfile` foreign key (default `true`)
113
- * @returns Schema file contents
114
- */
115
- function generateIdpUserSchemaFile(options) {
116
- const { usernameField, userTypeName, includeUserProfileFK = true } = options;
117
- return multiline`
118
- import { t } from "@tailor-platform/sdk";
119
- import { defineSchema } from "@tailor-platform/sdk/seed";
120
- import { createStandardSchema } from "@tailor-platform/sdk/test";
121
-
122
- const schemaType = t.object({
123
- name: t.string(),
124
- password: t.string(),
125
- });
126
-
127
- // Simple identity hook for _User (no TailorDB backing type)
128
- const hook = <T>(data: unknown) => data as T;
129
-
130
- export const schema = defineSchema(
131
- createStandardSchema(schemaType, hook),
132
- {
133
- ${includeUserProfileFK ? multiline`
134
- primaryKey: "name",
135
- indexes: [
136
- { name: "_user_name_unique_idx", columns: ["name"], unique: true },
137
- ],
138
- foreignKeys: [
139
- {
140
- column: "name",
141
- references: {
142
- table: "${userTypeName}",
143
- column: "${usernameField}",
144
- },
145
- },
146
- ],
147
- ` : multiline`
148
- primaryKey: "name",
149
- indexes: [
150
- { name: "_user_name_unique_idx", columns: ["name"], unique: true },
151
- ],
152
- `}
153
- }
154
- );
155
-
156
- `;
157
- }
158
-
159
- //#endregion
160
- //#region src/plugin/builtin/seed/lines-db-processor.ts
161
- /**
162
- * Processes TailorDB types to generate lines-db metadata
163
- * @param type - Parsed TailorDB type
164
- * @param source - Source file info
165
- * @returns Generated lines-db metadata
166
- */
167
- function processLinesDb(type, source) {
168
- if (isPluginGeneratedType(source)) return processLinesDbForPluginType(type, source);
169
- if (!source.filePath) throw new Error(`Missing source info for type ${type.name}`);
170
- if (!source.exportName) throw new Error(`Missing export name for type ${type.name}`);
171
- const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);
172
- return {
173
- typeName: type.name,
174
- exportName: source.exportName,
175
- importPath: source.filePath,
176
- optionalFields,
177
- omitFields,
178
- foreignKeys,
179
- indexes
180
- };
181
- }
182
- /**
183
- * Process lines-db metadata for plugin-generated types
184
- * @param type - Parsed TailorDB type
185
- * @param source - Plugin-generated type source info
186
- * @returns Generated lines-db metadata with plugin source
187
- */
188
- function processLinesDbForPluginType(type, source) {
189
- const { optionalFields, omitFields, indexes, foreignKeys } = extractFieldMetadata(type);
190
- return {
191
- typeName: type.name,
192
- exportName: source.exportName,
193
- importPath: "",
194
- optionalFields,
195
- omitFields,
196
- foreignKeys,
197
- indexes,
198
- pluginSource: source
199
- };
200
- }
201
- /**
202
- * Extract field metadata from TailorDB type
203
- * @param type - Parsed TailorDB type
204
- * @returns Field metadata including optional fields, omit fields, indexes, and foreign keys
205
- */
206
- function extractFieldMetadata(type) {
207
- const optionalFields = ["id"];
208
- const omitFields = [];
209
- const indexes = [];
210
- const foreignKeys = [];
211
- for (const [fieldName, field] of Object.entries(type.fields)) {
212
- if (field.config.hooks?.create) optionalFields.push(fieldName);
213
- if (field.config.serial) omitFields.push(fieldName);
214
- if (field.config.unique) indexes.push({
215
- name: `${type.name.toLowerCase()}_${fieldName}_unique_idx`,
216
- columns: [fieldName],
217
- unique: true
218
- });
219
- }
220
- if (type.indexes) for (const [indexName, indexDef] of Object.entries(type.indexes)) indexes.push({
221
- name: indexName,
222
- columns: indexDef.fields,
223
- unique: indexDef.unique
224
- });
225
- for (const [fieldName, field] of Object.entries(type.fields)) if (field.relation) foreignKeys.push({
226
- column: fieldName,
227
- references: {
228
- table: field.relation.targetType,
229
- column: field.relation.key
230
- }
231
- });
232
- return {
233
- optionalFields,
234
- omitFields,
235
- indexes,
236
- foreignKeys
237
- };
238
- }
239
- /**
240
- * Generate schema options code for lines-db
241
- * @param foreignKeys - Foreign key definitions
242
- * @param indexes - Index definitions
243
- * @returns Schema options code string
244
- */
245
- function generateSchemaOptions(foreignKeys, indexes) {
246
- const schemaOptions = [];
247
- if (foreignKeys.length > 0) {
248
- schemaOptions.push(`foreignKeys: [`);
249
- foreignKeys.forEach((fk) => {
250
- schemaOptions.push(` ${JSON.stringify(fk)},`);
251
- });
252
- schemaOptions.push(`],`);
253
- }
254
- if (indexes.length > 0) {
255
- schemaOptions.push(`indexes: [`);
256
- indexes.forEach((index) => {
257
- schemaOptions.push(` ${JSON.stringify(index)},`);
258
- });
259
- schemaOptions.push("],");
260
- }
261
- return schemaOptions.length > 0 ? [
262
- "\n {",
263
- ...schemaOptions.map((option) => ` ${option}`),
264
- " }"
265
- ].join("\n") : "";
266
- }
267
- /**
268
- * Generates the schema file content for lines-db (for user-defined types with import)
269
- * @param metadata - lines-db metadata
270
- * @param importPath - Import path for the TailorDB type
271
- * @returns Schema file contents
272
- */
273
- function generateLinesDbSchemaFile(metadata, importPath) {
274
- const { exportName, optionalFields, omitFields, foreignKeys, indexes } = metadata;
275
- return multiline`
276
- import { t } from "@tailor-platform/sdk";
277
- import { defineSchema } from "@tailor-platform/sdk/seed";
278
- import { createTailorDBHook, createStandardSchema } from "@tailor-platform/sdk/test";
279
- import { ${exportName} } from "${importPath}";
280
-
281
- ${multiline`
282
- const schemaType = t.object({
283
- ...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),
284
- ...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),
285
- });
286
- `}
287
-
288
- const hook = createTailorDBHook(${exportName});
289
-
290
- export const schema = defineSchema(
291
- createStandardSchema(schemaType, hook),${generateSchemaOptions(foreignKeys, indexes)}
292
- );
293
-
294
- `;
295
- }
296
- /**
297
- * Generates the schema file content using getGeneratedType API
298
- * (for plugin-generated types)
299
- * @param metadata - lines-db metadata (must have pluginSource)
300
- * @param params - Plugin import paths
301
- * @returns Schema file contents
302
- */
303
- function generateLinesDbSchemaFileWithPluginAPI(metadata, params) {
304
- const { typeName, exportName, optionalFields, omitFields, foreignKeys, indexes, pluginSource } = metadata;
305
- if (!pluginSource) throw new Error(`pluginSource is required for plugin-generated type "${typeName}"`);
306
- const { configImportPath, originalImportPath } = params;
307
- const schemaTypeCode = multiline`
308
- const schemaType = t.object({
309
- ...${exportName}.pickFields(${JSON.stringify(optionalFields)}, { optional: true }),
310
- ...${exportName}.omitFields(${JSON.stringify([...optionalFields, ...omitFields])}),
311
- });
312
- `;
313
- const schemaOptionsCode = generateSchemaOptions(foreignKeys, indexes);
314
- if (pluginSource.originalExportName && originalImportPath && pluginSource.generatedTypeKind) return multiline`
315
- import { join } from "node:path";
316
- import { t } from "@tailor-platform/sdk";
317
- import { getGeneratedType } from "@tailor-platform/sdk/plugin";
318
- import { defineSchema } from "@tailor-platform/sdk/seed";
319
- import { createTailorDBHook, createStandardSchema } from "@tailor-platform/sdk/test";
320
- import { ${pluginSource.originalExportName} } from "${originalImportPath}";
321
-
322
- const configPath = join(import.meta.dirname, "${configImportPath}");
323
- const ${exportName} = await getGeneratedType(configPath, "${pluginSource.pluginId}", ${pluginSource.originalExportName}, "${pluginSource.generatedTypeKind}");
324
-
325
- ${schemaTypeCode}
326
-
327
- const hook = createTailorDBHook(${exportName});
328
-
329
- export const schema = defineSchema(
330
- createStandardSchema(schemaType, hook),${schemaOptionsCode}
331
- );
332
-
333
- `;
334
- if (!pluginSource.generatedTypeKind) throw new Error(`Namespace plugin "${pluginSource.pluginId}" must provide generatedTypeKind for type "${typeName}"`);
335
- return multiline`
336
- import { join } from "node:path";
337
- import { t } from "@tailor-platform/sdk";
338
- import { getGeneratedType } from "@tailor-platform/sdk/plugin";
339
- import { defineSchema } from "@tailor-platform/sdk/seed";
340
- import { createTailorDBHook, createStandardSchema } from "@tailor-platform/sdk/test";
341
-
342
- const configPath = join(import.meta.dirname, "${configImportPath}");
343
- const ${exportName} = await getGeneratedType(configPath, "${pluginSource.pluginId}", null, "${pluginSource.generatedTypeKind}");
344
-
345
- ${schemaTypeCode}
346
-
347
- const hook = createTailorDBHook(${exportName});
348
-
349
- export const schema = defineSchema(
350
- createStandardSchema(schemaType, hook),${schemaOptionsCode}
351
- );
352
-
353
- `;
354
- }
355
-
356
- //#endregion
357
- //#region src/plugin/builtin/seed/seed-type-processor.ts
358
- /**
359
- * Processes TailorDB types to extract seed type information
360
- * @param type - Parsed TailorDB type
361
- * @param namespace - Namespace of the type
362
- * @returns Seed type information
363
- */
364
- function processSeedTypeInfo(type, namespace) {
365
- const dependencies = /* @__PURE__ */ new Set();
366
- const selfRefFields = [];
367
- for (const [fieldName, field] of Object.entries(type.fields)) {
368
- const targetType = field.relation?.targetType ?? field.config.foreignKeyType;
369
- if (!targetType) continue;
370
- if (targetType === type.name) selfRefFields.push(fieldName);
371
- else dependencies.add(targetType);
372
- }
373
- return {
374
- name: type.name,
375
- namespace,
376
- dependencies: Array.from(dependencies),
377
- selfRefFields,
378
- dataFile: `data/${type.name}.jsonl`
379
- };
380
- }
381
-
382
- //#endregion
383
- //#region src/plugin/builtin/seed/template-literal.ts
384
- /**
385
- * Escape generated script source before embedding it in a template literal.
386
- * @param scriptCode - Generated script source to embed.
387
- * @returns Escaped template literal content.
388
- */
389
- function escapeSeedScriptCodeForTemplateLiteral(scriptCode) {
390
- return scriptCode.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$/g, "\\$");
391
- }
392
-
393
- //#endregion
394
- //#region src/plugin/builtin/seed/index.ts
395
- /** Unique identifier for the seed generator plugin. */
396
- const SeedGeneratorID = "@tailor-platform/seed";
397
- function resolveIdpUserSyncFKs(option) {
398
- return {
399
- emitUserToIdpFK: !(option?.userToIdp ?? false),
400
- emitIdpToUserFK: !(option?.idpToUser ?? false)
401
- };
402
- }
403
- /**
404
- * Generate the IdP user seed function code using tailor.idp.Client via testExecScript
405
- * @param hasIdpUser - Whether IdP user is included
406
- * @param idpNamespace - The IDP namespace name
407
- * @returns JavaScript code for IdP user seeding function
408
- */
409
- function generateIdpUserSeedFunction(hasIdpUser, idpNamespace) {
410
- if (!hasIdpUser || !idpNamespace) return "";
411
- return multiline`
412
- // Seed _User via tailor.idp.Client (server-side)
413
- const seedIdpUser = async () => {
414
- console.log(styleText("cyan", " Seeding _User via tailor.idp.Client..."));
415
- const dataDir = join(configDir, "data");
416
- const data = loadSeedData(dataDir, ["_User"]);
417
- const rows = data["_User"] || [];
418
- if (rows.length === 0) {
419
- console.log(styleText("dim", " No _User data to seed"));
420
- return { success: true };
421
- }
422
- console.log(styleText("dim", \` Processing \${rows.length} _User records...\`));
423
-
424
- const idpSeedCode = \/* js *\/\`${escapeSeedScriptCodeForTemplateLiteral(generateIdpSeedScriptCode(idpNamespace))}\`;
425
-
426
- const result = await executeScript({
427
- client: operatorClient,
428
- workspaceId,
429
- name: "seed-idp-user.ts",
430
- code: idpSeedCode,
431
- arg: { users: rows },
432
- invoker: {
433
- namespace: authNamespace,
434
- machineUserName,
435
- },
436
- });
437
-
438
- if (result.logs) {
439
- for (const line of result.logs.split("\\n").filter(Boolean)) {
440
- console.log(styleText("dim", \` \${line}\`));
441
- }
442
- }
443
-
444
- if (result.success) {
445
- let parsed;
446
- try {
447
- parsed = JSON.parse(result.result || "{}");
448
- } catch (e) {
449
- console.error(styleText("red", \` ✗ Failed to parse seed result: \${e.message}\`));
450
- return { success: false };
451
- }
452
-
453
- if (parsed.processed) {
454
- console.log(styleText("green", \` ✓ _User: \${parsed.processed} rows processed\`));
455
- }
456
-
457
- if (!parsed.success) {
458
- const errors = Array.isArray(parsed.errors) ? parsed.errors : [];
459
- for (const err of errors) {
460
- console.error(styleText("red", \` ✗ \${err}\`));
461
- }
462
- return { success: false };
463
- }
464
-
465
- return { success: true };
466
- } else {
467
- console.error(styleText("red", \` ✗ Seed failed: \${result.error}\`));
468
- return { success: false };
469
- }
470
- };
471
- `;
472
- }
473
- /**
474
- * Generate the IdP user seed call code
475
- * @param hasIdpUser - Whether IdP user is included
476
- * @returns JavaScript code for calling IdP user seeding
477
- */
478
- function generateIdpUserSeedCall(hasIdpUser) {
479
- if (!hasIdpUser) return "";
480
- return multiline`
481
- // Seed _User if included and not skipped
482
- const shouldSeedUser = !skipIdp && (!entitiesToProcess || entitiesToProcess.includes("_User"));
483
- if (hasIdpUser && shouldSeedUser) {
484
- const result = await seedIdpUser();
485
- if (!result.success) {
486
- allSuccess = false;
487
- }
488
- }
489
- `;
490
- }
491
- /**
492
- * Generate the IdP user truncation function code using tailor.idp.Client via testExecScript
493
- * @param hasIdpUser - Whether IdP user is included
494
- * @param idpNamespace - The IDP namespace name
495
- * @returns JavaScript code for IdP user truncation function
496
- */
497
- function generateIdpUserTruncateFunction(hasIdpUser, idpNamespace) {
498
- if (!hasIdpUser || !idpNamespace) return "";
499
- return multiline`
500
- // Truncate _User via tailor.idp.Client (server-side)
501
- const truncateIdpUser = async () => {
502
- console.log(styleText("cyan", "Truncating _User via tailor.idp.Client..."));
503
-
504
- const idpTruncateCode = \/* js *\/\`${escapeSeedScriptCodeForTemplateLiteral(generateIdpTruncateScriptCode(idpNamespace))}\`;
505
-
506
- const result = await executeScript({
507
- client: operatorClient,
508
- workspaceId,
509
- name: "truncate-idp-user.ts",
510
- code: idpTruncateCode,
511
- invoker: {
512
- namespace: authNamespace,
513
- machineUserName,
514
- },
515
- });
516
-
517
- if (result.logs) {
518
- for (const line of result.logs.split("\\n").filter(Boolean)) {
519
- console.log(styleText("dim", \` \${line}\`));
520
- }
521
- }
522
-
523
- if (result.success) {
524
- let parsed;
525
- try {
526
- parsed = JSON.parse(result.result || "{}");
527
- } catch (e) {
528
- console.error(styleText("red", \` ✗ Failed to parse truncation result: \${e.message}\`));
529
- return { success: false };
530
- }
531
-
532
- if (parsed.deleted !== undefined) {
533
- console.log(styleText("green", \` ✓ _User: \${parsed.deleted} users deleted\`));
534
- }
535
-
536
- if (!parsed.success) {
537
- const errors = Array.isArray(parsed.errors) ? parsed.errors : [];
538
- for (const err of errors) {
539
- console.error(styleText("red", \` ✗ \${err}\`));
540
- }
541
- return { success: false };
542
- }
543
-
544
- return { success: true };
545
- } else {
546
- console.error(styleText("red", \` ✗ Truncation failed: \${result.error}\`));
547
- return { success: false };
548
- }
549
- };
550
- `;
551
- }
552
- /**
553
- * Generate the IdP user truncation call code within the truncate block
554
- * @param hasIdpUser - Whether IdP user is included
555
- * @returns JavaScript code for calling IdP user truncation
556
- */
557
- function generateIdpUserTruncateCall(hasIdpUser) {
558
- if (!hasIdpUser) return "";
559
- return multiline`
560
- // Truncate _User if applicable
561
- const shouldTruncateUser = !skipIdp && !hasNamespace && (!hasTypes || entitiesToProcess.includes("_User"));
562
- if (hasIdpUser && shouldTruncateUser) {
563
- const truncResult = await truncateIdpUser();
564
- if (!truncResult.success) {
565
- console.error(styleText("red", "IDP user truncation failed."));
566
- process.exit(1);
567
- }
568
- }
569
- `;
570
- }
571
- /**
572
- * Generates the exec.mjs script content using testExecScript API for TailorDB types
573
- * and tailor.idp.Client for _User (IdP managed)
574
- * @param defaultMachineUserName - Default machine user name from generator config (can be overridden at runtime)
575
- * @param relativeConfigPath - Config path relative to exec script
576
- * @param namespaceConfigs - Namespace configurations with types and dependencies
577
- * @param hasIdpUser - Whether _User is included
578
- * @param idpNamespace - The IDP namespace name, or null if not applicable
579
- * @returns exec.mjs file contents
580
- */
581
- function generateExecScript(defaultMachineUserName, relativeConfigPath, namespaceConfigs, hasIdpUser, idpNamespace) {
582
- const namespaceEntitiesEntries = namespaceConfigs.map(({ namespace, types }) => {
583
- return ` "${namespace}": [\n${types.map((e) => ` "${e}",`).join("\n")}\n ]`;
584
- }).join(",\n");
585
- const namespaceDepsEntries = namespaceConfigs.map(({ namespace, dependencies }) => {
586
- return ` "${namespace}": {\n${Object.entries(dependencies).map(([type, deps]) => ` "${type}": [${deps.map((d) => `"${d}"`).join(", ")}]`).join(",\n")}\n }`;
587
- }).join(",\n");
588
- const namespaceSelfRefEntries = namespaceConfigs.map(({ namespace, selfRefTypes }) => {
589
- return ` "${namespace}": [${selfRefTypes.map((t) => `"${t}"`).join(", ")}]`;
590
- }).join(",\n");
591
- return multiline`
592
- /**
593
- * @generated
594
- * This file is auto-generated by @tailor-platform/sdk's seedPlugin.
595
- * Do not edit by hand: changes will be overwritten on the next \`sdk generate\`.
596
- */
597
- import { readFileSync } from "node:fs";
598
- import { join, isAbsolute } from "node:path";
599
- import { parseArgs, styleText } from "node:util";
600
- import { createInterface } from "node:readline";
601
- import {
602
- show,
603
- truncate,
604
- bundleSeedScript,
605
- chunkSeedData,
606
- executeScript,
607
- initOperatorClient,
608
- loadAccessToken,
609
- loadWorkspaceId,
610
- } from "@tailor-platform/sdk/cli";
611
-
612
- // Handle "validate" subcommand before parseArgs
613
- const subcommand = process.argv[2];
614
- if (subcommand === "validate") {
615
- const { validateSeedData } = await import("@tailor-platform/sdk/seed");
616
- const validateArgs = parseArgs({
617
- args: process.argv.slice(3),
618
- options: {
619
- verbose: { type: "boolean", short: "v", default: false },
620
- help: { type: "boolean", short: "h", default: false },
621
- },
622
- allowPositionals: true,
623
- });
624
-
625
- if (validateArgs.values.help) {
626
- console.log(\`
627
- Usage: node exec.mjs validate [options] [path]
628
-
629
- Validate JSONL seed data against schema definitions.
630
-
631
- Arguments:
632
- path File or directory to validate (default: ./data)
633
-
634
- Options:
635
- -v, --verbose Show verbose error output
636
- -h, --help Show help
637
-
638
- Examples:
639
- node exec.mjs validate # Validate all seed data
640
- node exec.mjs validate ./data/User.jsonl # Validate specific file
641
- node exec.mjs validate -v # Verbose error output
642
- \`);
643
- process.exit(0);
644
- }
645
-
646
- const configDir = import.meta.dirname;
647
- const targetPath = validateArgs.positionals[0] || join(configDir, "data");
648
- const resolvedPath = isAbsolute(targetPath) ? targetPath : join(process.cwd(), targetPath);
649
-
650
- try {
651
- const result = await validateSeedData({ path: resolvedPath, verbose: validateArgs.values.verbose });
652
- if (result.output) console.log(result.output);
653
- if (!result.valid) {
654
- console.error(result.error);
655
- process.exit(1);
656
- }
657
- process.exit(0);
658
- } catch (error) {
659
- console.error(styleText("red", \`Error: \${error instanceof Error ? error.message : String(error)}\`));
660
- process.exit(1);
661
- }
662
- }
663
-
664
- // Parse command-line arguments
665
- const { values, positionals } = parseArgs({
666
- options: {
667
- "machine-user": { type: "string", short: "m" },
668
- namespace: { type: "string", short: "n" },
669
- "skip-idp": { type: "boolean", default: false },
670
- truncate: { type: "boolean", default: false },
671
- yes: { type: "boolean", default: false },
672
- profile: { type: "string", short: "p" },
673
- help: { type: "boolean", short: "h", default: false },
674
- },
675
- allowPositionals: true,
676
- });
677
-
678
- if (values.help) {
679
- console.log(\`
680
- Usage: node exec.mjs [command] [options] [types...]
681
-
682
- Commands:
683
- validate [path] Validate seed data against schema (default: ./data)
684
-
685
- Options:
686
- -m, --machine-user <name> Machine user name for authentication (required if not configured)
687
- -n, --namespace <ns> Process all types in specified namespace (excludes _User)
688
- --skip-idp Skip IdP user (_User) entity
689
- --truncate Truncate tables before seeding
690
- --yes Skip confirmation prompts (for truncate)
691
- -p, --profile <name> Workspace profile name
692
- -h, --help Show help
693
-
694
- Examples:
695
- node exec.mjs -m admin # Process all types with machine user
696
- node exec.mjs --namespace <namespace> # Process tailordb namespace only (no _User)
697
- node exec.mjs User Order # Process specific types only
698
- node exec.mjs --skip-idp # Process all except _User
699
- node exec.mjs --truncate # Truncate all tables, then seed all
700
- node exec.mjs --truncate --yes # Truncate all tables without confirmation, then seed all
701
- node exec.mjs --truncate --namespace <namespace> # Truncate tailordb, then seed tailordb
702
- node exec.mjs --truncate User Order # Truncate User and Order, then seed them
703
- node exec.mjs validate # Validate all seed data
704
- node exec.mjs validate ./data/User.jsonl # Validate specific file
705
- \`);
706
- process.exit(0);
707
- }
708
-
709
- // Helper function to prompt for y/n confirmation
710
- const promptConfirmation = (question) => {
711
- const rl = createInterface({
712
- input: process.stdin,
713
- output: process.stdout,
714
- });
715
-
716
- return new Promise((resolve) => {
717
- rl.question(styleText("yellow", question), (answer) => {
718
- rl.close();
719
- resolve(answer.toLowerCase().trim());
720
- });
721
- });
722
- };
723
-
724
- const configDir = import.meta.dirname;
725
- const configPath = join(configDir, "${relativeConfigPath}");
726
-
727
- // Determine machine user name (CLI argument takes precedence over config default)
728
- const defaultMachineUser = ${defaultMachineUserName ? `"${defaultMachineUserName}"` : "undefined"};
729
- const machineUserName = values["machine-user"] || defaultMachineUser;
730
-
731
- if (!machineUserName) {
732
- console.error(styleText("red", "Error: Machine user name is required."));
733
- console.error(styleText("yellow", "Specify --machine-user <name> or configure machineUserName in generator options."));
734
- process.exit(1);
735
- }
736
-
737
- // Entity configuration
738
- const namespaceEntities = {
739
- ${namespaceEntitiesEntries}
740
- };
741
- const namespaceDeps = {
742
- ${namespaceDepsEntries}
743
- };
744
- const namespaceSelfRefTypes = {
745
- ${namespaceSelfRefEntries}
746
- };
747
- const entities = Object.values(namespaceEntities).flat();
748
- const hasIdpUser = ${String(hasIdpUser)};
749
-
750
- // Determine which entities to process
751
- let entitiesToProcess = null;
752
-
753
- const hasNamespace = !!values.namespace;
754
- const hasTypes = positionals.length > 0;
755
- const skipIdp = values["skip-idp"];
756
-
757
- // Validate mutually exclusive options
758
- const optionCount = [hasNamespace, hasTypes].filter(Boolean).length;
759
- if (optionCount > 1) {
760
- console.error(styleText("red", "Error: Options --namespace and type names are mutually exclusive."));
761
- process.exit(1);
762
- }
763
-
764
- // --skip-idp and --namespace are redundant (namespace already excludes _User)
765
- if (skipIdp && hasNamespace) {
766
- console.warn(styleText("yellow", "Warning: --skip-idp is redundant with --namespace (namespace filtering already excludes _User)."));
767
- }
768
-
769
- // Filter by namespace (automatically excludes _User as it has no namespace)
770
- if (hasNamespace) {
771
- const namespace = values.namespace;
772
- entitiesToProcess = namespaceEntities[namespace];
773
-
774
- if (!entitiesToProcess || entitiesToProcess.length === 0) {
775
- console.error(styleText("red", \`Error: No entities found in namespace "\${namespace}"\`));
776
- console.error(styleText("yellow", \`Available namespaces: \${Object.keys(namespaceEntities).join(", ")}\`));
777
- process.exit(1);
778
- }
779
-
780
- console.log(styleText("cyan", \`Filtering by namespace: \${namespace}\`));
781
- console.log(styleText("dim", \`Entities: \${entitiesToProcess.join(", ")}\`));
782
- }
783
-
784
- // Filter by specific types
785
- if (hasTypes) {
786
- const requestedTypes = positionals;
787
- const notFoundTypes = [];
788
- const allTypes = hasIdpUser ? [...entities, "_User"] : entities;
789
-
790
- entitiesToProcess = requestedTypes.filter((type) => {
791
- if (!allTypes.includes(type)) {
792
- notFoundTypes.push(type);
793
- return false;
794
- }
795
- return true;
796
- });
797
-
798
- if (notFoundTypes.length > 0) {
799
- console.error(styleText("red", \`Error: The following types were not found: \${notFoundTypes.join(", ")}\`));
800
- console.error(styleText("yellow", \`Available types: \${allTypes.join(", ")}\`));
801
- process.exit(1);
802
- }
803
-
804
- console.log(styleText("cyan", \`Filtering by types: \${entitiesToProcess.join(", ")}\`));
805
- }
806
-
807
- // Apply --skip-idp filter
808
- if (skipIdp) {
809
- if (entitiesToProcess) {
810
- entitiesToProcess = entitiesToProcess.filter((entity) => entity !== "_User");
811
- } else {
812
- entitiesToProcess = entities.filter((entity) => entity !== "_User");
813
- }
814
- }
815
-
816
- // Get application info
817
- const appInfo = await show({ configPath, profile: values.profile });
818
- const authNamespace = appInfo.auth;
819
-
820
- // Initialize operator client (once for all namespaces)
821
- const accessToken = await loadAccessToken({ profile: values.profile });
822
- const workspaceId = await loadWorkspaceId({ profile: values.profile });
823
- const operatorClient = await initOperatorClient(accessToken);
824
-
825
- ${generateIdpUserTruncateFunction(hasIdpUser, idpNamespace)}
826
-
827
- // Truncate tables if requested
828
- if (values.truncate) {
829
- const answer = values.yes ? "y" : await promptConfirmation("Are you sure you want to truncate? (y/n): ");
830
- if (answer !== "y") {
831
- console.log(styleText("yellow", "Truncate cancelled."));
832
- process.exit(0);
833
- }
834
-
835
- console.log(styleText("cyan", "Truncating tables..."));
836
-
837
- try {
838
- if (hasNamespace) {
839
- await truncate({
840
- configPath,
841
- profile: values.profile,
842
- namespace: values.namespace,
843
- });
844
- } else if (hasTypes) {
845
- const typesToTruncate = entitiesToProcess.filter((t) => t !== "_User");
846
- if (typesToTruncate.length > 0) {
847
- await truncate({
848
- configPath,
849
- profile: values.profile,
850
- types: typesToTruncate,
851
- });
852
- } else {
853
- console.log(styleText("dim", "No TailorDB types to truncate (only _User was specified)."));
854
- }
855
- } else {
856
- await truncate({
857
- configPath,
858
- profile: values.profile,
859
- all: true,
860
- });
861
- }
862
- } catch (error) {
863
- console.error(styleText("red", \`Truncate failed: \${error.message}\`));
864
- process.exit(1);
865
- }
866
-
867
- ${generateIdpUserTruncateCall(hasIdpUser)}
868
-
869
- console.log(styleText("green", "Truncate completed."));
870
- }
871
-
872
- console.log(styleText("cyan", "\\nStarting seed data generation..."));
873
- if (skipIdp) {
874
- console.log(styleText("dim", \` Skipping IdP user (_User)\`));
875
- }
876
-
877
- // Load seed data from JSONL files
878
- const loadSeedData = (dataDir, typeNames) => {
879
- const data = {};
880
- for (const typeName of typeNames) {
881
- const jsonlPath = join(dataDir, \`\${typeName}.jsonl\`);
882
- try {
883
- const content = readFileSync(jsonlPath, "utf-8").trim();
884
- if (content) {
885
- data[typeName] = content.split("\\n").map((line) => JSON.parse(line));
886
- } else {
887
- data[typeName] = [];
888
- }
889
- } catch (error) {
890
- if (error.code === "ENOENT") {
891
- data[typeName] = [];
892
- } else {
893
- throw error;
894
- }
895
- }
896
- }
897
- return data;
898
- };
899
-
900
- // Topological sort for dependency order
901
- const topologicalSort = (types, deps) => {
902
- const visited = new Set();
903
- const result = [];
904
-
905
- const visit = (type) => {
906
- if (visited.has(type)) return;
907
- visited.add(type);
908
- const typeDeps = deps[type] || [];
909
- for (const dep of typeDeps) {
910
- if (types.includes(dep)) {
911
- visit(dep);
912
- }
913
- }
914
- result.push(type);
915
- };
916
-
917
- for (const type of types) {
918
- visit(type);
919
- }
920
- return result;
921
- };
922
-
923
- // Seed TailorDB types via testExecScript
924
- const seedViaTestExecScript = async (namespace, typesToSeed, deps, selfRefTypes) => {
925
- const dataDir = join(configDir, "data");
926
- const sortedTypes = topologicalSort(typesToSeed, deps);
927
- const data = loadSeedData(dataDir, sortedTypes);
928
-
929
- // Skip if no data
930
- const typesWithData = sortedTypes.filter((t) => data[t] && data[t].length > 0);
931
- if (typesWithData.length === 0) {
932
- console.log(styleText("dim", \` [\${namespace}] No data to seed\`));
933
- return { success: true, processed: {} };
934
- }
935
-
936
- console.log(styleText("cyan", \` [\${namespace}] Seeding \${typesWithData.length} types via Kysely batch insert...\`));
937
-
938
- // Bundle seed script
939
- const bundled = await bundleSeedScript(namespace, typesWithData);
940
-
941
- // Chunk seed data to fit within gRPC message size limits
942
- const chunks = chunkSeedData({
943
- data,
944
- order: sortedTypes,
945
- codeByteSize: new TextEncoder().encode(bundled.bundledCode).length,
946
- });
947
-
948
- if (chunks.length === 0) {
949
- console.log(styleText("dim", \` [\${namespace}] No data to seed\`));
950
- return { success: true, processed: {} };
951
- }
952
-
953
- if (chunks.length > 1) {
954
- console.log(styleText("dim", \` Split into \${chunks.length} chunks\`));
955
- }
956
-
957
- const allProcessed = {};
958
- let hasError = false;
959
- const allErrors = [];
960
-
961
- for (const chunk of chunks) {
962
- if (chunks.length > 1) {
963
- console.log(styleText("dim", \` Chunk \${chunk.index + 1}/\${chunk.total}: \${chunk.order.join(", ")}\`));
964
- }
965
-
966
- // Execute seed script for this chunk
967
- const result = await executeScript({
968
- client: operatorClient,
969
- workspaceId,
970
- name: \`seed-\${namespace}.ts\`,
971
- code: bundled.bundledCode,
972
- arg: { data: chunk.data, order: chunk.order, selfRefTypes },
973
- invoker: {
974
- namespace: authNamespace,
975
- machineUserName,
976
- },
977
- });
978
-
979
- // Parse result and display logs
980
- if (result.logs) {
981
- for (const line of result.logs.split("\\n").filter(Boolean)) {
982
- console.log(styleText("dim", \` \${line}\`));
983
- }
984
- }
985
-
986
- if (result.success) {
987
- let parsed;
988
- try {
989
- const parsedResult = JSON.parse(result.result || "{}");
990
- parsed = parsedResult && typeof parsedResult === "object" ? parsedResult : {};
991
- } catch (error) {
992
- const message = error instanceof Error ? error.message : String(error);
993
- console.error(styleText("red", \` ✗ Failed to parse seed result: \${message}\`));
994
- hasError = true;
995
- allErrors.push(message);
996
- continue;
997
- }
998
-
999
- const processed = parsed.processed || {};
1000
- for (const [type, count] of Object.entries(processed)) {
1001
- allProcessed[type] = (allProcessed[type] || 0) + count;
1002
- console.log(styleText("green", \` ✓ \${type}: \${count} rows inserted\`));
1003
- }
1004
-
1005
- if (!parsed.success) {
1006
- const errors = Array.isArray(parsed.errors) ? parsed.errors : [];
1007
- const errorMessage =
1008
- errors.length > 0 ? errors.join("\\n ") : "Seed script reported failure";
1009
- console.error(styleText("red", \` ✗ Seed failed:\\n \${errorMessage}\`));
1010
- hasError = true;
1011
- allErrors.push(errorMessage);
1012
- }
1013
- } else {
1014
- console.error(styleText("red", \` ✗ Seed failed: \${result.error}\`));
1015
- hasError = true;
1016
- allErrors.push(result.error);
1017
- }
1018
- }
1019
-
1020
- if (hasError) {
1021
- return { success: false, error: allErrors.join("\\n") };
1022
- }
1023
- return { success: true, processed: allProcessed };
1024
- };
1025
-
1026
- ${generateIdpUserSeedFunction(hasIdpUser, idpNamespace)}
1027
-
1028
- // Main execution
1029
- try {
1030
- let allSuccess = true;
1031
-
1032
- // Determine which namespaces and types to process
1033
- const namespacesToProcess = hasNamespace
1034
- ? [values.namespace]
1035
- : Object.keys(namespaceEntities);
1036
-
1037
- for (const namespace of namespacesToProcess) {
1038
- const nsTypes = namespaceEntities[namespace] || [];
1039
- const nsDeps = namespaceDeps[namespace] || {};
1040
- const nsSelfRefTypes = namespaceSelfRefTypes[namespace] || [];
1041
-
1042
- // Filter types if specific types requested
1043
- let typesToSeed = entitiesToProcess
1044
- ? nsTypes.filter((t) => entitiesToProcess.includes(t))
1045
- : nsTypes;
1046
-
1047
- if (typesToSeed.length === 0) continue;
1048
-
1049
- const result = await seedViaTestExecScript(namespace, typesToSeed, nsDeps, nsSelfRefTypes);
1050
- if (!result.success) {
1051
- allSuccess = false;
1052
- }
1053
- }
1054
-
1055
- ${generateIdpUserSeedCall(hasIdpUser)}
1056
-
1057
- if (allSuccess) {
1058
- console.log(styleText("green", "\\n✓ Seed data generation completed successfully"));
1059
- } else {
1060
- console.error(styleText("red", "\\n✗ Seed data generation completed with errors"));
1061
- process.exit(1);
1062
- }
1063
- } catch (error) {
1064
- console.error(styleText("red", \`\\n✗ Seed data generation failed: \${error.message}\`));
1065
- process.exit(1);
1066
- }
1067
-
1068
- `;
1069
- }
1070
- /**
1071
- * Plugin that generates seed data files with Kysely batch insert and tailor.idp.Client for _User.
1072
- * @param options - Plugin options
1073
- * @param options.distPath - Output directory path for generated seed files
1074
- * @param options.machineUserName - Default machine user name for authentication
1075
- * @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.
1076
- * @returns Plugin instance with onTailorDBReady hook
1077
- */
1078
- function seedPlugin(options) {
1079
- return {
1080
- id: SeedGeneratorID,
1081
- description: "Generates seed data files (Kysely batch insert + tailor.idp.Client for _User)",
1082
- pluginConfig: options,
1083
- async onTailorDBReady(ctx) {
1084
- const files = [];
1085
- const namespaceConfigs = [];
1086
- const idpUser = ctx.auth ? processIdpUser(ctx.auth) ?? null : null;
1087
- const hasIdpUser = idpUser !== null;
1088
- const idpUserSyncFKs = resolveIdpUserSyncFKs(ctx.pluginConfig.disableIdpUserSync);
1089
- for (const ns of ctx.tailordb) {
1090
- const types = [];
1091
- const dependencies = {};
1092
- const selfRefTypes = [];
1093
- for (const [typeName, type] of Object.entries(ns.types)) {
1094
- const source = assertDefined(ns.sourceInfo.get(typeName), `source info missing for type: ${typeName}`);
1095
- const typeInfo = processSeedTypeInfo(type, ns.namespace);
1096
- const linesDb = processLinesDb(type, source);
1097
- if (idpUserSyncFKs.emitUserToIdpFK && idpUser && typeName === idpUser.schema.userTypeName) linesDb.foreignKeys.push({
1098
- column: idpUser.schema.usernameField,
1099
- references: {
1100
- table: "_User",
1101
- column: "name"
1102
- }
1103
- });
1104
- types.push(typeInfo.name);
1105
- dependencies[typeInfo.name] = typeInfo.dependencies;
1106
- if (typeInfo.selfRefFields.length > 0) selfRefTypes.push(typeInfo.name);
1107
- files.push({
1108
- path: path.join(ctx.pluginConfig.distPath, typeInfo.dataFile),
1109
- content: "",
1110
- skipIfExists: true
1111
- });
1112
- const schemaOutputPath = path.join(ctx.pluginConfig.distPath, "data", `${linesDb.typeName}.schema.ts`);
1113
- if (linesDb.pluginSource && linesDb.pluginSource.pluginImportPath) {
1114
- let originalImportPath;
1115
- if (linesDb.pluginSource.originalFilePath && linesDb.pluginSource.originalExportName) {
1116
- const relativePath = path.relative(path.dirname(schemaOutputPath), linesDb.pluginSource.originalFilePath);
1117
- originalImportPath = relativePath.replace(/\.ts$/, "").startsWith(".") ? relativePath.replace(/\.ts$/, "") : `./${relativePath.replace(/\.ts$/, "")}`;
1118
- }
1119
- const schemaContent = generateLinesDbSchemaFileWithPluginAPI(linesDb, {
1120
- configImportPath: path.relative(path.dirname(schemaOutputPath), ctx.configPath),
1121
- originalImportPath
1122
- });
1123
- files.push({
1124
- path: schemaOutputPath,
1125
- content: schemaContent
1126
- });
1127
- } else {
1128
- const relativePath = path.relative(path.dirname(schemaOutputPath), linesDb.importPath);
1129
- const schemaContent = generateLinesDbSchemaFile(linesDb, relativePath.replace(/\.ts$/, "").startsWith(".") ? relativePath.replace(/\.ts$/, "") : `./${relativePath.replace(/\.ts$/, "")}`);
1130
- files.push({
1131
- path: schemaOutputPath,
1132
- content: schemaContent
1133
- });
1134
- }
1135
- }
1136
- namespaceConfigs.push({
1137
- namespace: ns.namespace,
1138
- types,
1139
- dependencies,
1140
- selfRefTypes
1141
- });
1142
- }
1143
- if (idpUser) {
1144
- files.push({
1145
- path: path.join(ctx.pluginConfig.distPath, idpUser.dataFile),
1146
- content: "",
1147
- skipIfExists: true
1148
- });
1149
- files.push({
1150
- path: path.join(ctx.pluginConfig.distPath, "data", `${idpUser.name}.schema.ts`),
1151
- content: generateIdpUserSchemaFile({
1152
- usernameField: idpUser.schema.usernameField,
1153
- userTypeName: idpUser.schema.userTypeName,
1154
- includeUserProfileFK: idpUserSyncFKs.emitIdpToUserFK
1155
- })
1156
- });
1157
- }
1158
- const relativeConfigPath = path.relative(ctx.pluginConfig.distPath, ctx.configPath);
1159
- files.push({
1160
- path: path.join(ctx.pluginConfig.distPath, "exec.mjs"),
1161
- content: generateExecScript(ctx.pluginConfig.machineUserName, relativeConfigPath, namespaceConfigs, hasIdpUser, idpUser?.idpNamespace ?? null)
1162
- });
1163
- return { files };
1164
- }
1165
- };
1166
- }
1167
-
1168
- //#endregion
1169
- export { seedPlugin as n, SeedGeneratorID as t };
1170
- //# sourceMappingURL=seed-CRSQJI_z.mjs.map