@tailor-platform/sdk 2.0.0-next.0 → 2.0.0-next.1
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 +105 -0
- package/dist/application-DB2r36Et.mjs +3 -0
- package/dist/{application-76hhIhnJ.mjs → application-DqS1yBg3.mjs} +217 -131
- package/dist/application-DqS1yBg3.mjs.map +1 -0
- package/dist/{assert-CKfwrmCV.mjs → assert-DBxo8jPo.mjs} +1 -2
- package/dist/{assert-CKfwrmCV.mjs.map → assert-DBxo8jPo.mjs.map} +1 -1
- package/dist/{authconnection-D8SJGMpj.mjs → authconnection-D2MhtTN5.mjs} +2 -3
- package/dist/{authconnection-D8SJGMpj.mjs.map → authconnection-D2MhtTN5.mjs.map} +1 -1
- package/dist/{authconnection-BIYzEh2p.d.mts → authconnection-DvUQAjQS.d.mts} +1 -1
- package/dist/{brand-DlnJ375c.mjs → brand-Eo4pLXPJ.mjs} +1 -2
- package/dist/{brand-DlnJ375c.mjs.map → brand-Eo4pLXPJ.mjs.map} +1 -1
- package/dist/cli/index.mjs +78 -131
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.d.mts +619 -751
- package/dist/cli/lib.mjs +9 -10
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/{client-C68VWo4g.mjs → client-Dbohmtkv.mjs} +1 -2
- package/dist/{client-CobIRHl-.mjs → client-z_oHGVNy.mjs} +10 -7
- package/dist/client-z_oHGVNy.mjs.map +1 -0
- package/dist/completion/zsh-worker.zsh +4029 -0
- package/dist/configure/index.d.mts +8 -7
- package/dist/configure/index.mjs +27 -28
- package/dist/configure/index.mjs.map +1 -1
- package/dist/{context-s0lxhu8_.mjs → context-Bd266-ru.mjs} +2 -3
- package/dist/{context-s0lxhu8_.mjs.map → context-Bd266-ru.mjs.map} +1 -1
- package/dist/{context-CUBwSBq4.d.mts → context-BuuIb8CC.d.mts} +1 -1
- package/dist/{crashreport-BhD0y14F.mjs → crashreport-BsjAkFWw.mjs} +19 -10
- package/dist/{crashreport-BhD0y14F.mjs.map → crashreport-BsjAkFWw.mjs.map} +1 -1
- package/dist/{crashreport-D1wKBJ8N.mjs → crashreport-pr6Rhvza.mjs} +1 -2
- package/dist/{enum-constants-C7DaWeQo.mjs → enum-constants-j9QBF0cB.mjs} +1 -2
- package/dist/enum-constants-j9QBF0cB.mjs.map +1 -0
- package/dist/{errors-EsY4XO6O.mjs → errors-Dtf2WPaW.mjs} +1 -2
- package/dist/{errors-EsY4XO6O.mjs.map → errors-Dtf2WPaW.mjs.map} +1 -1
- package/dist/{field-C4zdJLW5.mjs → field-DOsJCPFa.mjs} +1 -2
- package/dist/field-DOsJCPFa.mjs.map +1 -0
- package/dist/{file-BzK8z3X-.d.mts → file-BB8Vs9O_.d.mts} +1 -1
- package/dist/{file-B58Dm-2P.mjs → file-_oUZo76X.mjs} +2 -3
- package/dist/{file-B58Dm-2P.mjs.map → file-_oUZo76X.mjs.map} +1 -1
- package/dist/{file-utils-BHPxPXmn.mjs → file-utils-DcyIPFQh.mjs} +2 -3
- package/dist/{file-utils-BHPxPXmn.mjs.map → file-utils-DcyIPFQh.mjs.map} +1 -1
- package/dist/{globals-ByrCoDip.mjs → globals-Crz8o65k.mjs} +53 -5
- package/dist/globals-Crz8o65k.mjs.map +1 -0
- package/dist/http-adapter.generated-WgMnb7Sb.d.mts +580 -0
- package/dist/{iconv-kwrmd1U_.d.mts → iconv-Co-TOPuH.d.mts} +1 -1
- package/dist/{iconv-DreIffeM.mjs → iconv-D2vi8G36.mjs} +2 -3
- package/dist/{iconv-DreIffeM.mjs.map → iconv-D2vi8G36.mjs.map} +1 -1
- package/dist/{idp-Ch95ag8h.mjs → idp-BDbK5gjm.mjs} +2 -3
- package/dist/{idp-Ch95ag8h.mjs.map → idp-BDbK5gjm.mjs.map} +1 -1
- package/dist/{idp-BlBPtXJ-.d.mts → idp-DrhVrLmV.d.mts} +1 -1
- package/dist/{index-CQZVJ5SX.d.mts → index-5vPyRu1y.d.mts} +2 -2
- package/dist/{index-CfRFkXIO.d.mts → index-B7AKc18V.d.mts} +2 -2
- package/dist/{index-CLxubakC.d.mts → index-BlpzXncY.d.mts} +38 -247
- package/dist/{index-DRhMpdnA.d.mts → index-CK7u9isy.d.mts} +8 -8
- package/dist/{index-DUupuPhZ.d.mts → index-CNYe5lnW.d.mts} +2 -2
- package/dist/{index-CPRnOjjt.d.mts → index-DjUdWlzf.d.mts} +2 -2
- package/dist/index-ZePLwxw7.d.mts +208 -0
- package/dist/{interceptor-DOqRkCya.mjs → interceptor-D-q1rvRl.mjs} +1 -2
- package/dist/{interceptor-DOqRkCya.mjs.map → interceptor-D-q1rvRl.mjs.map} +1 -1
- package/dist/{job-BpsFXPbi.mjs → job-fuc3j1Ma.mjs} +9 -10
- package/dist/job-fuc3j1Ma.mjs.map +1 -0
- package/dist/kysely/index.mjs +0 -1
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/{kysely-type-D1e0Vwkd.mjs → kysely-type-DR8uzZTA.mjs} +2 -3
- package/dist/kysely-type-DR8uzZTA.mjs.map +1 -0
- package/dist/{logger-DpJyJvNz.mjs → logger-CxF-Ex5d.mjs} +1 -2
- package/dist/{logger-DpJyJvNz.mjs.map → logger-CxF-Ex5d.mjs.map} +1 -1
- package/dist/{mock-DMgIygjE.mjs → mock-BjFj5o1I.mjs} +9 -11
- package/dist/mock-BjFj5o1I.mjs.map +1 -0
- package/dist/{multiline-Cf9ODpr1.mjs → multiline-sfHpTZZK.mjs} +1 -2
- package/dist/{multiline-Cf9ODpr1.mjs.map → multiline-sfHpTZZK.mjs.map} +1 -1
- package/dist/{package-json-DcQApfPQ.mjs → package-json-8b0O9TlX.mjs} +1 -2
- package/dist/{package-json-DcQApfPQ.mjs.map → package-json-8b0O9TlX.mjs.map} +1 -1
- package/dist/package-json-Cv2Z-TqQ.mjs +3 -0
- package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +1 -2
- package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +1 -2
- package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -2
- package/dist/plugin/builtin/seed/index.d.mts +1 -1
- package/dist/plugin/builtin/seed/index.mjs +1 -2
- package/dist/plugin/index.d.mts +1 -3
- package/dist/plugin/index.mjs +0 -1
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/registry-DdsYlL_P.mjs +51 -0
- package/dist/registry-DdsYlL_P.mjs.map +1 -0
- package/dist/{repl-editor-CJG3sz7A.mjs → repl-editor-DmGr9zMw.mjs} +2 -3
- package/dist/{repl-editor-CJG3sz7A.mjs.map → repl-editor-DmGr9zMw.mjs.map} +1 -1
- package/dist/{chunk-BkoGK1jX.mjs → rolldown-runtime-DXywRVcq.mjs} +0 -1
- package/dist/runtime/authconnection.d.mts +1 -1
- package/dist/runtime/authconnection.mjs +1 -2
- package/dist/runtime/context.d.mts +1 -1
- package/dist/runtime/context.mjs +1 -2
- package/dist/runtime/file.d.mts +1 -1
- package/dist/runtime/file.mjs +1 -2
- package/dist/runtime/globals.d.mts +6 -39
- package/dist/runtime/globals.mjs +0 -1
- package/dist/runtime/iconv.d.mts +1 -1
- package/dist/runtime/iconv.mjs +1 -2
- package/dist/runtime/idp.d.mts +1 -1
- package/dist/runtime/idp.mjs +1 -2
- package/dist/runtime/index.d.mts +8 -8
- package/dist/runtime/index.mjs +7 -8
- package/dist/runtime/secretmanager.d.mts +1 -1
- package/dist/runtime/secretmanager.mjs +1 -2
- package/dist/runtime/workflow.d.mts +1 -1
- package/dist/runtime/workflow.mjs +1 -2
- package/dist/{runtime-C7qTBDD2.mjs → runtime-n9NCkjee.mjs} +301 -317
- package/dist/runtime-n9NCkjee.mjs.map +1 -0
- package/dist/{schema-1msIhXwA.mjs → schema-BhkpP5Hw.mjs} +3 -4
- package/dist/schema-BhkpP5Hw.mjs.map +1 -0
- package/dist/{secret-file-CWzF8rry.mjs → secret-file-DBqZhjFQ.mjs} +1 -2
- package/dist/{secret-file-CWzF8rry.mjs.map → secret-file-DBqZhjFQ.mjs.map} +1 -1
- package/dist/{secretmanager-CKLB3wAQ.d.mts → secretmanager-B3n4KHfm.d.mts} +1 -1
- package/dist/{secretmanager-B9h-U_8U.mjs → secretmanager-BVxw3ih_.mjs} +2 -3
- package/dist/{secretmanager-B9h-U_8U.mjs.map → secretmanager-BVxw3ih_.mjs.map} +1 -1
- package/dist/seed/index.mjs +0 -1
- package/dist/seed/index.mjs.map +1 -1
- package/dist/{seed-BH2FbrPV.mjs → seed-jf3008-h.mjs} +5 -16
- package/dist/seed-jf3008-h.mjs.map +1 -0
- package/dist/{service-wI3Hvrgx.mjs → service-CCL8ruDf.mjs} +3 -4
- package/dist/service-CCL8ruDf.mjs.map +1 -0
- package/dist/service-D6yonf2I.mjs +3 -0
- package/dist/{service-DMohAx8a2.mjs → service-DU1mVzri.mjs} +3 -4
- package/dist/service-DU1mVzri.mjs.map +1 -0
- package/dist/{telemetry-BQbbVo2t.mjs → telemetry-CdqJEzkj.mjs} +2 -3
- package/dist/{telemetry-BQbbVo2t.mjs.map → telemetry-CdqJEzkj.mjs.map} +1 -1
- package/dist/telemetry-ClwW5ohF.mjs +3 -0
- package/dist/test-env-key-D9kM6ETE.mjs +49 -0
- package/dist/test-env-key-D9kM6ETE.mjs.map +1 -0
- package/dist/type-source-DH_LH20p.mjs +13 -0
- package/dist/type-source-DH_LH20p.mjs.map +1 -0
- package/dist/{types-CmzfQP_m.mjs → types-B2RpYyA_.mjs} +2 -3
- package/dist/types-B2RpYyA_.mjs.map +1 -0
- package/dist/types-ClhIrW_C.mjs +4 -0
- package/dist/{tailordb-BlBGmQK-.d.mts → types-DCUhgpyI.d.mts} +142 -221
- package/dist/{plugin-C_FyVSdl.d.mts → types-DhO_VEZd.d.mts} +119 -179
- package/dist/types-DwDgacni.d.mts +338 -0
- package/dist/utils/test/index.d.mts +4 -3
- package/dist/utils/test/index.mjs +1 -2
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +1 -2
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.d.mts +42 -5
- package/dist/vitest/index.mjs +133 -4
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/setup.mjs +2 -3
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/{workflow-CMamswkK.d.mts → workflow-BbKvGLQg.d.mts} +1 -1
- package/dist/{workflow--aPbA8Uq.mjs → workflow-DgemCAz3.mjs} +2 -3
- package/dist/{workflow--aPbA8Uq.mjs.map → workflow-DgemCAz3.mjs.map} +1 -1
- package/dist/workflow.generated-DtQwEo-x.d.mts +671 -0
- package/docs/cli/application.md +0 -2
- package/docs/cli/completion.md +3 -0
- package/docs/cli/crashreport.md +0 -2
- package/docs/cli/function.md +1 -1
- package/docs/cli/user.md +3 -3
- package/docs/cli/workspace.md +3 -3
- package/docs/configuration.md +0 -2
- package/docs/plugin/custom.md +2 -2
- package/docs/plugin/index.md +1 -1
- package/docs/runtime.md +3 -3
- package/docs/services/aigateway.md +97 -0
- package/docs/services/auth.md +19 -2
- package/docs/services/executor.md +0 -2
- package/docs/services/resolver.md +2 -4
- package/docs/services/tailordb.md +1 -1
- package/docs/services/workflow.md +13 -15
- package/docs/testing.md +18 -11
- package/package.json +13 -12
- package/dist/actor-J2gJ0eK5.d.mts +0 -24
- package/dist/application-76hhIhnJ.mjs.map +0 -1
- package/dist/application-av2raLs6.mjs +0 -4
- package/dist/cli/skills.d.mts +0 -1
- package/dist/cli/skills.mjs +0 -22
- package/dist/cli/skills.mjs.map +0 -1
- package/dist/client-CobIRHl-.mjs.map +0 -1
- package/dist/enum-constants-C7DaWeQo.mjs.map +0 -1
- package/dist/env-B-g-qgE4.d.mts +0 -7
- package/dist/field-C4zdJLW5.mjs.map +0 -1
- package/dist/globals-ByrCoDip.mjs.map +0 -1
- package/dist/job-BpsFXPbi.mjs.map +0 -1
- package/dist/kysely-type-D1e0Vwkd.mjs.map +0 -1
- package/dist/mock-DMgIygjE.mjs.map +0 -1
- package/dist/package-json-wzO6nV9O.mjs +0 -4
- package/dist/registry-D0uB0OrK.mjs +0 -178
- package/dist/registry-D0uB0OrK.mjs.map +0 -1
- package/dist/runtime-C7qTBDD2.mjs.map +0 -1
- package/dist/schema-1msIhXwA.mjs.map +0 -1
- package/dist/seed-BH2FbrPV.mjs.map +0 -1
- package/dist/service-BHQIerYh.mjs +0 -4
- package/dist/service-DMohAx8a2.mjs.map +0 -1
- package/dist/service-wI3Hvrgx.mjs.map +0 -1
- package/dist/telemetry-w92bvGdC.mjs +0 -4
- package/dist/types-2Be3wSMc.mjs +0 -5
- package/dist/types-CmzfQP_m.mjs.map +0 -1
- package/dist/workflow.generated-Bf1tWylx.d.mts +0 -1416
- package/docs/generator/builtin.md +0 -257
- package/docs/generator/custom.md +0 -147
- package/docs/generator/index.md +0 -66
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
import { t as
|
|
3
|
-
import { t as brandValue } from "./brand-DlnJ375c.mjs";
|
|
1
|
+
import { t as mapAllowedValues } from "./field-DOsJCPFa.mjs";
|
|
2
|
+
import { t as brandValue } from "./brand-Eo4pLXPJ.mjs";
|
|
4
3
|
import { cloneDeep } from "es-toolkit";
|
|
5
4
|
|
|
6
5
|
//#region src/configure/services/tailordb/schema.ts
|
|
@@ -578,4 +577,4 @@ timestamps: () => ({
|
|
|
578
577
|
|
|
579
578
|
//#endregion
|
|
580
579
|
export { db as t };
|
|
581
|
-
//# sourceMappingURL=schema-
|
|
580
|
+
//# sourceMappingURL=schema-BhkpP5Hw.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-BhkpP5Hw.mjs","names":[],"sources":["../src/configure/services/tailordb/schema.ts"],"sourcesContent":["import { cloneDeep } from \"es-toolkit\";\nimport {\n type AllowedValues,\n type AllowedValuesOutput,\n mapAllowedValues,\n} from \"@/configure/types/field\";\nimport { brandValue } from \"@/utils/brand\";\nimport type { TailorTypeGqlPermission, TailorTypePermission } from \"./permission\";\nimport type { Hook, Hooks, ExcludeNestedDBFields, TypeFeatures } from \"./types\";\nimport type {\n TailorDBField as TailorDBFieldBase,\n TailorDBType as TailorDBTypeBase,\n DBFieldMetadata,\n DefinedDBFieldMetadata,\n SerialConfig,\n IndexDef,\n TailorDBTypeMetadata,\n RawRelationConfig,\n RelationType,\n} from \"@/configure/services/tailordb/types\";\nimport type {\n FieldOptions,\n FieldOutput,\n TailorFieldType,\n TailorToTs,\n TailorField as TailorFieldMinimal,\n FieldValidateInput,\n ValidateConfig,\n Validators,\n} from \"@/configure/types/field.types\";\nimport type { PluginAttachment, PluginConfigs } from \"@/plugin/types\";\nimport type { InferredAttributeMap, TailorUser } from \"@/runtime/types\";\nimport type { output, InferFieldsOutput, Prettify } from \"@/types/helpers\";\nimport type { RawPermissions } from \"@/types/tailordb.generated\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\n// Helper alias: DB fields can be arbitrarily nested, so we intentionally keep this loose.\n// oxlint-disable-next-line no-explicit-any\nexport type TailorAnyDBField = TailorDBField<any, any>;\n\n// Helper alias\n// oxlint-disable-next-line no-explicit-any\nexport type TailorAnyDBType = TailorDBType<any, any>;\n\n/**\n * Full TailorDBField interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBField<\n Defined extends DefinedDBFieldMetadata = DefinedDBFieldMetadata,\n // oxlint-disable-next-line no-explicit-any\n Output = any,\n> extends Omit<TailorDBFieldBase<Defined, Output>, \"fields\"> {\n readonly fields: Record<string, TailorAnyDBField>;\n _metadata: DBFieldMetadata;\n\n /**\n * Parse and validate a value against this field's validation rules\n */\n parse(args: FieldParseArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @private\n */\n _parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<Output>;\n\n /**\n * typeName is not available on TailorDB fields.\n * Use typeName on pipeline fields (t.enum / t.object) instead.\n */\n typeName(this: never, typeName: string): never;\n\n /**\n * Set a description for the field\n */\n description<CurrentDefined extends Defined>(\n this: CurrentDefined extends { description: unknown }\n ? never\n : TailorFieldMinimal<CurrentDefined, Output>,\n description: string,\n ): TailorDBField<Prettify<CurrentDefined & { description: true }>, Output>;\n\n /**\n * Define a relation to another type.\n */\n relation<S extends RelationType, T extends TailorAnyDBType, CurrentDefined extends Defined>(\n this: CurrentDefined extends { relation: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n config: RelationConfig<S, T>,\n ): TailorDBField<\n S extends \"oneToOne\" | \"1-1\"\n ? Prettify<CurrentDefined & { unique: true; index: true; relation: true }>\n : Prettify<CurrentDefined & { index: true; relation: true }>,\n Output\n >;\n\n /**\n * Define a self-referencing relation\n */\n relation<S extends RelationSelfConfig, CurrentDefined extends Defined>(\n this: CurrentDefined extends { relation: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n config: S,\n ): TailorDBField<\n S[\"type\"] extends \"oneToOne\" | \"1-1\"\n ? Prettify<CurrentDefined & { unique: true; index: true; relation: true }>\n : Prettify<CurrentDefined & { index: true; relation: true }>,\n Output\n >;\n\n /**\n * Add an index to the field\n */\n index<CurrentDefined extends Defined>(\n this: CurrentDefined extends { index: unknown }\n ? never\n : CurrentDefined extends { array: true }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n ): TailorDBField<Prettify<CurrentDefined & { index: true }>, Output>;\n\n /**\n * Make the field unique (also adds an index)\n */\n unique<CurrentDefined extends Defined>(\n this: CurrentDefined extends { unique: unknown }\n ? never\n : CurrentDefined extends { array: true }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n ): TailorDBField<Prettify<CurrentDefined & { unique: true; index: true }>, Output>;\n\n /**\n * Enable vector search on the field (string type only)\n */\n vector<CurrentDefined extends Defined>(\n this: CurrentDefined extends { vector: unknown }\n ? never\n : CurrentDefined extends { type: \"string\"; array: false }\n ? TailorDBField<CurrentDefined, Output>\n : never,\n ): TailorDBField<Prettify<CurrentDefined & { vector: true }>, Output>;\n\n /**\n * Add hooks for create/update operations on this field.\n */\n hooks<CurrentDefined extends Defined, const H extends Hook<unknown, Output>>(\n this: CurrentDefined extends { hooks: unknown }\n ? never\n : CurrentDefined extends { type: \"nested\" }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n hooks: H,\n ): TailorDBField<\n Prettify<\n CurrentDefined & {\n hooks?: {\n create: H extends { create: unknown } ? true : false;\n update: H extends { update: unknown } ? true : false;\n };\n serial: false;\n }\n >,\n Output\n >;\n\n /**\n * Add validation functions to the field.\n */\n validate<CurrentDefined extends Defined>(\n this: CurrentDefined extends { validate: unknown }\n ? never\n : TailorDBField<CurrentDefined, Output>,\n ...validate: FieldValidateInput<Output>[]\n ): TailorDBField<Prettify<CurrentDefined & { validate: true }>, Output>;\n\n /**\n * Configure serial/auto-increment behavior\n */\n serial<CurrentDefined extends Defined>(\n this: CurrentDefined extends { serial: unknown }\n ? never\n : Output extends null\n ? never\n : CurrentDefined extends { type: \"integer\" | \"string\"; array: false }\n ? TailorDBField<CurrentDefined, Output>\n : never,\n config: SerialConfig<CurrentDefined[\"type\"] & (\"integer\" | \"string\")>,\n ): TailorDBField<\n Prettify<\n CurrentDefined & {\n serial: true;\n hooks: { create: false; update: false };\n }\n >,\n Output\n >;\n\n /**\n * Clone the field with optional overrides for field options\n */\n clone<const NewOpt extends FieldOptions>(\n options?: NewOpt,\n ): TailorDBField<\n Prettify<\n Omit<Defined, \"array\"> & {\n array: NewOpt extends { array: true } ? true : Defined[\"array\"];\n }\n >,\n FieldOutput<TailorToTs[Defined[\"type\"]], NewOpt>\n >;\n}\n\n/**\n * Full TailorDBType interface with builder methods.\n * Extends the minimal structural interface from types/ with fluent API methods.\n */\nexport interface TailorDBType<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributeMap,\n> extends TailorDBTypeBase<Fields, User> {\n _description?: string;\n\n hooks(hooks: Hooks<Fields>): TailorDBType<Fields, User>;\n validate(validators: Validators<Fields>): TailorDBType<Fields, User>;\n features(features: Omit<TypeFeatures, \"pluralForm\">): TailorDBType<Fields, User>;\n indexes(...indexes: IndexDef<TailorDBType<Fields, User>>[]): TailorDBType<Fields, User>;\n files<const F extends string>(\n files: Record<F, string> & Partial<Record<keyof output<TailorDBType<Fields, User>>, never>>,\n ): TailorDBType<Fields, User>;\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User>>> = TailorTypePermission<\n U,\n output<TailorDBType<Fields, User>>\n >,\n >(\n permission: P,\n ): TailorDBType<Fields, U>;\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(\n permission: P,\n ): TailorDBType<Fields, U>;\n description(description: string): TailorDBType<Fields, User>;\n pickFields<K extends keyof Fields>(keys: K[]): Pick<Fields, K>;\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(\n keys: K[],\n options: Opt,\n ): {\n [P in K]: Fields[P] extends TailorDBField<infer D, infer _O>\n ? TailorDBField<\n Omit<D, \"array\"> & {\n array: Opt extends { array: true } ? true : D[\"array\"];\n },\n FieldOutput<TailorToTs[D[\"type\"]], Opt>\n >\n : never;\n };\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K>;\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User>;\n}\n\nexport type TailorDBInstance<\n // oxlint-disable-next-line no-explicit-any\n Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributeMap,\n> = TailorDBType<Fields, User>;\n\ninterface RelationConfig<S extends RelationType, T extends TailorDBType> {\n type: S;\n toward: {\n type: T;\n as?: string;\n key?: keyof T[\"fields\"] & string;\n };\n backward?: string;\n}\n\n// Special config variant for self-referencing relations\ntype RelationSelfConfig = {\n type: RelationType;\n toward: {\n type: \"self\";\n as?: string;\n key?: string;\n };\n backward?: string;\n};\n\nfunction isRelationSelfConfig(\n config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig,\n): config is RelationSelfConfig {\n return config.toward.type === \"self\";\n}\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>\\d{2}):(?<minute>\\d{2})$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})T(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(.(?<millisec>\\d{3}))?Z$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\ntype FieldParseArgs = {\n value: unknown;\n data: unknown;\n user: TailorUser;\n};\n\ntype FieldValidateValueArgs<T extends TailorFieldType> = {\n value: TailorToTs[T];\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\ntype FieldParseInternalArgs = {\n // Runtime input is unknown/untyped; we validate and narrow it inside the parser.\n // oxlint-disable-next-line no-explicit-any\n value: any;\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\n/**\n * Creates a new TailorDBField instance.\n * @param type - Field type\n * @param options - Field options\n * @param fields - Nested fields for object-like types\n * @param values - Allowed values for enum-like fields\n * @returns A new TailorDBField\n */\nfunction createTailorDBField<\n const T extends TailorFieldType,\n const TOptions extends FieldOptions,\n const OutputBase = TailorToTs[T],\n>(\n type: T,\n options?: TOptions,\n fields?: Record<string, TailorAnyDBField>,\n values?: AllowedValues,\n): TailorDBField<\n { type: T; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n> {\n type FieldType = TailorDBField<\n { type: T; array: TOptions extends { array: true } ? true : false },\n FieldOutput<OutputBase, TOptions>\n >;\n\n const _metadata: DBFieldMetadata = { required: true };\n let _rawRelation: RawRelationConfig | undefined;\n\n if (options) {\n if (options.optional === true) {\n _metadata.required = false;\n }\n if (options.array === true) {\n _metadata.array = true;\n }\n }\n if (values) {\n _metadata.allowedValues = mapAllowedValues(values);\n }\n\n /**\n * Validate a single value (not an array element)\n * Used internally for array element validation\n * @param args - Value, context data, and user\n * @returns Array of validation issues\n */\n function validateValue(args: FieldValidateValueArgs<T>): StandardSchemaV1.Issue[] {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // Type-specific validation\n switch (type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n break;\n\n case \"nested\":\n // Validate nested object fields\n // runtime value may not match the declared type\n // oxlint-disable typescript/no-unnecessary-condition\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date\n ) {\n // oxlint-enable typescript/no-unnecessary-condition\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n } else if (Object.keys(field.fields).length > 0) {\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = (value as Record<string, unknown>)[fieldName];\n const result = nestedField._parseInternal({\n value: fieldValue,\n data,\n user,\n pathArray: pathArray.concat(fieldName),\n });\n if (result.issues) {\n issues.push(...result.issues);\n }\n }\n }\n break;\n }\n\n // Custom validation functions\n const validateFns = field._metadata.validate;\n if (validateFns && validateFns.length > 0) {\n for (const validateInput of validateFns) {\n const { fn, message } =\n typeof validateInput === \"function\"\n ? { fn: validateInput, message: \"Validation failed\" }\n : { fn: validateInput[0], message: validateInput[1] };\n\n if (!fn({ value, data, user })) {\n issues.push({\n message,\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Internal parse method that tracks field path for nested validation\n * @param args - Parse arguments\n * @returns Parse result with value or issues\n */\n function parseInternal(\n args: FieldParseInternalArgs,\n ): StandardSchemaV1.Result<FieldOutput<OutputBase, TOptions>> {\n const { value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n\n // 1. Check required/optional\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // If optional and null/undefined, skip further validation and normalize to null\n if (!field._metadata.required && isNullOrUndefined) {\n return { value: value ?? null };\n }\n\n // 2. Check array type\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path: pathArray.length > 0 ? pathArray : undefined,\n });\n return { issues };\n }\n\n // Validate each array element (without array flag)\n for (let i = 0; i < value.length; i++) {\n const elementValue = value[i];\n const elementPath = pathArray.concat(`[${i}]`);\n\n // Validate element with same type but without array flag\n const elementIssues = validateValue({\n value: elementValue,\n data,\n user,\n pathArray: elementPath,\n });\n if (elementIssues.length > 0) {\n issues.push(...elementIssues);\n }\n }\n\n if (issues.length > 0) {\n return { issues };\n }\n return { value: value as FieldOutput<OutputBase, TOptions> };\n }\n\n // 3. Type-specific validation and custom validation\n const valueIssues = validateValue({ value, data, user, pathArray });\n issues.push(...valueIssues);\n\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value };\n }\n\n function cloneWith(metadataUpdates: Partial<DBFieldMetadata>) {\n const cloned = field.clone();\n Object.assign(cloned._metadata, metadataUpdates);\n return cloned;\n }\n\n const field: FieldType = {\n type,\n fields: (fields ?? {}) as Record<string, TailorAnyDBField>,\n _defined: undefined as unknown as {\n type: T;\n array: TOptions extends { array: true } ? true : false;\n },\n _output: undefined as FieldOutput<OutputBase, TOptions>,\n _metadata,\n\n get metadata() {\n return { ...this._metadata };\n },\n\n get rawRelation(): Readonly<RawRelationConfig> | undefined {\n return _rawRelation ? { ..._rawRelation, toward: { ..._rawRelation.toward } } : undefined;\n },\n\n description(description: string) {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ description }) as any;\n },\n\n // oxlint-disable-next-line no-explicit-any\n typeName: ((typeName: string) => cloneWith({ typeName })) as any,\n\n validate(...validateInputs: FieldValidateInput<FieldOutput<OutputBase, TOptions>>[]) {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ validate: validateInputs }) as any;\n },\n\n parse(args: FieldParseArgs): StandardSchemaV1.Result<FieldOutput<OutputBase, TOptions>> {\n return parseInternal({\n value: args.value,\n data: args.data,\n user: args.user,\n pathArray: [],\n });\n },\n\n _parseInternal: parseInternal,\n\n // TailorDBField specific methods\n relation(config: RelationConfig<RelationType, TailorDBType> | RelationSelfConfig) {\n const cloned = field.clone();\n const targetType = isRelationSelfConfig(config) ? \"self\" : config.toward.type.name;\n // oxlint-disable-next-line no-explicit-any\n (cloned as any)._setRawRelation({\n type: config.type,\n toward: {\n type: targetType,\n as: config.toward.as,\n key: config.toward.key,\n },\n backward: config.backward,\n });\n // oxlint-disable-next-line no-explicit-any\n return cloned as any;\n },\n\n index() {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ index: true }) as any;\n },\n\n unique() {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ unique: true, index: true }) as any;\n },\n\n vector() {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ vector: true }) as any;\n },\n\n hooks(hooks: Hook<unknown, FieldOutput<OutputBase, TOptions>>) {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ hooks }) as any;\n },\n\n serial(config: SerialConfig) {\n // oxlint-disable-next-line no-explicit-any\n return cloneWith({ serial: config }) as any;\n },\n\n clone(cloneOptions?: FieldOptions) {\n // Deep clone nested object fields if present\n let clonedFields = fields;\n if (fields) {\n const cloned: Record<string, TailorAnyDBField> = {};\n for (const [key, field] of Object.entries(fields)) {\n cloned[key] = field.clone();\n }\n clonedFields = cloned;\n }\n\n // Create a new field with cloned configuration\n const clonedField = createTailorDBField(type, options, clonedFields, values);\n\n // Deep copy metadata using cloneDeep (preserves function references)\n Object.assign(clonedField._metadata, cloneDeep(this._metadata));\n\n // Apply new options if provided\n if (cloneOptions) {\n if (cloneOptions.optional !== undefined) {\n clonedField._metadata.required = !cloneOptions.optional;\n }\n if (cloneOptions.array !== undefined) {\n clonedField._metadata.array = cloneOptions.array;\n }\n }\n\n // Copy raw relation if exists\n if (_rawRelation) {\n const clonedRawRelation = cloneDeep(_rawRelation);\n // oxlint-disable-next-line no-explicit-any\n (clonedField as any)._setRawRelation(clonedRawRelation);\n }\n\n // oxlint-disable-next-line no-explicit-any\n return clonedField as any;\n },\n\n // Internal method for clone to set rawRelation\n // @ts-ignore - Internal method not in interface\n _setRawRelation(relation: RawRelationConfig) {\n _rawRelation = relation;\n },\n };\n\n return field;\n}\n\nconst createField = createTailorDBField;\n\n/**\n * Create a UUID field.\n * @param options - Field configuration options\n * @returns A UUID field\n * @example db.uuid()\n * @example db.uuid({ optional: true })\n */\nfunction uuid<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"uuid\", options);\n}\n\n/**\n * Create a string field.\n * @param options - Field configuration options\n * @returns A string field\n * @example db.string()\n * @example db.string({ optional: true })\n */\nfunction string<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"string\", options);\n}\n\n/**\n * Create a boolean field.\n * Note: The method name is `bool` but creates a `boolean` type field.\n * @param options - Field configuration options\n * @returns A boolean field\n * @example db.bool()\n * @example db.bool({ optional: true })\n */\nfunction bool<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"boolean\", options);\n}\n\n/**\n * Create an integer field.\n * @param options - Field configuration options\n * @returns An integer field\n * @example db.int()\n * @example db.int({ optional: true })\n */\nfunction int<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"integer\", options);\n}\n\n/**\n * Create a float (decimal number) field.\n * @param options - Field configuration options\n * @returns A float field\n * @example db.float()\n * @example db.float({ optional: true })\n */\nfunction float<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"float\", options);\n}\n\ninterface DecimalFieldOptions extends FieldOptions {\n scale?: number;\n}\n\n/**\n * Create a decimal field (stored as string for precision).\n * @param options - Field configuration options including optional scale (0-12)\n * @returns A decimal field\n * @example db.decimal()\n * @example db.decimal({ scale: 2 })\n * @example db.decimal({ scale: 2, optional: true })\n */\nfunction decimal<const Opt extends DecimalFieldOptions>(options?: Opt) {\n if (options?.scale !== undefined) {\n if (!Number.isInteger(options.scale) || options.scale < 0 || options.scale > 12) {\n throw new Error(\"scale must be an integer between 0 and 12\");\n }\n }\n const field = createField(\"decimal\", options);\n if (options?.scale !== undefined) {\n field._metadata.scale = options.scale;\n }\n return field;\n}\n\n/**\n * Create a date field (date only, no time component).\n * Format: \"yyyy-MM-dd\"\n * @param options - Field configuration options\n * @returns A date field\n * @example db.date()\n */\nfunction date<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"date\", options);\n}\n\n/**\n * Create a datetime field (date and time).\n * Format: ISO 8601 \"yyyy-MM-ddTHH:mm:ssZ\"\n * @param options - Field configuration options\n * @returns A datetime field\n * @example db.datetime()\n */\nfunction datetime<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"datetime\", options);\n}\n\n/**\n * Create a time field (time only, no date component).\n * Format: \"HH:mm\"\n * @param options - Field configuration options\n * @returns A time field\n * @example db.time()\n */\nfunction time<const Opt extends FieldOptions>(options?: Opt) {\n return createField(\"time\", options);\n}\n\n/**\n * Create an enum field with a fixed set of allowed string values.\n * @param values - Array of allowed string values, or array of `{ value, description }` objects\n * @param options - Field configuration options\n * @returns An enum field\n * @example db.enum([\"active\", \"inactive\", \"suspended\"])\n * @example db.enum([\"small\", \"medium\", \"large\"], { optional: true })\n */\nfunction _enum<const V extends AllowedValues, const Opt extends FieldOptions>(\n values: V,\n options?: Opt,\n): TailorDBField<\n { type: \"enum\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<AllowedValuesOutput<V>, Opt>\n> {\n return createField<\"enum\", Opt, AllowedValuesOutput<V>>(\"enum\", options, undefined, values);\n}\n\n/**\n * Create a nested object field with sub-fields.\n * @param fields - Record of nested field definitions\n * @param options - Field configuration options\n * @returns A nested object field\n * @example db.object({ street: db.string(), city: db.string(), zip: db.string() })\n * @example db.object({ name: db.string() }, { optional: true })\n */\nfunction object<\n const F extends Record<string, TailorAnyDBField> & ExcludeNestedDBFields<F>,\n const Opt extends FieldOptions,\n>(fields: F, options?: Opt) {\n return createField(\"nested\", options, fields) as unknown as TailorDBField<\n { type: \"nested\"; array: Opt extends { array: true } ? true : false },\n FieldOutput<InferFieldsOutput<F>, Opt>\n >;\n}\n\n/**\n * Creates a new TailorDBType instance.\n * @param name - Type name\n * @param fields - Field definitions\n * @param options - Type options\n * @param options.pluralForm - Optional plural form\n * @param options.description - Optional description\n * @returns A new TailorDBType\n */\nfunction createTailorDBType<\n // oxlint-disable-next-line no-explicit-any\n const Fields extends Record<string, TailorAnyDBField> = any,\n User extends object = InferredAttributeMap,\n>(\n name: string,\n fields: Fields,\n options: { pluralForm?: string; description?: string },\n): TailorDBType<Fields, User> {\n let _description = options.description;\n let _settings: TypeFeatures = {};\n let _indexes: IndexDef<TailorDBType<Fields, User>>[] = [];\n const _permissions: RawPermissions = {};\n let _files: Record<string, string> = {};\n const _plugins: PluginAttachment[] = [];\n\n if (options.pluralForm) {\n if (name === options.pluralForm) {\n throw new Error(`The name and the plural form must be different. name=${name}`);\n }\n _settings.pluralForm = options.pluralForm;\n }\n\n const dbType: TailorDBType<Fields, User> = {\n name,\n fields: { ...fields },\n _output: null as unknown as InferFieldsOutput<Fields>,\n _description,\n\n get metadata(): TailorDBTypeMetadata {\n // Convert indexes to the format expected by the manifest\n const indexes: Record<string, { fields: string[]; unique?: boolean }> = {};\n if (_indexes.length > 0) {\n _indexes.forEach((index) => {\n const fieldNames = index.fields.map((field) => String(field));\n const key = index.name || `idx_${fieldNames.join(\"_\")}`;\n indexes[key] = {\n fields: fieldNames,\n unique: index.unique,\n };\n });\n }\n\n return {\n name: this.name,\n description: _description,\n settings: _settings,\n permissions: _permissions,\n files: _files,\n ...(Object.keys(indexes).length > 0 && { indexes }),\n };\n },\n\n hooks(hooks: Hooks<Fields>) {\n // `Hooks<Fields>` is strongly typed, but `Object.entries()` loses that information.\n // oxlint-disable-next-line no-explicit-any\n Object.entries(hooks).forEach(([fieldName, fieldHooks]: [string, any]) => {\n const field = this.fields[fieldName];\n if (field === undefined) throw new Error(`field not found: ${fieldName}`);\n (this.fields as Record<string, TailorAnyDBField>)[fieldName] = (\n field as TailorAnyDBField\n ).hooks(fieldHooks);\n });\n return this;\n },\n\n validate(validators: Validators<Fields>) {\n Object.entries(validators).forEach(([fieldName, fieldValidators]) => {\n const field = this.fields[fieldName] as TailorAnyDBField;\n\n const validators = fieldValidators as\n | FieldValidateInput<unknown>\n | FieldValidateInput<unknown>[];\n\n const isValidateConfig = (v: unknown): v is ValidateConfig<unknown> => {\n return Array.isArray(v) && v.length === 2 && typeof v[1] === \"string\";\n };\n\n let updatedField: TailorAnyDBField;\n if (Array.isArray(validators)) {\n if (isValidateConfig(validators)) {\n updatedField = field.validate(validators);\n } else {\n updatedField = field.validate(...validators);\n }\n } else {\n updatedField = field.validate(validators);\n }\n (this.fields as Record<string, TailorAnyDBField>)[fieldName] = updatedField;\n });\n return this;\n },\n\n features(features: Omit<TypeFeatures, \"pluralForm\">) {\n _settings = {\n ..._settings,\n ...features,\n };\n return this;\n },\n\n indexes(...indexes: IndexDef<TailorDBType<Fields, User>>[]) {\n _indexes = indexes;\n return this;\n },\n\n files<const F extends string>(\n files: Record<F, string> & Partial<Record<keyof output<TailorDBType<Fields, User>>, never>>,\n ) {\n _files = files;\n return this;\n },\n\n permission<\n U extends object = User,\n P extends TailorTypePermission<U, output<TailorDBType<Fields, User>>> = TailorTypePermission<\n U,\n output<TailorDBType<Fields, User>>\n >,\n >(permission: P) {\n const ret = this as TailorDBType<Fields, U>;\n _permissions.record = permission as RawPermissions[\"record\"];\n return ret;\n },\n\n gqlPermission<\n U extends object = User,\n P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>,\n >(permission: P) {\n const ret = this as TailorDBType<Fields, U>;\n _permissions.gql = permission as RawPermissions[\"gql\"];\n return ret;\n },\n\n description(description: string) {\n _description = description;\n this._description = description;\n return this;\n },\n\n pickFields<K extends keyof Fields, const Opt extends FieldOptions>(keys: K[], options?: Opt) {\n const result = {} as Record<K, TailorAnyDBField>;\n for (const key of keys) {\n const field = this.fields[key] as TailorAnyDBField;\n if (options) {\n result[key] = field.clone(options);\n } else {\n result[key] = field;\n }\n }\n // oxlint-disable-next-line no-explicit-any\n return result as any;\n },\n\n omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K> {\n const keysSet = new Set(keys);\n const result = {} as Record<string, TailorAnyDBField>;\n for (const key in this.fields) {\n if (Object.hasOwn(this.fields, key) && !keysSet.has(key as unknown as K)) {\n result[key] = this.fields[key] as TailorAnyDBField;\n }\n }\n return result as Omit<Fields, K>;\n },\n\n get plugins(): PluginAttachment[] {\n return _plugins;\n },\n\n plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: {\n [K in P]: PluginConfigs<keyof Fields & string>[K];\n }): TailorDBType<Fields, User> {\n for (const [pluginId, pluginConfig] of Object.entries(config)) {\n _plugins.push({ pluginId, config: pluginConfig });\n }\n return this;\n },\n };\n\n return brandValue(dbType, \"tailordb-type\");\n}\n\nconst idField = uuid();\ntype idField = typeof idField;\ntype DBType<F extends { id?: never } & Record<string, TailorAnyDBField>> = TailorDBInstance<\n { id: idField } & F\n>;\n\n/**\n * Creates a new database type with the specified fields.\n * An `id` field (UUID) is automatically added to every type.\n * @param name - The name of the type, or a tuple of [name, pluralForm]\n * @param fields - The field definitions for the type\n * @returns A new TailorDBType instance\n * @example\n * export const user = db.type(\"User\", {\n * name: db.string(),\n * email: db.string(),\n * age: db.int({ optional: true }),\n * role: db.enum([\"admin\", \"member\"]),\n * ...db.fields.timestamps(),\n * });\n * // Always export both the value and type:\n * export type user = typeof user;\n */\nfunction dbType<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fields: F,\n): DBType<F>;\n/**\n * Creates a new database type with the specified fields and description.\n * An `id` field (UUID) is automatically added to every type.\n * @param name - The name of the type, or a tuple of [name, pluralForm]\n * @param description - A description of the type\n * @param fields - The field definitions for the type\n * @returns A new TailorDBType instance\n */\nfunction dbType<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n description: string,\n fields: F,\n): DBType<F>;\nfunction dbType<const F extends { id?: never } & Record<string, TailorAnyDBField>>(\n name: string | [string, string],\n fieldsOrDescription: string | F,\n fields?: F,\n): DBType<F> {\n const typeName = Array.isArray(name) ? name[0] : name;\n const pluralForm = Array.isArray(name) ? name[1] : undefined;\n\n let description: string | undefined;\n let fieldDef: F;\n if (typeof fieldsOrDescription === \"string\") {\n description = fieldsOrDescription;\n fieldDef = fields as F;\n } else {\n fieldDef = fieldsOrDescription;\n }\n return createTailorDBType<{ id: idField } & F>(\n typeName,\n {\n id: idField,\n ...fieldDef,\n },\n { pluralForm, description },\n ) as DBType<F>;\n}\n\n/** TailorDB schema builder utilities for defining types and fields. */\nexport const db = {\n type: dbType,\n uuid,\n string,\n bool,\n int,\n float,\n decimal,\n date,\n datetime,\n time,\n enum: _enum,\n object,\n fields: {\n /**\n * Creates standard timestamp fields (createdAt, updatedAt) with auto-hooks.\n * createdAt is set on create, updatedAt is set on update.\n * A user-specified createdAt is respected when provided (e.g. seeding historical\n * records); the current time is used only when the value is omitted.\n * @returns An object with createdAt and updatedAt fields\n * @example\n * const model = db.type(\"Model\", {\n * name: db.string(),\n * ...db.fields.timestamps(),\n * });\n */\n timestamps: () => ({\n createdAt: datetime()\n .hooks({ create: ({ value }) => value ?? new Date() })\n .description(\"Record creation timestamp\"),\n updatedAt: datetime({ optional: true })\n .hooks({ update: () => new Date() })\n .description(\"Record last update timestamp\"),\n }),\n },\n};\n"],"mappings":";;;;;AAySA,SAAS,qBACP,QAC8B;C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IAAI,IAAI,KAAK,KAAK;CAEnD,IAAI;CACJ,IAAI;CACJ,IAAI,OAAO,wBAAwB,UAAU;EAC3C,cAAc;EACd,WAAW;CACb,OACE,WAAW;CAEb,OAAO,mBACL,UACA;EACE,IAAI;EACJ,GAAG;CACL,GACA;EAAE;EAAY;CAAY,CAC5B;AACF;;AAGA,MAAa,KAAK;CAChB,MAAM;CACN;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,MAAM;CACN;CACA,QAAQ;;;;;;;;;;;;;AAaN,mBAAmB;EACjB,WAAW,SAAS,CAAC,CAClB,MAAM,EAAE,SAAS,EAAE,YAAY,yBAAS,IAAI,KAAK,EAAE,CAAC,CAAC,CACrD,YAAY,2BAA2B;EAC1C,WAAW,SAAS,EAAE,UAAU,KAAK,CAAC,CAAC,CACpC,MAAM,EAAE,8BAAc,IAAI,KAAK,EAAE,CAAC,CAAC,CACnC,YAAY,8BAA8B;CAC/C,GACF;AACF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
import * as fs from "node:fs";
|
|
3
2
|
import * as path from "pathe";
|
|
4
3
|
|
|
@@ -62,4 +61,4 @@ function tightenSecretFilePermissions(filePath) {
|
|
|
62
61
|
|
|
63
62
|
//#endregion
|
|
64
63
|
export { tightenSecretFilePermissions as n, writeSecretFile as r, ensureSecretDir as t };
|
|
65
|
-
//# sourceMappingURL=secret-file-
|
|
64
|
+
//# sourceMappingURL=secret-file-DBqZhjFQ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secret-file-
|
|
1
|
+
{"version":3,"file":"secret-file-DBqZhjFQ.mjs","names":[],"sources":["../src/cli/shared/secret-file.ts"],"sourcesContent":["import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\n\nconst DIR_MODE = 0o700;\nconst FILE_MODE = 0o600;\n\n/**\n * Best-effort chmod that only fires when the current mode differs from the\n * target. No-op on Windows (where POSIX mode bits are advisory and ACLs\n * govern access) and on missing paths / permission errors.\n * @param target - Path to chmod\n * @param mode - Desired POSIX mode bits\n */\nfunction chmodIfDifferent(target: string, mode: number): void {\n if (process.platform === \"win32\") return;\n try {\n if ((fs.statSync(target).mode & 0o777) !== mode) {\n fs.chmodSync(target, mode);\n }\n } catch {\n // Missing path or permission error — best-effort.\n }\n}\n\n/**\n * Write a file that may contain secrets with restrictive permissions.\n * Creates the parent directory with 0o700 and the file with 0o600 on POSIX\n * systems so other users on the host cannot read access tokens, refresh\n * tokens, or crash report payloads. On Windows the POSIX mode bits are\n * effectively ignored and ACLs govern access, so the chmod calls are\n * best-effort and silently skipped.\n * @param filePath - Absolute path to write\n * @param content - File content\n */\nexport function writeSecretFile(filePath: string, content: string | Buffer): void {\n ensureSecretDir(path.dirname(filePath));\n fs.writeFileSync(filePath, content, { mode: FILE_MODE });\n chmodIfDifferent(filePath, FILE_MODE);\n}\n\n/**\n * Ensure a directory exists with 0o700 permissions on POSIX systems.\n * `mkdirSync({ recursive: true })` does not chmod existing directories,\n * so this also tightens permissions on directories that were previously\n * created with looser modes.\n * @param dir - Directory path\n */\nexport function ensureSecretDir(dir: string): void {\n fs.mkdirSync(dir, { recursive: true, mode: DIR_MODE });\n chmodIfDifferent(dir, DIR_MODE);\n}\n\n/**\n * Tighten an existing file and its parent directory to secret-file modes\n * (0o600 / 0o700) if they are looser. Used by read paths that may not\n * trigger a subsequent write, so that legacy world-readable files are\n * still secured the next time the CLI runs. Silent no-op on Windows and\n * on missing files / permission errors.\n * @param filePath - Absolute path that should be 0o600 and live under a 0o700 directory\n */\nexport function tightenSecretFilePermissions(filePath: string): void {\n chmodIfDifferent(filePath, FILE_MODE);\n chmodIfDifferent(path.dirname(filePath), DIR_MODE);\n}\n"],"mappings":";;;;AAGA,MAAM,WAAW;AACjB,MAAM,YAAY;;;;;;;;AASlB,SAAS,iBAAiB,QAAgB,MAAoB;CAC5D,IAAI,QAAQ,aAAa,SAAS;CAClC,IAAI;EACF,KAAK,GAAG,SAAS,MAAM,CAAC,CAAC,OAAO,SAAW,MACzC,GAAG,UAAU,QAAQ,IAAI;CAE7B,QAAQ,CAER;AACF;;;;;;;;;;;AAYA,SAAgB,gBAAgB,UAAkB,SAAgC;CAChF,gBAAgB,KAAK,QAAQ,QAAQ,CAAC;CACtC,GAAG,cAAc,UAAU,SAAS,EAAE,MAAM,UAAU,CAAC;CACvD,iBAAiB,UAAU,SAAS;AACtC;;;;;;;;AASA,SAAgB,gBAAgB,KAAmB;CACjD,GAAG,UAAU,KAAK;EAAE,WAAW;EAAM,MAAM;CAAS,CAAC;CACrD,iBAAiB,KAAK,QAAQ;AAChC;;;;;;;;;AAUA,SAAgB,6BAA6B,UAAwB;CACnE,iBAAiB,UAAU,SAAS;CACpC,iBAAiB,KAAK,QAAQ,QAAQ,GAAG,QAAQ;AACnD"}
|
|
@@ -52,4 +52,4 @@ declare const getSecrets: TailorSecretmanagerAPI["getSecrets"];
|
|
|
52
52
|
declare const getSecret: TailorSecretmanagerAPI["getSecret"];
|
|
53
53
|
//#endregion
|
|
54
54
|
export { secretmanager_d_exports as i, getSecret as n, getSecrets as r, TailorSecretmanagerAPI as t };
|
|
55
|
-
//# sourceMappingURL=secretmanager-
|
|
55
|
+
//# sourceMappingURL=secretmanager-B3n4KHfm.d.mts.map
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { t as __exportAll } from "./chunk-BkoGK1jX.mjs";
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-DXywRVcq.mjs";
|
|
3
2
|
|
|
4
3
|
//#region src/runtime/secretmanager.ts
|
|
5
4
|
var secretmanager_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -22,4 +21,4 @@ const getSecret = (...args) => api().getSecret(...args);
|
|
|
22
21
|
|
|
23
22
|
//#endregion
|
|
24
23
|
export { getSecrets as n, secretmanager_exports as r, getSecret as t };
|
|
25
|
-
//# sourceMappingURL=secretmanager-
|
|
24
|
+
//# sourceMappingURL=secretmanager-BVxw3ih_.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secretmanager-
|
|
1
|
+
{"version":3,"file":"secretmanager-BVxw3ih_.mjs","names":[],"sources":["../src/runtime/secretmanager.ts"],"sourcesContent":["/**\n * Secret manager utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.secretmanager` runtime API.\n * At runtime this delegates to `globalThis.tailor.secretmanager`. Use\n * `mockSecretmanager` from `@tailor-platform/sdk/vitest` to mock these calls\n * in unit tests.\n * @example\n * import { secretmanager } from \"@tailor-platform/sdk/runtime\";\n *\n * const apiKey = await secretmanager.getSecret(\"my-vault\", \"API_KEY\");\n * const all = await secretmanager.getSecrets(\"my-vault\", [\"A\", \"B\"] as const);\n */\n\n/**\n * Platform API surface for `tailor.secretmanager`. Describes the shape the\n * platform runtime injects on `globalThis.tailor.secretmanager`.\n *\n * Each method below is also re-exported as a top-level named export from this\n * module so callers can either `import * as secretmanager from\n * \"@tailor-platform/sdk/runtime/secretmanager\"` or pick individual methods.\n */\nexport interface TailorSecretmanagerAPI {\n /**\n * Returns multiple secrets from a vault. Missing names are omitted from the result.\n * @param vault - Vault name\n * @param names - Secret names to fetch (use `as const` to narrow the result key)\n * @returns Partial record keyed by the requested names\n */\n getSecrets<const T extends readonly string[]>(\n vault: string,\n names: T,\n ): Promise<Partial<Record<T[number], string>>>;\n\n /**\n * Returns a single secret from a vault, or `undefined` when missing.\n * @param vault - Vault name\n * @param name - Secret name\n * @returns The secret value, or `undefined` if not present\n */\n getSecret(vault: string, name: string): Promise<string | undefined>;\n}\n\nconst api = (): TailorSecretmanagerAPI =>\n (globalThis as { tailor: { secretmanager: TailorSecretmanagerAPI } }).tailor.secretmanager;\n\n/**\n * See {@link TailorSecretmanagerAPI.getSecrets}.\n * @param args - Forwarded to {@link TailorSecretmanagerAPI.getSecrets}\n * @returns Partial record keyed by the requested names\n */\nexport const getSecrets: TailorSecretmanagerAPI[\"getSecrets\"] = (...args) =>\n api().getSecrets(...args);\n\n/**\n * See {@link TailorSecretmanagerAPI.getSecret}.\n * @param args - Forwarded to {@link TailorSecretmanagerAPI.getSecret}\n * @returns The secret value, or `undefined` if not present\n */\nexport const getSecret: TailorSecretmanagerAPI[\"getSecret\"] = (...args) => api().getSecret(...args);\n"],"mappings":";;;;;;;AA2CA,MAAM,YACH,WAAqE,OAAO;;;;;;AAO/E,MAAa,cAAoD,GAAG,SAClE,IAAI,CAAC,CAAC,WAAW,GAAG,IAAI;;;;;;AAO1B,MAAa,aAAkD,GAAG,SAAS,IAAI,CAAC,CAAC,UAAU,GAAG,IAAI"}
|
package/dist/seed/index.mjs
CHANGED
package/dist/seed/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/seed/index.ts"],"sourcesContent":["/**\n * Seed integration module for generated seed code.\n *\n * Re-exports `@toiroakr/lines-db` through a single import path\n * to avoid phantom dependency issues with pnpm, and provides\n * seed-specific utility functions used by the code generator.\n */\n\nimport { stat } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport { LinesDB, ErrorFormatter } from \"@toiroakr/lines-db\";\n\nexport { defineSchema } from \"@toiroakr/lines-db\";\nexport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\ntype ValidateSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Show verbose error output */\n verbose?: boolean;\n};\n\ntype ValidateSeedResult =\n | { valid: true; output: string }\n | { valid: false; output: string; error: string };\n\n/**\n * Validate JSONL seed data against schema definitions.\n * Resolves the given path (directory or `.jsonl` file), runs LinesDB\n * validation, and returns formatted output and error messages.\n * @param options - Validation options including path and verbose flag\n * @returns Validation result with output messages and optional error details\n */\nexport async function validateSeedData(\n options: ValidateSeedDataOptions,\n): Promise<ValidateSeedResult> {\n const { path: resolvedPath, verbose = false } = options;\n\n const stats = await stat(resolvedPath);\n let dataDir: string;\n let tableName: string | undefined;\n if (stats.isDirectory()) {\n dataDir = resolvedPath;\n } else if (stats.isFile() && resolvedPath.endsWith(\".jsonl\")) {\n dataDir = dirname(resolvedPath);\n tableName = basename(resolvedPath, \".jsonl\");\n } else {\n throw new Error(`Invalid path: ${resolvedPath}. Must be a directory or .jsonl file.`);\n }\n\n const db = LinesDB.create({ dataDir });\n let result;\n try {\n result = await db.initialize({ tableName, detailedValidate: true });\n } finally {\n await db.close();\n }\n\n const outputLines: string[] = [];\n\n if (result.warnings.length > 0) {\n for (const warning of result.warnings) {\n outputLines.push(`⚠ ${warning}`);\n }\n outputLines.push(\"\");\n }\n\n if (result.valid) {\n outputLines.push(\"✓ All records are valid\");\n return { valid: true, output: outputLines.join(\"\\n\") };\n }\n\n const formatter = new ErrorFormatter({ verbose });\n const errorLines: string[] = [];\n const errorsByFile = new Map<string, typeof result.errors>();\n for (const error of result.errors) {\n const fileErrors = errorsByFile.get(error.file) || [];\n fileErrors.push(error);\n errorsByFile.set(error.file, fileErrors);\n }\n for (const [file, fileErrors] of errorsByFile) {\n errorLines.push(formatter.formatErrorHeader(fileErrors.length, file));\n errorLines.push(\"\");\n const validationErrors = fileErrors.filter(\n (e) => e.type !== \"foreignKey\" || !e.foreignKeyError,\n );\n const foreignKeyErrors = fileErrors.filter((e) => e.type === \"foreignKey\" && e.foreignKeyError);\n if (validationErrors.length > 0) {\n errorLines.push(\n formatter.formatValidationErrors(\n validationErrors.map((e) => ({\n file: e.file,\n rowIndex: e.rowIndex,\n issues: e.issues,\n })),\n ),\n );\n }\n for (const fkError of foreignKeyErrors) {\n if (fkError.foreignKeyError) {\n errorLines.push(\n formatter.formatForeignKeyError({\n file: fkError.file,\n rowIndex: fkError.rowIndex,\n column: fkError.foreignKeyError.column,\n value: fkError.foreignKeyError.value,\n referencedTable: fkError.foreignKeyError.referencedTable,\n referencedColumn: fkError.foreignKeyError.referencedColumn,\n }),\n );\n }\n }\n errorLines.push(\"\");\n }\n\n return { valid: false, output: outputLines.join(\"\\n\"), error: errorLines.join(\"\\n\") };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/seed/index.ts"],"sourcesContent":["/**\n * Seed integration module for generated seed code.\n *\n * Re-exports `@toiroakr/lines-db` through a single import path\n * to avoid phantom dependency issues with pnpm, and provides\n * seed-specific utility functions used by the code generator.\n */\n\nimport { stat } from \"node:fs/promises\";\nimport { basename, dirname } from \"node:path\";\nimport { LinesDB, ErrorFormatter } from \"@toiroakr/lines-db\";\n\nexport { defineSchema } from \"@toiroakr/lines-db\";\nexport type { ForeignKeyDefinition, IndexDefinition } from \"@toiroakr/lines-db\";\n\ntype ValidateSeedDataOptions = {\n /** Resolved absolute path to a data directory or a .jsonl file */\n path: string;\n /** Show verbose error output */\n verbose?: boolean;\n};\n\ntype ValidateSeedResult =\n | { valid: true; output: string }\n | { valid: false; output: string; error: string };\n\n/**\n * Validate JSONL seed data against schema definitions.\n * Resolves the given path (directory or `.jsonl` file), runs LinesDB\n * validation, and returns formatted output and error messages.\n * @param options - Validation options including path and verbose flag\n * @returns Validation result with output messages and optional error details\n */\nexport async function validateSeedData(\n options: ValidateSeedDataOptions,\n): Promise<ValidateSeedResult> {\n const { path: resolvedPath, verbose = false } = options;\n\n const stats = await stat(resolvedPath);\n let dataDir: string;\n let tableName: string | undefined;\n if (stats.isDirectory()) {\n dataDir = resolvedPath;\n } else if (stats.isFile() && resolvedPath.endsWith(\".jsonl\")) {\n dataDir = dirname(resolvedPath);\n tableName = basename(resolvedPath, \".jsonl\");\n } else {\n throw new Error(`Invalid path: ${resolvedPath}. Must be a directory or .jsonl file.`);\n }\n\n const db = LinesDB.create({ dataDir });\n let result;\n try {\n result = await db.initialize({ tableName, detailedValidate: true });\n } finally {\n await db.close();\n }\n\n const outputLines: string[] = [];\n\n if (result.warnings.length > 0) {\n for (const warning of result.warnings) {\n outputLines.push(`⚠ ${warning}`);\n }\n outputLines.push(\"\");\n }\n\n if (result.valid) {\n outputLines.push(\"✓ All records are valid\");\n return { valid: true, output: outputLines.join(\"\\n\") };\n }\n\n const formatter = new ErrorFormatter({ verbose });\n const errorLines: string[] = [];\n const errorsByFile = new Map<string, typeof result.errors>();\n for (const error of result.errors) {\n const fileErrors = errorsByFile.get(error.file) || [];\n fileErrors.push(error);\n errorsByFile.set(error.file, fileErrors);\n }\n for (const [file, fileErrors] of errorsByFile) {\n errorLines.push(formatter.formatErrorHeader(fileErrors.length, file));\n errorLines.push(\"\");\n const validationErrors = fileErrors.filter(\n (e) => e.type !== \"foreignKey\" || !e.foreignKeyError,\n );\n const foreignKeyErrors = fileErrors.filter((e) => e.type === \"foreignKey\" && e.foreignKeyError);\n if (validationErrors.length > 0) {\n errorLines.push(\n formatter.formatValidationErrors(\n validationErrors.map((e) => ({\n file: e.file,\n rowIndex: e.rowIndex,\n issues: e.issues,\n })),\n ),\n );\n }\n for (const fkError of foreignKeyErrors) {\n if (fkError.foreignKeyError) {\n errorLines.push(\n formatter.formatForeignKeyError({\n file: fkError.file,\n rowIndex: fkError.rowIndex,\n column: fkError.foreignKeyError.column,\n value: fkError.foreignKeyError.value,\n referencedTable: fkError.foreignKeyError.referencedTable,\n referencedColumn: fkError.foreignKeyError.referencedColumn,\n }),\n );\n }\n }\n errorLines.push(\"\");\n }\n\n return { valid: false, output: outputLines.join(\"\\n\"), error: errorLines.join(\"\\n\") };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,eAAsB,iBACpB,SAC6B;CAC7B,MAAM,EAAE,MAAM,cAAc,UAAU,UAAU;CAEhD,MAAM,QAAQ,MAAM,KAAK,YAAY;CACrC,IAAI;CACJ,IAAI;CACJ,IAAI,MAAM,YAAY,GACpB,UAAU;MACL,IAAI,MAAM,OAAO,KAAK,aAAa,SAAS,QAAQ,GAAG;EAC5D,UAAU,QAAQ,YAAY;EAC9B,YAAY,SAAS,cAAc,QAAQ;CAC7C,OACE,MAAM,IAAI,MAAM,iBAAiB,aAAa,sCAAsC;CAGtF,MAAM,KAAK,QAAQ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AAQ;GAClB,QAAQ,QAAQ,gBAAgB;GAChC,OAAO,QAAQ,gBAAgB;GAC/B,iBAAiB,QAAQ,gBAAgB;GACzC,kBAAkB,QAAQ,gBAAgB;EAC5C,CAAC,CACH;EAGJ,WAAW,KAAK,EAAE;CACpB;CAEA,OAAO;EAAE,OAAO;EAAO,QAAQ,YAAY,KAAK,IAAI;EAAG,OAAO,WAAW,KAAK,IAAI;CAAE;AACtF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import { t as
|
|
3
|
-
import { t as
|
|
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
4
|
import * as path from "pathe";
|
|
5
5
|
|
|
6
6
|
//#region src/plugin/builtin/seed/idp-user-processor.ts
|
|
@@ -156,17 +156,6 @@ function generateIdpUserSchemaFile(options) {
|
|
|
156
156
|
`;
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
-
//#endregion
|
|
160
|
-
//#region src/types/tailordb.ts
|
|
161
|
-
/**
|
|
162
|
-
* Checks if a type source is generated by a plugin.
|
|
163
|
-
* @param source - The type source entry to check.
|
|
164
|
-
* @returns True if the source was generated by a plugin.
|
|
165
|
-
*/
|
|
166
|
-
function isPluginGeneratedType(source) {
|
|
167
|
-
return source.pluginId !== void 0;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
159
|
//#endregion
|
|
171
160
|
//#region src/plugin/builtin/seed/lines-db-processor.ts
|
|
172
161
|
/**
|
|
@@ -1167,5 +1156,5 @@ function seedPlugin(options) {
|
|
|
1167
1156
|
}
|
|
1168
1157
|
|
|
1169
1158
|
//#endregion
|
|
1170
|
-
export { seedPlugin as n,
|
|
1171
|
-
//# sourceMappingURL=seed-
|
|
1159
|
+
export { seedPlugin as n, SeedGeneratorID as t };
|
|
1160
|
+
//# sourceMappingURL=seed-jf3008-h.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"seed-jf3008-h.mjs","names":["ml"],"sources":["../src/plugin/builtin/seed/idp-user-processor.ts","../src/plugin/builtin/seed/lines-db-processor.ts","../src/plugin/builtin/seed/seed-type-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\n for (let i = 0; i < input.users.length; i++) {\n try {\n await client.createUser(input.users[i]);\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 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 { LinesDbMetadata } from \"./types\";\nimport type {\n PluginGeneratedTypeSource,\n TailorDBType,\n TypeSourceInfoEntry,\n} from \"@/parser/service/tailordb/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 type { SeedTypeInfo } from \"./types\";\nimport type { TailorDBType } from \"@/parser/service/tailordb/types\";\n\n/**\n * Processes TailorDB types to extract seed type information\n * @param type - Parsed TailorDB type\n * @param namespace - Namespace of the type\n * @returns Seed type information\n */\nexport function processSeedTypeInfo(type: TailorDBType, namespace: string): SeedTypeInfo {\n // Extract dependencies from relations (including keyOnly which only sets foreignKeyType)\n const dependencies: Set<string> = new Set();\n const selfRefFields: string[] = [];\n\n for (const [fieldName, field] of Object.entries(type.fields)) {\n const targetType = field.relation?.targetType ?? field.config.foreignKeyType;\n if (!targetType) continue;\n\n if (targetType === type.name) {\n selfRefFields.push(fieldName);\n } else {\n dependencies.add(targetType);\n }\n }\n\n return {\n name: type.name,\n namespace,\n dependencies: Array.from(dependencies),\n selfRefFields,\n dataFile: `data/${type.name}.jsonl`,\n };\n}\n","import * as path from \"pathe\";\nimport { assertDefined } from \"@/utils/assert\";\nimport ml from \"@/utils/multiline\";\nimport {\n processIdpUser,\n generateIdpUserSchemaFile,\n generateIdpSeedScriptCode,\n generateIdpTruncateScriptCode,\n} from \"./idp-user-processor\";\nimport {\n processLinesDb,\n generateLinesDbSchemaFile,\n generateLinesDbSchemaFileWithPluginAPI,\n type PluginSchemaParams,\n} from \"./lines-db-processor\";\nimport { processSeedTypeInfo } from \"./seed-type-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\ntype SeedPluginOptions = {\n distPath: string;\n machineUserName?: string;\n /**\n * Disable individual `_User <-> userProfile` foreign keys emitted into\n * the generated seed schema. Both directions are emitted by default.\n *\n * Set a direction to `true` to relax it — for example to seed invited\n * users that do not yet have an IdP credential.\n */\n disableIdpUserSync?: DisableIdpUserSyncDirections;\n};\n\nfunction resolveIdpUserSyncFKs(option: SeedPluginOptions[\"disableIdpUserSync\"]): {\n emitUserToIdpFK: boolean;\n emitIdpToUserFK: boolean;\n} {\n return {\n emitUserToIdpFK: !(option?.userToIdp ?? false),\n emitIdpToUserFK: !(option?.idpToUser ?? false),\n };\n}\n\ntype NamespaceConfig = {\n namespace: string;\n types: string[];\n dependencies: Record<string, string[]>;\n selfRefTypes: string[];\n};\n\n/**\n * Generate the IdP user seed function code using tailor.idp.Client via testExecScript\n * @param hasIdpUser - Whether IdP user is included\n * @param idpNamespace - The IDP namespace name\n * @returns JavaScript code for IdP user seeding function\n */\nfunction generateIdpUserSeedFunction(hasIdpUser: boolean, idpNamespace: string | null): string {\n if (!hasIdpUser || !idpNamespace) return \"\";\n\n const scriptCode = generateIdpSeedScriptCode(idpNamespace);\n\n return ml`\n // Seed _User via tailor.idp.Client (server-side)\n const seedIdpUser = async () => {\n console.log(styleText(\"cyan\", \" Seeding _User via tailor.idp.Client...\"));\n const dataDir = join(configDir, \"data\");\n const data = loadSeedData(dataDir, [\"_User\"]);\n const rows = data[\"_User\"] || [];\n if (rows.length === 0) {\n console.log(styleText(\"dim\", \" No _User data to seed\"));\n return { success: true };\n }\n console.log(styleText(\"dim\", \\` Processing \\${rows.length} _User records...\\`));\n\n const idpSeedCode = \\/* js *\\/\\`${scriptCode.replace(/`/g, \"\\\\`\").replace(/\\$/g, \"\\\\$\")}\\`;\n\n const result = await executeScript({\n client: operatorClient,\n workspaceId,\n name: \"seed-idp-user.ts\",\n code: idpSeedCode,\n arg: JSON.stringify({ users: rows }),\n invoker: {\n namespace: authNamespace,\n machineUserName,\n },\n });\n\n if (result.logs) {\n for (const line of result.logs.split(\"\\\\n\").filter(Boolean)) {\n console.log(styleText(\"dim\", \\` \\${line}\\`));\n }\n }\n\n if (result.success) {\n let parsed;\n try {\n parsed = JSON.parse(result.result || \"{}\");\n } catch (e) {\n console.error(styleText(\"red\", \\` ✗ Failed to parse seed result: \\${e.message}\\`));\n return { success: false };\n }\n\n if (parsed.processed) {\n console.log(styleText(\"green\", \\` ✓ _User: \\${parsed.processed} rows processed\\`));\n }\n\n if (!parsed.success) {\n const errors = Array.isArray(parsed.errors) ? parsed.errors : [];\n for (const err of errors) {\n console.error(styleText(\"red\", \\` ✗ \\${err}\\`));\n }\n return { success: false };\n }\n\n return { success: true };\n } else {\n console.error(styleText(\"red\", \\` ✗ Seed failed: \\${result.error}\\`));\n return { success: false };\n }\n };\n `;\n}\n\n/**\n * Generate the IdP user seed call code\n * @param hasIdpUser - Whether IdP user is included\n * @returns JavaScript code for calling IdP user seeding\n */\nfunction generateIdpUserSeedCall(hasIdpUser: boolean): string {\n if (!hasIdpUser) return \"\";\n\n return ml`\n // Seed _User if included and not skipped\n const shouldSeedUser = !skipIdp && (!entitiesToProcess || entitiesToProcess.includes(\"_User\"));\n if (hasIdpUser && shouldSeedUser) {\n const result = await seedIdpUser();\n if (!result.success) {\n allSuccess = false;\n }\n }\n `;\n}\n\n/**\n * Generate the IdP user truncation function code using tailor.idp.Client via testExecScript\n * @param hasIdpUser - Whether IdP user is included\n * @param idpNamespace - The IDP namespace name\n * @returns JavaScript code for IdP user truncation function\n */\nfunction generateIdpUserTruncateFunction(hasIdpUser: boolean, idpNamespace: string | null): string {\n if (!hasIdpUser || !idpNamespace) return \"\";\n\n const scriptCode = generateIdpTruncateScriptCode(idpNamespace);\n\n return ml`\n // Truncate _User via tailor.idp.Client (server-side)\n const truncateIdpUser = async () => {\n console.log(styleText(\"cyan\", \"Truncating _User via tailor.idp.Client...\"));\n\n const idpTruncateCode = \\/* js *\\/\\`${scriptCode.replace(/`/g, \"\\\\`\").replace(/\\$/g, \"\\\\$\")}\\`;\n\n const result = await executeScript({\n client: operatorClient,\n workspaceId,\n name: \"truncate-idp-user.ts\",\n code: idpTruncateCode,\n arg: JSON.stringify({}),\n invoker: {\n namespace: authNamespace,\n machineUserName,\n },\n });\n\n if (result.logs) {\n for (const line of result.logs.split(\"\\\\n\").filter(Boolean)) {\n console.log(styleText(\"dim\", \\` \\${line}\\`));\n }\n }\n\n if (result.success) {\n let parsed;\n try {\n parsed = JSON.parse(result.result || \"{}\");\n } catch (e) {\n console.error(styleText(\"red\", \\` ✗ Failed to parse truncation result: \\${e.message}\\`));\n return { success: false };\n }\n\n if (parsed.deleted !== undefined) {\n console.log(styleText(\"green\", \\` ✓ _User: \\${parsed.deleted} users deleted\\`));\n }\n\n if (!parsed.success) {\n const errors = Array.isArray(parsed.errors) ? parsed.errors : [];\n for (const err of errors) {\n console.error(styleText(\"red\", \\` ✗ \\${err}\\`));\n }\n return { success: false };\n }\n\n return { success: true };\n } else {\n console.error(styleText(\"red\", \\` ✗ Truncation failed: \\${result.error}\\`));\n return { success: false };\n }\n };\n `;\n}\n\n/**\n * Generate the IdP user truncation call code within the truncate block\n * @param hasIdpUser - Whether IdP user is included\n * @returns JavaScript code for calling IdP user truncation\n */\nfunction generateIdpUserTruncateCall(hasIdpUser: boolean): string {\n if (!hasIdpUser) return \"\";\n\n return ml`\n // Truncate _User if applicable\n const shouldTruncateUser = !skipIdp && !hasNamespace && (!hasTypes || entitiesToProcess.includes(\"_User\"));\n if (hasIdpUser && shouldTruncateUser) {\n const truncResult = await truncateIdpUser();\n if (!truncResult.success) {\n console.error(styleText(\"red\", \"IDP user truncation failed.\"));\n process.exit(1);\n }\n }\n `;\n}\n\n/**\n * Generates the exec.mjs script content using testExecScript API for TailorDB types\n * and tailor.idp.Client for _User (IdP managed)\n * @param defaultMachineUserName - Default machine user name from generator config (can be overridden at runtime)\n * @param relativeConfigPath - Config path relative to exec script\n * @param namespaceConfigs - Namespace configurations with types and dependencies\n * @param hasIdpUser - Whether _User is included\n * @param idpNamespace - The IDP namespace name, or null if not applicable\n * @returns exec.mjs file contents\n */\nfunction generateExecScript(\n defaultMachineUserName: string | undefined,\n relativeConfigPath: string,\n namespaceConfigs: NamespaceConfig[],\n hasIdpUser: boolean,\n idpNamespace: string | null,\n): string {\n // Generate namespaceEntities object\n const namespaceEntitiesEntries = namespaceConfigs\n .map(({ namespace, types }) => {\n const entitiesFormatted = types.map((e) => ` \"${e}\",`).join(\"\\n\");\n return ` \"${namespace}\": [\\n${entitiesFormatted}\\n ]`;\n })\n .join(\",\\n\");\n\n // Generate dependency map for each namespace\n const namespaceDepsEntries = namespaceConfigs\n .map(({ namespace, dependencies }) => {\n const depsObj = Object.entries(dependencies)\n .map(([type, deps]) => ` \"${type}\": [${deps.map((d) => `\"${d}\"`).join(\", \")}]`)\n .join(\",\\n\");\n return ` \"${namespace}\": {\\n${depsObj}\\n }`;\n })\n .join(\",\\n\");\n\n // Generate self-referencing types map for each namespace\n const namespaceSelfRefEntries = namespaceConfigs\n .map(({ namespace, selfRefTypes }) => {\n const formatted = selfRefTypes.map((t) => `\"${t}\"`).join(\", \");\n return ` \"${namespace}\": [${formatted}]`;\n })\n .join(\",\\n\");\n\n return ml /* js */ `\n /**\n * @generated\n * This file is auto-generated by @tailor-platform/sdk's seedPlugin.\n * Do not edit by hand: changes will be overwritten on the next \\`sdk generate\\`.\n */\n import { readFileSync } from \"node:fs\";\n import { join, isAbsolute } from \"node:path\";\n import { parseArgs, styleText } from \"node:util\";\n import { createInterface } from \"node:readline\";\n import {\n show,\n truncate,\n bundleSeedScript,\n chunkSeedData,\n executeScript,\n initOperatorClient,\n loadAccessToken,\n loadWorkspaceId,\n } from \"@tailor-platform/sdk/cli\";\n\n // Handle \"validate\" subcommand before parseArgs\n const subcommand = process.argv[2];\n if (subcommand === \"validate\") {\n const { validateSeedData } = await import(\"@tailor-platform/sdk/seed\");\n const validateArgs = parseArgs({\n args: process.argv.slice(3),\n options: {\n verbose: { type: \"boolean\", short: \"v\", default: false },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n allowPositionals: true,\n });\n\n if (validateArgs.values.help) {\n console.log(\\`\n Usage: node exec.mjs validate [options] [path]\n\n Validate JSONL seed data against schema definitions.\n\n Arguments:\n path File or directory to validate (default: ./data)\n\n Options:\n -v, --verbose Show verbose error output\n -h, --help Show help\n\n Examples:\n node exec.mjs validate # Validate all seed data\n node exec.mjs validate ./data/User.jsonl # Validate specific file\n node exec.mjs validate -v # Verbose error output\n \\`);\n process.exit(0);\n }\n\n const configDir = import.meta.dirname;\n const targetPath = validateArgs.positionals[0] || join(configDir, \"data\");\n const resolvedPath = isAbsolute(targetPath) ? targetPath : join(process.cwd(), targetPath);\n\n try {\n const result = await validateSeedData({ path: resolvedPath, verbose: validateArgs.values.verbose });\n if (result.output) console.log(result.output);\n if (!result.valid) {\n console.error(result.error);\n process.exit(1);\n }\n process.exit(0);\n } catch (error) {\n console.error(styleText(\"red\", \\`Error: \\${error instanceof Error ? error.message : String(error)}\\`));\n process.exit(1);\n }\n }\n\n // Parse command-line arguments\n const { values, positionals } = parseArgs({\n options: {\n \"machine-user\": { type: \"string\", short: \"m\" },\n namespace: { type: \"string\", short: \"n\" },\n \"skip-idp\": { type: \"boolean\", default: false },\n truncate: { type: \"boolean\", default: false },\n yes: { type: \"boolean\", default: false },\n profile: { type: \"string\", short: \"p\" },\n help: { type: \"boolean\", short: \"h\", default: false },\n },\n allowPositionals: true,\n });\n\n if (values.help) {\n console.log(\\`\n Usage: node exec.mjs [command] [options] [types...]\n\n Commands:\n validate [path] Validate seed data against schema (default: ./data)\n\n Options:\n -m, --machine-user <name> Machine user name for authentication (required if not configured)\n -n, --namespace <ns> Process all types in specified namespace (excludes _User)\n --skip-idp Skip IdP user (_User) entity\n --truncate Truncate tables before seeding\n --yes Skip confirmation prompts (for truncate)\n -p, --profile <name> Workspace profile name\n -h, --help Show help\n\n Examples:\n node exec.mjs -m admin # Process all types with machine user\n node exec.mjs --namespace <namespace> # Process tailordb namespace only (no _User)\n node exec.mjs User Order # Process specific types only\n node exec.mjs --skip-idp # Process all except _User\n node exec.mjs --truncate # Truncate all tables, then seed all\n node exec.mjs --truncate --yes # Truncate all tables without confirmation, then seed all\n node exec.mjs --truncate --namespace <namespace> # Truncate tailordb, then seed tailordb\n node exec.mjs --truncate User Order # Truncate User and Order, then seed them\n node exec.mjs validate # Validate all seed data\n node exec.mjs validate ./data/User.jsonl # Validate specific file\n \\`);\n process.exit(0);\n }\n\n // Helper function to prompt for y/n confirmation\n const promptConfirmation = (question) => {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n return new Promise((resolve) => {\n rl.question(styleText(\"yellow\", question), (answer) => {\n rl.close();\n resolve(answer.toLowerCase().trim());\n });\n });\n };\n\n const configDir = import.meta.dirname;\n const configPath = join(configDir, \"${relativeConfigPath}\");\n\n // Determine machine user name (CLI argument takes precedence over config default)\n const defaultMachineUser = ${defaultMachineUserName ? `\"${defaultMachineUserName}\"` : \"undefined\"};\n const machineUserName = values[\"machine-user\"] || defaultMachineUser;\n\n if (!machineUserName) {\n console.error(styleText(\"red\", \"Error: Machine user name is required.\"));\n console.error(styleText(\"yellow\", \"Specify --machine-user <name> or configure machineUserName in generator options.\"));\n process.exit(1);\n }\n\n // Entity configuration\n const namespaceEntities = {\n${namespaceEntitiesEntries}\n };\n const namespaceDeps = {\n${namespaceDepsEntries}\n };\n const namespaceSelfRefTypes = {\n${namespaceSelfRefEntries}\n };\n const entities = Object.values(namespaceEntities).flat();\n const hasIdpUser = ${String(hasIdpUser)};\n\n // Determine which entities to process\n let entitiesToProcess = null;\n\n const hasNamespace = !!values.namespace;\n const hasTypes = positionals.length > 0;\n const skipIdp = values[\"skip-idp\"];\n\n // Validate mutually exclusive options\n const optionCount = [hasNamespace, hasTypes].filter(Boolean).length;\n if (optionCount > 1) {\n console.error(styleText(\"red\", \"Error: Options --namespace and type names are mutually exclusive.\"));\n process.exit(1);\n }\n\n // --skip-idp and --namespace are redundant (namespace already excludes _User)\n if (skipIdp && hasNamespace) {\n console.warn(styleText(\"yellow\", \"Warning: --skip-idp is redundant with --namespace (namespace filtering already excludes _User).\"));\n }\n\n // Filter by namespace (automatically excludes _User as it has no namespace)\n if (hasNamespace) {\n const namespace = values.namespace;\n entitiesToProcess = namespaceEntities[namespace];\n\n if (!entitiesToProcess || entitiesToProcess.length === 0) {\n console.error(styleText(\"red\", \\`Error: No entities found in namespace \"\\${namespace}\"\\`));\n console.error(styleText(\"yellow\", \\`Available namespaces: \\${Object.keys(namespaceEntities).join(\", \")}\\`));\n process.exit(1);\n }\n\n console.log(styleText(\"cyan\", \\`Filtering by namespace: \\${namespace}\\`));\n console.log(styleText(\"dim\", \\`Entities: \\${entitiesToProcess.join(\", \")}\\`));\n }\n\n // Filter by specific types\n if (hasTypes) {\n const requestedTypes = positionals;\n const notFoundTypes = [];\n const allTypes = hasIdpUser ? [...entities, \"_User\"] : entities;\n\n entitiesToProcess = requestedTypes.filter((type) => {\n if (!allTypes.includes(type)) {\n notFoundTypes.push(type);\n return false;\n }\n return true;\n });\n\n if (notFoundTypes.length > 0) {\n console.error(styleText(\"red\", \\`Error: The following types were not found: \\${notFoundTypes.join(\", \")}\\`));\n console.error(styleText(\"yellow\", \\`Available types: \\${allTypes.join(\", \")}\\`));\n process.exit(1);\n }\n\n console.log(styleText(\"cyan\", \\`Filtering by types: \\${entitiesToProcess.join(\", \")}\\`));\n }\n\n // Apply --skip-idp filter\n if (skipIdp) {\n if (entitiesToProcess) {\n entitiesToProcess = entitiesToProcess.filter((entity) => entity !== \"_User\");\n } else {\n entitiesToProcess = entities.filter((entity) => entity !== \"_User\");\n }\n }\n\n // Get application info\n const appInfo = await show({ configPath, profile: values.profile });\n const authNamespace = appInfo.auth;\n\n // Initialize operator client (once for all namespaces)\n const accessToken = await loadAccessToken({ profile: values.profile });\n const workspaceId = await loadWorkspaceId({ profile: values.profile });\n const operatorClient = await initOperatorClient(accessToken);\n\n ${generateIdpUserTruncateFunction(hasIdpUser, idpNamespace)}\n\n // Truncate tables if requested\n if (values.truncate) {\n const answer = values.yes ? \"y\" : await promptConfirmation(\"Are you sure you want to truncate? (y/n): \");\n if (answer !== \"y\") {\n console.log(styleText(\"yellow\", \"Truncate cancelled.\"));\n process.exit(0);\n }\n\n console.log(styleText(\"cyan\", \"Truncating tables...\"));\n\n try {\n if (hasNamespace) {\n await truncate({\n configPath,\n profile: values.profile,\n namespace: values.namespace,\n });\n } else if (hasTypes) {\n const typesToTruncate = entitiesToProcess.filter((t) => t !== \"_User\");\n if (typesToTruncate.length > 0) {\n await truncate({\n configPath,\n profile: values.profile,\n types: typesToTruncate,\n });\n } else {\n console.log(styleText(\"dim\", \"No TailorDB types to truncate (only _User was specified).\"));\n }\n } else {\n await truncate({\n configPath,\n profile: values.profile,\n all: true,\n });\n }\n } catch (error) {\n console.error(styleText(\"red\", \\`Truncate failed: \\${error.message}\\`));\n process.exit(1);\n }\n\n ${generateIdpUserTruncateCall(hasIdpUser)}\n\n console.log(styleText(\"green\", \"Truncate completed.\"));\n }\n\n console.log(styleText(\"cyan\", \"\\\\nStarting seed data generation...\"));\n if (skipIdp) {\n console.log(styleText(\"dim\", \\` Skipping IdP user (_User)\\`));\n }\n\n // Load seed data from JSONL files\n const loadSeedData = (dataDir, typeNames) => {\n const data = {};\n for (const typeName of typeNames) {\n const jsonlPath = join(dataDir, \\`\\${typeName}.jsonl\\`);\n try {\n const content = readFileSync(jsonlPath, \"utf-8\").trim();\n if (content) {\n data[typeName] = content.split(\"\\\\n\").map((line) => JSON.parse(line));\n } else {\n data[typeName] = [];\n }\n } catch (error) {\n if (error.code === \"ENOENT\") {\n data[typeName] = [];\n } else {\n throw error;\n }\n }\n }\n return data;\n };\n\n // Topological sort for dependency order\n const topologicalSort = (types, deps) => {\n const visited = new Set();\n const result = [];\n\n const visit = (type) => {\n if (visited.has(type)) return;\n visited.add(type);\n const typeDeps = deps[type] || [];\n for (const dep of typeDeps) {\n if (types.includes(dep)) {\n visit(dep);\n }\n }\n result.push(type);\n };\n\n for (const type of types) {\n visit(type);\n }\n return result;\n };\n\n // Seed TailorDB types via testExecScript\n const seedViaTestExecScript = async (namespace, typesToSeed, deps, selfRefTypes) => {\n const dataDir = join(configDir, \"data\");\n const sortedTypes = topologicalSort(typesToSeed, deps);\n const data = loadSeedData(dataDir, sortedTypes);\n\n // Skip if no data\n const typesWithData = sortedTypes.filter((t) => data[t] && data[t].length > 0);\n if (typesWithData.length === 0) {\n console.log(styleText(\"dim\", \\` [\\${namespace}] No data to seed\\`));\n return { success: true, processed: {} };\n }\n\n console.log(styleText(\"cyan\", \\` [\\${namespace}] Seeding \\${typesWithData.length} types via Kysely batch insert...\\`));\n\n // Bundle seed script\n const bundled = await bundleSeedScript(namespace, typesWithData);\n\n // Chunk seed data to fit within gRPC message size limits\n const chunks = chunkSeedData({\n data,\n order: sortedTypes,\n codeByteSize: new TextEncoder().encode(bundled.bundledCode).length,\n });\n\n if (chunks.length === 0) {\n console.log(styleText(\"dim\", \\` [\\${namespace}] No data to seed\\`));\n return { success: true, processed: {} };\n }\n\n if (chunks.length > 1) {\n console.log(styleText(\"dim\", \\` Split into \\${chunks.length} chunks\\`));\n }\n\n const allProcessed = {};\n let hasError = false;\n const allErrors = [];\n\n for (const chunk of chunks) {\n if (chunks.length > 1) {\n console.log(styleText(\"dim\", \\` Chunk \\${chunk.index + 1}/\\${chunk.total}: \\${chunk.order.join(\", \")}\\`));\n }\n\n // Execute seed script for this chunk\n const result = await executeScript({\n client: operatorClient,\n workspaceId,\n name: \\`seed-\\${namespace}.ts\\`,\n code: bundled.bundledCode,\n arg: JSON.stringify({ data: chunk.data, order: chunk.order, selfRefTypes }),\n invoker: {\n namespace: authNamespace,\n machineUserName,\n },\n });\n\n // Parse result and display logs\n if (result.logs) {\n for (const line of result.logs.split(\"\\\\n\").filter(Boolean)) {\n console.log(styleText(\"dim\", \\` \\${line}\\`));\n }\n }\n\n if (result.success) {\n let parsed;\n try {\n const parsedResult = JSON.parse(result.result || \"{}\");\n parsed = parsedResult && typeof parsedResult === \"object\" ? parsedResult : {};\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(styleText(\"red\", \\` ✗ Failed to parse seed result: \\${message}\\`));\n hasError = true;\n allErrors.push(message);\n continue;\n }\n\n const processed = parsed.processed || {};\n for (const [type, count] of Object.entries(processed)) {\n allProcessed[type] = (allProcessed[type] || 0) + count;\n console.log(styleText(\"green\", \\` ✓ \\${type}: \\${count} rows inserted\\`));\n }\n\n if (!parsed.success) {\n const errors = Array.isArray(parsed.errors) ? parsed.errors : [];\n const errorMessage =\n errors.length > 0 ? errors.join(\"\\\\n \") : \"Seed script reported failure\";\n console.error(styleText(\"red\", \\` ✗ Seed failed:\\\\n \\${errorMessage}\\`));\n hasError = true;\n allErrors.push(errorMessage);\n }\n } else {\n console.error(styleText(\"red\", \\` ✗ Seed failed: \\${result.error}\\`));\n hasError = true;\n allErrors.push(result.error);\n }\n }\n\n if (hasError) {\n return { success: false, error: allErrors.join(\"\\\\n\") };\n }\n return { success: true, processed: allProcessed };\n };\n\n ${generateIdpUserSeedFunction(hasIdpUser, idpNamespace)}\n\n // Main execution\n try {\n let allSuccess = true;\n\n // Determine which namespaces and types to process\n const namespacesToProcess = hasNamespace\n ? [values.namespace]\n : Object.keys(namespaceEntities);\n\n for (const namespace of namespacesToProcess) {\n const nsTypes = namespaceEntities[namespace] || [];\n const nsDeps = namespaceDeps[namespace] || {};\n const nsSelfRefTypes = namespaceSelfRefTypes[namespace] || [];\n\n // Filter types if specific types requested\n let typesToSeed = entitiesToProcess\n ? nsTypes.filter((t) => entitiesToProcess.includes(t))\n : nsTypes;\n\n if (typesToSeed.length === 0) continue;\n\n const result = await seedViaTestExecScript(namespace, typesToSeed, nsDeps, nsSelfRefTypes);\n if (!result.success) {\n allSuccess = false;\n }\n }\n\n ${generateIdpUserSeedCall(hasIdpUser)}\n\n if (allSuccess) {\n console.log(styleText(\"green\", \"\\\\n✓ Seed data generation completed successfully\"));\n } else {\n console.error(styleText(\"red\", \"\\\\n✗ Seed data generation completed with errors\"));\n process.exit(1);\n }\n } catch (error) {\n console.error(styleText(\"red\", \\`\\\\n✗ Seed data generation failed: \\${error.message}\\`));\n process.exit(1);\n }\n\n `;\n}\n\n/**\n * Plugin that generates seed data files with Kysely batch insert and tailor.idp.Client for _User.\n * @param options - Plugin options\n * @param options.distPath - Output directory path for generated seed files\n * @param options.machineUserName - Default machine user name for authentication\n * @param options.disableIdpUserSync - Skip emitting individual `_User <-> userProfile` foreign keys. Both directions are emitted by default; set a direction to `true` to relax that side.\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function seedPlugin(options: SeedPluginOptions): Plugin<unknown, SeedPluginOptions> {\n return {\n id: SeedGeneratorID,\n description: \"Generates seed data files (Kysely batch insert + tailor.idp.Client for _User)\",\n pluginConfig: options,\n\n async onTailorDBReady(ctx: TailorDBReadyContext<SeedPluginOptions>): Promise<GeneratorResult> {\n const files: GeneratorResult[\"files\"] = [];\n const namespaceConfigs: NamespaceConfig[] = [];\n\n // Process IdP user early so we can add reverse FK to the user profile type\n const idpUser = ctx.auth ? (processIdpUser(ctx.auth) ?? null) : null;\n const hasIdpUser = idpUser !== null;\n const idpUserSyncFKs = resolveIdpUserSyncFKs(ctx.pluginConfig.disableIdpUserSync);\n\n for (const ns of ctx.tailordb) {\n const types: string[] = [];\n const dependencies: Record<string, string[]> = {};\n const selfRefTypes: string[] = [];\n\n for (const [typeName, type] of Object.entries(ns.types)) {\n const source = assertDefined(\n ns.sourceInfo.get(typeName),\n `source info missing for type: ${typeName}`,\n );\n const typeInfo = processSeedTypeInfo(type, ns.namespace);\n const linesDb = processLinesDb(type, source);\n\n // Add reverse FK from userProfile type to _User (opt-out via disableIdpUserSync.userToIdp: true)\n if (\n idpUserSyncFKs.emitUserToIdpFK &&\n idpUser &&\n typeName === idpUser.schema.userTypeName\n ) {\n linesDb.foreignKeys.push({\n column: idpUser.schema.usernameField,\n references: {\n table: \"_User\",\n column: \"name\",\n },\n });\n }\n\n types.push(typeInfo.name);\n dependencies[typeInfo.name] = typeInfo.dependencies;\n if (typeInfo.selfRefFields.length > 0) {\n selfRefTypes.push(typeInfo.name);\n }\n\n // Generate empty JSONL data file\n files.push({\n path: path.join(ctx.pluginConfig.distPath, typeInfo.dataFile),\n content: \"\",\n skipIfExists: true,\n });\n\n const schemaOutputPath = path.join(\n ctx.pluginConfig.distPath,\n \"data\",\n `${linesDb.typeName}.schema.ts`,\n );\n\n // Plugin-generated type: use getGeneratedType API\n if (linesDb.pluginSource && linesDb.pluginSource.pluginImportPath) {\n // Build original type import path\n let originalImportPath: string | undefined;\n if (linesDb.pluginSource.originalFilePath && linesDb.pluginSource.originalExportName) {\n const relativePath = path.relative(\n path.dirname(schemaOutputPath),\n linesDb.pluginSource.originalFilePath,\n );\n originalImportPath = relativePath.replace(/\\.ts$/, \"\").startsWith(\".\")\n ? relativePath.replace(/\\.ts$/, \"\")\n : `./${relativePath.replace(/\\.ts$/, \"\")}`;\n }\n\n // Compute relative path from schema output to config file\n const configImportPath = path.relative(path.dirname(schemaOutputPath), ctx.configPath);\n\n const params: PluginSchemaParams = {\n configImportPath,\n originalImportPath,\n };\n\n const schemaContent = generateLinesDbSchemaFileWithPluginAPI(linesDb, params);\n\n files.push({\n path: schemaOutputPath,\n content: schemaContent,\n });\n } else {\n // User-defined type: import from source file\n const relativePath = path.relative(path.dirname(schemaOutputPath), linesDb.importPath);\n const typeImportPath = relativePath.replace(/\\.ts$/, \"\").startsWith(\".\")\n ? relativePath.replace(/\\.ts$/, \"\")\n : `./${relativePath.replace(/\\.ts$/, \"\")}`;\n const schemaContent = generateLinesDbSchemaFile(linesDb, typeImportPath);\n\n files.push({\n path: schemaOutputPath,\n content: schemaContent,\n });\n }\n }\n\n namespaceConfigs.push({\n namespace: ns.namespace,\n types,\n dependencies,\n selfRefTypes,\n });\n }\n\n if (idpUser) {\n // Generate empty JSONL data file\n files.push({\n path: path.join(ctx.pluginConfig.distPath, idpUser.dataFile),\n content: \"\",\n skipIfExists: true,\n });\n\n // Generate schema file with foreign key (opt-out via disableIdpUserSync.idpToUser: true)\n files.push({\n path: path.join(ctx.pluginConfig.distPath, \"data\", `${idpUser.name}.schema.ts`),\n content: generateIdpUserSchemaFile({\n usernameField: idpUser.schema.usernameField,\n userTypeName: idpUser.schema.userTypeName,\n includeUserProfileFK: idpUserSyncFKs.emitIdpToUserFK,\n }),\n });\n }\n\n // Generate exec.mjs (machineUserName can be provided at runtime if not configured)\n const relativeConfigPath = path.relative(ctx.pluginConfig.distPath, ctx.configPath);\n files.push({\n path: path.join(ctx.pluginConfig.distPath, \"exec.mjs\"),\n content: generateExecScript(\n ctx.pluginConfig.machineUserName,\n relativeConfigPath,\n namespaceConfigs,\n hasIdpUser,\n idpUser?.idpNamespace ?? null,\n ),\n });\n\n return { files };\n },\n };\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,MAA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AAiB,KAAK;KACpB,WAAW,GAAG;KACd;KACA;KACA;IACF,CAAC;GACH;GAEA,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;GAGA,MAAM,qBAAqB,KAAK,SAAS,IAAI,aAAa,UAAU,IAAI,UAAU;GAClF,MAAM,KAAK;IACT,MAAM,KAAK,KAAK,IAAI,aAAa,UAAU,UAAU;IACrD,SAAS,mBACP,IAAI,aAAa,iBACjB,oBACA,kBACA,YACA,SAAS,gBAAgB,IAC3B;GACF,CAAC;GAED,OAAO,EAAE,MAAM;EACjB;CACF;AACF"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
import { n as
|
|
3
|
-
import { n as logger, r as styles } from "./logger-DpJyJvNz.mjs";
|
|
1
|
+
import { n as isSdkBranded } from "./brand-Eo4pLXPJ.mjs";
|
|
2
|
+
import { n as logger, r as styles } from "./logger-CxF-Ex5d.mjs";
|
|
4
3
|
import { z } from "zod";
|
|
5
4
|
import * as fs from "node:fs";
|
|
6
5
|
import * as path from "pathe";
|
|
@@ -457,4 +456,4 @@ function createExecutorService(params) {
|
|
|
457
456
|
|
|
458
457
|
//#endregion
|
|
459
458
|
export { TailorFieldSchema as a, AuthInvokerSchema as i, ExecutorSchema as n, loadFilesWithIgnores as o, AuthConfigSchema as r, functionSchema as s, createExecutorService as t };
|
|
460
|
-
//# sourceMappingURL=service-
|
|
459
|
+
//# sourceMappingURL=service-CCL8ruDf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-CCL8ruDf.mjs","names":[],"sources":["../src/parser/service/common.ts","../src/cli/services/file-loader.ts","../src/parser/service/auth-connection/schema.ts","../src/parser/service/field/schema.ts","../src/parser/service/auth/schema.ts","../src/parser/service/executor/schema.ts","../src/cli/services/executor/service.ts"],"sourcesContent":["import { z } from \"zod\";\n\n// Use `z.custom` instead of `z.function`, since `z.function` changes `toString` representation.\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nexport const functionSchema = z.custom<Function>((val) => typeof val === \"function\");\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { logger } from \"@/cli/shared/logger\";\n\nexport interface FileLoadConfig {\n files: string[];\n ignores?: string[];\n}\n\nconst DEFAULT_IGNORE_PATTERNS = [\"**/*.test.ts\", \"**/*.spec.ts\"];\n\n/**\n * Load files matching the given patterns, excluding files that match ignore patterns.\n * By default, test files (*.test.ts, *.spec.ts) are excluded unless ignores is explicitly specified.\n * @param config - Configuration with files patterns and optional ignores patterns\n * @returns Array of absolute file paths\n */\nexport function loadFilesWithIgnores(config: FileLoadConfig): string[] {\n // Use user-provided patterns if specified, otherwise use defaults\n const ignorePatterns = config.ignores ?? DEFAULT_IGNORE_PATTERNS;\n\n const ignoreFiles = new Set<string>();\n for (const ignorePattern of ignorePatterns) {\n const absoluteIgnorePattern = path.resolve(process.cwd(), ignorePattern);\n try {\n const matchedIgnoreFiles = fs.globSync(absoluteIgnorePattern);\n matchedIgnoreFiles.forEach((file) => ignoreFiles.add(file));\n } catch (error) {\n logger.warn(`Failed to glob ignore pattern \"${ignorePattern}\": ${String(error)}`);\n }\n }\n\n const files: string[] = [];\n for (const pattern of config.files) {\n const absolutePattern = path.resolve(process.cwd(), pattern);\n try {\n const matchedFiles = fs.globSync(absolutePattern);\n // Filter out ignored files\n const filteredFiles = matchedFiles.filter((file) => !ignoreFiles.has(file));\n files.push(...filteredFiles);\n } catch (error) {\n logger.warn(`Failed to glob pattern \"${pattern}\": ${String(error)}`);\n }\n }\n\n return files;\n}\n","import { z } from \"zod\";\n\nexport const AuthConnectionOAuth2ConfigSchema = z.object({\n providerUrl: z.string().describe(\"OAuth2 provider URL\"),\n issuerUrl: z.string().describe(\"OAuth2 issuer URL\"),\n clientId: z.string().describe(\"OAuth2 client ID\"),\n clientSecret: z.string().describe(\"OAuth2 client secret\"),\n authUrl: z.string().optional().describe(\"OAuth2 authorization endpoint override\"),\n tokenUrl: z.string().optional().describe(\"OAuth2 token endpoint override\"),\n});\n\nexport const AuthConnectionConfigSchema = z\n .object({\n type: z.literal(\"oauth2\").describe(\"Connection type\"),\n })\n .and(AuthConnectionOAuth2ConfigSchema);\n","import { z } from \"zod\";\nimport { functionSchema } from \"../common\";\n\nconst TailorFieldTypeSchema = z.enum([\n \"uuid\",\n \"string\",\n \"boolean\",\n \"integer\",\n \"float\",\n \"decimal\",\n \"enum\",\n \"date\",\n \"datetime\",\n \"time\",\n \"nested\",\n]);\n\nconst AllowedValueSchema = z.object({\n value: z.string().describe(\"The allowed value\"),\n description: z.string().optional().describe(\"Description of the allowed value\"),\n});\n\nconst FieldMetadataSchema = z.object({\n required: z.boolean().optional().describe(\"Whether the field is required\"),\n array: z.boolean().optional().describe(\"Whether the field is an array\"),\n description: z.string().optional().describe(\"Field description\"),\n allowedValues: z.array(AllowedValueSchema).optional().describe(\"Allowed values for enum fields\"),\n hooks: z\n .object({\n create: functionSchema.optional().describe(\"Hook function called on creation\"),\n update: functionSchema.optional().describe(\"Hook function called on update\"),\n })\n .optional()\n .describe(\"Lifecycle hooks\"),\n typeName: z.string().optional().describe(\"Type name for nested or enum fields\"),\n});\n\nexport const TailorFieldSchema = z.object({\n type: TailorFieldTypeSchema.describe(\"Field data type\"),\n metadata: FieldMetadataSchema.describe(\"Field metadata configuration\"),\n get fields() {\n return z.record(z.string(), TailorFieldSchema);\n },\n});\n","import { z } from \"zod\";\nimport { AuthConnectionConfigSchema } from \"@/parser/service/auth-connection\";\nimport { TailorFieldSchema } from \"@/parser/service/field/schema\";\nimport type { ValueOperand } from \"@/configure/services/auth/types\";\n\nexport const AuthInvokerObjectSchema = z.object({\n namespace: z.string().describe(\"Auth namespace\"),\n machineUserName: z.string().describe(\"Machine user name for authentication\"),\n});\n\nexport const AuthInvokerSchema = z.union([\n z.string().describe(\"Machine user name (namespace auto-resolved from auth service)\"),\n AuthInvokerObjectSchema,\n]);\n\nconst secretValueSchema = z.object({\n vaultName: z.string().describe(\"Vault name containing the secret\"),\n secretKey: z.string().describe(\"Key of the secret in the vault\"),\n});\n\nexport const OIDCSchema = z.object({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"OIDC\"),\n clientID: z.string().describe(\"OAuth2 client ID\"),\n clientSecret: secretValueSchema.describe(\"OAuth2 client secret\"),\n providerURL: z.string().describe(\"OIDC provider URL\"),\n issuerURL: z.string().optional().describe(\"OIDC issuer URL (defaults to providerURL)\"),\n usernameClaim: z.string().optional().describe(\"JWT claim to use as username\"),\n});\n\nexport const SAMLSchema = z\n .object({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"SAML\"),\n enableSignRequest: z.boolean().default(false).describe(\"Enable signing of SAML requests\"),\n metadataURL: z\n .string()\n .optional()\n .describe(\"URL to fetch SAML metadata (mutually exclusive with rawMetadata)\"),\n rawMetadata: z\n .string()\n .optional()\n .describe(\"Raw SAML metadata XML (mutually exclusive with metadataURL)\"),\n defaultRedirectURL: z\n .string()\n .optional()\n .describe(\"URL to redirect to when SAML ACS receives a response with an empty RelayState.\"),\n })\n .refine((value) => {\n const hasMetadata = value.metadataURL !== undefined;\n const hasRaw = value.rawMetadata !== undefined;\n return hasMetadata !== hasRaw;\n }, \"Provide either metadataURL or rawMetadata\");\n\nexport const IDTokenSchema = z.object({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"IDToken\"),\n providerURL: z.string().describe(\"ID token provider URL\"),\n issuerURL: z.string().optional().describe(\"ID token issuer URL\"),\n clientID: z.string().describe(\"Client ID for ID token validation\"),\n usernameClaim: z.string().optional().describe(\"JWT claim to use as username\"),\n});\n\nexport const BuiltinIdPSchema = z.object({\n name: z.string().describe(\"Identity provider name\"),\n kind: z.literal(\"BuiltInIdP\"),\n namespace: z.string().describe(\"IdP namespace\"),\n clientName: z.string().describe(\"OAuth2 client name in the IdP\"),\n});\n\nexport const IdProviderSchema = z.discriminatedUnion(\"kind\", [\n OIDCSchema,\n SAMLSchema,\n IDTokenSchema,\n BuiltinIdPSchema,\n]);\n\nexport const OAuth2ClientGrantTypeSchema = z\n .union([z.literal(\"authorization_code\"), z.literal(\"refresh_token\")])\n .describe(\"OAuth2 grant type\");\n\nexport const OAuth2ClientSchema = z\n .object({\n description: z.string().optional().describe(\"Client description\"),\n grantTypes: z\n .array(OAuth2ClientGrantTypeSchema)\n .default([\"authorization_code\", \"refresh_token\"])\n .describe(\"Allowed OAuth2 grant types\"),\n redirectURIs: z\n .array(\n z.union([\n z.templateLiteral([\"https://\", z.string()]),\n z.templateLiteral([\"http://\", z.string()]),\n z.templateLiteral([z.string(), \":url\"]),\n z.templateLiteral([z.string(), \":url/\", z.string()]),\n ]),\n )\n .describe(\"Allowed redirect URIs\"),\n clientType: z\n .union([z.literal(\"confidential\"), z.literal(\"public\"), z.literal(\"browser\")])\n .optional()\n .describe(\"OAuth2 client type\"),\n accessTokenLifetimeSeconds: z\n .number()\n .int()\n .min(60, \"Minimum access token lifetime is 60 seconds\")\n .max(86400, \"Maximum access token lifetime is 1 day (86400 seconds)\")\n .optional()\n .describe(\"Access token lifetime in seconds (60-86400)\")\n .transform((val) => (val ? { seconds: BigInt(val), nanos: 0 } : undefined)),\n refreshTokenLifetimeSeconds: z\n .number()\n .int()\n .min(60, \"Minimum refresh token lifetime is 60 seconds\")\n .max(604800, \"Maximum refresh token lifetime is 7 days (604800 seconds)\")\n .optional()\n .describe(\"Refresh token lifetime in seconds (60-604800)\")\n .transform((val) => (val ? { seconds: BigInt(val), nanos: 0 } : undefined)),\n requireDpop: z\n .boolean()\n .optional()\n .describe(\"Require DPoP (Demonstrating Proof-of-Possession) for token requests\"),\n })\n .refine((data) => !(data.clientType === \"browser\" && data.requireDpop === true), {\n message: \"requireDpop cannot be set to true for browser clients as they don't support DPoP\",\n path: [\"requireDpop\"],\n });\n\nexport const SCIMAuthorizationSchema = z.object({\n type: z.union([z.literal(\"oauth2\"), z.literal(\"bearer\")]).describe(\"SCIM authorization type\"),\n bearerSecret: secretValueSchema\n .optional()\n .describe(\"Bearer token secret (required for bearer type)\"),\n});\n\nexport const SCIMAttributeTypeSchema = z\n .union([\n z.literal(\"string\"),\n z.literal(\"number\"),\n z.literal(\"boolean\"),\n z.literal(\"datetime\"),\n z.literal(\"complex\"),\n ])\n .describe(\"SCIM attribute data type\");\n\nexport const SCIMAttributeSchema = z.object({\n type: SCIMAttributeTypeSchema.describe(\"Attribute data type\"),\n name: z.string().describe(\"Attribute name\"),\n description: z.string().optional().describe(\"Attribute description\"),\n mutability: z\n .union([z.literal(\"readOnly\"), z.literal(\"readWrite\"), z.literal(\"writeOnly\")])\n .optional()\n .describe(\"Attribute mutability\"),\n required: z.boolean().optional().describe(\"Whether the attribute is required\"),\n multiValued: z.boolean().optional().describe(\"Whether the attribute can have multiple values\"),\n uniqueness: z\n .union([z.literal(\"none\"), z.literal(\"server\"), z.literal(\"global\")])\n .optional()\n .describe(\"Uniqueness constraint\"),\n canonicalValues: z.array(z.string()).nullable().optional().describe(\"List of canonical values\"),\n get subAttributes() {\n return z.array(SCIMAttributeSchema).nullable().optional();\n },\n});\n\nconst SCIMSchemaSchema = z.object({\n name: z.string().describe(\"SCIM schema name\"),\n attributes: z.array(SCIMAttributeSchema).describe(\"Schema attributes\"),\n});\n\nexport const SCIMAttributeMappingSchema = z.object({\n tailorDBField: z.string().describe(\"TailorDB field name to map to\"),\n scimPath: z.string().describe(\"SCIM attribute path\"),\n});\n\nexport const SCIMResourceSchema = z.object({\n name: z.string().describe(\"SCIM resource name\"),\n tailorDBNamespace: z.string().describe(\"TailorDB namespace for the resource\"),\n tailorDBType: z.string().describe(\"TailorDB type name for the resource\"),\n coreSchema: SCIMSchemaSchema.describe(\"Core SCIM schema definition\"),\n attributeMapping: z.array(SCIMAttributeMappingSchema).describe(\"Attribute mapping configuration\"),\n});\n\nexport const SCIMSchema = z.object({\n machineUserName: z.string().describe(\"Machine user name for SCIM operations\"),\n authorization: SCIMAuthorizationSchema.describe(\"SCIM authorization configuration\"),\n resources: z.array(SCIMResourceSchema).describe(\"SCIM resource definitions\"),\n});\n\nexport const TenantProviderSchema = z.object({\n namespace: z.string().describe(\"TailorDB namespace for the tenant type\"),\n type: z.string().describe(\"TailorDB type name for tenants\"),\n signatureField: z.string().describe(\"Field used as the tenant signature\"),\n});\n\nconst UserProfileSchema = z.object({\n namespace: z.string().optional().describe(\"TailorDB namespace where the user type is defined\"),\n // FIXME: improve TailorDBInstance schema validation\n type: z.object({\n name: z.string(),\n fields: z.any(),\n metadata: z.any(),\n hooks: z.any(),\n validate: z.any(),\n features: z.any(),\n indexes: z.any(),\n files: z.any(),\n permission: z.any(),\n gqlPermission: z.any(),\n _output: z.any(),\n }),\n usernameField: z.string(),\n attributes: z.record(z.string(), z.literal(true)).optional(),\n attributeList: z.array(z.string()).optional(),\n});\n\nconst ValueOperandSchema: z.ZodType<ValueOperand> = z.union([\n z.string(),\n z.boolean(),\n z.array(z.string()),\n z.array(z.boolean()),\n]);\n\nconst MachineUserSchema = z.object({\n attributes: z.record(z.string(), ValueOperandSchema).optional(),\n attributeList: z.array(z.uuid()).optional(),\n});\n\nconst BeforeLoginHookSchema = z.object({\n handler: z.function(),\n invoker: z.string(),\n});\n\nconst AuthConfigBaseSchema = z.object({\n name: z.string().describe(\"Auth service name\"),\n hooks: z\n .object({\n beforeLogin: BeforeLoginHookSchema.optional().describe(\"Before login auth hook\"),\n })\n .optional()\n .describe(\"Auth hooks\"),\n machineUsers: z\n .record(z.string(), MachineUserSchema)\n .optional()\n .describe(\"Machine user definitions\"),\n oauth2Clients: z\n .record(z.string(), OAuth2ClientSchema)\n .optional()\n .describe(\"OAuth2 client definitions\"),\n idProvider: IdProviderSchema.optional().describe(\"Identity provider configuration\"),\n scim: SCIMSchema.optional().describe(\"SCIM provisioning configuration\"),\n tenantProvider: TenantProviderSchema.optional().describe(\"Multi-tenant provider configuration\"),\n connections: z\n .record(z.string(), AuthConnectionConfigSchema)\n .optional()\n .describe(\"Auth connection definitions for external OAuth2 providers\"),\n publishSessionEvents: z.boolean().optional().describe(\"Enable publishing session events\"),\n});\n\nexport const AuthConfigSchema = z\n .xor(\n [\n AuthConfigBaseSchema.extend({\n userProfile: UserProfileSchema.optional().describe(\"User profile configuration\"),\n machineUserAttributes: z.undefined().optional(),\n }),\n AuthConfigBaseSchema.extend({\n userProfile: z.undefined().optional(),\n machineUserAttributes: z\n .record(z.string(), TailorFieldSchema)\n .describe(\"Machine user attribute fields\"),\n }),\n ],\n {\n error: (iss) => {\n // zod may report error codes not covered by its type definitions\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (iss.code !== \"invalid_union\") return undefined;\n // zod may report error codes not covered by its type definitions\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n if (iss.errors.length < 2) return undefined;\n const isOnlyMutexViolation = iss.errors.every((variantErrors) =>\n variantErrors.every(\n (e) =>\n e.path.length === 1 &&\n (e.path[0] === \"userProfile\" || e.path[0] === \"machineUserAttributes\"),\n ),\n );\n if (isOnlyMutexViolation) {\n return \"Specify either `userProfile` or `machineUserAttributes`, not both.\";\n }\n return undefined;\n },\n },\n )\n .brand(\"AuthConfig\");\n","import { z } from \"zod\";\nimport { AuthInvokerSchema } from \"../auth\";\nimport { functionSchema } from \"../common\";\n\nexport const TailorDBTriggerSchema = z.object({\n kind: z.literal(\"tailordb\").describe(\"TailorDB record event trigger\"),\n events: z\n .array(\n z.enum([\n \"tailordb.type_record.created\",\n \"tailordb.type_record.updated\",\n \"tailordb.type_record.deleted\",\n ]),\n )\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"TailorDB event types to trigger on\"),\n typeName: z.string().describe(\"TailorDB type name to watch for events\"),\n condition: functionSchema.optional().describe(\"Condition function to filter events\"),\n});\n\nexport const ResolverExecutedTriggerSchema = z.object({\n kind: z.literal(\"resolverExecuted\"),\n resolverName: z.string().describe(\"Name of the resolver to trigger on\"),\n condition: functionSchema.optional().describe(\"Condition function to filter events\"),\n});\n\nexport const ScheduleTriggerSchema = z.object({\n kind: z.literal(\"schedule\"),\n cron: z.string().describe(\"CRON expression for the schedule\"),\n timezone: z\n .string()\n .optional()\n .default(\"UTC\")\n .describe(\"Timezone for the CRON schedule (default: UTC)\"),\n});\n\nexport const IncomingWebhookTriggerResponseSchema = z.object({\n body: functionSchema.optional().describe(\"Function returning the response body\"),\n statusCode: z.number().int().optional().describe(\"HTTP status code for the response\"),\n});\n\nexport const IncomingWebhookTriggerSchema = z.object({\n kind: z.literal(\"incomingWebhook\"),\n response: IncomingWebhookTriggerResponseSchema.optional().describe(\"Response configuration\"),\n});\n\nexport const IdpUserTriggerSchema = z.object({\n kind: z.literal(\"idpUser\").describe(\"IdP user event trigger\"),\n events: z\n .array(z.enum([\"idp.user.created\", \"idp.user.updated\", \"idp.user.deleted\"]))\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"IdP user event types to trigger on\"),\n idp: z\n .string()\n .optional()\n .describe(\n \"IdP namespace name to subscribe to. If omitted, the project's only IdP is used; throws when multiple IdPs exist.\",\n ),\n});\n\nexport const AuthAccessTokenTriggerSchema = z.object({\n kind: z.literal(\"authAccessToken\").describe(\"Auth access token event trigger\"),\n events: z\n .array(\n z.enum([\n \"auth.access_token.issued\",\n \"auth.access_token.refreshed\",\n \"auth.access_token.revoked\",\n ]),\n )\n .min(1)\n .transform((arr) => [...new Set(arr)])\n .describe(\"Auth access token event types to trigger on\"),\n});\n\nexport const TriggerSchema = z.discriminatedUnion(\"kind\", [\n TailorDBTriggerSchema,\n ResolverExecutedTriggerSchema,\n ScheduleTriggerSchema,\n IncomingWebhookTriggerSchema,\n IdpUserTriggerSchema,\n AuthAccessTokenTriggerSchema,\n]);\n\nexport const FunctionOperationSchema = z.object({\n kind: z.enum([\"function\", \"jobFunction\"]),\n body: functionSchema.describe(\"Function implementation\"),\n authInvoker: AuthInvokerSchema.optional().describe(\"Auth invoker for the function execution\"),\n});\n\nexport const GqlOperationSchema = z.object({\n kind: z.literal(\"graphql\"),\n appName: z.string().optional().describe(\"Target application name for the GraphQL query\"),\n query: z.preprocess((val) => String(val), z.string().describe(\"GraphQL query string\")),\n variables: functionSchema.optional().describe(\"Function to compute GraphQL variables\"),\n authInvoker: AuthInvokerSchema.optional().describe(\"Auth invoker for the GraphQL execution\"),\n});\n\nexport const WebhookOperationSchema = z.object({\n kind: z.literal(\"webhook\"),\n url: functionSchema.describe(\"Function returning the webhook URL\"),\n requestBody: functionSchema.optional().describe(\"Function to compute the request body\"),\n headers: z\n .record(z.string(), z.union([z.string(), z.object({ vault: z.string(), key: z.string() })]))\n .optional()\n .describe(\"HTTP headers for the webhook request\"),\n});\n\nexport const WorkflowOperationSchema = z.preprocess(\n (val) => {\n if (\n val == null ||\n typeof val !== \"object\" ||\n !(\"workflow\" in val) ||\n typeof val.workflow !== \"object\" ||\n val.workflow === null\n ) {\n return val;\n }\n\n const { workflow, ...rest } = val as { workflow: { name: string } };\n return { ...rest, workflowName: workflow.name };\n },\n z.object({\n kind: z.literal(\"workflow\"),\n workflowName: z.string().describe(\"Name of the workflow to execute\"),\n args: z\n .union([z.record(z.string(), z.unknown()), functionSchema])\n .optional()\n .describe(\"Arguments to pass to the workflow\"),\n authInvoker: AuthInvokerSchema.optional().describe(\"Auth invoker for the workflow execution\"),\n }),\n);\n\nconst OperationSchema = z.union([\n FunctionOperationSchema,\n GqlOperationSchema,\n WebhookOperationSchema,\n WorkflowOperationSchema,\n]);\n\nexport const ExecutorSchema = z.object({\n name: z.string().describe(\"Executor name\"),\n description: z.string().optional().describe(\"Executor description\"),\n disabled: z.boolean().optional().default(false).describe(\"Whether the executor is disabled\"),\n trigger: TriggerSchema.describe(\"Event trigger configuration\"),\n operation: OperationSchema.describe(\"Operation to execute when triggered\"),\n});\n","import { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { loadFilesWithIgnores } from \"@/cli/services/file-loader\";\nimport { logger, styles } from \"@/cli/shared/logger\";\nimport { ExecutorSchema } from \"@/parser/service/executor\";\nimport { isSdkBranded } from \"@/utils/brand\";\nimport type { ExecutorServiceConfig } from \"@/configure/config/types\";\nimport type { Executor } from \"@/types/executor.generated\";\n\n/**\n * Information about a plugin-generated executor converted to Executor format\n */\nexport interface PluginExecutor {\n /** The executor in standard Executor format */\n executor: Executor;\n /** Plugin ID that generated this executor */\n pluginId: string;\n /** Source type name (for type-attached executors) */\n sourceTypeName?: string;\n}\n\nexport type ExecutorService = {\n readonly config: ExecutorServiceConfig;\n readonly executors: Record<string, Executor>;\n readonly pluginExecutors: ReadonlyArray<PluginExecutor>;\n loadExecutors: () => Promise<Record<string, Executor> | undefined>;\n loadPluginExecutorFiles: (filePaths: string[]) => Promise<void>;\n};\n\n/**\n * Parameters for creating an ExecutorService\n */\nexport interface CreateExecutorServiceParams {\n /** The executor service configuration */\n config: ExecutorServiceConfig;\n}\n\n/**\n * Creates a new ExecutorService instance.\n * @param params - Parameters for creating the service\n * @returns A new ExecutorService instance\n */\nexport function createExecutorService(params: CreateExecutorServiceParams): ExecutorService {\n const { config } = params;\n const executors: Record<string, Executor> = {};\n const pluginExecutors: PluginExecutor[] = [];\n let loadPromise: Promise<Record<string, Executor> | undefined> | undefined;\n\n const loadExecutorForFile = async (executorFile: string): Promise<Executor | undefined> => {\n try {\n const executorModule = await import(pathToFileURL(executorFile).href);\n const result = ExecutorSchema.safeParse(executorModule.default);\n if (result.success) {\n const relativePath = path.relative(process.cwd(), executorFile);\n logger.log(\n `Executor: ${styles.successBright(`\"${result.data.name}\"`)} loaded from ${styles.path(relativePath)}`,\n );\n executors[executorFile] = result.data;\n return result.data;\n }\n if (isSdkBranded(executorModule.default, \"executor\")) {\n throw result.error;\n }\n } catch (error) {\n const relativePath = path.relative(process.cwd(), executorFile);\n logger.error(`Failed to load executor from ${styles.bold(relativePath)}`);\n logger.error(String(error));\n throw error;\n }\n return undefined;\n };\n\n return {\n config,\n get executors() {\n return executors;\n },\n get pluginExecutors() {\n return pluginExecutors;\n },\n loadExecutors: async () => {\n if (!loadPromise) {\n loadPromise = (async () => {\n if (config.files.length === 0) {\n return undefined;\n }\n\n const executorFiles = loadFilesWithIgnores(config);\n\n logger.newline();\n logger.log(`Found ${styles.highlight(executorFiles.length.toString())} executor files`);\n\n await Promise.all(executorFiles.map((executorFile) => loadExecutorForFile(executorFile)));\n return executors;\n })();\n }\n return loadPromise;\n },\n loadPluginExecutorFiles: async (filePaths: string[]) => {\n if (filePaths.length === 0) return;\n\n logger.newline();\n logger.log(\n `Loading ${styles.highlight(filePaths.length.toString())} plugin-generated executor files`,\n );\n\n for (const filePath of filePaths) {\n const executor = await loadExecutorForFile(filePath);\n if (executor) {\n // Track as plugin executor (plugin ID is extracted from file path)\n // File path format: .tailor-sdk/plugin/{executor-name}.ts\n pluginExecutors.push({\n executor,\n pluginId: \"plugin-generated\",\n sourceTypeName: undefined,\n });\n }\n }\n },\n };\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,iBAAiB,EAAE,QAAkB,QAAQ,OAAO,QAAQ,UAAU;;;;ACKnF,MAAM,0BAA0B,CAAC,gBAAgB,cAAc;;;;;;;AAQ/D,SAAgB,qBAAqB,QAAkC;CAErE,MAAM,iBAAiB,OAAO,WAAW;CAEzC,MAAM,8BAAc,IAAI,IAAY;CACpC,KAAK,MAAM,iBAAiB,gBAAgB;EAC1C,MAAM,wBAAwB,KAAK,QAAQ,QAAQ,IAAI,GAAG,aAAa;EACvE,IAAI;GAEF,AAD2B,GAAG,SAAS,qBACtB,CAAC,CAAC,SAAS,SAAS,YAAY,IAAI,IAAI,CAAC;EAC5D,SAAS,OAAO;GACd,OAAO,KA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AC;IACxF,OAAO;GACT,EAAC,CAAE;GAEL,OAAO;EACT;EACA,yBAAyB,OAAO,cAAwB;GACtD,IAAI,UAAU,WAAW,GAAG;GAE5B,OAAO,QAAQ;GACf,OAAO,IACL,WAAW,OAAO,UAAU,UAAU,OAAO,SAAS,CAAC,EAAE,iCAC3D;GAEA,KAAK,MAAM,YAAY,WAAW;IAChC,MAAM,WAAW,MAAM,oBAAoB,QAAQ;IACnD,IAAI,UAGF,gBAAgB,KAAK;KACnB;KACA,UAAU;KACV,gBAAgB;IAClB,CAAC;GAEL;EACF;CACF;AACF"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
import { t as createCLIError } from "./errors-EsY4XO6O.mjs";
|
|
1
|
+
import { n as logger, r as styles } from "./logger-CxF-Ex5d.mjs";
|
|
2
|
+
import { t as createCLIError } from "./errors-Dtf2WPaW.mjs";
|
|
4
3
|
import * as path from "pathe";
|
|
5
4
|
import { readPackageJSON } from "pkg-types";
|
|
6
5
|
import { spawnSync } from "node:child_process";
|
|
@@ -129,4 +128,4 @@ async function upgrade(options) {
|
|
|
129
128
|
|
|
130
129
|
//#endregion
|
|
131
130
|
export { upgrade };
|
|
132
|
-
//# sourceMappingURL=service-
|
|
131
|
+
//# sourceMappingURL=service-DU1mVzri.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-DU1mVzri.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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