@tailor-platform/sdk 2.20.0 → 2.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/application-D4913edS.mjs +199 -0
  3. package/dist/application-D4913edS.mjs.map +1 -0
  4. package/dist/application-DBHaxmJE.mjs +1 -0
  5. package/dist/cli/lib.mjs +1 -1
  6. package/dist/cli/main.d.mts +1 -0
  7. package/dist/cli/main.mjs +35 -35
  8. package/dist/cli/main.mjs.map +1 -1
  9. package/dist/completion/zsh-worker.zsh +654 -131
  10. package/dist/configure/index.d.mts +2 -1
  11. package/dist/configure/index.mjs +12 -1
  12. package/dist/configure/index.mjs.map +1 -1
  13. package/dist/configure/services/secrets/index.d.mts +14 -0
  14. package/dist/configure/services/tailordb/schema.d.mts +3 -2
  15. package/dist/configure/types/secret-vault-name.d.mts +32 -0
  16. package/dist/{crashreport-Cyuz1qiu.mjs → crashreport-BAz-ph5O.mjs} +3 -3
  17. package/dist/{crashreport-Cyuz1qiu.mjs.map → crashreport-BAz-ph5O.mjs.map} +1 -1
  18. package/dist/crashreport-BfOkOFgc.mjs +1 -0
  19. package/dist/{date-B7-oyTGE.mjs → date-Dri6Yas-.mjs} +2 -2
  20. package/dist/date-Dri6Yas-.mjs.map +1 -0
  21. package/dist/{errors-BjJnpXkK.mjs → errors-sNtg2Mv3.mjs} +2 -2
  22. package/dist/{errors-BjJnpXkK.mjs.map → errors-sNtg2Mv3.mjs.map} +1 -1
  23. package/dist/es-builtins-SfvXRVoG.mjs +2 -0
  24. package/dist/{es-builtins-BHCXINQp.mjs.map → es-builtins-SfvXRVoG.mjs.map} +1 -1
  25. package/dist/field-parse-DhnFs9WG.mjs +2 -0
  26. package/dist/field-parse-DhnFs9WG.mjs.map +1 -0
  27. package/dist/{globals-CMHSnj4w.mjs → globals-BCmGX05J.mjs} +2 -2
  28. package/dist/{globals-CMHSnj4w.mjs.map → globals-BCmGX05J.mjs.map} +1 -1
  29. package/dist/guards-DsX7dJCP.mjs +2 -0
  30. package/dist/{guards-ForsrxnH.mjs.map → guards-DsX7dJCP.mjs.map} +1 -1
  31. package/dist/{kysely-type-B_oA8D1k.mjs → kysely-type-C-iyFFH7.mjs} +2 -2
  32. package/dist/{kysely-type-B_oA8D1k.mjs.map → kysely-type-C-iyFFH7.mjs.map} +1 -1
  33. package/dist/{logger-72hM4JWZ.mjs → logger-Cp5U2IDI.mjs} +2 -2
  34. package/dist/{logger-72hM4JWZ.mjs.map → logger-Cp5U2IDI.mjs.map} +1 -1
  35. package/dist/manager-C0dE7pd0.mjs +2 -0
  36. package/dist/{manager-qfbUL7ru.mjs.map → manager-C0dE7pd0.mjs.map} +1 -1
  37. package/dist/plugin/builtin/enum-constants/index.mjs +1 -1
  38. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
  39. package/dist/plugin/builtin/file-utils/index.mjs +1 -1
  40. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
  41. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  42. package/dist/plugin/index.mjs +1 -1
  43. package/dist/plugin/index.mjs.map +1 -1
  44. package/dist/register-ts-hook-YtsAGTMD.mjs +921 -0
  45. package/dist/{register-ts-hook-FsCX38LQ.mjs.map → register-ts-hook-YtsAGTMD.mjs.map} +1 -1
  46. package/dist/registry-BijIDRVA.mjs +2 -0
  47. package/dist/{registry-HlEaGvl5.mjs.map → registry-BijIDRVA.mjs.map} +1 -1
  48. package/dist/repl-editor-DGJBfIt1.mjs +2 -0
  49. package/dist/{repl-editor-BG1aDOfH.mjs.map → repl-editor-DGJBfIt1.mjs.map} +1 -1
  50. package/dist/runtime/field-parse.d.mts +17 -1
  51. package/dist/runtime/index.d.mts +2 -1
  52. package/dist/runtime/index.mjs +1 -1
  53. package/dist/runtime/secretmanager.d.mts +8 -20
  54. package/dist/schema-CRtAmDcl.mjs +2 -0
  55. package/dist/{schema-BKvcWdVf.mjs.map → schema-CRtAmDcl.mjs.map} +1 -1
  56. package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
  57. package/dist/seed/index.mjs +2 -2
  58. package/dist/seed/index.mjs.map +1 -1
  59. package/dist/{service-B4Gh_bbL.mjs → service-8xznUrPU.mjs} +2 -2
  60. package/dist/{service-B4Gh_bbL.mjs.map → service-8xznUrPU.mjs.map} +1 -1
  61. package/dist/{service-CuqkHP1r.mjs → service-BrGSi2IQ.mjs} +3 -3
  62. package/dist/{service-CuqkHP1r.mjs.map → service-BrGSi2IQ.mjs.map} +1 -1
  63. package/dist/service-DWMm-4Vm.mjs +1 -0
  64. package/dist/service_pb-DNskuJQC.mjs +1 -0
  65. package/dist/service_pb-y2GYIgfs.mjs +2 -0
  66. package/dist/{service_pb-DprmLNsq.mjs.map → service_pb-y2GYIgfs.mjs.map} +1 -1
  67. package/dist/tailordb-ddl-DqInYupv.mjs +7 -0
  68. package/dist/{tailordb-ddl-Fgm2cNvT.mjs.map → tailordb-ddl-DqInYupv.mjs.map} +1 -1
  69. package/dist/utils/test/index.mjs +1 -1
  70. package/dist/utils/test/index.mjs.map +1 -1
  71. package/dist/vitest/environment.mjs +1 -1
  72. package/dist/vitest/environment.mjs.map +1 -1
  73. package/dist/vitest/index.mjs +1 -1
  74. package/dist/vitest/index.mjs.map +1 -1
  75. package/dist/vitest/setup.mjs +1 -1
  76. package/dist/workspace_resource_pb-D2njwgsE.mjs +2 -0
  77. package/dist/{workspace_resource_pb-BOoRts_z.mjs.map → workspace_resource_pb-D2njwgsE.mjs.map} +1 -1
  78. package/docs/migration/v3.md +64 -0
  79. package/docs/services/resolver.md +21 -0
  80. package/docs/services/secret.md +20 -15
  81. package/package.json +12 -12
  82. package/dist/application-B6NYnrhv.mjs +0 -199
  83. package/dist/application-B6NYnrhv.mjs.map +0 -1
  84. package/dist/application-BlbyGJsd.mjs +0 -1
  85. package/dist/crashreport-CgymxQDu.mjs +0 -1
  86. package/dist/date-B7-oyTGE.mjs.map +0 -1
  87. package/dist/es-builtins-BHCXINQp.mjs +0 -2
  88. package/dist/field-parse-BbNyotv5.mjs +0 -2
  89. package/dist/field-parse-BbNyotv5.mjs.map +0 -1
  90. package/dist/guards-ForsrxnH.mjs +0 -2
  91. package/dist/manager-qfbUL7ru.mjs +0 -2
  92. package/dist/register-ts-hook-FsCX38LQ.mjs +0 -917
  93. package/dist/registry-HlEaGvl5.mjs +0 -2
  94. package/dist/repl-editor-BG1aDOfH.mjs +0 -2
  95. package/dist/schema-BKvcWdVf.mjs +0 -2
  96. package/dist/service-BgrEteZ2.mjs +0 -1
  97. package/dist/service_pb-DKrsO1_u.mjs +0 -1
  98. package/dist/service_pb-DprmLNsq.mjs +0 -2
  99. package/dist/tailordb-ddl-Fgm2cNvT.mjs +0 -7
  100. package/dist/workspace_resource_pb-BOoRts_z.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"kysely-type-B_oA8D1k.mjs","names":[],"sources":["../src/plugin/builtin/kysely-type/type-processor.ts","../src/plugin/builtin/kysely-type/pglite-schema.ts","../src/plugin/builtin/kysely-type/index.ts"],"sourcesContent":["import { COLUMN_TYPE_ALIASES, mapFieldTypeToColumnType } from \"#/utils/field-column-type\";\nimport multiline from \"#/utils/multiline\";\nimport {\n type KyselyFieldConfig,\n type KyselyNamespaceMetadata,\n type KyselyTypeMetadata,\n type UsedUtilityTypes,\n} from \"./types\";\nimport type { TailorDBType } from \"#/parser/service/tailordb/types\";\n\ntype FieldTypeResult = {\n type: string;\n usedUtilityTypes: UsedUtilityTypes;\n};\n\nfunction emptyUsedUtilityTypes(): UsedUtilityTypes {\n return { Timestamp: false, Serial: false, ObjectColumnType: false, ArrayColumnType: false };\n}\n\nfunction mergeUsedUtilityTypes(a: UsedUtilityTypes, b: UsedUtilityTypes): UsedUtilityTypes {\n return {\n Timestamp: a.Timestamp || b.Timestamp,\n Serial: a.Serial || b.Serial,\n ObjectColumnType: a.ObjectColumnType || b.ObjectColumnType,\n ArrayColumnType: a.ArrayColumnType || b.ArrayColumnType,\n };\n}\n\n/**\n * Get the enum type definition.\n * @param fieldConfig - The field configuration\n * @returns The enum type as a string union\n */\nfunction getEnumType(fieldConfig: KyselyFieldConfig): string {\n const allowedValues = fieldConfig.allowedValues;\n\n if (allowedValues && Array.isArray(allowedValues)) {\n return allowedValues\n .map((v: string | { value: string }) => {\n const value = typeof v === \"string\" ? v : v.value;\n return `\"${value}\"`;\n })\n .join(\" | \");\n }\n return \"string\";\n}\n\n/**\n * Get the nested object type definition.\n * @param fieldConfig - The field configuration\n * @returns The nested type with used utility types\n */\nfunction getNestedType(fieldConfig: KyselyFieldConfig): FieldTypeResult {\n const fields = fieldConfig.fields;\n if (!fields || typeof fields !== \"object\") {\n return {\n type: \"string\",\n usedUtilityTypes: emptyUsedUtilityTypes(),\n };\n }\n\n const fieldResults = Object.entries(fields).map(([fieldName, config]) => {\n const result = generateFieldType(config);\n const optional = config.required !== true ? \"?\" : \"\";\n return {\n fieldType: `${fieldName}${optional}: ${result.type}`,\n usedUtilityTypes: result.usedUtilityTypes,\n };\n });\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => mergeUsedUtilityTypes(acc, result.usedUtilityTypes),\n emptyUsedUtilityTypes(),\n );\n\n const fieldTypes = fieldResults.map((r) => r.fieldType);\n const obj = `{\\n ${fieldTypes.join(\";\\n \")}${fieldTypes.length > 0 ? \";\" : \"\"}\\n}`;\n\n const hasOptionalFields = Object.values(fields).some((config) => config.required !== true);\n const hasGeneratedFields = Object.values(fields).some(\n (config) =>\n config.hooks?.create || config.default !== undefined || config.optionalOnCreate === true,\n );\n if (aggregatedUtilityTypes.Timestamp || hasOptionalFields || hasGeneratedFields) {\n return {\n type: `ObjectColumnType<${obj}>`,\n usedUtilityTypes: { ...aggregatedUtilityTypes, ObjectColumnType: true },\n };\n }\n return { type: obj, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Get the base Kysely type for a field (without array/null modifiers).\n * @param fieldConfig - The field configuration\n * @returns The base type with used utility types\n */\nfunction getBaseType(fieldConfig: KyselyFieldConfig): FieldTypeResult {\n const fieldType = fieldConfig.type;\n const usedUtilityTypes = emptyUsedUtilityTypes();\n\n if (fieldType === \"enum\") {\n return { type: getEnumType(fieldConfig), usedUtilityTypes };\n }\n if (fieldType === \"nested\") {\n return getNestedType(fieldConfig);\n }\n\n const type = mapFieldTypeToColumnType(fieldType);\n usedUtilityTypes.Timestamp = type === \"Timestamp\";\n\n return { type, usedUtilityTypes };\n}\n\n/**\n * Generate the complete field type including array and null modifiers.\n * @param fieldConfig - The field configuration\n * @returns The complete field type with used utility types\n */\nfunction generateFieldType(fieldConfig: KyselyFieldConfig): FieldTypeResult {\n const baseTypeResult = getBaseType(fieldConfig);\n const usedUtilityTypes = { ...baseTypeResult.usedUtilityTypes };\n\n const isArray = fieldConfig.array === true;\n const isNullable = fieldConfig.required !== true;\n\n // A ColumnType-shaped alias and ObjectColumnType cannot be wrapped with [] for\n // arrays, because Kysely only resolves ColumnType at the top-level table\n // property. Use ArrayColumnType to keep the ColumnType at the top level.\n const isColumnTypeBase = COLUMN_TYPE_ALIASES.has(baseTypeResult.type);\n\n let finalType = baseTypeResult.type;\n if (isArray) {\n if (isColumnTypeBase || finalType.startsWith(\"ObjectColumnType<\")) {\n finalType = `ArrayColumnType<${baseTypeResult.type}>`;\n usedUtilityTypes.ArrayColumnType = true;\n } else {\n const needsParens = fieldConfig.type === \"enum\";\n finalType = needsParens ? `(${baseTypeResult.type})[]` : `${baseTypeResult.type}[]`;\n }\n }\n if (isNullable) {\n finalType = `${finalType} | null`;\n }\n\n if (fieldConfig.serial) {\n usedUtilityTypes.Serial = true;\n finalType = `Serial<${finalType}>`;\n }\n if (\n fieldConfig.hooks?.create ||\n fieldConfig.default !== undefined ||\n fieldConfig.optionalOnCreate === true\n ) {\n finalType = `Generated<${finalType}>`;\n }\n\n return { type: finalType, usedUtilityTypes };\n}\n\n/**\n * Generate the table interface.\n * @param name - Table name\n * @param fields - Field configurations keyed by field name\n * @returns The type definition and used utility types\n */\nfunction generateTableInterface(\n name: string,\n fields: Record<string, KyselyFieldConfig>,\n): {\n typeDef: string;\n usedUtilityTypes: UsedUtilityTypes;\n} {\n const fieldEntries = Object.entries(fields).filter(([fieldName]) => fieldName !== \"id\");\n\n const fieldResults = fieldEntries.map(([fieldName, fieldConfig]) => ({\n fieldName,\n ...generateFieldType(fieldConfig),\n }));\n\n const fieldLines = [\n \"id: Generated<string>;\",\n ...fieldResults.map((result) => `${result.fieldName}: ${result.type};`),\n ];\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => mergeUsedUtilityTypes(acc, result.usedUtilityTypes),\n emptyUsedUtilityTypes(),\n );\n\n const typeDef = multiline /* ts */ `\n ${name}: {\n ${fieldLines.join(\"\\n\")}\n }\n `;\n\n return { typeDef, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Generate KyselyTypeMetadata from field configurations.\n * @param name - Table name\n * @param fields - Field configurations keyed by field name\n * @returns Generated Kysely type metadata\n */\nexport function processKyselyFields(\n name: string,\n fields: Record<string, KyselyFieldConfig>,\n): KyselyTypeMetadata {\n const result = generateTableInterface(name, fields);\n\n return {\n name,\n typeDef: result.typeDef,\n usedUtilityTypes: result.usedUtilityTypes,\n };\n}\n\n/**\n * Convert a TailorDBType into KyselyTypeMetadata.\n * @param type - Parsed TailorDB table\n * @returns Generated Kysely type metadata\n */\nexport async function processKyselyType(type: TailorDBType): Promise<KyselyTypeMetadata> {\n return processKyselyFields(\n type.name,\n Object.fromEntries(\n Object.entries(type.fields).map(([fieldName, parsedField]) => [\n fieldName,\n parsedField.config,\n ]),\n ),\n );\n}\n\n/**\n * Generate unified types file from multiple namespaces.\n * @param namespaceData - Namespace metadata\n * @returns Generated types file contents\n */\nexport function generateUnifiedKyselyTypes(namespaceData: KyselyNamespaceMetadata[]): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Aggregate used utility types from all namespaces\n const globalUsedUtilityTypes = namespaceData\n .flatMap((ns) => ns.types)\n .reduce(\n (acc, type) => mergeUsedUtilityTypes(acc, type.usedUtilityTypes),\n emptyUsedUtilityTypes(),\n );\n\n const utilityTypeImports: string[] = [\"type Generated\"];\n if (globalUsedUtilityTypes.Timestamp) {\n utilityTypeImports.push(\"type Timestamp\");\n }\n if (globalUsedUtilityTypes.ObjectColumnType) {\n utilityTypeImports.push(\"type ObjectColumnType\");\n }\n if (globalUsedUtilityTypes.ArrayColumnType) {\n utilityTypeImports.push(\"type ArrayColumnType\");\n }\n if (globalUsedUtilityTypes.Serial) {\n utilityTypeImports.push(\"type Serial\");\n }\n\n const importsSection = multiline /* ts */ `\n import {\n createGetDB,\n ${utilityTypeImports.join(\",\\n\")},\n type NamespaceDB,\n type NamespaceInsertable,\n type NamespaceSelectable,\n type NamespaceTable,\n type NamespaceTableName,\n type NamespaceTransaction,\n type NamespaceUpdateable,\n } from \"@tailor-platform/sdk/kysely\";\n `;\n\n // Generate Namespace interface with multiple namespaces\n const namespaceInterfaces = namespaceData\n .map(({ namespace, types }) => {\n const typeDefsWithIndent = types\n .map((type) => {\n return type.typeDef\n .split(\"\\n\")\n .map((line) => (line.trim() ? ` ${line}` : \"\"))\n .join(\"\\n\");\n })\n .join(\"\\n\\n\");\n\n return ` \"${namespace}\": {\\n${typeDefsWithIndent}\\n }`;\n })\n .join(\",\\n\");\n\n const namespaceInterface = `export interface Namespace {\\n${namespaceInterfaces}\\n}`;\n\n const getDBFunction = multiline /* ts */ `\n export const getDB = createGetDB<Namespace>();\n\n export type DB<N extends keyof Namespace = keyof Namespace> = NamespaceDB<Namespace, N>;\n `;\n\n const utilityTypeExports = multiline /* ts */ `\n export type Transaction<K extends keyof Namespace | DB = keyof Namespace> =\n NamespaceTransaction<Namespace, K>;\n\n type TableName = NamespaceTableName<Namespace>;\n export type Table<T extends TableName> = NamespaceTable<Namespace, T>;\n\n export type Insertable<T extends TableName> = NamespaceInsertable<Namespace, T>;\n export type Selectable<T extends TableName> = NamespaceSelectable<Namespace, T>;\n export type Updateable<T extends TableName> = NamespaceUpdateable<Namespace, T>;\n `;\n\n return (\n [importsSection, namespaceInterface, getDBFunction, utilityTypeExports].join(\"\\n\\n\") + \"\\n\"\n );\n}\n","import { generatePgliteSchemaModule, type DDLTableConfig } from \"#/utils/tailordb-ddl\";\nimport type { TailorDBType } from \"#/parser/service/tailordb/types\";\n\n/** Tables of one namespace, as the schema module groups them. */\nexport interface PGliteSchemaNamespace {\n namespace: string;\n tables: Record<string, TailorDBType>;\n}\n\n/**\n * Reduce parsed tables to what the DDL generator reads.\n * @param tables - Parsed TailorDB tables keyed by name\n * @returns DDL table configs in the same order\n */\nexport function toDDLTables(tables: Record<string, TailorDBType>): DDLTableConfig[] {\n return Object.values(tables).map((type) => ({\n name: type.name,\n fields: Object.fromEntries(\n Object.entries(type.fields).map(([fieldName, field]) => [fieldName, field.config]),\n ),\n indexes: type.indexes,\n }));\n}\n\n/**\n * Render the module that exports each namespace's `CREATE TABLE` script for\n * `pglite.exec()`.\n * @param namespaces - Namespaces with their parsed tables\n * @returns TypeScript source of the schema module\n */\nexport function generatePGliteSchemaModule(namespaces: readonly PGliteSchemaNamespace[]): string {\n return generatePgliteSchemaModule(\n namespaces.map(({ namespace, tables }) => ({ namespace, tables: toDDLTables(tables) })),\n { generatedBy: \"the kysely-type plugin\" },\n );\n}\n","import { resolve } from \"pathe\";\nimport { generatePGliteSchemaModule } from \"./pglite-schema\";\nimport { processKyselyType, generateUnifiedKyselyTypes } from \"./type-processor\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\nimport type { KyselyTypeMetadata, KyselyNamespaceMetadata } from \"./types\";\n\n/** Unique identifier for the Kysely type generator plugin. */\nexport const KyselyGeneratorID = \"@tailor-platform/kysely-type\";\n\ntype KyselyTypePluginOptions = {\n distPath: string;\n pgliteSchemaPath?: string;\n};\n\n// Register this plugin's config type under its own id, via the package's\n// real public specifier, so callers can resolve it type-safely from a\n// `Plugin[]` array (see plugin/get-plugin-config.ts's resolvePluginConfig)\n// without importing KyselyTypePluginOptions, which stays unexported.\ndeclare module \"@tailor-platform/sdk/plugin\" {\n interface PluginConfigRegistry {\n \"@tailor-platform/kysely-type\": KyselyTypePluginOptions;\n }\n}\n\n/** Conventional output path used when `kyselyTypePlugin` has no `distPath` configured. */\nexport const DEFAULT_KYSELY_TYPES_DIST_PATH = \"./generated/tailordb.ts\";\n\n/**\n * Plugin that generates Kysely type definitions for TailorDB tables.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated types\n * @param options.pgliteSchemaPath - Output file path for the PGlite `CREATE TABLE` script module; omit to skip it\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function kyselyTypePlugin(\n options: KyselyTypePluginOptions,\n): Plugin<unknown, KyselyTypePluginOptions> {\n return {\n id: KyselyGeneratorID,\n description: \"Generates Kysely type definitions for TailorDB tables\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<KyselyTypePluginOptions>,\n ): Promise<GeneratorResult> {\n const { distPath, pgliteSchemaPath } = ctx.pluginConfig;\n if (pgliteSchemaPath && resolve(distPath) === resolve(pgliteSchemaPath)) {\n throw new Error(\"distPath and pgliteSchemaPath must resolve to different files.\");\n }\n\n const allNamespaceData: KyselyNamespaceMetadata[] = [];\n\n for (const ns of ctx.tailordb) {\n const typeMetadataList: KyselyTypeMetadata[] = [];\n\n for (const type of Object.values(ns.tables)) {\n const metadata = await processKyselyType(type);\n typeMetadataList.push(metadata);\n }\n\n if (typeMetadataList.length === 0) continue;\n\n allNamespaceData.push({\n namespace: ns.namespace,\n types: typeMetadataList,\n });\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allNamespaceData.length > 0) {\n const content = generateUnifiedKyselyTypes(allNamespaceData);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n if (ctx.pluginConfig.pgliteSchemaPath) {\n files.push({\n path: ctx.pluginConfig.pgliteSchemaPath,\n content: generatePGliteSchema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B,UAAW,EAAG,UACd,MAAO,CACT,CAAC,CACH,CAEA,IAAM,EAAkC,CAAC,EACzC,GAAI,EAAiB,OAAS,EAAG,CAC/B,IAAM,EAAU,2BAA2B,CAAgB,EAC3D,EAAM,KAAK,CACT,KAAM,EAAI,aAAa,SACvB,SACF,CAAC,EACG,EAAI,aAAa,kBACnB,EAAM,KAAK,CACT,KAAM,EAAI,aAAa,iBACvB,QAAS,2BACP,EAAI,SAAS,OAAQ,GAAO,OAAO,KAAK,EAAG,MAAM,CAAC,CAAC,OAAS,CAAC,CAC/D,CACF,CAAC,CAEL,CAEA,MAAO,CAAE,OAAM,CACjB,CACF,CACF"}
1
+ {"version":3,"file":"kysely-type-C-iyFFH7.mjs","names":[],"sources":["../src/plugin/builtin/kysely-type/type-processor.ts","../src/plugin/builtin/kysely-type/pglite-schema.ts","../src/plugin/builtin/kysely-type/index.ts"],"sourcesContent":["import { COLUMN_TYPE_ALIASES, mapFieldTypeToColumnType } from \"#/utils/field-column-type\";\nimport multiline from \"#/utils/multiline\";\nimport {\n type KyselyFieldConfig,\n type KyselyNamespaceMetadata,\n type KyselyTypeMetadata,\n type UsedUtilityTypes,\n} from \"./types\";\nimport type { TailorDBType } from \"#/parser/service/tailordb/types\";\n\ntype FieldTypeResult = {\n type: string;\n usedUtilityTypes: UsedUtilityTypes;\n};\n\nfunction emptyUsedUtilityTypes(): UsedUtilityTypes {\n return { Timestamp: false, Serial: false, ObjectColumnType: false, ArrayColumnType: false };\n}\n\nfunction mergeUsedUtilityTypes(a: UsedUtilityTypes, b: UsedUtilityTypes): UsedUtilityTypes {\n return {\n Timestamp: a.Timestamp || b.Timestamp,\n Serial: a.Serial || b.Serial,\n ObjectColumnType: a.ObjectColumnType || b.ObjectColumnType,\n ArrayColumnType: a.ArrayColumnType || b.ArrayColumnType,\n };\n}\n\n/**\n * Get the enum type definition.\n * @param fieldConfig - The field configuration\n * @returns The enum type as a string union\n */\nfunction getEnumType(fieldConfig: KyselyFieldConfig): string {\n const allowedValues = fieldConfig.allowedValues;\n\n if (allowedValues && Array.isArray(allowedValues)) {\n return allowedValues\n .map((v: string | { value: string }) => {\n const value = typeof v === \"string\" ? v : v.value;\n return `\"${value}\"`;\n })\n .join(\" | \");\n }\n return \"string\";\n}\n\n/**\n * Get the nested object type definition.\n * @param fieldConfig - The field configuration\n * @returns The nested type with used utility types\n */\nfunction getNestedType(fieldConfig: KyselyFieldConfig): FieldTypeResult {\n const fields = fieldConfig.fields;\n if (!fields || typeof fields !== \"object\") {\n return {\n type: \"string\",\n usedUtilityTypes: emptyUsedUtilityTypes(),\n };\n }\n\n const fieldResults = Object.entries(fields).map(([fieldName, config]) => {\n const result = generateFieldType(config);\n const optional = config.required !== true ? \"?\" : \"\";\n return {\n fieldType: `${fieldName}${optional}: ${result.type}`,\n usedUtilityTypes: result.usedUtilityTypes,\n };\n });\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => mergeUsedUtilityTypes(acc, result.usedUtilityTypes),\n emptyUsedUtilityTypes(),\n );\n\n const fieldTypes = fieldResults.map((r) => r.fieldType);\n const obj = `{\\n ${fieldTypes.join(\";\\n \")}${fieldTypes.length > 0 ? \";\" : \"\"}\\n}`;\n\n const hasOptionalFields = Object.values(fields).some((config) => config.required !== true);\n const hasGeneratedFields = Object.values(fields).some(\n (config) =>\n config.hooks?.create || config.default !== undefined || config.optionalOnCreate === true,\n );\n if (aggregatedUtilityTypes.Timestamp || hasOptionalFields || hasGeneratedFields) {\n return {\n type: `ObjectColumnType<${obj}>`,\n usedUtilityTypes: { ...aggregatedUtilityTypes, ObjectColumnType: true },\n };\n }\n return { type: obj, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Get the base Kysely type for a field (without array/null modifiers).\n * @param fieldConfig - The field configuration\n * @returns The base type with used utility types\n */\nfunction getBaseType(fieldConfig: KyselyFieldConfig): FieldTypeResult {\n const fieldType = fieldConfig.type;\n const usedUtilityTypes = emptyUsedUtilityTypes();\n\n if (fieldType === \"enum\") {\n return { type: getEnumType(fieldConfig), usedUtilityTypes };\n }\n if (fieldType === \"nested\") {\n return getNestedType(fieldConfig);\n }\n\n const type = mapFieldTypeToColumnType(fieldType);\n usedUtilityTypes.Timestamp = type === \"Timestamp\";\n\n return { type, usedUtilityTypes };\n}\n\n/**\n * Generate the complete field type including array and null modifiers.\n * @param fieldConfig - The field configuration\n * @returns The complete field type with used utility types\n */\nfunction generateFieldType(fieldConfig: KyselyFieldConfig): FieldTypeResult {\n const baseTypeResult = getBaseType(fieldConfig);\n const usedUtilityTypes = { ...baseTypeResult.usedUtilityTypes };\n\n const isArray = fieldConfig.array === true;\n const isNullable = fieldConfig.required !== true;\n\n // A ColumnType-shaped alias and ObjectColumnType cannot be wrapped with [] for\n // arrays, because Kysely only resolves ColumnType at the top-level table\n // property. Use ArrayColumnType to keep the ColumnType at the top level.\n const isColumnTypeBase = COLUMN_TYPE_ALIASES.has(baseTypeResult.type);\n\n let finalType = baseTypeResult.type;\n if (isArray) {\n if (isColumnTypeBase || finalType.startsWith(\"ObjectColumnType<\")) {\n finalType = `ArrayColumnType<${baseTypeResult.type}>`;\n usedUtilityTypes.ArrayColumnType = true;\n } else {\n const needsParens = fieldConfig.type === \"enum\";\n finalType = needsParens ? `(${baseTypeResult.type})[]` : `${baseTypeResult.type}[]`;\n }\n }\n if (isNullable) {\n finalType = `${finalType} | null`;\n }\n\n if (fieldConfig.serial) {\n usedUtilityTypes.Serial = true;\n finalType = `Serial<${finalType}>`;\n }\n if (\n fieldConfig.hooks?.create ||\n fieldConfig.default !== undefined ||\n fieldConfig.optionalOnCreate === true\n ) {\n finalType = `Generated<${finalType}>`;\n }\n\n return { type: finalType, usedUtilityTypes };\n}\n\n/**\n * Generate the table interface.\n * @param name - Table name\n * @param fields - Field configurations keyed by field name\n * @returns The type definition and used utility types\n */\nfunction generateTableInterface(\n name: string,\n fields: Record<string, KyselyFieldConfig>,\n): {\n typeDef: string;\n usedUtilityTypes: UsedUtilityTypes;\n} {\n const fieldEntries = Object.entries(fields).filter(([fieldName]) => fieldName !== \"id\");\n\n const fieldResults = fieldEntries.map(([fieldName, fieldConfig]) => ({\n fieldName,\n ...generateFieldType(fieldConfig),\n }));\n\n const fieldLines = [\n \"id: Generated<string>;\",\n ...fieldResults.map((result) => `${result.fieldName}: ${result.type};`),\n ];\n\n const aggregatedUtilityTypes = fieldResults.reduce(\n (acc, result) => mergeUsedUtilityTypes(acc, result.usedUtilityTypes),\n emptyUsedUtilityTypes(),\n );\n\n const typeDef = multiline /* ts */ `\n ${name}: {\n ${fieldLines.join(\"\\n\")}\n }\n `;\n\n return { typeDef, usedUtilityTypes: aggregatedUtilityTypes };\n}\n\n/**\n * Generate KyselyTypeMetadata from field configurations.\n * @param name - Table name\n * @param fields - Field configurations keyed by field name\n * @returns Generated Kysely type metadata\n */\nexport function processKyselyFields(\n name: string,\n fields: Record<string, KyselyFieldConfig>,\n): KyselyTypeMetadata {\n const result = generateTableInterface(name, fields);\n\n return {\n name,\n typeDef: result.typeDef,\n usedUtilityTypes: result.usedUtilityTypes,\n };\n}\n\n/**\n * Convert a TailorDBType into KyselyTypeMetadata.\n * @param type - Parsed TailorDB table\n * @returns Generated Kysely type metadata\n */\nexport async function processKyselyType(type: TailorDBType): Promise<KyselyTypeMetadata> {\n return processKyselyFields(\n type.name,\n Object.fromEntries(\n Object.entries(type.fields).map(([fieldName, parsedField]) => [\n fieldName,\n parsedField.config,\n ]),\n ),\n );\n}\n\n/**\n * Generate unified types file from multiple namespaces.\n * @param namespaceData - Namespace metadata\n * @returns Generated types file contents\n */\nexport function generateUnifiedKyselyTypes(namespaceData: KyselyNamespaceMetadata[]): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Aggregate used utility types from all namespaces\n const globalUsedUtilityTypes = namespaceData\n .flatMap((ns) => ns.types)\n .reduce(\n (acc, type) => mergeUsedUtilityTypes(acc, type.usedUtilityTypes),\n emptyUsedUtilityTypes(),\n );\n\n const utilityTypeImports: string[] = [\"type Generated\"];\n if (globalUsedUtilityTypes.Timestamp) {\n utilityTypeImports.push(\"type Timestamp\");\n }\n if (globalUsedUtilityTypes.ObjectColumnType) {\n utilityTypeImports.push(\"type ObjectColumnType\");\n }\n if (globalUsedUtilityTypes.ArrayColumnType) {\n utilityTypeImports.push(\"type ArrayColumnType\");\n }\n if (globalUsedUtilityTypes.Serial) {\n utilityTypeImports.push(\"type Serial\");\n }\n\n const importsSection = multiline /* ts */ `\n import {\n createGetDB,\n ${utilityTypeImports.join(\",\\n\")},\n type NamespaceDB,\n type NamespaceInsertable,\n type NamespaceSelectable,\n type NamespaceTable,\n type NamespaceTableName,\n type NamespaceTransaction,\n type NamespaceUpdateable,\n } from \"@tailor-platform/sdk/kysely\";\n `;\n\n // Generate Namespace interface with multiple namespaces\n const namespaceInterfaces = namespaceData\n .map(({ namespace, types }) => {\n const typeDefsWithIndent = types\n .map((type) => {\n return type.typeDef\n .split(\"\\n\")\n .map((line) => (line.trim() ? ` ${line}` : \"\"))\n .join(\"\\n\");\n })\n .join(\"\\n\\n\");\n\n return ` \"${namespace}\": {\\n${typeDefsWithIndent}\\n }`;\n })\n .join(\",\\n\");\n\n const namespaceInterface = `export interface Namespace {\\n${namespaceInterfaces}\\n}`;\n\n const getDBFunction = multiline /* ts */ `\n export const getDB = createGetDB<Namespace>();\n\n export type DB<N extends keyof Namespace = keyof Namespace> = NamespaceDB<Namespace, N>;\n `;\n\n const utilityTypeExports = multiline /* ts */ `\n export type Transaction<K extends keyof Namespace | DB = keyof Namespace> =\n NamespaceTransaction<Namespace, K>;\n\n type TableName = NamespaceTableName<Namespace>;\n export type Table<T extends TableName> = NamespaceTable<Namespace, T>;\n\n export type Insertable<T extends TableName> = NamespaceInsertable<Namespace, T>;\n export type Selectable<T extends TableName> = NamespaceSelectable<Namespace, T>;\n export type Updateable<T extends TableName> = NamespaceUpdateable<Namespace, T>;\n `;\n\n return (\n [importsSection, namespaceInterface, getDBFunction, utilityTypeExports].join(\"\\n\\n\") + \"\\n\"\n );\n}\n","import { generatePgliteSchemaModule, type DDLTableConfig } from \"#/utils/tailordb-ddl\";\nimport type { TailorDBType } from \"#/parser/service/tailordb/types\";\n\n/** Tables of one namespace, as the schema module groups them. */\nexport interface PGliteSchemaNamespace {\n namespace: string;\n tables: Record<string, TailorDBType>;\n}\n\n/**\n * Reduce parsed tables to what the DDL generator reads.\n * @param tables - Parsed TailorDB tables keyed by name\n * @returns DDL table configs in the same order\n */\nexport function toDDLTables(tables: Record<string, TailorDBType>): DDLTableConfig[] {\n return Object.values(tables).map((type) => ({\n name: type.name,\n fields: Object.fromEntries(\n Object.entries(type.fields).map(([fieldName, field]) => [fieldName, field.config]),\n ),\n indexes: type.indexes,\n }));\n}\n\n/**\n * Render the module that exports each namespace's `CREATE TABLE` script for\n * `pglite.exec()`.\n * @param namespaces - Namespaces with their parsed tables\n * @returns TypeScript source of the schema module\n */\nexport function generatePGliteSchemaModule(namespaces: readonly PGliteSchemaNamespace[]): string {\n return generatePgliteSchemaModule(\n namespaces.map(({ namespace, tables }) => ({ namespace, tables: toDDLTables(tables) })),\n { generatedBy: \"the kysely-type plugin\" },\n );\n}\n","import { resolve } from \"pathe\";\nimport { generatePGliteSchemaModule } from \"./pglite-schema\";\nimport { processKyselyType, generateUnifiedKyselyTypes } from \"./type-processor\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\nimport type { KyselyTypeMetadata, KyselyNamespaceMetadata } from \"./types\";\n\n/** Unique identifier for the Kysely type generator plugin. */\nexport const KyselyGeneratorID = \"@tailor-platform/kysely-type\";\n\ntype KyselyTypePluginOptions = {\n distPath: string;\n pgliteSchemaPath?: string;\n};\n\n// Register this plugin's config type under its own id, via the package's\n// real public specifier, so callers can resolve it type-safely from a\n// `Plugin[]` array (see plugin/get-plugin-config.ts's resolvePluginConfig)\n// without importing KyselyTypePluginOptions, which stays unexported.\ndeclare module \"@tailor-platform/sdk/plugin\" {\n interface PluginConfigRegistry {\n \"@tailor-platform/kysely-type\": KyselyTypePluginOptions;\n }\n}\n\n/** Conventional output path used when `kyselyTypePlugin` has no `distPath` configured. */\nexport const DEFAULT_KYSELY_TYPES_DIST_PATH = \"./generated/tailordb.ts\";\n\n/**\n * Plugin that generates Kysely type definitions for TailorDB tables.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated types\n * @param options.pgliteSchemaPath - Output file path for the PGlite `CREATE TABLE` script module; omit to skip it\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function kyselyTypePlugin(\n options: KyselyTypePluginOptions,\n): Plugin<unknown, KyselyTypePluginOptions> {\n return {\n id: KyselyGeneratorID,\n description: \"Generates Kysely type definitions for TailorDB tables\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<KyselyTypePluginOptions>,\n ): Promise<GeneratorResult> {\n const { distPath, pgliteSchemaPath } = ctx.pluginConfig;\n if (pgliteSchemaPath && resolve(distPath) === resolve(pgliteSchemaPath)) {\n throw new Error(\"distPath and pgliteSchemaPath must resolve to different files.\");\n }\n\n const allNamespaceData: KyselyNamespaceMetadata[] = [];\n\n for (const ns of ctx.tailordb) {\n const typeMetadataList: KyselyTypeMetadata[] = [];\n\n for (const type of Object.values(ns.tables)) {\n const metadata = await processKyselyType(type);\n typeMetadataList.push(metadata);\n }\n\n if (typeMetadataList.length === 0) continue;\n\n allNamespaceData.push({\n namespace: ns.namespace,\n types: typeMetadataList,\n });\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allNamespaceData.length > 0) {\n const content = generateUnifiedKyselyTypes(allNamespaceData);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n if (ctx.pluginConfig.pgliteSchemaPath) {\n files.push({\n path: ctx.pluginConfig.pgliteSchemaPath,\n content: generatePGliteSchemaModule(\n ctx.tailordb.filter((ns) => Object.keys(ns.tables).length > 0),\n ),\n });\n }\n }\n\n return { files };\n },\n };\n}\n"],"mappings":"2IAeA,SAAS,uBAA0C,CACjD,MAAO,CAA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,EAC3D,EAAM,KAAK,CACT,KAAM,EAAI,aAAa,SACvB,SACF,CAAC,EACG,EAAI,aAAa,kBACnB,EAAM,KAAK,CACT,KAAM,EAAI,aAAa,iBACvB,QAAS,2BACP,EAAI,SAAS,OAAQ,GAAO,OAAO,KAAK,EAAG,MAAM,CAAC,CAAC,OAAS,CAAC,CAC/D,CACF,CAAC,CAEL,CAEA,MAAO,CAAE,OAAM,CACjB,CACF,CACF"}
@@ -2,8 +2,8 @@ import{formatWithOptions as e,stripVTControlCharacters as t,styleText as n}from"
2
2
  `?!1:t<=31||t===127}function normalizeControlCharacters(e){let t=e.match(o)??[];return e.split(o).map(e=>{let t=[];for(let n of e)n===` `?t.push(` `.repeat(8)):isStrippableControlCharacter(n)||t.push(n);return t.join(``)}).reduce((e,n,r)=>e+n+(t[r]??``),``)}function sanitizeCell(e){return normalizeControlCharacters(String(e??``).replace(s,`
3
3
  `))}const l=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Nonspacing_Mark}|\p{Enclosing_Mark}|\p{Surrogate})+$/v,u=/^\p{RGI_Emoji}$/v;function displayWidth(e){let t=0;for(let{segment:n}of c.segment(e.replace(o,``))){if(l.test(n))continue;if(u.test(n)){t+=2;continue}let e=n.codePointAt(0);t+=e===void 0?0:i(e)}return t}function toCellLines(e){return e.split(`
4
4
  `).map(e=>({text:e,width:displayWidth(e)}))}function padCell(e,t){return e.text+` `.repeat(Math.max(0,t-e.width))}function renderBorder(e,t,n,r){return e+r.map(e=>`─`.repeat(e+2)).join(t)+n}function validateConsistentColumnCount(e){let t=e[0]?.length;t!==void 0&&e.forEach((e,n)=>{if(e.length!==t)throw Error(`renderTable: all rows must have the same number of columns (expected ${t}, row ${n} has ${e.length}).`)})}function renderTable(e,t={}){let n=e.map(e=>e.map(sanitizeCell));validateConsistentColumnCount(n);let r=n.length,i=n[0]?.length??0;if(r===0||i===0)return``;let a=n.map(e=>Array.from({length:i},(t,n)=>toCellLines(e[n]??``))),o=Array.from({length:i},(e,t)=>maxOf(a.map(e=>maxOf((e[t]??[]).map(e=>e.width))))),shouldDrawLine=e=>t.singleLine?e===0||e===r:(t.drawHorizontalLine??(()=>!0))(e,r),s=[];return shouldDrawLine(0)&&s.push(renderBorder(`┌`,`┬`,`┐`,o)),a.forEach((e,t)=>{let n=maxOf(e.map(e=>e.length),1);for(let t=0;t<n;t++){let n=e.map((e,n)=>padCell(e[t]??{text:``,width:0},o[n]??0));s.push(`│ ${n.join(` │ `)} │`)}t<r-1&&shouldDrawLine(t+1)&&s.push(renderBorder(`├`,`┼`,`┤`,o))}),shouldDrawLine(r)&&s.push(renderBorder(`└`,`┴`,`┘`,o)),`${s.join(`
5
- `)}\n`}const d=new Set([`true`,`t`,`yes`,`y`,`on`,`1`]),f=new Set([`false`,`f`,`no`,`n`,`off`,`0`]);function parseBoolean(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t!==``){if(d.has(t))return!0;if(f.has(t))return!1}}var CIPromptError=class extends Error{constructor(e){super(e??`Interactive prompts are not available in this environment. Provide the required options explicitly.`),this.name=`CIPromptError`}};const p={success:a.green,error:a.red,warning:a.yellow,info:a.cyan,create:a.green,update:a.yellow,delete:a.red,replace:a.magenta,unchanged:a.gray,bold:a.bold,dim:a.gray,highlight:a.cyanBright,successBright:a.greenBright,errorBright:a.redBright,resourceType:a.bold,resourceName:a.cyan,path:a.cyan,value:a.white,placeholder:e=>a.italic(a.gray(e))},m={success:p.success(`✓`),error:p.error(`✖`),warning:p.warning(`⚠`),info:p.info(`i`),create:p.create(`+`),update:p.update(`~`),delete:p.delete(`-`),replace:p.replace(`±`),bullet:p.dim(`•`),arrow:p.dim(`→`)};let h=!1,g=!1;const _=new Set,v=`<redacted>`;function buildAutomaton(e){let t={children:new Map,fail:void 0,outputs:[]};t.fail=t;for(let n of e){let e=t;for(let r=0;r<n.length;r++){let i=n[r],a=e.children.get(i);a||(a={children:new Map,fail:t,outputs:[]},e.children.set(i,a)),e=a}e.outputs.push(n)}let n=[...t.children.values()];for(let e=0;e<n.length;e++){let r=n[e];for(let[e,i]of r.children){let a=r.fail;for(;a!==t&&!a.children.has(e);)a=a.fail;i.fail=a.children.get(e)??t,i.outputs=i.outputs.concat(i.fail.outputs),n.push(i)}}return t}let y=null;function getAutomaton(){return y??=buildAutomaton(_),y}function findSecretSpans(e){let t=[],n=getAutomaton(),r=n;for(let i=0;i<e.length;i++){let a=e[i];for(;r!==n&&!r.children.has(a);)r=r.fail;r=r.children.get(a)??n;for(let e of r.outputs)t.push([i+1-e.length,i+1])}return t}function redactSecrets(e){if(_.size===0)return e;let t=[];for(let n=0,r;(r=e.indexOf(v,n))!==-1;)t.push([r,r+10]),n=r+10;let n=findSecretSpans(e).filter(([e,n])=>!t.some(([t,r])=>e>=t&&n<=r));if(n.length===0)return e;n.sort(([e],[t])=>e-t);let r=[];for(let e of n){let t=r.at(-1);t&&e[0]<=t[1]?t[1]=Math.max(t[1],e[1]):r.push(e)}let i=``,a=0;for(let[t,n]of r)i+=e.slice(a,t)+v,a=n;return i+e.slice(a)}const b={info:`ℹ`,success:`✔`,warn:`⚠`,error:`✖`,debug:`⚙`,trace:`→`,log:``},x={info:p.info,success:p.success,warn:p.warning,error:p.error,debug:p.dim,trace:p.dim,log:e=>e};function formatLogLine(e){let{mode:t,indent:n,type:r,message:i,timestamp:a}=e,o=n>0?` `.repeat(n):``,s=x[r]||(e=>e);if(t===`plain`)return`${o}${s(i)}\n`;let c=b[r]||``,l=s(`${c?`${c} `:``}${i}`);return`${o}${a??``}${l}\n`}function writeLog(t,n,r){let i=r?.mode??`default`,a=r?.indent??0,o={breakLength:process.stdout.columns||80},s=formatLogLine({mode:i,indent:a,type:t,message:e(o,n),timestamp:i===`stream`?`${new Date().toLocaleTimeString()} `:``});process.stderr.write(renderFor(process.stderr,redactSecrets(s)))}const S={get jsonMode(){return h},set jsonMode(e){h=e},get verbose(){return g||parseBoolean(process.env.DEBUG)===!0||process.env.RUNNER_DEBUG===`1`},set verbose(e){g=e},info(e,t){writeLog(`info`,e,t)},success(e,t){writeLog(`success`,e,t)},warn(e,t){writeLog(`warn`,e,t)},error(e,t){writeLog(`error`,e,t)},log(e){writeLog(`log`,e,{mode:`plain`})},newline(){process.stderr.write(`
5
+ `)}\n`}const d=/* @__PURE__ */ new Set([`true`,`t`,`yes`,`y`,`on`,`1`]),f=/* @__PURE__ */ new Set([`false`,`f`,`no`,`n`,`off`,`0`]);function parseBoolean(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t!==``){if(d.has(t))return!0;if(f.has(t))return!1}}var CIPromptError=class extends Error{constructor(e){super(e??`Interactive prompts are not available in this environment. Provide the required options explicitly.`),this.name=`CIPromptError`}};const p={success:a.green,error:a.red,warning:a.yellow,info:a.cyan,create:a.green,update:a.yellow,delete:a.red,replace:a.magenta,unchanged:a.gray,bold:a.bold,dim:a.gray,highlight:a.cyanBright,successBright:a.greenBright,errorBright:a.redBright,resourceType:a.bold,resourceName:a.cyan,path:a.cyan,value:a.white,placeholder:e=>a.italic(a.gray(e))},m={success:p.success(`✓`),error:p.error(`✖`),warning:p.warning(`⚠`),info:p.info(`i`),create:p.create(`+`),update:p.update(`~`),delete:p.delete(`-`),replace:p.replace(`±`),bullet:p.dim(`•`),arrow:p.dim(`→`)};let h=!1,g=!1;const _=/* @__PURE__ */ new Set,v=`<redacted>`;function buildAutomaton(e){let t={children:/* @__PURE__ */ new Map,fail:void 0,outputs:[]};t.fail=t;for(let n of e){let e=t;for(let r=0;r<n.length;r++){let i=n[r],a=e.children.get(i);a||(a={children:/* @__PURE__ */ new Map,fail:t,outputs:[]},e.children.set(i,a)),e=a}e.outputs.push(n)}let n=[...t.children.values()];for(let e=0;e<n.length;e++){let r=n[e];for(let[e,i]of r.children){let a=r.fail;for(;a!==t&&!a.children.has(e);)a=a.fail;i.fail=a.children.get(e)??t,i.outputs=i.outputs.concat(i.fail.outputs),n.push(i)}}return t}let y=null;function getAutomaton(){return y??=buildAutomaton(_),y}function findSecretSpans(e){let t=[],n=getAutomaton(),r=n;for(let i=0;i<e.length;i++){let a=e[i];for(;r!==n&&!r.children.has(a);)r=r.fail;r=r.children.get(a)??n;for(let e of r.outputs)t.push([i+1-e.length,i+1])}return t}function redactSecrets(e){if(_.size===0)return e;let t=[];for(let n=0,r;(r=e.indexOf(v,n))!==-1;)t.push([r,r+10]),n=r+10;let n=findSecretSpans(e).filter(([e,n])=>!t.some(([t,r])=>e>=t&&n<=r));if(n.length===0)return e;n.sort(([e],[t])=>e-t);let r=[];for(let e of n){let t=r.at(-1);t&&e[0]<=t[1]?t[1]=Math.max(t[1],e[1]):r.push(e)}let i=``,a=0;for(let[t,n]of r)i+=e.slice(a,t)+v,a=n;return i+e.slice(a)}const b={info:`ℹ`,success:`✔`,warn:`⚠`,error:`✖`,debug:`⚙`,trace:`→`,log:``},x={info:p.info,success:p.success,warn:p.warning,error:p.error,debug:p.dim,trace:p.dim,log:e=>e};function formatLogLine(e){let{mode:t,indent:n,type:r,message:i,timestamp:a}=e,o=n>0?` `.repeat(n):``,s=x[r]||(e=>e);if(t===`plain`)return`${o}${s(i)}\n`;let c=b[r]||``,l=s(`${c?`${c} `:``}${i}`);return`${o}${a??``}${l}\n`}function writeLog(t,n,r){let i=r?.mode??`default`,a=r?.indent??0,o={breakLength:process.stdout.columns||80},s=formatLogLine({mode:i,indent:a,type:t,message:e(o,n),timestamp:i===`stream`?`${(/* @__PURE__ */ new Date()).toLocaleTimeString()} `:``});process.stderr.write(renderFor(process.stderr,redactSecrets(s)))}const S={get jsonMode(){return h},set jsonMode(e){h=e},get verbose(){return g||parseBoolean(process.env.DEBUG)===!0||process.env.RUNNER_DEBUG===`1`},set verbose(e){g=e},info(e,t){writeLog(`info`,e,t)},success(e,t){writeLog(`success`,e,t)},warn(e,t){writeLog(`warn`,e,t)},error(e,t){writeLog(`error`,e,t)},log(e){writeLog(`log`,e,{mode:`plain`})},newline(){process.stderr.write(`
6
6
  `)},debug(e){S.verbose&&writeLog(`log`,p.dim(e),{mode:`plain`})},registerSecret(e){if(typeof e!=`string`||[...e].length<4)return;let t=_.size;_.add(e);let n=JSON.stringify(e).slice(1,-1);n!==e&&_.add(n);let r=new URLSearchParams([[`v`,e]]).toString().slice(2);r!==e&&_.add(r),_.size!==t&&(y=null)},out(e,t){if(typeof e==`string`){process.stdout.write(renderFor(process.stdout,e.endsWith(`
7
7
  `)?e:e+`
8
8
  `));return}if(this.jsonMode){console.log(JSON.stringify(e));return}let n=t?.display,formatValue=(e,n=!1)=>t?.showNull&&e===null?`NULL`:e==null?`N/A`:e instanceof Date?r(e,{addSuffix:!0}):typeof e==`object`?n?JSON.stringify(e,null,2):JSON.stringify(e):String(e),isExcluded=e=>n!==void 0&&e in n&&n[e]===null,transformValue=(e,t,r,i=!1)=>{if(n&&e in n){let i=n[e];if(i)return i(t,r)}return formatValue(t,i)};if(!Array.isArray(e)){let t=renderTable(Object.entries(e).filter(([e])=>!isExcluded(e)).map(([t,n])=>[t,transformValue(t,n,e,!0)]),{singleLine:!1});process.stdout.write(renderFor(process.stdout,t));return}if(e.length===0)return;let i=Array.from(new Set(e.flatMap(e=>Object.keys(e)))).filter(e=>!isExcluded(e));if(i.length===0)return;let a=renderTable([i,...e.map(e=>i.map(t=>transformValue(t,e[t],e)))],{drawHorizontalLine:(e,t)=>e===0||e===1||e===t});process.stdout.write(renderFor(process.stdout,a))}};export{m as a,renderFor as c,p as i,S as n,parseBoolean as o,redactSecrets as r,renderTable as s,CIPromptError as t};
9
- //# sourceMappingURL=logger-72hM4JWZ.mjs.map
9
+ //# sourceMappingURL=logger-Cp5U2IDI.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger-72hM4JWZ.mjs","names":[],"sources":["../../shared/src/color.ts","../src/cli/shared/ascii-table.ts","../src/cli/shared/parse-boolean.ts","../src/cli/shared/logger.ts"],"sourcesContent":["import { stripVTControlCharacters, styleText } from \"node:util\";\n\n/** Applies a style to text */\nexport type StyleFn = (text: string) => string;\n\ntype StyleName = Exclude<Parameters<typeof styleText>[0], readonly unknown[] | unknown[]>;\n\nconst style =\n (name: StyleName): StyleFn =>\n (text) =>\n styleText(name, text, { validateStream: false });\n\n/**\n * Style functions by name, so call sites read `color.bold(text)`. Styling is\n * always applied; `renderFor` drops it again when the destination stream has no\n * color support. Add a name here when a package needs one that is not listed.\n */\nexport const color = {\n bold: style(\"bold\"),\n dim: style(\"dim\"),\n italic: style(\"italic\"),\n gray: style(\"gray\"),\n white: style(\"white\"),\n red: style(\"red\"),\n green: style(\"green\"),\n yellow: style(\"yellow\"),\n cyan: style(\"cyan\"),\n magenta: style(\"magenta\"),\n redBright: style(\"redBright\"),\n greenBright: style(\"greenBright\"),\n cyanBright: style(\"cyanBright\"),\n};\n\n// Node's rules for whether a destination gets colors, applied by hand. Asking\n// styleText instead would be shorter but only correct on Node: Bun ignores both\n// the stream option and NO_COLOR (reproduced on 1.3.14), so it reports every\n// destination as color-capable and escapes end up in redirected output.\n//\n// FORCE_COLOR decides on its own when set, which is how CI keeps colors through\n// a pipe. NO_COLOR counts as set at any non-empty value, \"0\" included.\nconst supportsColor = (stream: NodeJS.WriteStream): boolean => {\n const forced = process.env.FORCE_COLOR;\n if (forced !== undefined) return forced !== \"0\" && forced !== \"false\";\n if (process.env.NODE_DISABLE_COLORS !== undefined) return false;\n if ((process.env.NO_COLOR ?? \"\") !== \"\") return false;\n if (process.env.TERM === \"dumb\") return false;\n return stream.isTTY === true;\n};\n\n/**\n * Prepares styled text for the stream it is written to.\n * @param stream - Stream the text is written to\n * @param text - Styled text\n * @returns Text with styling removed when the stream has no color support\n */\nexport function renderFor(stream: NodeJS.WriteStream, text: string): string {\n return supportsColor(stream) ? text : stripVTControlCharacters(text);\n}\n","import { eastAsianWidth } from \"get-east-asian-width\";\n\n// eslint-disable-next-line no-control-regex\nconst ANSI_ESCAPE_PATTERN = /\\x1b\\[[0-9;]*m/g;\nconst CARRIAGE_RETURN_PATTERN = /\\r\\n?/g;\n\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nexport interface AsciiTableConfig {\n /** Suppress horizontal lines between rows, keeping only the outer border. */\n singleLine?: boolean;\n /** Decide whether to draw the horizontal line at `lineIndex` (range `[0, rowCount]` inclusive). */\n drawHorizontalLine?: (lineIndex: number, rowCount: number) => boolean;\n}\n\ninterface CellLine {\n text: string;\n width: number;\n}\n\nfunction maxOf(values: number[], fallback = 0): number {\n return values.reduce((max, value) => (value > max ? value : max), fallback);\n}\n\nconst TAB_WIDTH = 8;\n\nfunction isStrippableControlCharacter(char: string): boolean {\n const codePoint = char.codePointAt(0) ?? 0;\n if (char === \"\\n\") {\n return false;\n }\n return codePoint <= 0x1f || codePoint === 0x7f;\n}\n\n// Only SGR (color/style) escape sequences are meant to survive; a bare ESC\n// that isn't part of a recognized SGR sequence (e.g. a screen-clear CSI\n// sequence, or a BEL-terminated OSC sequence) is treated like any other\n// control character below and stripped, rather than passed through to the\n// terminal or left with its terminator removed.\nfunction normalizeControlCharacters(value: string): string {\n const sgrSequences = value.match(ANSI_ESCAPE_PATTERN) ?? [];\n return value\n .split(ANSI_ESCAPE_PATTERN)\n .map((segment) => {\n const chars: string[] = [];\n for (const char of segment) {\n if (char === \"\\t\") {\n chars.push(\" \".repeat(TAB_WIDTH));\n } else if (!isStrippableControlCharacter(char)) {\n chars.push(char);\n }\n }\n return chars.join(\"\");\n })\n .reduce((result, segment, i) => result + segment + (sgrSequences[i] ?? \"\"), \"\");\n}\n\nfunction sanitizeCell(cell: unknown): string {\n return normalizeControlCharacters(String(cell ?? \"\").replace(CARRIAGE_RETURN_PATTERN, \"\\n\"));\n}\n\n// Clusters made up entirely of non-printing code points (lone joiners,\n// variation selectors, combining marks, etc.) render with no visible glyph.\nconst ZERO_WIDTH_CLUSTER_PATTERN =\n /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Nonspacing_Mark}|\\p{Enclosing_Mark}|\\p{Surrogate})+$/v;\n// RGI_Emoji covers flags, keycaps, and VS16-forced presentation sequences,\n// which render as 2 columns in terminals even though their first code point\n// alone would measure as narrow/neutral.\nconst RGI_EMOJI_PATTERN = /^\\p{RGI_Emoji}$/v;\n\nfunction displayWidth(value: string): number {\n let width = 0;\n for (const { segment } of graphemeSegmenter.segment(value.replace(ANSI_ESCAPE_PATTERN, \"\"))) {\n if (ZERO_WIDTH_CLUSTER_PATTERN.test(segment)) {\n continue;\n }\n if (RGI_EMOJI_PATTERN.test(segment)) {\n width += 2;\n continue;\n }\n const codePoint = segment.codePointAt(0);\n width += codePoint === undefined ? 0 : eastAsianWidth(codePoint);\n }\n return width;\n}\n\nfunction toCellLines(cell: string): CellLine[] {\n return cell.split(\"\\n\").map((text) => ({ text, width: displayWidth(text) }));\n}\n\nfunction padCell(cellLine: CellLine, width: number): string {\n return cellLine.text + \" \".repeat(Math.max(0, width - cellLine.width));\n}\n\nfunction renderBorder(left: string, join: string, right: string, columnWidths: number[]): string {\n return left + columnWidths.map((width) => \"─\".repeat(width + 2)).join(join) + right;\n}\n\nfunction validateConsistentColumnCount(rows: string[][]): void {\n const columnCount = rows[0]?.length;\n if (columnCount === undefined) {\n return;\n }\n rows.forEach((row, index) => {\n if (row.length !== columnCount) {\n throw new Error(\n `renderTable: all rows must have the same number of columns (expected ${columnCount}, row ${index} has ${row.length}).`,\n );\n }\n });\n}\n\n/**\n * Renders a 2D array of values as a table using single-line Unicode box-drawing borders.\n * Column widths account for East Asian wide characters (measured per grapheme cluster,\n * so combining marks and ZWJ emoji sequences aren't overcounted, non-printing clusters\n * such as a lone joiner or combining mark measure as 0, and flags, keycaps, and\n * VS16-forced emoji presentation are measured as 2 columns) and strip ANSI SGR (color/style)\n * escape codes before measuring. Use this instead of importing a table-rendering package\n * directly.\n * @param data - Table rows; every row must have the same number of columns. Each cell is\n * stringified (`null`/`undefined` become an empty string rather than the literal text\n * \"null\"/\"undefined\"), may contain embedded newlines, has `\\r`/`\\r\\n` normalized to `\\n`,\n * has tabs expanded to spaces, and has other control characters stripped.\n * @param config - Rendering options\n * @returns The rendered table terminated with a trailing newline, or `\"\"` when there are no\n * rows or no columns to display\n */\nexport function renderTable(data: unknown[][], config: AsciiTableConfig = {}): string {\n const rows = data.map((row) => row.map(sanitizeCell));\n validateConsistentColumnCount(rows);\n\n const rowCount = rows.length;\n const columnCount = rows[0]?.length ?? 0;\n if (rowCount === 0 || columnCount === 0) {\n return \"\";\n }\n\n const rowsCellLines = rows.map((row) =>\n Array.from({ length: columnCount }, (_, col) => toCellLines(row[col] ?? \"\")),\n );\n const columnWidths = Array.from({ length: columnCount }, (_, col) =>\n maxOf(rowsCellLines.map((row) => maxOf((row[col] ?? []).map((line) => line.width)))),\n );\n\n const shouldDrawLine = (lineIndex: number): boolean =>\n config.singleLine\n ? lineIndex === 0 || lineIndex === rowCount\n : (config.drawHorizontalLine ?? (() => true))(lineIndex, rowCount);\n\n const lines: string[] = [];\n if (shouldDrawLine(0)) {\n lines.push(renderBorder(\"┌\", \"┬\", \"┐\", columnWidths));\n }\n\n rowsCellLines.forEach((cellLines, rowIndex) => {\n const rowHeight = maxOf(\n cellLines.map((columnLines) => columnLines.length),\n 1,\n );\n for (let line = 0; line < rowHeight; line++) {\n const cells = cellLines.map((columnLines, col) =>\n padCell(columnLines[line] ?? { text: \"\", width: 0 }, columnWidths[col] ?? 0),\n );\n lines.push(`│ ${cells.join(\" │ \")} │`);\n }\n if (rowIndex < rowCount - 1 && shouldDrawLine(rowIndex + 1)) {\n lines.push(renderBorder(\"├\", \"┼\", \"┤\", columnWidths));\n }\n });\n\n if (shouldDrawLine(rowCount)) {\n lines.push(renderBorder(\"└\", \"┴\", \"┘\", columnWidths));\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n","const TRUTHY_VALUES = new Set([\"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"]);\nconst FALSY_VALUES = new Set([\"false\", \"f\", \"no\", \"n\", \"off\", \"0\"]);\n\n/**\n * Parse a string value as a boolean.\n *\n * Recognized values (case-insensitive, trimmed) follow Python's\n * `distutils.util.strtobool` convention:\n * - truthy: `true, t, yes, y, on, 1`\n * - falsy: `false, f, no, n, off, 0`\n *\n * Undefined, empty strings, and unrecognized values return `undefined` so\n * that callers can fall back to their own defaults.\n * @param value - The input string (e.g. an environment variable or CLI flag value)\n * @returns `true`, `false`, or `undefined` when the value is unset or unrecognized\n */\nexport function parseBoolean(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined;\n const normalized = value.trim().toLowerCase();\n if (normalized === \"\") return undefined;\n if (TRUTHY_VALUES.has(normalized)) return true;\n if (FALSY_VALUES.has(normalized)) return false;\n return undefined;\n}\n","import { formatWithOptions, type InspectOptions } from \"node:util\";\nimport { color, renderFor } from \"@tailor-platform/shared/color\";\nimport { formatDistanceToNowStrict } from \"date-fns\";\nimport { renderTable } from \"./ascii-table\";\nimport { parseBoolean } from \"./parse-boolean\";\n\n/**\n * Error thrown when a prompt is attempted in a non-interactive environment\n */\nexport class CIPromptError extends Error {\n constructor(message?: string) {\n super(\n message ??\n \"Interactive prompts are not available in this environment. Provide the required options explicitly.\",\n );\n this.name = \"CIPromptError\";\n }\n}\n\n/**\n * Semantic style functions for inline text styling\n */\nexport const styles = {\n // Status colors\n success: color.green,\n error: color.red,\n warning: color.yellow,\n info: color.cyan,\n\n // Action colors (for change sets)\n create: color.green,\n update: color.yellow,\n delete: color.red,\n replace: color.magenta,\n unchanged: color.gray,\n\n // Emphasis\n bold: color.bold,\n dim: color.gray,\n highlight: color.cyanBright,\n successBright: color.greenBright,\n errorBright: color.redBright,\n\n // Resource types\n resourceType: color.bold,\n resourceName: color.cyan,\n\n // File paths\n path: color.cyan,\n\n // Values\n value: color.white,\n placeholder: (text: string) => color.italic(color.gray(text)),\n};\n\n/**\n * Standardized symbols for CLI output\n */\nexport const symbols = {\n success: styles.success(\"\\u2713\"),\n error: styles.error(\"\\u2716\"),\n warning: styles.warning(\"\\u26a0\"),\n info: styles.info(\"i\"),\n create: styles.create(\"+\"),\n update: styles.update(\"~\"),\n delete: styles.delete(\"-\"),\n replace: styles.replace(\"\\u00b1\"),\n bullet: styles.dim(\"\\u2022\"),\n arrow: styles.dim(\"\\u2192\"),\n};\n\n/**\n * Log output modes\n */\nexport type LogMode = \"default\" | \"stream\" | \"plain\";\n\nexport interface LogOptions {\n /** Output mode (default: \"default\") */\n mode?: LogMode;\n /** Number of spaces to indent the entire line (default: 0) */\n indent?: number;\n}\n\n/** Field transformer function. null excludes the field from table output. */\nexport type FieldTransformer = ((value: unknown, item: object) => string) | null;\n\nexport interface OutOptions {\n /** Table display field transform/exclude settings. Only applied in table mode (not JSON). */\n display?: Record<string, FieldTransformer>;\n\n /** Show null values in table output (default: false) */\n showNull?: boolean;\n}\n\n// In JSON mode, all logs go to stderr to keep stdout clean for JSON data\nlet _jsonMode = false;\nlet _verbose = false;\n\n// Values registered via `logger.registerSecret()`, redacted from diagnostic log output\nconst _secrets = new Set<string>();\nconst REDACTED_PLACEHOLDER = \"<redacted>\";\n// Below this length, a registered value is too likely to match unrelated text.\nconst MIN_SECRET_LENGTH = 4;\n\n/**\n * Aho-Corasick trie node. Indexed by individual UTF-16 code units (not Unicode code\n * points), matching how `string.indexOf`/`.slice` already index this file's strings — a\n * surrogate-pair character occupies two nodes, same as it occupies two `string` indices.\n */\ninterface TrieNode {\n children: Map<string, TrieNode>;\n fail: TrieNode;\n /** Secrets ending at this node, including those reached via `fail` links (precomputed). */\n outputs: string[];\n}\n\n/**\n * Builds a multi-pattern matcher for every registered secret, so `findSecretSpans` below\n * can find all of their occurrences in one pass over the text (`O(text.length + matches)`)\n * instead of scanning the full text once per registered secret. Rebuilt only when\n * `registerSecret` adds a genuinely new value (see `_automaton` below), so its\n * `O(total secret length)` construction cost is amortized across every log line redacted\n * while the secret set doesn't change.\n * @param secrets - Currently registered secrets\n * @returns Root of the built trie\n */\nfunction buildAutomaton(secrets: ReadonlySet<string>): TrieNode {\n const root: TrieNode = {\n children: new Map(),\n fail: undefined as unknown as TrieNode,\n outputs: [],\n };\n root.fail = root;\n\n for (const secret of secrets) {\n let node = root;\n for (let i = 0; i < secret.length; i++) {\n const ch = secret[i] as string;\n let next = node.children.get(ch);\n if (!next) {\n next = { children: new Map(), fail: root, outputs: [] };\n node.children.set(ch, next);\n }\n node = next;\n }\n node.outputs.push(secret);\n }\n\n // A head index instead of Array#shift(): shift() re-indexes every remaining element on\n // each call, which would make this loop quadratic in the number of trie nodes rather than\n // the linear BFS this is meant to be.\n const queue: TrieNode[] = [...root.children.values()];\n for (let head = 0; head < queue.length; head++) {\n const parent = queue[head] as TrieNode;\n for (const [ch, child] of parent.children) {\n let fail = parent.fail;\n while (fail !== root && !fail.children.has(ch)) fail = fail.fail;\n child.fail = fail.children.get(ch) ?? root;\n child.outputs = child.outputs.concat(child.fail.outputs);\n queue.push(child);\n }\n }\n return root;\n}\n\n// Cached automaton for the current `_secrets` contents; `null` means rebuild on next use.\n// Invalidated only when `registerSecret` actually grows `_secrets` (Set#add on an existing\n// value is a no-op), so re-registering an already-known secret never triggers a rebuild.\nlet _automaton: TrieNode | null = null;\n\nfunction getAutomaton(): TrieNode {\n _automaton ??= buildAutomaton(_secrets);\n return _automaton;\n}\n\n/**\n * Finds every occurrence of every registered secret in `text`, including overlapping ones,\n * in a single pass over `text` via the Aho-Corasick automaton.\n * @param text - Text to search\n * @returns Match spans as `[start, end)` pairs, in the order found\n */\nfunction findSecretSpans(text: string): Array<[start: number, end: number]> {\n const spans: Array<[start: number, end: number]> = [];\n const root = getAutomaton();\n let node = root;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i] as string;\n while (node !== root && !node.children.has(ch)) node = node.fail;\n node = node.children.get(ch) ?? root;\n for (const secret of node.outputs) {\n spans.push([i + 1 - secret.length, i + 1]);\n }\n }\n return spans;\n}\n\n/**\n * Redacts every registered secret from `text` in a single pass over the original text.\n *\n * Matches are found against the original text only - never against text a previous\n * replacement produced - and overlapping/adjacent matches (whether one secret contains\n * another, or two secrets merely cross, e.g. registering \"abcde\" and \"defghi\" against\n * \"abcdefghi\") are merged into one contiguous span before any substitution happens. This\n * avoids two failure modes an iterative \"replace one secret, then the next\" approach has:\n * a later secret re-matching inside a placeholder a previous replacement already inserted,\n * and a crossing (non-nested) overlap leaving a fragment of one secret unredacted.\n *\n * Idempotent: a match that falls inside an occurrence of `<redacted>` already present in\n * `text` is discarded rather than substituted again. Without this, calling this function\n * twice on the same text (which happens whenever something already redacted, such as a\n * `--json` error envelope, is later passed to a diagnostic log call) could corrupt the\n * placeholder itself if a registered secret happens to be one of its substrings (e.g. a\n * secret literally containing \"redact\").\n * @param text - Text to redact\n * @returns `text` with every registered secret occurrence replaced by `<redacted>`\n */\nexport function redactSecrets(text: string): string {\n if (_secrets.size === 0) return text;\n\n const protectedSpans: Array<[start: number, end: number]> = [];\n for (let from = 0, index: number; (index = text.indexOf(REDACTED_PLACEHOLDER, from)) !== -1;) {\n protectedSpans.push([index, index + REDACTED_PLACEHOLDER.length]);\n from = index + REDACTED_PLACEHOLDER.length;\n }\n\n // Only a match wholly inside a protected placeholder is discarded (it can only be the\n // placeholder's own text, e.g. a registered secret that is a substring of \"redacted\").\n // A match that merely overlaps one — extending outside it, e.g. a registered secret that\n // happens to be \"leak<redacted>\" — still has real secret content outside the placeholder\n // and must still be replaced.\n //\n // A registered secret wholly contained in the placeholder (up to and including a secret\n // equal to \"<redacted>\" itself) is indistinguishable from the placeholder in rendered\n // output either way: substituting REDACTED_PLACEHOLDER for text that already reads\n // REDACTED_PLACEHOLDER is a no-op. Discarding the match here (rather than \"fixing\" it to\n // substitute anyway) isn't a redaction gap — it just skips redundant work on text that's\n // already the safe, masked form.\n const spans = findSecretSpans(text).filter(\n ([start, end]) => !protectedSpans.some(([pStart, pEnd]) => start >= pStart && end <= pEnd),\n );\n if (spans.length === 0) return text;\n spans.sort(([a], [b]) => a - b);\n\n const merged: Array<[start: number, end: number]> = [];\n for (const span of spans) {\n const last = merged.at(-1);\n if (last && span[0] <= last[1]) {\n last[1] = Math.max(last[1], span[1]);\n } else {\n merged.push(span);\n }\n }\n\n let result = \"\";\n let cursor = 0;\n for (const [start, end] of merged) {\n result += text.slice(cursor, start) + REDACTED_PLACEHOLDER;\n cursor = end;\n }\n return result + text.slice(cursor);\n}\n\n/**\n * Reset the registered-secret redaction state. Used for testing.\n *\n * `_secrets` is process-lifetime, module-level state with no production unregister API\n * (a real process should never stop hiding a secret it once saw). Test files that call\n * `logger.registerSecret()` and run in a Vitest project with `isolate: false` share this\n * state across files, so a value registered in one file's test can still be redacted in an\n * unrelated later file's assertions unless cleared between tests.\n */\nexport function resetSecretRegistry(): void {\n _secrets.clear();\n _automaton = null;\n}\n\n// Type icons for log output\nconst TYPE_ICONS: Record<string, string> = {\n info: \"ℹ\",\n success: \"✔\",\n warn: \"⚠\",\n error: \"✖\",\n debug: \"⚙\",\n trace: \"→\",\n log: \"\",\n};\n\n// Color functions for icon and message text\nconst TYPE_COLORS: Record<string, (text: string) => string> = {\n info: styles.info,\n success: styles.success,\n warn: styles.warning,\n error: styles.error,\n debug: styles.dim,\n trace: styles.dim,\n log: (text) => text,\n};\n\ninterface FormatLogLineOptions {\n mode: string;\n indent: number;\n type: string;\n message: string;\n timestamp?: string;\n}\n\n/**\n * Formats a log line with the appropriate prefix and indentation\n * @param opts - Formatting options\n * @returns Formatted log line\n */\nexport function formatLogLine(opts: FormatLogLineOptions): string {\n const { mode, indent, type, message, timestamp } = opts;\n const indentPrefix = indent > 0 ? \" \".repeat(indent) : \"\";\n const colorFn = TYPE_COLORS[type] || ((text: string) => text);\n\n // Plain mode: color only, no icon, no timestamp\n if (mode === \"plain\") {\n return `${indentPrefix}${colorFn(message)}\\n`;\n }\n\n // Default/Stream mode: with icon and color\n const icon = TYPE_ICONS[type] || \"\";\n const prefix = icon ? `${icon} ` : \"\";\n const coloredOutput = colorFn(`${prefix}${message}`);\n const timestampPrefix = timestamp ?? \"\";\n\n return `${indentPrefix}${timestampPrefix}${coloredOutput}\\n`;\n}\n\n/**\n * Writes a formatted log line to stderr.\n * @param type - Log type (info, success, warn, error, log)\n * @param message - Log message\n * @param opts - Log options (mode and indent)\n */\nfunction writeLog(type: string, message: string, opts?: LogOptions): void {\n const mode = opts?.mode ?? \"default\";\n const indent = opts?.indent ?? 0;\n const inspectOpts: InspectOptions = {\n breakLength: process.stdout.columns || 80,\n };\n const formattedMessage = formatWithOptions(inspectOpts, message);\n const timestamp = mode === \"stream\" ? `${new Date().toLocaleTimeString()} ` : \"\";\n const output = formatLogLine({ mode, indent, type, message: formattedMessage, timestamp });\n process.stderr.write(renderFor(process.stderr, redactSecrets(output)));\n}\n\n/**\n * The CLI logger. Diagnostics go to stderr; `out()` writes primary output to\n * stdout as a table, or as JSON when `jsonMode` is on. `--json` and\n * `--verbose` feed the `jsonMode` / `verbose` state, which CLI plugins share\n * with the SDK code paths they call.\n */\nexport const logger = {\n get jsonMode(): boolean {\n return _jsonMode;\n },\n set jsonMode(value: boolean) {\n _jsonMode = value;\n },\n\n get verbose(): boolean {\n return _verbose || parseBoolean(process.env.DEBUG) === true || process.env.RUNNER_DEBUG === \"1\";\n },\n set verbose(value: boolean) {\n _verbose = value;\n },\n\n info(message: string, opts?: LogOptions): void {\n writeLog(\"info\", message, opts);\n },\n\n success(message: string, opts?: LogOptions): void {\n writeLog(\"success\", message, opts);\n },\n\n warn(message: string, opts?: LogOptions): void {\n writeLog(\"warn\", message, opts);\n },\n\n error(message: string, opts?: LogOptions): void {\n writeLog(\"error\", message, opts);\n },\n\n log(message: string): void {\n writeLog(\"log\", message, { mode: \"plain\" });\n },\n\n newline(): void {\n process.stderr.write(\"\\n\");\n },\n\n debug(message: string): void {\n if (logger.verbose) {\n writeLog(\"log\", styles.dim(message), { mode: \"plain\" });\n }\n },\n\n /**\n * Registers a value to be redacted from diagnostic log output (`info`/`success`/`warn`/\n * `error`/`log`/`debug`). Any occurrence of `value` — or of its JSON-string-escaped form\n * (so a value embedded in `JSON.stringify`d output, e.g. `--json` mode error envelopes, is\n * also caught) or its `application/x-www-form-urlencoded` form (so a value that reached the\n * process via a URL query string, e.g. an OAuth authorization code decoded from a callback\n * URL via `URLSearchParams`, is still caught if that same URL — still encoded — is later\n * echoed into a diagnostic message) — is replaced with `<redacted>` before it reaches\n * stderr. Does not affect `out()`, since some commands intentionally print secret values as\n * their primary result.\n *\n * Values shorter than 4 characters are ignored, since they are too likely to match\n * unrelated text. A non-string value (e.g. `undefined` from an unvalidated external\n * payload cast to a typed shape) is ignored the same way, rather than throwing, since a\n * logging call must never be what crashes the process.\n * @param value - The secret value to redact from future log output\n */\n registerSecret(value: string): void {\n // Counts Unicode code points, not UTF-16 code units, so a value made of surrogate-pair\n // characters (e.g. emoji) isn't undercounted as longer than it actually is.\n if (typeof value !== \"string\" || [...value].length < MIN_SECRET_LENGTH) return;\n const sizeBefore = _secrets.size;\n _secrets.add(value);\n const jsonEscaped = JSON.stringify(value).slice(1, -1);\n if (jsonEscaped !== value) _secrets.add(jsonEscaped);\n // Uses URLSearchParams rather than encodeURIComponent: form-urlencoding (what\n // URLSearchParams produces, and what a URL query string actually contains) encodes a\n // space as \"+\", not \"%20\", and unlike encodeURIComponent it never throws on a lone\n // surrogate (invalid UTF-16) — it substitutes U+FFFD instead, matching how the URL\n // itself would already have encoded that same malformed input.\n const formEncoded = new URLSearchParams([[\"v\", value]]).toString().slice(2);\n if (formEncoded !== value) _secrets.add(formEncoded);\n // Set#add on an already-registered value is a no-op, so this only invalidates the\n // cached automaton (see findSecretSpans) when a genuinely new secret was added.\n if (_secrets.size !== sizeBefore) _automaton = null;\n },\n\n out(data: string | object | object[], options?: OutOptions): void {\n if (typeof data === \"string\") {\n process.stdout.write(renderFor(process.stdout, data.endsWith(\"\\n\") ? data : data + \"\\n\"));\n return;\n }\n\n if (this.jsonMode) {\n // eslint-disable-next-line no-restricted-syntax\n console.log(JSON.stringify(data));\n return;\n }\n\n const display = options?.display;\n\n // Helper to format a value for table display\n const formatValue = (value: unknown, pretty = false): string => {\n if (options?.showNull && value === null) return \"NULL\";\n if (value === null || value === undefined) return \"N/A\";\n if (value instanceof Date) {\n return formatDistanceToNowStrict(value, { addSuffix: true });\n }\n if (typeof value === \"object\") {\n return pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);\n }\n return String(value);\n };\n\n // Helper to check if field should be excluded\n const isExcluded = (key: string): boolean => {\n return display !== undefined && key in display && display[key] === null;\n };\n\n // Helper to apply transformer or default formatting\n const transformValue = (key: string, value: unknown, item: object, pretty = false): string => {\n if (display && key in display) {\n const transformer = display[key];\n if (transformer) {\n return transformer(value, item);\n }\n }\n return formatValue(value, pretty);\n };\n\n if (!Array.isArray(data)) {\n const entries = Object.entries(data).filter(([key]) => !isExcluded(key));\n const formattedEntries = entries.map(([key, value]) => [\n key,\n transformValue(key, value, data, true),\n ]);\n const t = renderTable(formattedEntries, { singleLine: false });\n process.stdout.write(renderFor(process.stdout, t));\n return;\n }\n\n if (data.length === 0) {\n return;\n }\n\n const allHeaders = Array.from(new Set(data.flatMap((item) => Object.keys(item))));\n const headers = allHeaders.filter((h) => !isExcluded(h));\n if (headers.length === 0) {\n return;\n }\n const rows = data.map((item) =>\n headers.map((header) =>\n transformValue(header, (item as Record<string, unknown>)[header], item),\n ),\n );\n\n const t = renderTable([headers, ...rows], {\n drawHorizontalLine: (lineIndex, rowCount) => {\n return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount;\n },\n });\n process.stdout.write(renderFor(process.stdout, t));\n },\n};\n"],"mappings":"sMAOA,MAAM,MACH,GACA,GACC,EAAU,EAAM,EAAM,CAAE,eAAgB,EAAM,CAAC,EAOtC,EAAQ,CACnB,KAAM,MAAM,MAAM,EAClB,IAAK,MAAM,KAAK,EAChB,OAAQ,MAAM,QAAQ,EACtB,KAAM,MAAM,MAAM,EAClB,MAAO,MAAM,OAAO,EACpB,IAAK,MAAM,KAAK,EAChB,MAAO,MAAM,OAAO,EACpB,OAAQ,MAAM,QAAQ,EACtB,KAAM,MAAM,MAAM,EAClB,QAAS,MAAM,SAAS,EACxB,UAAW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AAO,EAAY,EAAO,CAAI,CAElC,CACA,OAAO,YAAY,EAAO,CAAM,CAClC,EAEA,GAAI,CAAC,MAAM,QAAQ,CAAI,EAAG,CAMxB,IAAM,EAAI,YALM,OAAO,QAAQ,CAAI,CAAC,CAAC,QAAQ,CAAC,KAAS,CAAC,WAAW,CAAG,CACvC,CAAC,CAAC,KAAK,CAAC,EAAK,KAAW,CACrD,EACA,eAAe,EAAK,EAAO,EAAM,EAAI,CACvC,CACsB,EAAkB,CAAE,WAAY,EAAM,CAAC,EAC7D,QAAQ,OAAO,MAAM,UAAU,QAAQ,OAAQ,CAAC,CAAC,EACjD,MACF,CAEA,GAAI,EAAK,SAAW,EAClB,OAIF,IAAM,EADa,MAAM,KAAK,IAAI,IAAI,EAAK,QAAS,GAAS,OAAO,KAAK,CAAI,CAAC,CAAC,CACtD,CAAC,CAAC,OAAQ,GAAM,CAAC,WAAW,CAAC,CAAC,EACvD,GAAI,EAAQ,SAAW,EACrB,OAQF,IAAM,EAAI,YAAY,CAAC,EAAS,GANnB,EAAK,IAAK,GACrB,EAAQ,IAAK,GACX,eAAe,EAAS,EAAiC,GAAS,CAAI,CACxE,CAGiC,CAAI,EAAG,CACxC,oBAAqB,EAAW,IACvB,IAAc,GAAK,IAAc,GAAK,IAAc,CAE/D,CAAC,EACD,QAAQ,OAAO,MAAM,UAAU,QAAQ,OAAQ,CAAC,CAAC,CACnD,CACF"}
1
+ {"version":3,"file":"logger-Cp5U2IDI.mjs","names":[],"sources":["../../shared/src/color.ts","../src/cli/shared/ascii-table.ts","../src/cli/shared/parse-boolean.ts","../src/cli/shared/logger.ts"],"sourcesContent":["import { stripVTControlCharacters, styleText } from \"node:util\";\n\n/** Applies a style to text */\nexport type StyleFn = (text: string) => string;\n\ntype StyleName = Exclude<Parameters<typeof styleText>[0], readonly unknown[] | unknown[]>;\n\nconst style =\n (name: StyleName): StyleFn =>\n (text) =>\n styleText(name, text, { validateStream: false });\n\n/**\n * Style functions by name, so call sites read `color.bold(text)`. Styling is\n * always applied; `renderFor` drops it again when the destination stream has no\n * color support. Add a name here when a package needs one that is not listed.\n */\nexport const color = {\n bold: style(\"bold\"),\n dim: style(\"dim\"),\n italic: style(\"italic\"),\n gray: style(\"gray\"),\n white: style(\"white\"),\n red: style(\"red\"),\n green: style(\"green\"),\n yellow: style(\"yellow\"),\n cyan: style(\"cyan\"),\n magenta: style(\"magenta\"),\n redBright: style(\"redBright\"),\n greenBright: style(\"greenBright\"),\n cyanBright: style(\"cyanBright\"),\n};\n\n// Node's rules for whether a destination gets colors, applied by hand. Asking\n// styleText instead would be shorter but only correct on Node: Bun ignores both\n// the stream option and NO_COLOR (reproduced on 1.3.14), so it reports every\n// destination as color-capable and escapes end up in redirected output.\n//\n// FORCE_COLOR decides on its own when set, which is how CI keeps colors through\n// a pipe. NO_COLOR counts as set at any non-empty value, \"0\" included.\nconst supportsColor = (stream: NodeJS.WriteStream): boolean => {\n const forced = process.env.FORCE_COLOR;\n if (forced !== undefined) return forced !== \"0\" && forced !== \"false\";\n if (process.env.NODE_DISABLE_COLORS !== undefined) return false;\n if ((process.env.NO_COLOR ?? \"\") !== \"\") return false;\n if (process.env.TERM === \"dumb\") return false;\n return stream.isTTY === true;\n};\n\n/**\n * Prepares styled text for the stream it is written to.\n * @param stream - Stream the text is written to\n * @param text - Styled text\n * @returns Text with styling removed when the stream has no color support\n */\nexport function renderFor(stream: NodeJS.WriteStream, text: string): string {\n return supportsColor(stream) ? text : stripVTControlCharacters(text);\n}\n","import { eastAsianWidth } from \"get-east-asian-width\";\n\n// eslint-disable-next-line no-control-regex\nconst ANSI_ESCAPE_PATTERN = /\\x1b\\[[0-9;]*m/g;\nconst CARRIAGE_RETURN_PATTERN = /\\r\\n?/g;\n\nconst graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\n\nexport interface AsciiTableConfig {\n /** Suppress horizontal lines between rows, keeping only the outer border. */\n singleLine?: boolean;\n /** Decide whether to draw the horizontal line at `lineIndex` (range `[0, rowCount]` inclusive). */\n drawHorizontalLine?: (lineIndex: number, rowCount: number) => boolean;\n}\n\ninterface CellLine {\n text: string;\n width: number;\n}\n\nfunction maxOf(values: number[], fallback = 0): number {\n return values.reduce((max, value) => (value > max ? value : max), fallback);\n}\n\nconst TAB_WIDTH = 8;\n\nfunction isStrippableControlCharacter(char: string): boolean {\n const codePoint = char.codePointAt(0) ?? 0;\n if (char === \"\\n\") {\n return false;\n }\n return codePoint <= 0x1f || codePoint === 0x7f;\n}\n\n// Only SGR (color/style) escape sequences are meant to survive; a bare ESC\n// that isn't part of a recognized SGR sequence (e.g. a screen-clear CSI\n// sequence, or a BEL-terminated OSC sequence) is treated like any other\n// control character below and stripped, rather than passed through to the\n// terminal or left with its terminator removed.\nfunction normalizeControlCharacters(value: string): string {\n const sgrSequences = value.match(ANSI_ESCAPE_PATTERN) ?? [];\n return value\n .split(ANSI_ESCAPE_PATTERN)\n .map((segment) => {\n const chars: string[] = [];\n for (const char of segment) {\n if (char === \"\\t\") {\n chars.push(\" \".repeat(TAB_WIDTH));\n } else if (!isStrippableControlCharacter(char)) {\n chars.push(char);\n }\n }\n return chars.join(\"\");\n })\n .reduce((result, segment, i) => result + segment + (sgrSequences[i] ?? \"\"), \"\");\n}\n\nfunction sanitizeCell(cell: unknown): string {\n return normalizeControlCharacters(String(cell ?? \"\").replace(CARRIAGE_RETURN_PATTERN, \"\\n\"));\n}\n\n// Clusters made up entirely of non-printing code points (lone joiners,\n// variation selectors, combining marks, etc.) render with no visible glyph.\nconst ZERO_WIDTH_CLUSTER_PATTERN =\n /^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Nonspacing_Mark}|\\p{Enclosing_Mark}|\\p{Surrogate})+$/v;\n// RGI_Emoji covers flags, keycaps, and VS16-forced presentation sequences,\n// which render as 2 columns in terminals even though their first code point\n// alone would measure as narrow/neutral.\nconst RGI_EMOJI_PATTERN = /^\\p{RGI_Emoji}$/v;\n\nfunction displayWidth(value: string): number {\n let width = 0;\n for (const { segment } of graphemeSegmenter.segment(value.replace(ANSI_ESCAPE_PATTERN, \"\"))) {\n if (ZERO_WIDTH_CLUSTER_PATTERN.test(segment)) {\n continue;\n }\n if (RGI_EMOJI_PATTERN.test(segment)) {\n width += 2;\n continue;\n }\n const codePoint = segment.codePointAt(0);\n width += codePoint === undefined ? 0 : eastAsianWidth(codePoint);\n }\n return width;\n}\n\nfunction toCellLines(cell: string): CellLine[] {\n return cell.split(\"\\n\").map((text) => ({ text, width: displayWidth(text) }));\n}\n\nfunction padCell(cellLine: CellLine, width: number): string {\n return cellLine.text + \" \".repeat(Math.max(0, width - cellLine.width));\n}\n\nfunction renderBorder(left: string, join: string, right: string, columnWidths: number[]): string {\n return left + columnWidths.map((width) => \"─\".repeat(width + 2)).join(join) + right;\n}\n\nfunction validateConsistentColumnCount(rows: string[][]): void {\n const columnCount = rows[0]?.length;\n if (columnCount === undefined) {\n return;\n }\n rows.forEach((row, index) => {\n if (row.length !== columnCount) {\n throw new Error(\n `renderTable: all rows must have the same number of columns (expected ${columnCount}, row ${index} has ${row.length}).`,\n );\n }\n });\n}\n\n/**\n * Renders a 2D array of values as a table using single-line Unicode box-drawing borders.\n * Column widths account for East Asian wide characters (measured per grapheme cluster,\n * so combining marks and ZWJ emoji sequences aren't overcounted, non-printing clusters\n * such as a lone joiner or combining mark measure as 0, and flags, keycaps, and\n * VS16-forced emoji presentation are measured as 2 columns) and strip ANSI SGR (color/style)\n * escape codes before measuring. Use this instead of importing a table-rendering package\n * directly.\n * @param data - Table rows; every row must have the same number of columns. Each cell is\n * stringified (`null`/`undefined` become an empty string rather than the literal text\n * \"null\"/\"undefined\"), may contain embedded newlines, has `\\r`/`\\r\\n` normalized to `\\n`,\n * has tabs expanded to spaces, and has other control characters stripped.\n * @param config - Rendering options\n * @returns The rendered table terminated with a trailing newline, or `\"\"` when there are no\n * rows or no columns to display\n */\nexport function renderTable(data: unknown[][], config: AsciiTableConfig = {}): string {\n const rows = data.map((row) => row.map(sanitizeCell));\n validateConsistentColumnCount(rows);\n\n const rowCount = rows.length;\n const columnCount = rows[0]?.length ?? 0;\n if (rowCount === 0 || columnCount === 0) {\n return \"\";\n }\n\n const rowsCellLines = rows.map((row) =>\n Array.from({ length: columnCount }, (_, col) => toCellLines(row[col] ?? \"\")),\n );\n const columnWidths = Array.from({ length: columnCount }, (_, col) =>\n maxOf(rowsCellLines.map((row) => maxOf((row[col] ?? []).map((line) => line.width)))),\n );\n\n const shouldDrawLine = (lineIndex: number): boolean =>\n config.singleLine\n ? lineIndex === 0 || lineIndex === rowCount\n : (config.drawHorizontalLine ?? (() => true))(lineIndex, rowCount);\n\n const lines: string[] = [];\n if (shouldDrawLine(0)) {\n lines.push(renderBorder(\"┌\", \"┬\", \"┐\", columnWidths));\n }\n\n rowsCellLines.forEach((cellLines, rowIndex) => {\n const rowHeight = maxOf(\n cellLines.map((columnLines) => columnLines.length),\n 1,\n );\n for (let line = 0; line < rowHeight; line++) {\n const cells = cellLines.map((columnLines, col) =>\n padCell(columnLines[line] ?? { text: \"\", width: 0 }, columnWidths[col] ?? 0),\n );\n lines.push(`│ ${cells.join(\" │ \")} │`);\n }\n if (rowIndex < rowCount - 1 && shouldDrawLine(rowIndex + 1)) {\n lines.push(renderBorder(\"├\", \"┼\", \"┤\", columnWidths));\n }\n });\n\n if (shouldDrawLine(rowCount)) {\n lines.push(renderBorder(\"└\", \"┴\", \"┘\", columnWidths));\n }\n\n return `${lines.join(\"\\n\")}\\n`;\n}\n","const TRUTHY_VALUES = new Set([\"true\", \"t\", \"yes\", \"y\", \"on\", \"1\"]);\nconst FALSY_VALUES = new Set([\"false\", \"f\", \"no\", \"n\", \"off\", \"0\"]);\n\n/**\n * Parse a string value as a boolean.\n *\n * Recognized values (case-insensitive, trimmed) follow Python's\n * `distutils.util.strtobool` convention:\n * - truthy: `true, t, yes, y, on, 1`\n * - falsy: `false, f, no, n, off, 0`\n *\n * Undefined, empty strings, and unrecognized values return `undefined` so\n * that callers can fall back to their own defaults.\n * @param value - The input string (e.g. an environment variable or CLI flag value)\n * @returns `true`, `false`, or `undefined` when the value is unset or unrecognized\n */\nexport function parseBoolean(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined;\n const normalized = value.trim().toLowerCase();\n if (normalized === \"\") return undefined;\n if (TRUTHY_VALUES.has(normalized)) return true;\n if (FALSY_VALUES.has(normalized)) return false;\n return undefined;\n}\n","import { formatWithOptions, type InspectOptions } from \"node:util\";\nimport { color, renderFor } from \"@tailor-platform/shared/color\";\nimport { formatDistanceToNowStrict } from \"date-fns\";\nimport { renderTable } from \"./ascii-table\";\nimport { parseBoolean } from \"./parse-boolean\";\n\n/**\n * Error thrown when a prompt is attempted in a non-interactive environment\n */\nexport class CIPromptError extends Error {\n constructor(message?: string) {\n super(\n message ??\n \"Interactive prompts are not available in this environment. Provide the required options explicitly.\",\n );\n this.name = \"CIPromptError\";\n }\n}\n\n/**\n * Semantic style functions for inline text styling\n */\nexport const styles = {\n // Status colors\n success: color.green,\n error: color.red,\n warning: color.yellow,\n info: color.cyan,\n\n // Action colors (for change sets)\n create: color.green,\n update: color.yellow,\n delete: color.red,\n replace: color.magenta,\n unchanged: color.gray,\n\n // Emphasis\n bold: color.bold,\n dim: color.gray,\n highlight: color.cyanBright,\n successBright: color.greenBright,\n errorBright: color.redBright,\n\n // Resource types\n resourceType: color.bold,\n resourceName: color.cyan,\n\n // File paths\n path: color.cyan,\n\n // Values\n value: color.white,\n placeholder: (text: string) => color.italic(color.gray(text)),\n};\n\n/**\n * Standardized symbols for CLI output\n */\nexport const symbols = {\n success: styles.success(\"\\u2713\"),\n error: styles.error(\"\\u2716\"),\n warning: styles.warning(\"\\u26a0\"),\n info: styles.info(\"i\"),\n create: styles.create(\"+\"),\n update: styles.update(\"~\"),\n delete: styles.delete(\"-\"),\n replace: styles.replace(\"\\u00b1\"),\n bullet: styles.dim(\"\\u2022\"),\n arrow: styles.dim(\"\\u2192\"),\n};\n\n/**\n * Log output modes\n */\nexport type LogMode = \"default\" | \"stream\" | \"plain\";\n\nexport interface LogOptions {\n /** Output mode (default: \"default\") */\n mode?: LogMode;\n /** Number of spaces to indent the entire line (default: 0) */\n indent?: number;\n}\n\n/** Field transformer function. null excludes the field from table output. */\nexport type FieldTransformer = ((value: unknown, item: object) => string) | null;\n\nexport interface OutOptions {\n /** Table display field transform/exclude settings. Only applied in table mode (not JSON). */\n display?: Record<string, FieldTransformer>;\n\n /** Show null values in table output (default: false) */\n showNull?: boolean;\n}\n\n// In JSON mode, all logs go to stderr to keep stdout clean for JSON data\nlet _jsonMode = false;\nlet _verbose = false;\n\n// Values registered via `logger.registerSecret()`, redacted from diagnostic log output\nconst _secrets = new Set<string>();\nconst REDACTED_PLACEHOLDER = \"<redacted>\";\n// Below this length, a registered value is too likely to match unrelated text.\nconst MIN_SECRET_LENGTH = 4;\n\n/**\n * Aho-Corasick trie node. Indexed by individual UTF-16 code units (not Unicode code\n * points), matching how `string.indexOf`/`.slice` already index this file's strings — a\n * surrogate-pair character occupies two nodes, same as it occupies two `string` indices.\n */\ninterface TrieNode {\n children: Map<string, TrieNode>;\n fail: TrieNode;\n /** Secrets ending at this node, including those reached via `fail` links (precomputed). */\n outputs: string[];\n}\n\n/**\n * Builds a multi-pattern matcher for every registered secret, so `findSecretSpans` below\n * can find all of their occurrences in one pass over the text (`O(text.length + matches)`)\n * instead of scanning the full text once per registered secret. Rebuilt only when\n * `registerSecret` adds a genuinely new value (see `_automaton` below), so its\n * `O(total secret length)` construction cost is amortized across every log line redacted\n * while the secret set doesn't change.\n * @param secrets - Currently registered secrets\n * @returns Root of the built trie\n */\nfunction buildAutomaton(secrets: ReadonlySet<string>): TrieNode {\n const root: TrieNode = {\n children: new Map(),\n fail: undefined as unknown as TrieNode,\n outputs: [],\n };\n root.fail = root;\n\n for (const secret of secrets) {\n let node = root;\n for (let i = 0; i < secret.length; i++) {\n const ch = secret[i] as string;\n let next = node.children.get(ch);\n if (!next) {\n next = { children: new Map(), fail: root, outputs: [] };\n node.children.set(ch, next);\n }\n node = next;\n }\n node.outputs.push(secret);\n }\n\n // A head index instead of Array#shift(): shift() re-indexes every remaining element on\n // each call, which would make this loop quadratic in the number of trie nodes rather than\n // the linear BFS this is meant to be.\n const queue: TrieNode[] = [...root.children.values()];\n for (let head = 0; head < queue.length; head++) {\n const parent = queue[head] as TrieNode;\n for (const [ch, child] of parent.children) {\n let fail = parent.fail;\n while (fail !== root && !fail.children.has(ch)) fail = fail.fail;\n child.fail = fail.children.get(ch) ?? root;\n child.outputs = child.outputs.concat(child.fail.outputs);\n queue.push(child);\n }\n }\n return root;\n}\n\n// Cached automaton for the current `_secrets` contents; `null` means rebuild on next use.\n// Invalidated only when `registerSecret` actually grows `_secrets` (Set#add on an existing\n// value is a no-op), so re-registering an already-known secret never triggers a rebuild.\nlet _automaton: TrieNode | null = null;\n\nfunction getAutomaton(): TrieNode {\n _automaton ??= buildAutomaton(_secrets);\n return _automaton;\n}\n\n/**\n * Finds every occurrence of every registered secret in `text`, including overlapping ones,\n * in a single pass over `text` via the Aho-Corasick automaton.\n * @param text - Text to search\n * @returns Match spans as `[start, end)` pairs, in the order found\n */\nfunction findSecretSpans(text: string): Array<[start: number, end: number]> {\n const spans: Array<[start: number, end: number]> = [];\n const root = getAutomaton();\n let node = root;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i] as string;\n while (node !== root && !node.children.has(ch)) node = node.fail;\n node = node.children.get(ch) ?? root;\n for (const secret of node.outputs) {\n spans.push([i + 1 - secret.length, i + 1]);\n }\n }\n return spans;\n}\n\n/**\n * Redacts every registered secret from `text` in a single pass over the original text.\n *\n * Matches are found against the original text only - never against text a previous\n * replacement produced - and overlapping/adjacent matches (whether one secret contains\n * another, or two secrets merely cross, e.g. registering \"abcde\" and \"defghi\" against\n * \"abcdefghi\") are merged into one contiguous span before any substitution happens. This\n * avoids two failure modes an iterative \"replace one secret, then the next\" approach has:\n * a later secret re-matching inside a placeholder a previous replacement already inserted,\n * and a crossing (non-nested) overlap leaving a fragment of one secret unredacted.\n *\n * Idempotent: a match that falls inside an occurrence of `<redacted>` already present in\n * `text` is discarded rather than substituted again. Without this, calling this function\n * twice on the same text (which happens whenever something already redacted, such as a\n * `--json` error envelope, is later passed to a diagnostic log call) could corrupt the\n * placeholder itself if a registered secret happens to be one of its substrings (e.g. a\n * secret literally containing \"redact\").\n * @param text - Text to redact\n * @returns `text` with every registered secret occurrence replaced by `<redacted>`\n */\nexport function redactSecrets(text: string): string {\n if (_secrets.size === 0) return text;\n\n const protectedSpans: Array<[start: number, end: number]> = [];\n for (let from = 0, index: number; (index = text.indexOf(REDACTED_PLACEHOLDER, from)) !== -1;) {\n protectedSpans.push([index, index + REDACTED_PLACEHOLDER.length]);\n from = index + REDACTED_PLACEHOLDER.length;\n }\n\n // Only a match wholly inside a protected placeholder is discarded (it can only be the\n // placeholder's own text, e.g. a registered secret that is a substring of \"redacted\").\n // A match that merely overlaps one — extending outside it, e.g. a registered secret that\n // happens to be \"leak<redacted>\" — still has real secret content outside the placeholder\n // and must still be replaced.\n //\n // A registered secret wholly contained in the placeholder (up to and including a secret\n // equal to \"<redacted>\" itself) is indistinguishable from the placeholder in rendered\n // output either way: substituting REDACTED_PLACEHOLDER for text that already reads\n // REDACTED_PLACEHOLDER is a no-op. Discarding the match here (rather than \"fixing\" it to\n // substitute anyway) isn't a redaction gap — it just skips redundant work on text that's\n // already the safe, masked form.\n const spans = findSecretSpans(text).filter(\n ([start, end]) => !protectedSpans.some(([pStart, pEnd]) => start >= pStart && end <= pEnd),\n );\n if (spans.length === 0) return text;\n spans.sort(([a], [b]) => a - b);\n\n const merged: Array<[start: number, end: number]> = [];\n for (const span of spans) {\n const last = merged.at(-1);\n if (last && span[0] <= last[1]) {\n last[1] = Math.max(last[1], span[1]);\n } else {\n merged.push(span);\n }\n }\n\n let result = \"\";\n let cursor = 0;\n for (const [start, end] of merged) {\n result += text.slice(cursor, start) + REDACTED_PLACEHOLDER;\n cursor = end;\n }\n return result + text.slice(cursor);\n}\n\n/**\n * Reset the registered-secret redaction state. Used for testing.\n *\n * `_secrets` is process-lifetime, module-level state with no production unregister API\n * (a real process should never stop hiding a secret it once saw). Test files that call\n * `logger.registerSecret()` and run in a Vitest project with `isolate: false` share this\n * state across files, so a value registered in one file's test can still be redacted in an\n * unrelated later file's assertions unless cleared between tests.\n */\nexport function resetSecretRegistry(): void {\n _secrets.clear();\n _automaton = null;\n}\n\n// Type icons for log output\nconst TYPE_ICONS: Record<string, string> = {\n info: \"ℹ\",\n success: \"✔\",\n warn: \"⚠\",\n error: \"✖\",\n debug: \"⚙\",\n trace: \"→\",\n log: \"\",\n};\n\n// Color functions for icon and message text\nconst TYPE_COLORS: Record<string, (text: string) => string> = {\n info: styles.info,\n success: styles.success,\n warn: styles.warning,\n error: styles.error,\n debug: styles.dim,\n trace: styles.dim,\n log: (text) => text,\n};\n\ninterface FormatLogLineOptions {\n mode: string;\n indent: number;\n type: string;\n message: string;\n timestamp?: string;\n}\n\n/**\n * Formats a log line with the appropriate prefix and indentation\n * @param opts - Formatting options\n * @returns Formatted log line\n */\nexport function formatLogLine(opts: FormatLogLineOptions): string {\n const { mode, indent, type, message, timestamp } = opts;\n const indentPrefix = indent > 0 ? \" \".repeat(indent) : \"\";\n const colorFn = TYPE_COLORS[type] || ((text: string) => text);\n\n // Plain mode: color only, no icon, no timestamp\n if (mode === \"plain\") {\n return `${indentPrefix}${colorFn(message)}\\n`;\n }\n\n // Default/Stream mode: with icon and color\n const icon = TYPE_ICONS[type] || \"\";\n const prefix = icon ? `${icon} ` : \"\";\n const coloredOutput = colorFn(`${prefix}${message}`);\n const timestampPrefix = timestamp ?? \"\";\n\n return `${indentPrefix}${timestampPrefix}${coloredOutput}\\n`;\n}\n\n/**\n * Writes a formatted log line to stderr.\n * @param type - Log type (info, success, warn, error, log)\n * @param message - Log message\n * @param opts - Log options (mode and indent)\n */\nfunction writeLog(type: string, message: string, opts?: LogOptions): void {\n const mode = opts?.mode ?? \"default\";\n const indent = opts?.indent ?? 0;\n const inspectOpts: InspectOptions = {\n breakLength: process.stdout.columns || 80,\n };\n const formattedMessage = formatWithOptions(inspectOpts, message);\n const timestamp = mode === \"stream\" ? `${new Date().toLocaleTimeString()} ` : \"\";\n const output = formatLogLine({ mode, indent, type, message: formattedMessage, timestamp });\n process.stderr.write(renderFor(process.stderr, redactSecrets(output)));\n}\n\n/**\n * The CLI logger. Diagnostics go to stderr; `out()` writes primary output to\n * stdout as a table, or as JSON when `jsonMode` is on. `--json` and\n * `--verbose` feed the `jsonMode` / `verbose` state, which CLI plugins share\n * with the SDK code paths they call.\n */\nexport const logger = {\n get jsonMode(): boolean {\n return _jsonMode;\n },\n set jsonMode(value: boolean) {\n _jsonMode = value;\n },\n\n get verbose(): boolean {\n return _verbose || parseBoolean(process.env.DEBUG) === true || process.env.RUNNER_DEBUG === \"1\";\n },\n set verbose(value: boolean) {\n _verbose = value;\n },\n\n info(message: string, opts?: LogOptions): void {\n writeLog(\"info\", message, opts);\n },\n\n success(message: string, opts?: LogOptions): void {\n writeLog(\"success\", message, opts);\n },\n\n warn(message: string, opts?: LogOptions): void {\n writeLog(\"warn\", message, opts);\n },\n\n error(message: string, opts?: LogOptions): void {\n writeLog(\"error\", message, opts);\n },\n\n log(message: string): void {\n writeLog(\"log\", message, { mode: \"plain\" });\n },\n\n newline(): void {\n process.stderr.write(\"\\n\");\n },\n\n debug(message: string): void {\n if (logger.verbose) {\n writeLog(\"log\", styles.dim(message), { mode: \"plain\" });\n }\n },\n\n /**\n * Registers a value to be redacted from diagnostic log output (`info`/`success`/`warn`/\n * `error`/`log`/`debug`). Any occurrence of `value` — or of its JSON-string-escaped form\n * (so a value embedded in `JSON.stringify`d output, e.g. `--json` mode error envelopes, is\n * also caught) or its `application/x-www-form-urlencoded` form (so a value that reached the\n * process via a URL query string, e.g. an OAuth authorization code decoded from a callback\n * URL via `URLSearchParams`, is still caught if that same URL — still encoded — is later\n * echoed into a diagnostic message) — is replaced with `<redacted>` before it reaches\n * stderr. Does not affect `out()`, since some commands intentionally print secret values as\n * their primary result.\n *\n * Values shorter than 4 characters are ignored, since they are too likely to match\n * unrelated text. A non-string value (e.g. `undefined` from an unvalidated external\n * payload cast to a typed shape) is ignored the same way, rather than throwing, since a\n * logging call must never be what crashes the process.\n * @param value - The secret value to redact from future log output\n */\n registerSecret(value: string): void {\n // Counts Unicode code points, not UTF-16 code units, so a value made of surrogate-pair\n // characters (e.g. emoji) isn't undercounted as longer than it actually is.\n if (typeof value !== \"string\" || [...value].length < MIN_SECRET_LENGTH) return;\n const sizeBefore = _secrets.size;\n _secrets.add(value);\n const jsonEscaped = JSON.stringify(value).slice(1, -1);\n if (jsonEscaped !== value) _secrets.add(jsonEscaped);\n // Uses URLSearchParams rather than encodeURIComponent: form-urlencoding (what\n // URLSearchParams produces, and what a URL query string actually contains) encodes a\n // space as \"+\", not \"%20\", and unlike encodeURIComponent it never throws on a lone\n // surrogate (invalid UTF-16) — it substitutes U+FFFD instead, matching how the URL\n // itself would already have encoded that same malformed input.\n const formEncoded = new URLSearchParams([[\"v\", value]]).toString().slice(2);\n if (formEncoded !== value) _secrets.add(formEncoded);\n // Set#add on an already-registered value is a no-op, so this only invalidates the\n // cached automaton (see findSecretSpans) when a genuinely new secret was added.\n if (_secrets.size !== sizeBefore) _automaton = null;\n },\n\n out(data: string | object | object[], options?: OutOptions): void {\n if (typeof data === \"string\") {\n process.stdout.write(renderFor(process.stdout, data.endsWith(\"\\n\") ? data : data + \"\\n\"));\n return;\n }\n\n if (this.jsonMode) {\n // eslint-disable-next-line no-restricted-syntax\n console.log(JSON.stringify(data));\n return;\n }\n\n const display = options?.display;\n\n // Helper to format a value for table display\n const formatValue = (value: unknown, pretty = false): string => {\n if (options?.showNull && value === null) return \"NULL\";\n if (value === null || value === undefined) return \"N/A\";\n if (value instanceof Date) {\n return formatDistanceToNowStrict(value, { addSuffix: true });\n }\n if (typeof value === \"object\") {\n return pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value);\n }\n return String(value);\n };\n\n // Helper to check if field should be excluded\n const isExcluded = (key: string): boolean => {\n return display !== undefined && key in display && display[key] === null;\n };\n\n // Helper to apply transformer or default formatting\n const transformValue = (key: string, value: unknown, item: object, pretty = false): string => {\n if (display && key in display) {\n const transformer = display[key];\n if (transformer) {\n return transformer(value, item);\n }\n }\n return formatValue(value, pretty);\n };\n\n if (!Array.isArray(data)) {\n const entries = Object.entries(data).filter(([key]) => !isExcluded(key));\n const formattedEntries = entries.map(([key, value]) => [\n key,\n transformValue(key, value, data, true),\n ]);\n const t = renderTable(formattedEntries, { singleLine: false });\n process.stdout.write(renderFor(process.stdout, t));\n return;\n }\n\n if (data.length === 0) {\n return;\n }\n\n const allHeaders = Array.from(new Set(data.flatMap((item) => Object.keys(item))));\n const headers = allHeaders.filter((h) => !isExcluded(h));\n if (headers.length === 0) {\n return;\n }\n const rows = data.map((item) =>\n headers.map((header) =>\n transformValue(header, (item as Record<string, unknown>)[header], item),\n ),\n );\n\n const t = renderTable([headers, ...rows], {\n drawHorizontalLine: (lineIndex, rowCount) => {\n return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount;\n },\n });\n process.stdout.write(renderFor(process.stdout, t));\n },\n};\n"],"mappings":"sMAOA,MAAM,MACH,GACA,GACC,EAAU,EAAM,EAAM,CAAE,eAAgB,EAAM,CAAC,EAOtC,EAAQ,CACnB,KAAM,MAAM,MAAM,EAClB,IAAK,MAAM,KAAK,EAChB,OAAQ,MAAM,QAAQ,EACtB,KAAM,MAAM,MAAM,EAClB,MAAO,MAAM,OAAO,EACpB,IAAK,MAAM,KAAK,EAChB,MAAO,MAAM,OAAO,EACpB,OAAQ,MAAM,QAAQ,EACtB,KAAM,MAAM,MAAM,EAClB,QAAS,MAAM,SAAS,EACxB,UAAW,MAAM,WAAW,EAC5B,YAAa,MAAM,aAAa,EAChC,WAAY,MAAM,YAAY,CAChC,EASM,cAAiB,GAAwC,CAC7D,IAAM,EAAS,QAAQ,IAAI,YAK3B,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EAAI,YALM,OAAO,QAAQ,CAAI,CAAC,CAAC,QAAQ,CAAC,KAAS,CAAC,WAAW,CAAG,CACvC,CAAC,CAAC,KAAK,CAAC,EAAK,KAAW,CACrD,EACA,eAAe,EAAK,EAAO,EAAM,EAAI,CACvC,CACsB,EAAkB,CAAE,WAAY,EAAM,CAAC,EAC7D,QAAQ,OAAO,MAAM,UAAU,QAAQ,OAAQ,CAAC,CAAC,EACjD,MACF,CAEA,GAAI,EAAK,SAAW,EAClB,OAIF,IAAM,EADa,MAAM,KAAK,IAAI,IAAI,EAAK,QAAS,GAAS,OAAO,KAAK,CAAI,CAAC,CAAC,CACtD,CAAC,CAAC,OAAQ,GAAM,CAAC,WAAW,CAAC,CAAC,EACvD,GAAI,EAAQ,SAAW,EACrB,OAQF,IAAM,EAAI,YAAY,CAAC,EAAS,GANnB,EAAK,IAAK,GACrB,EAAQ,IAAK,GACX,eAAe,EAAS,EAAiC,GAAS,CAAI,CACxE,CAGiC,CAAI,EAAG,CACxC,oBAAqB,EAAW,IACvB,IAAc,GAAK,IAAc,GAAK,IAAc,CAE/D,CAAC,EACD,QAAQ,OAAO,MAAM,UAAU,QAAQ,OAAQ,CAAC,CAAC,CACnD,CACF"}
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./schema-CRtAmDcl.mjs";import{t}from"./assert-WeXvmG4j.mjs";import{n,r,t as i}from"./guards-DsX7dJCP.mjs";var PluginManager=class{plugins=/* @__PURE__ */ new Map;generatedExecutors=[];generatedTables=[];namespaceGeneratedTableKeys=/* @__PURE__ */ new Set;namespaceGeneratedExecutorKeys=/* @__PURE__ */ new Set;pluginExecutorFiles=[];constructor(e=[]){for(let t of e){if(this.plugins.has(t.id))throw Error(`Duplicate plugin ID "${t.id}" detected. Each plugin must have a unique ID.`);this.plugins.set(t.id,t)}}async processAttachment(e){let n=this.plugins.get(e.pluginId);if(!n)return{success:!1,error:`Plugin "${e.pluginId}" not found`};let r=n.tableConfigRequired;if((typeof r==`function`?r(n.pluginConfig):r===!0)&&(e.tableConfig===void 0||e.tableConfig===null))return{success:!1,error:`Plugin "${n.id}" requires tableConfig, but none was provided for table "${e.table.name}".`};if(!n.onTableLoaded)return{success:!1,error:`Plugin "${n.id}" does not support table-attached processing (missing onTableLoaded method). Use onNamespaceLoaded via definePlugins() instead.`};let i;try{i=await n.onTableLoaded({table:e.table,tableConfig:e.tableConfig,pluginConfig:n.pluginConfig,namespace:e.namespace})}catch(t){let r=t instanceof Error?t.message:String(t);return{success:!1,error:`Plugin "${n.id}" threw an error while processing table "${e.table.name}": ${r}`}}if(i.tables&&Object.keys(i.tables).length>0){let r=t(n.importPath,`plugin "${n.id}" missing importPath`);for(let[t,a]of Object.entries(i.tables))this.generatedTables.push({pluginId:e.pluginId,pluginImportPath:r,sourceTableName:e.table.name,kind:t,table:a,namespace:e.namespace,pluginConfig:n.pluginConfig})}if(i.executors&&i.executors.length>0)for(let t of i.executors)this.generatedExecutors.push({executor:t,pluginId:e.pluginId,namespace:e.namespace,sourceTableName:e.table.name});return{success:!0,output:i}}async processNamespacePlugins(e){let r=[];for(let[i,a]of this.plugins){if(!a.onNamespaceLoaded)continue;let o=a.pluginConfig,s={pluginConfig:o,namespace:e},c;try{c=await a.onNamespaceLoaded(s)}catch(t){let n=t instanceof Error?t.message:String(t);r.push({pluginId:i,config:o,result:{success:!1,error:`Plugin "${a.id}" threw an error during namespace processing for "${e}": ${n}`}});continue}if(c.executors&&c.executors.length>0)for(let t of c.executors){let n=`${i}:${t.name}`;this.namespaceGeneratedExecutorKeys.has(n)||(this.namespaceGeneratedExecutorKeys.add(n),this.generatedExecutors.push({executor:t,pluginId:i,namespace:e}))}if(c.tables&&Object.keys(c.tables).length>0){let r=t(a.importPath,`plugin "${a.id}" missing importPath`);for(let[t,o]of Object.entries(c.tables)){let s=`${i}:${t}:${n(o)??``}`;this.namespaceGeneratedTableKeys.has(s)||(this.namespaceGeneratedTableKeys.add(s),this.generatedTables.push({pluginId:i,pluginImportPath:r,sourceTableName:`(namespace)`,kind:t,table:o,namespace:e,pluginConfig:a.pluginConfig}))}}r.push({pluginId:i,config:o,result:{success:!0,output:c}})}return r}async processAttachmentsForTable(e){let{rawTable:t,attachments:r,namespace:i}=e,a=t,o,s=[],c=[];for(let e of r){let t=await this.processAttachment({table:a,tableConfig:e.config,namespace:i,pluginId:e.pluginId});if(!t.success)throw Error(t.error);let r=t.output,l=r.extends?.fields;l&&Object.keys(l).length>0&&(a=this.extendTable({originalTable:a,extendFields:l,pluginId:e.pluginId}),o=a,c.push({kind:`extended`,tableName:a.name,fieldCount:Object.keys(l).length,pluginId:e.pluginId}));let u=this.getPlugin(e.pluginId);for(let[t,i]of Object.entries(r.tables??{})){let r=n(i)??``;s.push({tableName:r,table:i,kind:t,pluginId:e.pluginId,pluginImportPath:this.getPluginImportPath(e.pluginId)??``,pluginConfig:u?.pluginConfig}),c.push({kind:`generated`,tableName:r,pluginId:e.pluginId})}}return{extendedTable:o,generatedTables:s,events:c}}getNamespacePluginIds(){return Array.from(this.plugins.entries()).filter(([,e])=>e.onNamespaceLoaded!==void 0).map(([e])=>e)}get pluginCount(){return this.plugins.size}getPlugin(e){return this.plugins.get(e)}getPluginImportPath(e){return this.plugins.get(e)?.importPath}getPluginGeneratedExecutors(){return this.generatedExecutors}getPluginGeneratedExecutorsWithImportPath(){return this.generatedExecutors.map(e=>({...e,pluginImportPath:this.getPluginImportPath(e.pluginId)??``}))}getPluginGeneratedTables(){return this.generatedTables}getPluginGeneratedExecutorsForNamespace(e){return this.generatedExecutors.filter(t=>t.namespace===e)}getPluginsWithGenerationHooks(){return Array.from(this.plugins.values()).filter(e=>r(e))}getPluginGenerationDependencies(e){let t=this.plugins.get(e);return t?i(t):/* @__PURE__ */ new Set}generatePluginFiles(e){let{outputDir:t,sourceTableInfoMap:n,configPath:r,tableGenerator:i,executorGenerator:a}=e,o=i(this.generatedTables,t),s=this.getPluginGeneratedExecutorsWithImportPath();return this.pluginExecutorFiles=a(s,t,o,n,r),this.pluginExecutorFiles}extendTable(t){let{originalTable:n,extendFields:r,pluginId:i}=t,a=Object.keys(n.fields),o=Object.keys(n.metadata.files),s=Object.keys(r),c=s.filter(e=>a.includes(e)),l=s.filter(e=>o.includes(e));if(c.length>0)throw Error(`Plugin "${i}" attempted to add fields that already exist in table "${n.name}": ${c.join(`, `)}. extendFields cannot overwrite existing fields.`);if(l.length>0)throw Error(`Plugin "${i}" attempted to add fields that collide with file keys already declared via .files() on table "${n.name}": ${l.join(`, `)}.`);let{id:u,...d}={...n.fields,...r},f=n.metadata.settings?.pluralForm,p=f?[n.name,f]:n.name;return copyMetadataToExtendedTable(n,e.table(p,d))}};function copyMetadataToExtendedTable(e,t){let n=t;e._description&&(n=n.description(e._description));let r=e.metadata;if(Object.keys(r.files).length>0&&(n=n.files(r.files)),r.settings){let{pluralForm:e,...t}=r.settings;Object.keys(t).length>0&&(n=n.features(t))}if(r.permissions.record&&(n=n.permission(r.permissions.record)),r.permissions.gql&&(n=n.gqlPermission(r.permissions.gql)),r.indexes&&Object.keys(r.indexes).length>0){let e=Object.entries(r.indexes).map(([e,t])=>({name:e,fields:t.fields,unique:t.unique}));n=n.indexes(...e)}if(r.typeHook&&(n=n.hooks(r.typeHook)),r.typeValidate&&(n=n.validate(r.typeValidate)),e.plugins.length>0)for(let t of e.plugins)n=n.plugin({[t.pluginId]:t.config});return n}export{PluginManager as t};
2
+ //# sourceMappingURL=manager-C0dE7pd0.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager-qfbUL7ru.mjs","names":[],"sources":["../src/plugin/manager.ts"],"sourcesContent":["import { db, type TailorAnyDBType } from \"#/configure/services/tailordb/index\";\nimport {\n getPluginGenerationDependencies,\n getRawPluginTableName,\n hasGenerationHooks,\n} from \"#/plugin/guards\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type {\n TailorTypePermission,\n TailorTypeGqlPermission,\n} from \"#/configure/services/tailordb/permission\";\nimport type {\n TailorAnyDBField,\n TypeHook,\n TypeValidateFn,\n} from \"#/configure/services/tailordb/types\";\nimport type {\n DependencyKind,\n Plugin,\n PluginAttachment,\n PluginGeneratedExecutor,\n PluginGeneratedTable,\n PluginNamespaceProcessContext,\n PluginOutput,\n TablePluginOutput,\n} from \"#/plugin/types\";\nimport type { TailorDBTypeRaw } from \"#/types/tailordb.generated\";\n\n/**\n * Context for processing a single plugin attachment on a raw TailorDBType\n */\nexport interface ProcessAttachmentContext {\n table: TailorAnyDBType;\n tableConfig: unknown;\n namespace: string;\n pluginId: string;\n}\n\n/**\n * Information about a plugin-generated table (for table file generation)\n */\nexport interface PluginGeneratedTableInfo {\n /** Plugin ID that generated this table */\n pluginId: string;\n /** Plugin import path for resolving executor files */\n pluginImportPath: string;\n /** Source table name that triggered the plugin */\n sourceTableName: string;\n /** Kind identifier for this generated table */\n kind: string;\n /** The generated TailorDB table object */\n table: PluginGeneratedTable;\n /** Namespace where this table was generated */\n namespace: string;\n /** Plugin config used to generate this table */\n pluginConfig?: unknown;\n}\n\n/**\n * Extended executor info with plugin import path\n */\nexport interface PluginExecutorInfoExtended extends PluginExecutorInfo {\n /** Plugin's import path for resolving executor files */\n pluginImportPath: string;\n}\n\n/**\n * Result of processing a table-attached plugin\n */\nexport type ProcessAttachmentResult =\n | { success: true; output: TablePluginOutput }\n | { success: false; error: string };\n\n/**\n * Result of processing a namespace plugin\n */\nexport type ProcessNamespaceResult =\n | { success: true; output: PluginOutput }\n | { success: false; error: string };\n\n/**\n * Parameters for processing all plugin attachments of a TailorDB table.\n */\nexport interface ProcessAttachmentsForTableParams {\n rawTable: TailorDBTypeRaw;\n attachments: PluginAttachment[];\n namespace: string;\n}\n\n/**\n * Progress event emitted while processing plugin attachments for a TailorDB table.\n * Plain data so the caller (typically the cli) can format and output it.\n */\ntype ProcessAttachmentEvent =\n | { kind: \"extended\"; tableName: string; fieldCount: number; pluginId: string }\n | { kind: \"generated\"; tableName: string; pluginId: string };\n\n/**\n * Generated table produced by a plugin during attachment processing.\n * `table` is raw plugin output; the caller must validate it before use.\n */\ninterface ProcessAttachmentsGeneratedTable {\n tableName: string;\n table: unknown;\n kind: string;\n pluginId: string;\n pluginImportPath: string;\n pluginConfig?: unknown;\n}\n\n/**\n * Result of {@link PluginManager.processAttachmentsForTable}.\n */\nexport interface ProcessAttachmentsForTableResult {\n /**\n * Final table after all extends are applied; undefined if no plugin extended the table.\n * Raw builder output; the caller must validate it before use.\n */\n extendedTable?: unknown;\n /** Tables newly generated by plugins for this attachment chain. */\n generatedTables: ProcessAttachmentsGeneratedTable[];\n /** Events for the caller to render. */\n events: ProcessAttachmentEvent[];\n}\n\n/**\n * Information about a plugin-generated executor\n */\nexport interface PluginExecutorInfo {\n /** The executor definition */\n executor: PluginGeneratedExecutor;\n /** Plugin ID that generated this executor */\n pluginId: string;\n /** Namespace where the executor was generated */\n namespace: string;\n /** Source table name (for table-attached executors, undefined for namespace) */\n sourceTableName?: string;\n}\n\n/**\n * Manages plugin registration and processing\n */\nexport class PluginManager {\n private plugins: Map<string, Plugin> = new Map();\n private generatedExecutors: PluginExecutorInfo[] = [];\n private generatedTables: PluginGeneratedTableInfo[] = [];\n private namespaceGeneratedTableKeys: Set<string> = new Set();\n private namespaceGeneratedExecutorKeys: Set<string> = new Set();\n\n /** Generated plugin executor file paths */\n private pluginExecutorFiles: string[] = [];\n\n constructor(plugins: Plugin[] = []) {\n for (const plugin of plugins) {\n if (this.plugins.has(plugin.id)) {\n throw new Error(\n `Duplicate plugin ID \"${plugin.id}\" detected. Each plugin must have a unique ID.`,\n );\n }\n this.plugins.set(plugin.id, plugin);\n }\n }\n\n /**\n * Process a single plugin attachment on a raw TailorDBType.\n * This method is called during table loading before parsing.\n * @param context - Context containing the raw table, config, namespace, and plugin ID\n * @returns Result with plugin output on success, or error message on failure\n */\n async processAttachment(context: ProcessAttachmentContext): Promise<ProcessAttachmentResult> {\n const plugin = this.plugins.get(context.pluginId);\n if (!plugin) {\n return {\n success: false,\n error: `Plugin \"${context.pluginId}\" not found`,\n };\n }\n\n const tableConfigRequired = plugin.tableConfigRequired;\n const resolvedRequired =\n typeof tableConfigRequired === \"function\"\n ? tableConfigRequired(plugin.pluginConfig)\n : tableConfigRequired === true;\n if (resolvedRequired && (context.tableConfig === undefined || context.tableConfig === null)) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" requires tableConfig, but none was provided for table \"${context.table.name}\".`,\n };\n }\n\n // Check if plugin supports table-attached processing\n if (!plugin.onTableLoaded) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" does not support table-attached processing (missing onTableLoaded method). Use onNamespaceLoaded via definePlugins() instead.`,\n };\n }\n\n // Execute plugin onTableLoaded with the raw TailorDB table\n let output: TablePluginOutput;\n try {\n output = await plugin.onTableLoaded({\n table: context.table,\n tableConfig: context.tableConfig,\n pluginConfig: plugin.pluginConfig,\n namespace: context.namespace,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error while processing table \"${context.table.name}\": ${message}`,\n };\n }\n\n // Collect generated tables\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n this.generatedTables.push({\n pluginId: context.pluginId,\n pluginImportPath: importPath,\n sourceTableName: context.table.name,\n kind,\n table,\n namespace: context.namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n // Collect generated executors\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n this.generatedExecutors.push({\n executor,\n pluginId: context.pluginId,\n namespace: context.namespace,\n sourceTableName: context.table.name,\n });\n }\n }\n\n return { success: true, output };\n }\n\n /**\n * Process namespace plugins that don't require a source table.\n * This method is called once per namespace for plugins with onNamespaceLoaded method.\n * @param namespace - The target namespace for generated tables\n * @returns Array of results with plugin outputs and configs\n */\n async processNamespacePlugins(\n namespace: string,\n ): Promise<Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }>> {\n const results: Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }> =\n [];\n\n for (const [pluginId, plugin] of this.plugins) {\n // Skip plugins without onNamespaceLoaded method\n if (!plugin.onNamespaceLoaded) {\n continue;\n }\n\n // Use stored plugin config (from definePlugins)\n const config = plugin.pluginConfig;\n\n // Execute plugin onNamespaceLoaded\n const context: PluginNamespaceProcessContext = {\n pluginConfig: config,\n namespace,\n };\n\n let output: Awaited<ReturnType<NonNullable<Plugin[\"onNamespaceLoaded\"]>>>;\n try {\n output = await plugin.onNamespaceLoaded(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n results.push({\n pluginId,\n config,\n result: {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error during namespace processing for \"${namespace}\": ${message}`,\n },\n });\n continue;\n }\n\n // Collect generated executors (namespace - no source table)\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n const executorKey = `${pluginId}:${executor.name}`;\n if (this.namespaceGeneratedExecutorKeys.has(executorKey)) {\n continue;\n }\n this.namespaceGeneratedExecutorKeys.add(executorKey);\n this.generatedExecutors.push({\n executor,\n pluginId,\n namespace,\n });\n }\n }\n\n // Collect generated tables (namespace - no source table)\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n const tableKey = `${pluginId}:${kind}:${getRawPluginTableName(table) ?? \"\"}`;\n if (this.namespaceGeneratedTableKeys.has(tableKey)) {\n continue;\n }\n this.namespaceGeneratedTableKeys.add(tableKey);\n this.generatedTables.push({\n pluginId,\n pluginImportPath: importPath,\n sourceTableName: \"(namespace)\",\n kind,\n table,\n namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n results.push({\n pluginId,\n config,\n result: { success: true, output },\n });\n }\n\n return results;\n }\n\n /**\n * Run every plugin attachment for a single TailorDB table in order, threading the\n * extended table through the chain. Returns plain data (no logging, no shared state)\n * so the caller decides how to apply updates and render progress.\n * @param params - The raw table, its attachments, and the target namespace\n * @returns Final extended table (if any), generated tables, and render events\n */\n async processAttachmentsForTable(\n params: ProcessAttachmentsForTableParams,\n ): Promise<ProcessAttachmentsForTableResult> {\n const { rawTable, attachments, namespace } = params;\n // The runtime value is a configure-layer builder instance; we accept the structural\n // TailorDBTypeRaw at the boundary so callers (cli) don't need to depend on TailorAnyDBType.\n let currentTable: TailorAnyDBType = rawTable as unknown as TailorAnyDBType;\n let extendedTable: TailorAnyDBType | undefined;\n const generatedTables: ProcessAttachmentsGeneratedTable[] = [];\n const events: ProcessAttachmentEvent[] = [];\n\n for (const attachment of attachments) {\n const result = await this.processAttachment({\n table: currentTable,\n tableConfig: attachment.config,\n namespace,\n pluginId: attachment.pluginId,\n });\n if (!result.success) {\n throw new Error(result.error);\n }\n\n const output = result.output;\n const extendFields = output.extends?.fields;\n if (extendFields && Object.keys(extendFields).length > 0) {\n currentTable = this.extendTable({\n originalTable: currentTable,\n extendFields,\n pluginId: attachment.pluginId,\n });\n extendedTable = currentTable;\n events.push({\n kind: \"extended\",\n tableName: currentTable.name,\n fieldCount: Object.keys(extendFields).length,\n pluginId: attachment.pluginId,\n });\n }\n\n const plugin = this.getPlugin(attachment.pluginId);\n for (const [kind, table] of Object.entries(output.tables ?? {})) {\n const tableName = getRawPluginTableName(table) ?? \"\";\n generatedTables.push({\n tableName,\n table,\n kind,\n pluginId: attachment.pluginId,\n pluginImportPath: this.getPluginImportPath(attachment.pluginId) ?? \"\",\n pluginConfig: plugin?.pluginConfig,\n });\n events.push({ kind: \"generated\", tableName, pluginId: attachment.pluginId });\n }\n }\n\n return { extendedTable, generatedTables, events };\n }\n\n /**\n * Get plugins that have onNamespaceLoaded method\n * @returns Array of plugin IDs that support namespace processing\n */\n getNamespacePluginIds(): string[] {\n return Array.from(this.plugins.entries())\n .filter(([, plugin]) => plugin.onNamespaceLoaded !== undefined)\n .map(([id]) => id);\n }\n\n /**\n * Get the count of registered plugins\n * @returns Number of registered plugins\n */\n get pluginCount(): number {\n return this.plugins.size;\n }\n\n /**\n * Get a plugin by its ID\n * @param pluginId - The plugin ID to look up\n * @returns The plugin instance, or undefined if not found\n */\n getPlugin(pluginId: string): Plugin | undefined {\n return this.plugins.get(pluginId);\n }\n\n /**\n * Get the import path for a plugin\n * @param pluginId - The plugin ID to look up\n * @returns The plugin's import path, or undefined if not found\n */\n getPluginImportPath(pluginId: string): string | undefined {\n return this.plugins.get(pluginId)?.importPath;\n }\n\n /**\n * Get all plugin-generated executors\n * @returns Array of plugin-generated executor info\n */\n getPluginGeneratedExecutors(): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors;\n }\n\n /**\n * Get all plugin-generated executors with import paths\n * @returns Array of plugin-generated executor info with import paths\n */\n getPluginGeneratedExecutorsWithImportPath(): ReadonlyArray<PluginExecutorInfoExtended> {\n return this.generatedExecutors.map((info) => ({\n ...info,\n pluginImportPath: this.getPluginImportPath(info.pluginId) ?? \"\",\n }));\n }\n\n /**\n * Get all plugin-generated tables\n * @returns Array of plugin-generated table info\n */\n getPluginGeneratedTables(): ReadonlyArray<PluginGeneratedTableInfo> {\n return this.generatedTables;\n }\n\n /**\n * Get plugin-generated executors for a specific namespace\n * @param namespace - The namespace to filter by\n * @returns Array of plugin-generated executor info for the namespace\n */\n getPluginGeneratedExecutorsForNamespace(namespace: string): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors.filter((info) => info.namespace === namespace);\n }\n\n /**\n * Get plugins that have any generation-time hooks.\n * @returns Array of plugins with generation hooks\n */\n getPluginsWithGenerationHooks(): Plugin[] {\n return Array.from(this.plugins.values()).filter((plugin) => hasGenerationHooks(plugin));\n }\n\n /**\n * Get the generation-time dependencies for a specific plugin.\n * @param pluginId - The plugin ID to look up\n * @returns Set of dependency kinds, or empty set if plugin not found\n */\n getPluginGenerationDependencies(pluginId: string): Set<DependencyKind> {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) return new Set();\n return getPluginGenerationDependencies(plugin);\n }\n\n /**\n * Generate plugin files (tables and executors) and store the executor file paths.\n * @param params - Parameters for file generation\n * @returns Generated executor file paths\n */\n generatePluginFiles(params: GeneratePluginFilesParams): string[] {\n const { outputDir, sourceTableInfoMap, configPath, tableGenerator, executorGenerator } = params;\n\n // Generate table files\n const tableGenerationResult = tableGenerator(this.generatedTables, outputDir);\n\n // Generate executor files\n const pluginExecutors = this.getPluginGeneratedExecutorsWithImportPath();\n this.pluginExecutorFiles = executorGenerator(\n pluginExecutors,\n outputDir,\n tableGenerationResult,\n sourceTableInfoMap,\n configPath,\n );\n\n return this.pluginExecutorFiles;\n }\n\n /**\n * Extend a TailorDB table with new fields.\n * This method handles the `db.table()` call and metadata copying internally.\n * @param params - Parameters for table extension\n * @returns The extended TailorDB table\n */\n extendTable(params: ExtendTableParams): TailorAnyDBType {\n const { originalTable, extendFields, pluginId } = params;\n const existingFieldNames = Object.keys(originalTable.fields);\n const existingFileNames = Object.keys(originalTable.metadata.files);\n const newFieldNames = Object.keys(extendFields);\n const duplicateFields = newFieldNames.filter((name) => existingFieldNames.includes(name));\n const duplicateFiles = newFieldNames.filter((name) => existingFileNames.includes(name));\n\n if (duplicateFields.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that already exist in table \"${originalTable.name}\": ${duplicateFields.join(\", \")}. ` +\n `extendFields cannot overwrite existing fields.`,\n );\n }\n\n if (duplicateFiles.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that collide with file keys already declared via .files() on table \"${originalTable.name}\": ${duplicateFiles.join(\", \")}.`,\n );\n }\n\n const mergedFields = {\n ...originalTable.fields,\n ...extendFields,\n };\n\n const { id: _id, ...fieldsWithoutId } = mergedFields;\n const pluralForm = originalTable.metadata.settings?.pluralForm;\n const tableName = pluralForm\n ? ([originalTable.name, pluralForm] as [string, string])\n : originalTable.name;\n const extendedTable = db.table(tableName, fieldsWithoutId);\n return copyMetadataToExtendedTable(originalTable, extendedTable);\n }\n}\n\n/**\n * Source info for user-defined tables\n */\nexport type SourceTableInfo = {\n filePath: string;\n exportName: string;\n};\n\n/**\n * Result of generating plugin table files\n */\nexport interface PluginTableGenerationResult {\n /** Map of table name to generated file path (relative to outputDir) */\n tableFilePaths: Map<string, string>;\n /** List of all generated file paths (absolute) */\n generatedFiles: string[];\n}\n\n/**\n * Parameters for generating plugin files\n */\nexport interface GeneratePluginFilesParams {\n /** Base output directory (e.g., .tailor/plugin) */\n outputDir: string;\n /** Map of source table names to their source info */\n sourceTableInfoMap: Map<string, SourceTableInfo>;\n /** Path to tailor.config.ts (used for resolving plugin import paths) */\n configPath: string;\n /** Function to generate table files */\n tableGenerator: (\n tables: ReadonlyArray<PluginGeneratedTableInfo>,\n outputDir: string,\n ) => PluginTableGenerationResult;\n /** Function to generate executor files */\n executorGenerator: (\n executors: ReadonlyArray<PluginExecutorInfoExtended>,\n outputDir: string,\n tableGenerationResult: PluginTableGenerationResult,\n sourceTableInfoMap: Map<string, SourceTableInfo>,\n configPath: string,\n ) => string[];\n}\n\n/**\n * Parameters for extending a TailorDB table\n */\nexport interface ExtendTableParams {\n /** The original TailorDB table to extend */\n originalTable: TailorAnyDBType;\n /** New fields to add to the table */\n extendFields: Record<string, unknown>;\n /** The ID of the plugin extending the table */\n pluginId: string;\n}\n\n/**\n * Copy metadata from original table to extended table.\n * Preserves files, settings, permissions, indexes, and plugins.\n * @param original - The original TailorDB table with metadata\n * @param extended - The newly created extended table\n * @returns The extended table with copied metadata\n */\nfunction copyMetadataToExtendedTable(\n original: TailorAnyDBType,\n extended: TailorAnyDBType,\n): TailorAnyDBType {\n let result = extended;\n\n // Copy description\n if (original._description) {\n result = result.description(original._description);\n }\n\n // Copy files metadata\n const metadata = original.metadata;\n if (Object.keys(metadata.files).length > 0) {\n result = result.files(metadata.files);\n }\n\n // Copy settings/features (excluding pluralForm which is set during construction)\n if (metadata.settings) {\n const { pluralForm: _pluralForm, ...features } = metadata.settings;\n if (Object.keys(features).length > 0) {\n result = result.features(\n features as typeof features & { aggregation?: true; bulkUpsert?: true },\n );\n }\n }\n\n // Copy permissions from metadata\n // Zod schema operand types are wider unions than the configure layer's discriminated PermissionCondition,\n // so type assertions are needed here.\n if (metadata.permissions.record) {\n result = result.permission(metadata.permissions.record as TailorTypePermission);\n }\n if (metadata.permissions.gql) {\n result = result.gqlPermission(metadata.permissions.gql as TailorTypeGqlPermission);\n }\n\n // Copy indexes from metadata (indexes are stored in metadata, not as a direct property)\n if (metadata.indexes && Object.keys(metadata.indexes).length > 0) {\n const indexDefs = Object.entries(metadata.indexes).map(([name, def]) => ({\n name,\n // Cast fields array to tuple type (IndexDef expects [T, T, ...T[]])\n fields: def.fields as [string, string, ...string[]],\n unique: def.unique,\n }));\n result = result.indexes(...indexDefs);\n }\n\n if (metadata.typeHook) {\n result = result.hooks(metadata.typeHook as TypeHook<Record<string, TailorAnyDBField>>);\n }\n if (metadata.typeValidate) {\n result = result.validate(\n metadata.typeValidate as TypeValidateFn<Record<string, TailorAnyDBField>>,\n );\n }\n\n // Copy plugins (but don't re-process them)\n if (original.plugins.length > 0) {\n for (const plugin of original.plugins) {\n // Use type assertion as plugin ID is dynamic at runtime\n result = result.plugin({\n [plugin.pluginId]: plugin.config,\n });\n }\n }\n\n return result;\n}\n"],"mappings":"6HA8IA,IAAa,cAAb,KAA2B,CACzB,QAAuC,IAAI,IAC3C,mBAAmD,CAAC,EACpD,gBAAsD,CAAC,EACvD,4BAAmD,IAAI,IACvD,+BAAsD,IAAI,IAG1D,oBAAwC,CAAC,EAEzC,YAAY,EAAoB,CAAC,EAAG,CAClC,IAAK,IAAM,KAAU,EAAS,CAC5B,GAAI,KAAK,QAAQ,IAAI,EAAO,EAAE,EAC5B,MAAU,MACR,wBAAwB,EAAO,GAAG,+CACpC,EAEF,KAAK,QAAQ,IAAI,EAAO,GAA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d,EAAE,EACF,EAAS,EAAO,QAAQ,GAAG,CAAS,CACtC,CAYA,GAVI,EAAS,WACX,EAAS,EAAO,MAAM,EAAS,QAAsD,GAEnF,EAAS,eACX,EAAS,EAAO,SACd,EAAS,YACX,GAIE,EAAS,QAAQ,OAAS,EAC5B,IAAK,IAAM,KAAU,EAAS,QAE5B,EAAS,EAAO,OAAO,EACpB,EAAO,UAAW,EAAO,MAC5B,CAAC,EAIL,OAAO,CACT"}
1
+ {"version":3,"file":"manager-C0dE7pd0.mjs","names":[],"sources":["../src/plugin/manager.ts"],"sourcesContent":["import { db, type TailorAnyDBType } from \"#/configure/services/tailordb/index\";\nimport {\n getPluginGenerationDependencies,\n getRawPluginTableName,\n hasGenerationHooks,\n} from \"#/plugin/guards\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type {\n TailorTypePermission,\n TailorTypeGqlPermission,\n} from \"#/configure/services/tailordb/permission\";\nimport type {\n TailorAnyDBField,\n TypeHook,\n TypeValidateFn,\n} from \"#/configure/services/tailordb/types\";\nimport type {\n DependencyKind,\n Plugin,\n PluginAttachment,\n PluginGeneratedExecutor,\n PluginGeneratedTable,\n PluginNamespaceProcessContext,\n PluginOutput,\n TablePluginOutput,\n} from \"#/plugin/types\";\nimport type { TailorDBTypeRaw } from \"#/types/tailordb.generated\";\n\n/**\n * Context for processing a single plugin attachment on a raw TailorDBType\n */\nexport interface ProcessAttachmentContext {\n table: TailorAnyDBType;\n tableConfig: unknown;\n namespace: string;\n pluginId: string;\n}\n\n/**\n * Information about a plugin-generated table (for table file generation)\n */\nexport interface PluginGeneratedTableInfo {\n /** Plugin ID that generated this table */\n pluginId: string;\n /** Plugin import path for resolving executor files */\n pluginImportPath: string;\n /** Source table name that triggered the plugin */\n sourceTableName: string;\n /** Kind identifier for this generated table */\n kind: string;\n /** The generated TailorDB table object */\n table: PluginGeneratedTable;\n /** Namespace where this table was generated */\n namespace: string;\n /** Plugin config used to generate this table */\n pluginConfig?: unknown;\n}\n\n/**\n * Extended executor info with plugin import path\n */\nexport interface PluginExecutorInfoExtended extends PluginExecutorInfo {\n /** Plugin's import path for resolving executor files */\n pluginImportPath: string;\n}\n\n/**\n * Result of processing a table-attached plugin\n */\nexport type ProcessAttachmentResult =\n | { success: true; output: TablePluginOutput }\n | { success: false; error: string };\n\n/**\n * Result of processing a namespace plugin\n */\nexport type ProcessNamespaceResult =\n | { success: true; output: PluginOutput }\n | { success: false; error: string };\n\n/**\n * Parameters for processing all plugin attachments of a TailorDB table.\n */\nexport interface ProcessAttachmentsForTableParams {\n rawTable: TailorDBTypeRaw;\n attachments: PluginAttachment[];\n namespace: string;\n}\n\n/**\n * Progress event emitted while processing plugin attachments for a TailorDB table.\n * Plain data so the caller (typically the cli) can format and output it.\n */\ntype ProcessAttachmentEvent =\n | { kind: \"extended\"; tableName: string; fieldCount: number; pluginId: string }\n | { kind: \"generated\"; tableName: string; pluginId: string };\n\n/**\n * Generated table produced by a plugin during attachment processing.\n * `table` is raw plugin output; the caller must validate it before use.\n */\ninterface ProcessAttachmentsGeneratedTable {\n tableName: string;\n table: unknown;\n kind: string;\n pluginId: string;\n pluginImportPath: string;\n pluginConfig?: unknown;\n}\n\n/**\n * Result of {@link PluginManager.processAttachmentsForTable}.\n */\nexport interface ProcessAttachmentsForTableResult {\n /**\n * Final table after all extends are applied; undefined if no plugin extended the table.\n * Raw builder output; the caller must validate it before use.\n */\n extendedTable?: unknown;\n /** Tables newly generated by plugins for this attachment chain. */\n generatedTables: ProcessAttachmentsGeneratedTable[];\n /** Events for the caller to render. */\n events: ProcessAttachmentEvent[];\n}\n\n/**\n * Information about a plugin-generated executor\n */\nexport interface PluginExecutorInfo {\n /** The executor definition */\n executor: PluginGeneratedExecutor;\n /** Plugin ID that generated this executor */\n pluginId: string;\n /** Namespace where the executor was generated */\n namespace: string;\n /** Source table name (for table-attached executors, undefined for namespace) */\n sourceTableName?: string;\n}\n\n/**\n * Manages plugin registration and processing\n */\nexport class PluginManager {\n private plugins: Map<string, Plugin> = new Map();\n private generatedExecutors: PluginExecutorInfo[] = [];\n private generatedTables: PluginGeneratedTableInfo[] = [];\n private namespaceGeneratedTableKeys: Set<string> = new Set();\n private namespaceGeneratedExecutorKeys: Set<string> = new Set();\n\n /** Generated plugin executor file paths */\n private pluginExecutorFiles: string[] = [];\n\n constructor(plugins: Plugin[] = []) {\n for (const plugin of plugins) {\n if (this.plugins.has(plugin.id)) {\n throw new Error(\n `Duplicate plugin ID \"${plugin.id}\" detected. Each plugin must have a unique ID.`,\n );\n }\n this.plugins.set(plugin.id, plugin);\n }\n }\n\n /**\n * Process a single plugin attachment on a raw TailorDBType.\n * This method is called during table loading before parsing.\n * @param context - Context containing the raw table, config, namespace, and plugin ID\n * @returns Result with plugin output on success, or error message on failure\n */\n async processAttachment(context: ProcessAttachmentContext): Promise<ProcessAttachmentResult> {\n const plugin = this.plugins.get(context.pluginId);\n if (!plugin) {\n return {\n success: false,\n error: `Plugin \"${context.pluginId}\" not found`,\n };\n }\n\n const tableConfigRequired = plugin.tableConfigRequired;\n const resolvedRequired =\n typeof tableConfigRequired === \"function\"\n ? tableConfigRequired(plugin.pluginConfig)\n : tableConfigRequired === true;\n if (resolvedRequired && (context.tableConfig === undefined || context.tableConfig === null)) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" requires tableConfig, but none was provided for table \"${context.table.name}\".`,\n };\n }\n\n // Check if plugin supports table-attached processing\n if (!plugin.onTableLoaded) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" does not support table-attached processing (missing onTableLoaded method). Use onNamespaceLoaded via definePlugins() instead.`,\n };\n }\n\n // Execute plugin onTableLoaded with the raw TailorDB table\n let output: TablePluginOutput;\n try {\n output = await plugin.onTableLoaded({\n table: context.table,\n tableConfig: context.tableConfig,\n pluginConfig: plugin.pluginConfig,\n namespace: context.namespace,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error while processing table \"${context.table.name}\": ${message}`,\n };\n }\n\n // Collect generated tables\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n this.generatedTables.push({\n pluginId: context.pluginId,\n pluginImportPath: importPath,\n sourceTableName: context.table.name,\n kind,\n table,\n namespace: context.namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n // Collect generated executors\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n this.generatedExecutors.push({\n executor,\n pluginId: context.pluginId,\n namespace: context.namespace,\n sourceTableName: context.table.name,\n });\n }\n }\n\n return { success: true, output };\n }\n\n /**\n * Process namespace plugins that don't require a source table.\n * This method is called once per namespace for plugins with onNamespaceLoaded method.\n * @param namespace - The target namespace for generated tables\n * @returns Array of results with plugin outputs and configs\n */\n async processNamespacePlugins(\n namespace: string,\n ): Promise<Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }>> {\n const results: Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }> =\n [];\n\n for (const [pluginId, plugin] of this.plugins) {\n // Skip plugins without onNamespaceLoaded method\n if (!plugin.onNamespaceLoaded) {\n continue;\n }\n\n // Use stored plugin config (from definePlugins)\n const config = plugin.pluginConfig;\n\n // Execute plugin onNamespaceLoaded\n const context: PluginNamespaceProcessContext = {\n pluginConfig: config,\n namespace,\n };\n\n let output: Awaited<ReturnType<NonNullable<Plugin[\"onNamespaceLoaded\"]>>>;\n try {\n output = await plugin.onNamespaceLoaded(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n results.push({\n pluginId,\n config,\n result: {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error during namespace processing for \"${namespace}\": ${message}`,\n },\n });\n continue;\n }\n\n // Collect generated executors (namespace - no source table)\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n const executorKey = `${pluginId}:${executor.name}`;\n if (this.namespaceGeneratedExecutorKeys.has(executorKey)) {\n continue;\n }\n this.namespaceGeneratedExecutorKeys.add(executorKey);\n this.generatedExecutors.push({\n executor,\n pluginId,\n namespace,\n });\n }\n }\n\n // Collect generated tables (namespace - no source table)\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n const tableKey = `${pluginId}:${kind}:${getRawPluginTableName(table) ?? \"\"}`;\n if (this.namespaceGeneratedTableKeys.has(tableKey)) {\n continue;\n }\n this.namespaceGeneratedTableKeys.add(tableKey);\n this.generatedTables.push({\n pluginId,\n pluginImportPath: importPath,\n sourceTableName: \"(namespace)\",\n kind,\n table,\n namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n results.push({\n pluginId,\n config,\n result: { success: true, output },\n });\n }\n\n return results;\n }\n\n /**\n * Run every plugin attachment for a single TailorDB table in order, threading the\n * extended table through the chain. Returns plain data (no logging, no shared state)\n * so the caller decides how to apply updates and render progress.\n * @param params - The raw table, its attachments, and the target namespace\n * @returns Final extended table (if any), generated tables, and render events\n */\n async processAttachmentsForTable(\n params: ProcessAttachmentsForTableParams,\n ): Promise<ProcessAttachmentsForTableResult> {\n const { rawTable, attachments, namespace } = params;\n // The runtime value is a configure-layer builder instance; we accept the structural\n // TailorDBTypeRaw at the boundary so callers (cli) don't need to depend on TailorAnyDBType.\n let currentTable: TailorAnyDBType = rawTable as unknown as TailorAnyDBType;\n let extendedTable: TailorAnyDBType | undefined;\n const generatedTables: ProcessAttachmentsGeneratedTable[] = [];\n const events: ProcessAttachmentEvent[] = [];\n\n for (const attachment of attachments) {\n const result = await this.processAttachment({\n table: currentTable,\n tableConfig: attachment.config,\n namespace,\n pluginId: attachment.pluginId,\n });\n if (!result.success) {\n throw new Error(result.error);\n }\n\n const output = result.output;\n const extendFields = output.extends?.fields;\n if (extendFields && Object.keys(extendFields).length > 0) {\n currentTable = this.extendTable({\n originalTable: currentTable,\n extendFields,\n pluginId: attachment.pluginId,\n });\n extendedTable = currentTable;\n events.push({\n kind: \"extended\",\n tableName: currentTable.name,\n fieldCount: Object.keys(extendFields).length,\n pluginId: attachment.pluginId,\n });\n }\n\n const plugin = this.getPlugin(attachment.pluginId);\n for (const [kind, table] of Object.entries(output.tables ?? {})) {\n const tableName = getRawPluginTableName(table) ?? \"\";\n generatedTables.push({\n tableName,\n table,\n kind,\n pluginId: attachment.pluginId,\n pluginImportPath: this.getPluginImportPath(attachment.pluginId) ?? \"\",\n pluginConfig: plugin?.pluginConfig,\n });\n events.push({ kind: \"generated\", tableName, pluginId: attachment.pluginId });\n }\n }\n\n return { extendedTable, generatedTables, events };\n }\n\n /**\n * Get plugins that have onNamespaceLoaded method\n * @returns Array of plugin IDs that support namespace processing\n */\n getNamespacePluginIds(): string[] {\n return Array.from(this.plugins.entries())\n .filter(([, plugin]) => plugin.onNamespaceLoaded !== undefined)\n .map(([id]) => id);\n }\n\n /**\n * Get the count of registered plugins\n * @returns Number of registered plugins\n */\n get pluginCount(): number {\n return this.plugins.size;\n }\n\n /**\n * Get a plugin by its ID\n * @param pluginId - The plugin ID to look up\n * @returns The plugin instance, or undefined if not found\n */\n getPlugin(pluginId: string): Plugin | undefined {\n return this.plugins.get(pluginId);\n }\n\n /**\n * Get the import path for a plugin\n * @param pluginId - The plugin ID to look up\n * @returns The plugin's import path, or undefined if not found\n */\n getPluginImportPath(pluginId: string): string | undefined {\n return this.plugins.get(pluginId)?.importPath;\n }\n\n /**\n * Get all plugin-generated executors\n * @returns Array of plugin-generated executor info\n */\n getPluginGeneratedExecutors(): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors;\n }\n\n /**\n * Get all plugin-generated executors with import paths\n * @returns Array of plugin-generated executor info with import paths\n */\n getPluginGeneratedExecutorsWithImportPath(): ReadonlyArray<PluginExecutorInfoExtended> {\n return this.generatedExecutors.map((info) => ({\n ...info,\n pluginImportPath: this.getPluginImportPath(info.pluginId) ?? \"\",\n }));\n }\n\n /**\n * Get all plugin-generated tables\n * @returns Array of plugin-generated table info\n */\n getPluginGeneratedTables(): ReadonlyArray<PluginGeneratedTableInfo> {\n return this.generatedTables;\n }\n\n /**\n * Get plugin-generated executors for a specific namespace\n * @param namespace - The namespace to filter by\n * @returns Array of plugin-generated executor info for the namespace\n */\n getPluginGeneratedExecutorsForNamespace(namespace: string): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors.filter((info) => info.namespace === namespace);\n }\n\n /**\n * Get plugins that have any generation-time hooks.\n * @returns Array of plugins with generation hooks\n */\n getPluginsWithGenerationHooks(): Plugin[] {\n return Array.from(this.plugins.values()).filter((plugin) => hasGenerationHooks(plugin));\n }\n\n /**\n * Get the generation-time dependencies for a specific plugin.\n * @param pluginId - The plugin ID to look up\n * @returns Set of dependency kinds, or empty set if plugin not found\n */\n getPluginGenerationDependencies(pluginId: string): Set<DependencyKind> {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) return new Set();\n return getPluginGenerationDependencies(plugin);\n }\n\n /**\n * Generate plugin files (tables and executors) and store the executor file paths.\n * @param params - Parameters for file generation\n * @returns Generated executor file paths\n */\n generatePluginFiles(params: GeneratePluginFilesParams): string[] {\n const { outputDir, sourceTableInfoMap, configPath, tableGenerator, executorGenerator } = params;\n\n // Generate table files\n const tableGenerationResult = tableGenerator(this.generatedTables, outputDir);\n\n // Generate executor files\n const pluginExecutors = this.getPluginGeneratedExecutorsWithImportPath();\n this.pluginExecutorFiles = executorGenerator(\n pluginExecutors,\n outputDir,\n tableGenerationResult,\n sourceTableInfoMap,\n configPath,\n );\n\n return this.pluginExecutorFiles;\n }\n\n /**\n * Extend a TailorDB table with new fields.\n * This method handles the `db.table()` call and metadata copying internally.\n * @param params - Parameters for table extension\n * @returns The extended TailorDB table\n */\n extendTable(params: ExtendTableParams): TailorAnyDBType {\n const { originalTable, extendFields, pluginId } = params;\n const existingFieldNames = Object.keys(originalTable.fields);\n const existingFileNames = Object.keys(originalTable.metadata.files);\n const newFieldNames = Object.keys(extendFields);\n const duplicateFields = newFieldNames.filter((name) => existingFieldNames.includes(name));\n const duplicateFiles = newFieldNames.filter((name) => existingFileNames.includes(name));\n\n if (duplicateFields.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that already exist in table \"${originalTable.name}\": ${duplicateFields.join(\", \")}. ` +\n `extendFields cannot overwrite existing fields.`,\n );\n }\n\n if (duplicateFiles.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that collide with file keys already declared via .files() on table \"${originalTable.name}\": ${duplicateFiles.join(\", \")}.`,\n );\n }\n\n const mergedFields = {\n ...originalTable.fields,\n ...extendFields,\n };\n\n const { id: _id, ...fieldsWithoutId } = mergedFields;\n const pluralForm = originalTable.metadata.settings?.pluralForm;\n const tableName = pluralForm\n ? ([originalTable.name, pluralForm] as [string, string])\n : originalTable.name;\n const extendedTable = db.table(tableName, fieldsWithoutId);\n return copyMetadataToExtendedTable(originalTable, extendedTable);\n }\n}\n\n/**\n * Source info for user-defined tables\n */\nexport type SourceTableInfo = {\n filePath: string;\n exportName: string;\n};\n\n/**\n * Result of generating plugin table files\n */\nexport interface PluginTableGenerationResult {\n /** Map of table name to generated file path (relative to outputDir) */\n tableFilePaths: Map<string, string>;\n /** List of all generated file paths (absolute) */\n generatedFiles: string[];\n}\n\n/**\n * Parameters for generating plugin files\n */\nexport interface GeneratePluginFilesParams {\n /** Base output directory (e.g., .tailor/plugin) */\n outputDir: string;\n /** Map of source table names to their source info */\n sourceTableInfoMap: Map<string, SourceTableInfo>;\n /** Path to tailor.config.ts (used for resolving plugin import paths) */\n configPath: string;\n /** Function to generate table files */\n tableGenerator: (\n tables: ReadonlyArray<PluginGeneratedTableInfo>,\n outputDir: string,\n ) => PluginTableGenerationResult;\n /** Function to generate executor files */\n executorGenerator: (\n executors: ReadonlyArray<PluginExecutorInfoExtended>,\n outputDir: string,\n tableGenerationResult: PluginTableGenerationResult,\n sourceTableInfoMap: Map<string, SourceTableInfo>,\n configPath: string,\n ) => string[];\n}\n\n/**\n * Parameters for extending a TailorDB table\n */\nexport interface ExtendTableParams {\n /** The original TailorDB table to extend */\n originalTable: TailorAnyDBType;\n /** New fields to add to the table */\n extendFields: Record<string, unknown>;\n /** The ID of the plugin extending the table */\n pluginId: string;\n}\n\n/**\n * Copy metadata from original table to extended table.\n * Preserves files, settings, permissions, indexes, and plugins.\n * @param original - The original TailorDB table with metadata\n * @param extended - The newly created extended table\n * @returns The extended table with copied metadata\n */\nfunction copyMetadataToExtendedTable(\n original: TailorAnyDBType,\n extended: TailorAnyDBType,\n): TailorAnyDBType {\n let result = extended;\n\n // Copy description\n if (original._description) {\n result = result.description(original._description);\n }\n\n // Copy files metadata\n const metadata = original.metadata;\n if (Object.keys(metadata.files).length > 0) {\n result = result.files(metadata.files);\n }\n\n // Copy settings/features (excluding pluralForm which is set during construction)\n if (metadata.settings) {\n const { pluralForm: _pluralForm, ...features } = metadata.settings;\n if (Object.keys(features).length > 0) {\n result = result.features(\n features as typeof features & { aggregation?: true; bulkUpsert?: true },\n );\n }\n }\n\n // Copy permissions from metadata\n // Zod schema operand types are wider unions than the configure layer's discriminated PermissionCondition,\n // so type assertions are needed here.\n if (metadata.permissions.record) {\n result = result.permission(metadata.permissions.record as TailorTypePermission);\n }\n if (metadata.permissions.gql) {\n result = result.gqlPermission(metadata.permissions.gql as TailorTypeGqlPermission);\n }\n\n // Copy indexes from metadata (indexes are stored in metadata, not as a direct property)\n if (metadata.indexes && Object.keys(metadata.indexes).length > 0) {\n const indexDefs = Object.entries(metadata.indexes).map(([name, def]) => ({\n name,\n // Cast fields array to tuple type (IndexDef expects [T, T, ...T[]])\n fields: def.fields as [string, string, ...string[]],\n unique: def.unique,\n }));\n result = result.indexes(...indexDefs);\n }\n\n if (metadata.typeHook) {\n result = result.hooks(metadata.typeHook as TypeHook<Record<string, TailorAnyDBField>>);\n }\n if (metadata.typeValidate) {\n result = result.validate(\n metadata.typeValidate as TypeValidateFn<Record<string, TailorAnyDBField>>,\n );\n }\n\n // Copy plugins (but don't re-process them)\n if (original.plugins.length > 0) {\n for (const plugin of original.plugins) {\n // Use type assertion as plugin ID is dynamic at runtime\n result = result.plugin({\n [plugin.pluginId]: plugin.config,\n });\n }\n }\n\n return result;\n}\n"],"mappings":"6HA8IA,IAAa,cAAb,KAA2B,CACzB,wBAAuC,IAAI,IAC3C,mBAAmD,CAAC,EACpD,gBAAsD,CAAC,EACvD,4CAAmD,IAAI,IACvD,+CAAsD,IAAI,IAG1D,oBAAwC,CAAC,EAEzC,YAAY,EAAoB,CAAC,EAAG,CAClC,IAAK,IAAM,KAAU,EAAS,CAC5B,GAAI,KAAK,QAAQ,IAAI,EAAO,EAAE,EAC5B,MAAU,MACR,wBAAwB,EAAO,GAAG,+CACpC,EAEF,KAAK,QAAQ,IAAI,EAAO,GAAI,CAAM,CACpC,CACF,CAQA,MAAM,kBAAkB,EAAqE,CAC3F,IAAM,EAAS,KAAK,QAAQ,IAAI,EAAQ,QAAQ,EAChD,GAAI,CAAC,EACH,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAQ,SAAS,YACrC,EAGF,IAAM,EAAsB,EAAO,oBAKnC,IAHE,OAAO,GAAwB,WAC3B,EAAoB,EAAO,YAAY,EACvC,IAAwB,MACL,EAAQ,cAAgB,IAAA,IAAa,EAAQ,cAAgB,MACpF,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAO,GAAG,2DAA2D,EAAQ,MAAM,KAAK,GAC5G,EAIF,GAAI,CAAC,EAAO,cACV,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAO,GAAG,gIAC9B,EAIF,IAAI,EACJ,GAAI,CACF,EAAS,MAAM,EAAO,cAAc,CAClC,MAAO,EAAQ,MACf,YAAa,EAAQ,YACrB,aAAc,EAAO,aACrB,UAAW,EAAQ,SACrB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eACX,EAAS,EAAO,YAAY,EAAS,YAAY,GAInD,IAAM,EAAW,EAAS,SAM1B,GALI,OAAO,KAAK,EAAS,KAAK,CAAC,CAAC,OAAS,IACvC,EAAS,EAAO,MAAM,EAAS,KAAK,GAIlC,EAAS,SAAU,CACrB,GAAM,CAAE,WAAY,EAAa,GAAG,GAAa,EAAS,SACtD,OAAO,KAAK,CAAQ,CAAC,CAAC,OAAS,IACjC,EAAS,EAAO,SACd,CACF,EAEJ,CAaA,GARI,EAAS,YAAY,SACvB,EAAS,EAAO,WAAW,EAAS,YAAY,MAA8B,GAE5E,EAAS,YAAY,MACvB,EAAS,EAAO,cAAc,EAAS,YAAY,GAA8B,GAI/E,EAAS,SAAW,OAAO,KAAK,EAAS,OAAO,CAAC,CAAC,OAAS,EAAG,CAChE,IAAM,EAAY,OAAO,QAAQ,EAAS,OAAO,CAAC,CAAC,KAAK,CAAC,EAAM,MAAU,CACvE,OAEA,OAAQ,EAAI,OACZ,OAAQ,EAAI,MACd,EAAE,EACF,EAAS,EAAO,QAAQ,GAAG,CAAS,CACtC,CAYA,GAVI,EAAS,WACX,EAAS,EAAO,MAAM,EAAS,QAAsD,GAEnF,EAAS,eACX,EAAS,EAAO,SACd,EAAS,YACX,GAIE,EAAS,QAAQ,OAAS,EAC5B,IAAK,IAAM,KAAU,EAAS,QAE5B,EAAS,EAAO,OAAO,EACpB,EAAO,UAAW,EAAO,MAC5B,CAAC,EAIL,OAAO,CACT"}
@@ -1,4 +1,4 @@
1
- function generateUnifiedEnumConstants(e){if(e.length===0)return``;let t=new Map;for(let n of e)t.set(n.name,n);let n=Array.from(t.values()).map(e=>{let t=e.values.map(e=>` "${e.value.replace(/[-\s]/g,`_`)}": "${e.value}"`).join(`,
1
+ function generateUnifiedEnumConstants(e){if(e.length===0)return``;let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n.name,n);let n=Array.from(t.values()).map(e=>{let t=e.values.map(e=>` "${e.value.replace(/[-\s]/g,`_`)}": "${e.value}"`).join(`,
2
2
  `),n=e.values.some(e=>e.description),r=``;if(e.fieldDescription||n){let t=[];if(e.fieldDescription&&(t.push(` * ${e.fieldDescription}`),n&&t.push(` *`)),n){let n=e.values.map(e=>` * @property ${[e.value.replace(/[-\s]/g,`_`),e.description].filter(Boolean).join(` - `)}`);t.push(...n)}t.length>0&&(r=`/**\n${t.join(`
3
3
  `)}\n */\n`)}return`${`${r}export const ${e.name} = {\n${t}\n} as const;`}\n${`export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`}`}).join(`
4
4
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/plugin/builtin/enum-constants/generate-enum-constants.ts","../../../../src/plugin/builtin/enum-constants/process-enum-type.ts","../../../../src/plugin/builtin/enum-constants/index.ts"],"sourcesContent":["import type { EnumDefinition } from \"./types\";\n\n/**\n * Generate enum constant definitions from collected metadata.\n * @param allEnums - All collected enum definitions\n * @returns Generated enum constant definitions\n */\nexport function generateUnifiedEnumConstants(allEnums: EnumDefinition[]): string {\n if (allEnums.length === 0) {\n return \"\";\n }\n\n const enumMap = new Map<string, EnumDefinition>();\n for (const enumDef of allEnums) {\n enumMap.set(enumDef.name, enumDef);\n }\n\n const enumDefs = Array.from(enumMap.values())\n .map((e) => {\n const members = e.values\n .map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` \"${key}\": \"${v.value}\"`;\n })\n .join(\",\\n\");\n\n const hasDescriptions = e.values.some((v) => v.description);\n let jsDoc = \"\";\n if (e.fieldDescription || hasDescriptions) {\n const lines: string[] = [];\n\n if (e.fieldDescription) {\n lines.push(` * ${e.fieldDescription}`);\n if (hasDescriptions) {\n lines.push(\" *\");\n }\n }\n\n if (hasDescriptions) {\n const propertyDocs = e.values.map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` * @property ${[key, v.description].filter(Boolean).join(\" - \")}`;\n });\n lines.push(...propertyDocs);\n }\n\n if (lines.length > 0) {\n jsDoc = `/**\\n${lines.join(\"\\n\")}\\n */\\n`;\n }\n }\n\n const constDef = `${jsDoc}export const ${e.name} = {\\n${members}\\n} as const;`;\n const typeDef = `export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`;\n return `${constDef}\\n${typeDef}`;\n })\n .join(\"\\n\\n\");\n\n if (!enumDefs) {\n return \"\";\n }\n\n return enumDefs + \"\\n\";\n}\n","import type { TailorDBType } from \"#/parser/service/tailordb/types\";\nimport type { EnumConstantMetadata } from \"./types\";\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nfunction collectEnums(type: TailorDBType): EnumConstantMetadata[\"enums\"] {\n const enums: EnumConstantMetadata[\"enums\"] = [];\n\n for (const [fieldName, parsedField] of Object.entries(type.fields)) {\n if (parsedField.config.type === \"enum\" && parsedField.config.allowedValues) {\n const enumTypeName = `${type.name}${capitalizeFirst(fieldName)}`;\n enums.push({\n name: enumTypeName,\n values: parsedField.config.allowedValues,\n fieldDescription: parsedField.config.description,\n });\n }\n\n // Process nested fields\n if (parsedField.config.type === \"nested\" && parsedField.config.fields) {\n for (const [nestedFieldName, nestedFieldConfig] of Object.entries(\n parsedField.config.fields,\n )) {\n if (nestedFieldConfig.type === \"enum\" && nestedFieldConfig.allowedValues) {\n const fullFieldName = `${fieldName}${capitalizeFirst(nestedFieldName)}`;\n const enumTypeName = `${type.name}${capitalizeFirst(fullFieldName)}`;\n enums.push({\n name: enumTypeName,\n values: nestedFieldConfig.allowedValues,\n fieldDescription: nestedFieldConfig.description,\n });\n }\n }\n }\n }\n\n return enums;\n}\n\n/**\n * Process a TailorDB table and extract enum metadata.\n * @param type - The parsed TailorDB table to process\n * @returns Enum constant metadata for the table\n */\nexport async function processEnumType(type: TailorDBType): Promise<EnumConstantMetadata> {\n const enums = collectEnums(type);\n\n return {\n name: type.name,\n enums,\n };\n}\n","import { generateUnifiedEnumConstants } from \"./generate-enum-constants\";\nimport { processEnumType } from \"./process-enum-type\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\nimport type { EnumDefinition } from \"./types\";\n\n/** Unique identifier for the enum constants generator plugin. */\nexport const EnumConstantsGeneratorID = \"@tailor-platform/enum-constants\";\n\ntype EnumConstantsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates enum constants from TailorDB table definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated constants\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function enumConstantsPlugin(\n options: EnumConstantsPluginOptions,\n): Plugin<unknown, EnumConstantsPluginOptions> {\n return {\n id: EnumConstantsGeneratorID,\n description: \"Generates enum constants from TailorDB table definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<EnumConstantsPluginOptions>,\n ): Promise<GeneratorResult> {\n const allEnums: EnumDefinition[] = [];\n\n for (const ns of ctx.tailordb) {\n for (const type of Object.values(ns.tables)) {\n const metadata = await processEnumType(type);\n allEnums.push(...metadata.enums);\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allEnums.length > 0) {\n const content = generateUnifiedEnumConstants(allEnums);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":"AAOA,SAAgB,6BAA6B,EAAoC,CAC/E,GAAI,EAAS,SAAW,EACtB,MAAO,GAGT,IAAM,EAAU,IAAI,IACpB,IAAK,IAAM,KAAW,EACpB,EAAQ,IAAI,EAAQ,KAAM,CAAO,EAGnC,IAAM,EAAW,MAAM,KAAK,EAAQ,OAAO,CAAC,CAAC,CAC1C,IAAK,GAAM,CACV,IAAM,EAAU,EAAE,OACf,IAAK,GAEG,MADK,EAAE,MAAM,QAAQ,SAAU,GACvB,EAAE,MAAM,EAAE,MAAM,EAChC,CAAC,CACD,KAAK;CAAK,EAEP,EAAkB,EAAE,OAAO,KAAM,GAAM,EAAE,WAAW,EACtD,EAAQ,GACZ,GAAI,EAAE,kBAAoB,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gB,CAAe,IAC9D,EAAe,GAAG,EAAK,OAAO,gBAAgB,CAAa,IACjE,EAAM,KAAK,CACT,KAAM,EACN,OAAQ,EAAkB,cAC1B,iBAAkB,EAAkB,WACtC,CAAC,CACH,EAGN,CAEA,OAAO,CACT,CAOA,eAAsB,gBAAgB,EAAmD,CACvF,IAAM,EAAQ,aAAa,CAAI,EAE/B,MAAO,CACL,KAAM,EAAK,KACX,OACF,CACF,CC/CA,MAAa,EAA2B,kCAYxC,SAAgB,oBACd,EAC6C,CAC7C,MAAO,CACL,GAAI,EACJ,YAAa,2DACb,aAAc,EAEd,MAAM,gBACJ,EAC0B,CAC1B,IAAM,EAA6B,CAAC,EAEpC,IAAK,IAAM,KAAM,EAAI,SACnB,IAAK,IAAM,KAAQ,OAAO,OAAO,EAAG,MAAM,EAAG,CAC3C,IAAM,EAAW,MAAM,gBAAgB,CAAI,EAC3C,EAAS,KAAK,GAAG,EAAS,KAAK,CACjC,CAGF,IAAM,EAAkC,CAAC,EACzC,GAAI,EAAS,OAAS,EAAG,CACvB,IAAM,EAAU,6BAA6B,CAAQ,EACrD,EAAM,KAAK,CACT,KAAM,EAAI,aAAa,SACvB,SACF,CAAC,CACH,CAEA,MAAO,CAAE,OAAM,CACjB,CACF,CACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../src/plugin/builtin/enum-constants/generate-enum-constants.ts","../../../../src/plugin/builtin/enum-constants/process-enum-type.ts","../../../../src/plugin/builtin/enum-constants/index.ts"],"sourcesContent":["import type { EnumDefinition } from \"./types\";\n\n/**\n * Generate enum constant definitions from collected metadata.\n * @param allEnums - All collected enum definitions\n * @returns Generated enum constant definitions\n */\nexport function generateUnifiedEnumConstants(allEnums: EnumDefinition[]): string {\n if (allEnums.length === 0) {\n return \"\";\n }\n\n const enumMap = new Map<string, EnumDefinition>();\n for (const enumDef of allEnums) {\n enumMap.set(enumDef.name, enumDef);\n }\n\n const enumDefs = Array.from(enumMap.values())\n .map((e) => {\n const members = e.values\n .map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` \"${key}\": \"${v.value}\"`;\n })\n .join(\",\\n\");\n\n const hasDescriptions = e.values.some((v) => v.description);\n let jsDoc = \"\";\n if (e.fieldDescription || hasDescriptions) {\n const lines: string[] = [];\n\n if (e.fieldDescription) {\n lines.push(` * ${e.fieldDescription}`);\n if (hasDescriptions) {\n lines.push(\" *\");\n }\n }\n\n if (hasDescriptions) {\n const propertyDocs = e.values.map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` * @property ${[key, v.description].filter(Boolean).join(\" - \")}`;\n });\n lines.push(...propertyDocs);\n }\n\n if (lines.length > 0) {\n jsDoc = `/**\\n${lines.join(\"\\n\")}\\n */\\n`;\n }\n }\n\n const constDef = `${jsDoc}export const ${e.name} = {\\n${members}\\n} as const;`;\n const typeDef = `export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`;\n return `${constDef}\\n${typeDef}`;\n })\n .join(\"\\n\\n\");\n\n if (!enumDefs) {\n return \"\";\n }\n\n return enumDefs + \"\\n\";\n}\n","import type { TailorDBType } from \"#/parser/service/tailordb/types\";\nimport type { EnumConstantMetadata } from \"./types\";\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nfunction collectEnums(type: TailorDBType): EnumConstantMetadata[\"enums\"] {\n const enums: EnumConstantMetadata[\"enums\"] = [];\n\n for (const [fieldName, parsedField] of Object.entries(type.fields)) {\n if (parsedField.config.type === \"enum\" && parsedField.config.allowedValues) {\n const enumTypeName = `${type.name}${capitalizeFirst(fieldName)}`;\n enums.push({\n name: enumTypeName,\n values: parsedField.config.allowedValues,\n fieldDescription: parsedField.config.description,\n });\n }\n\n // Process nested fields\n if (parsedField.config.type === \"nested\" && parsedField.config.fields) {\n for (const [nestedFieldName, nestedFieldConfig] of Object.entries(\n parsedField.config.fields,\n )) {\n if (nestedFieldConfig.type === \"enum\" && nestedFieldConfig.allowedValues) {\n const fullFieldName = `${fieldName}${capitalizeFirst(nestedFieldName)}`;\n const enumTypeName = `${type.name}${capitalizeFirst(fullFieldName)}`;\n enums.push({\n name: enumTypeName,\n values: nestedFieldConfig.allowedValues,\n fieldDescription: nestedFieldConfig.description,\n });\n }\n }\n }\n }\n\n return enums;\n}\n\n/**\n * Process a TailorDB table and extract enum metadata.\n * @param type - The parsed TailorDB table to process\n * @returns Enum constant metadata for the table\n */\nexport async function processEnumType(type: TailorDBType): Promise<EnumConstantMetadata> {\n const enums = collectEnums(type);\n\n return {\n name: type.name,\n enums,\n };\n}\n","import { generateUnifiedEnumConstants } from \"./generate-enum-constants\";\nimport { processEnumType } from \"./process-enum-type\";\nimport type { Plugin, GeneratorResult, TailorDBReadyContext } from \"#/plugin/types\";\nimport type { EnumDefinition } from \"./types\";\n\n/** Unique identifier for the enum constants generator plugin. */\nexport const EnumConstantsGeneratorID = \"@tailor-platform/enum-constants\";\n\ntype EnumConstantsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates enum constants from TailorDB table definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated constants\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function enumConstantsPlugin(\n options: EnumConstantsPluginOptions,\n): Plugin<unknown, EnumConstantsPluginOptions> {\n return {\n id: EnumConstantsGeneratorID,\n description: \"Generates enum constants from TailorDB table definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<EnumConstantsPluginOptions>,\n ): Promise<GeneratorResult> {\n const allEnums: EnumDefinition[] = [];\n\n for (const ns of ctx.tailordb) {\n for (const type of Object.values(ns.tables)) {\n const metadata = await processEnumType(type);\n allEnums.push(...metadata.enums);\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allEnums.length > 0) {\n const content = generateUnifiedEnumConstants(allEnums);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":"AAOA,SAAgB,6BAA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
1
- import{t as e}from"../../../multiline-EyzjEwn9.mjs";function generateUnifiedFileUtils(t){if(t.length===0)return``;let n=new Map,r=new Map;for(let{namespace:e,types:i}of t)for(let t of i)n.set(t.name,e),r.set(t.name,t.fileFields);if(n.size===0)return``;let i=Array.from(r.entries()).map(([e,t])=>` ${e}: {\n fields: ${t.map(e=>`"${e}"`).join(` | `)};\n };`).join(`
1
+ import{t as e}from"../../../multiline-EyzjEwn9.mjs";function generateUnifiedFileUtils(t){if(t.length===0)return``;let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;for(let{namespace:e,types:i}of t)for(let t of i)n.set(t.name,e),r.set(t.name,t.fileFields);if(n.size===0)return``;let i=Array.from(r.entries()).map(([e,t])=>` ${e}: {\n fields: ${t.map(e=>`"${e}"`).join(` | `)};\n };`).join(`
2
2
  `),a=e`
3
3
  import { file } from "@tailor-platform/sdk/runtime/file";
4
4
  import type {