@tailor-platform/sdk 2.30.0 → 2.33.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 (120) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/dist/ai/index.d.mts +112 -0
  3. package/dist/ai/index.mjs +2 -0
  4. package/dist/ai/index.mjs.map +1 -0
  5. package/dist/aigateway-DsWDjzk4.mjs.map +1 -1
  6. package/dist/{application-D0xNJbag.mjs → application-B9_NHiUC.mjs} +40 -32
  7. package/dist/application-B9_NHiUC.mjs.map +1 -0
  8. package/dist/application-Bet1K5C4.mjs +1 -0
  9. package/dist/assert-WeXvmG4j.mjs.map +1 -1
  10. package/dist/authconnection-CynFBIv8.mjs.map +1 -1
  11. package/dist/brand-C8nMKhJC.mjs.map +1 -1
  12. package/dist/cli/commands/deploy/staticwebsite.d.mts +1 -0
  13. package/dist/cli/lib.mjs +1 -1
  14. package/dist/cli/lib.mjs.map +1 -1
  15. package/dist/cli/main.mjs +44 -33
  16. package/dist/cli/main.mjs.map +1 -1
  17. package/dist/cli/services/resolver/service.d.mts +1 -0
  18. package/dist/cli/shared/client.d.mts +52 -1
  19. package/dist/cli/ts-hook.d.mts +0 -2
  20. package/dist/cli/ts-hook.mjs +0 -113
  21. package/dist/completion/zsh-worker.zsh +30 -6
  22. package/dist/configure/index.mjs.map +1 -1
  23. package/dist/configure/services/staticwebsite/index.d.mts +6 -1
  24. package/dist/context-D0QjfxzD.mjs.map +1 -1
  25. package/dist/crashreport-BCIy33Cz.mjs.map +1 -1
  26. package/dist/date-CgP7gMG_.mjs.map +1 -1
  27. package/dist/date-representation-Cr7W7Pn2.mjs.map +1 -1
  28. package/dist/errors-BOF68LJ5.mjs.map +1 -1
  29. package/dist/es-builtins-SfvXRVoG.mjs.map +1 -1
  30. package/dist/field-parse-C41e3UAF.mjs.map +1 -1
  31. package/dist/file-DKBOj5q4.mjs.map +1 -1
  32. package/dist/globals-BCmGX05J.mjs.map +1 -1
  33. package/dist/guards-yDXyKC9F.mjs.map +1 -1
  34. package/dist/iconv-DlFMt2gW.mjs.map +1 -1
  35. package/dist/idp-G_ojPBB5.mjs.map +1 -1
  36. package/dist/interceptor-DQg3cR_9.mjs.map +1 -1
  37. package/dist/kysely/index.mjs.map +1 -1
  38. package/dist/kysely-type-DxyIWXc6.mjs +51 -0
  39. package/dist/kysely-type-DxyIWXc6.mjs.map +1 -0
  40. package/dist/logger-DP2BjQ93.mjs.map +1 -1
  41. package/dist/logger-RgtbhJ83.mjs.map +1 -1
  42. package/dist/manager-DTRhIupk.mjs +2 -0
  43. package/dist/manager-DTRhIupk.mjs.map +1 -0
  44. package/dist/migration-steps-C6F3zNdQ.mjs.map +1 -1
  45. package/dist/multiline-EyzjEwn9.mjs.map +1 -1
  46. package/dist/node-builtins-DYfhPBnz.mjs.map +1 -1
  47. package/dist/package-json-C690ceex.mjs.map +1 -1
  48. package/dist/platform-serialize-DkiTdHOt.mjs.map +1 -1
  49. package/dist/plugin/builtin/enum-constants/index.mjs +2 -2
  50. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
  51. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
  52. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  53. package/dist/plugin/index.mjs +1 -1
  54. package/dist/plugin/index.mjs.map +1 -1
  55. package/dist/plugin/types.d.mts +3 -0
  56. package/dist/register-ts-hook-Dp9reSRG.mjs +1053 -0
  57. package/dist/register-ts-hook-Dp9reSRG.mjs.map +1 -0
  58. package/dist/registry-BijIDRVA.mjs.map +1 -1
  59. package/dist/repl-editor-DkrCZmmg.mjs +2 -0
  60. package/dist/repl-editor-DkrCZmmg.mjs.map +1 -0
  61. package/dist/schema-B6hJQWp6.mjs.map +1 -1
  62. package/dist/secret-file-C9wp_FCX.mjs.map +1 -1
  63. package/dist/secretmanager-vHQoXdQz.mjs.map +1 -1
  64. package/dist/seed/index.mjs.map +1 -1
  65. package/dist/seed-Cn-3JApy.mjs.map +1 -1
  66. package/dist/service-9SBPNpK8.mjs.map +1 -1
  67. package/dist/service-9rwi_I4d.mjs.map +1 -1
  68. package/dist/service_pb-6EkMfdOb.mjs +2 -0
  69. package/dist/service_pb-6EkMfdOb.mjs.map +1 -0
  70. package/dist/service_pb-CsJKokDl.mjs +1 -0
  71. package/dist/tailor-proto/src/tailor/v1/metadata_pb.d.mts +5 -2
  72. package/dist/tailor-proto/src/tailor/v1/security_pb.d.mts +213 -0
  73. package/dist/tailor-proto/src/tailor/v1/security_resource_pb.d.mts +301 -0
  74. package/dist/tailor-proto/src/tailor/v1/service_pb.d.mts +200 -8
  75. package/dist/tailor-proto/src/tailor/v1/staticwebsite_pb.d.mts +201 -1
  76. package/dist/tailor-proto/src/tailor/v1/staticwebsite_resource_pb.d.mts +88 -1
  77. package/dist/telemetry-DfT2UfI4.mjs +2 -0
  78. package/dist/telemetry-DfT2UfI4.mjs.map +1 -0
  79. package/dist/{telemetry-DpkFGBmu.mjs → telemetry-nqOtDWNO.mjs} +1 -1
  80. package/dist/type-source--ZNcV8RJ.mjs.map +1 -1
  81. package/dist/types/staticwebsite.generated.d.mts +9 -1
  82. package/dist/user-agent-vdHYF3QL.mjs.map +1 -1
  83. package/dist/utils/test/index.mjs.map +1 -1
  84. package/dist/vitest/environment.mjs.map +1 -1
  85. package/dist/vitest/index.d.mts +2 -2
  86. package/dist/vitest/index.mjs +1 -1
  87. package/dist/vitest/index.mjs.map +1 -1
  88. package/dist/vitest/pglite-kysely.d.mts +19 -0
  89. package/dist/vitest/setup.mjs.map +1 -1
  90. package/dist/wait-point-invoker-eiP-IIux.mjs.map +1 -1
  91. package/dist/wait-point-registry-B-ESkTZX.mjs.map +1 -1
  92. package/dist/workflow-Cs9ISw6j.mjs.map +1 -1
  93. package/dist/{workspace_resource_pb-CaoM2npP.mjs → workspace_resource_pb-C4CkoYww.mjs} +2 -2
  94. package/dist/workspace_resource_pb-C4CkoYww.mjs.map +1 -0
  95. package/docs/ai.md +92 -0
  96. package/docs/cli/tailordb.md +17 -15
  97. package/docs/cli/workspace.md +1 -1
  98. package/docs/github-actions.md +98 -11
  99. package/docs/plugin/custom.md +34 -0
  100. package/docs/plugin/index.md +1 -0
  101. package/docs/services/staticwebsite.md +31 -1
  102. package/docs/services/tailordb/migration.md +78 -41
  103. package/docs/testing.md +2 -1
  104. package/package.json +20 -13
  105. package/dist/application-C2bPmmbh.mjs +0 -1
  106. package/dist/application-D0xNJbag.mjs.map +0 -1
  107. package/dist/kysely-type-BWMfV301.mjs +0 -48
  108. package/dist/kysely-type-BWMfV301.mjs.map +0 -1
  109. package/dist/manager-Bk-7vkwd.mjs +0 -2
  110. package/dist/manager-Bk-7vkwd.mjs.map +0 -1
  111. package/dist/register-ts-hook-CDnN_Jx2.mjs +0 -1012
  112. package/dist/register-ts-hook-CDnN_Jx2.mjs.map +0 -1
  113. package/dist/repl-editor-DGJBfIt1.mjs +0 -2
  114. package/dist/repl-editor-DGJBfIt1.mjs.map +0 -1
  115. package/dist/service_pb-Bbu2QSIr.mjs +0 -2
  116. package/dist/service_pb-Bbu2QSIr.mjs.map +0 -1
  117. package/dist/service_pb-urxAIYHT.mjs +0 -1
  118. package/dist/telemetry-Xk7J829P.mjs +0 -2
  119. package/dist/telemetry-Xk7J829P.mjs.map +0 -1
  120. package/dist/workspace_resource_pb-CaoM2npP.mjs.map +0 -1
@@ -1,48 +0,0 @@
1
- import{t as e}from"./multiline-EyzjEwn9.mjs";import{resolve as t}from"pathe";const n=new TextEncoder;function mapFieldTypeToPostgresType(e){switch(e){case`uuid`:return`uuid`;case`string`:case`enum`:return`text`;case`boolean`:case`bool`:return`boolean`;case`integer`:return`integer`;case`float`:return`double precision`;case`decimal`:return`numeric`;case`date`:return`date`;case`datetime`:return`timestamptz`;case`time`:return`time`;case`nested`:return`jsonb`;default:throw Error(`Field type "${e}" has no PostgreSQL column type.`)}}function identifier(e){return`"${e.replaceAll(`"`,`""`)}"`}function fnv1aHex(e){let t=2166136261;for(let r of n.encode(e))t=Math.imul(t^r,16777619)>>>0;return t.toString(16).padStart(8,`0`)}function derivedIdentifier(e,t,r){let i=`_${fnv1aHex(JSON.stringify([e,t,r]))}_${r}`,a=`${e}_${t}`;for(;n.encode(a+i).length>63;)a=a.slice(0,-1);return identifier(a+i)}function stringLiteral(e){return`'${e.replaceAll(`'`,`''`)}'`}function columnType(e){let t=e.type===`decimal`?`numeric(1000, ${e.scale??6})`:mapFieldTypeToPostgresType(e.type);return e.array&&e.type!==`nested`?`${t}[]`:t}function scalarLiteral(e,t,n){let r=mapFieldTypeToPostgresType(t.type);if(e instanceof Date){if(Number.isNaN(e.getTime()))throw Error(`Default of field ${n} is an invalid Date.`);return`${stringLiteral(e.toISOString())}::${r}`}switch(typeof e){case`string`:return r===`text`?stringLiteral(e):`${stringLiteral(e)}::${r}`;case`number`:if(!Number.isFinite(e))throw Error(`Default of field ${n} is not a finite number.`);return String(e);case`boolean`:return e?`TRUE`:`FALSE`;default:throw Error(`Default of field ${n} cannot be rendered as a SQL literal.`)}}const r=/* @__PURE__ */ new Map([[`datetime`,`now()`],[`date`,`CURRENT_DATE`],[`time`,`LOCALTIME`]]);function defaultExpression(e,t){let n=e.default,i=r.get(e.type);if(n===`now`&&i!==void 0)return i;if(e.array){if(!Array.isArray(n))throw Error(`Default of array field ${t} must be an array.`);let r=columnType(e);return n.length===0?`'{}'::${r}`:`ARRAY[${n.map(n=>scalarLiteral(n,e,t)).join(`, `)}]::${r}`}return scalarLiteral(n,e,t)}function parseSerialFormat(e,t){let n=/^(?<prefix>[^%]*)%(?<zero>0?)(?<width>\d*)(?<conversion>[a-zA-Z])(?<suffix>[^%]*)$/.exec(e)?.groups,r=n?.conversion;if(!n||r!==`d`&&r!==`x`&&r!==`X`)throw Error(`Serial format "${e}" of field ${t} is not supported; use a single %d, %x, or %X specifier with an optional width (e.g. "INV-%05d").`);return{prefix:n.prefix??``,zeroPad:n.zero===`0`,width:n.width?Number(n.width):0,conversion:r,suffix:n.suffix??``}}function sequenceName(e,t){return derivedIdentifier(e,t,`seq`)}function sequenceRange(e){let t=[`START WITH ${e.start}`,`MINVALUE ${e.start}`];return e.maxValue!==void 0&&t.push(`MAXVALUE ${e.maxValue}`),t.join(` `)}const i={d:e=>e,x:e=>`to_hex(${e})`,X:e=>`upper(to_hex(${e}))`};function serialStringDefault(e,t,n){let r=`nextval(${stringLiteral(e)})`;if(t===void 0)return`(${r}::text)`;let{prefix:a,width:o,zeroPad:s,conversion:c,suffix:l}=parseSerialFormat(t,n),u=i[c](r),d=c===`d`?`${u}::text`:u;return o>0&&(d=`format('%${o}s', ${u})`,s&&(d=`translate(${d}, ' ', '0')`)),`(${[...a?[stringLiteral(a)]:[],d,...l?[stringLiteral(l)]:[]].join(` || `)})`}function columnDefinition(e,t,n){let r=identifier(t),i=`${identifier(e)}.${r}`,a=[r,columnType(n)];if(n.serial)return n.type===`integer`?(a.push(`GENERATED BY DEFAULT AS IDENTITY (${sequenceRange(n.serial)})`),n.unique&&a.push(`UNIQUE`),a.join(` `)):(n.required&&a.push(`NOT NULL`),n.unique&&a.push(`UNIQUE`),a.push(`DEFAULT ${serialStringDefault(sequenceName(e,t),n.serial.format,i)}`),a.join(` `));let o=n.default!==void 0,s=n.hooks?.create!==void 0||n.optionalOnCreate===!0;return n.required&&(o||!s)&&a.push(`NOT NULL`),n.unique&&a.push(`UNIQUE`),o&&a.push(`DEFAULT ${defaultExpression(n,i)}`),a.join(` `)}function generateTableDDL(e){let t=identifier(e.name),n=[],r=[],i=[` "id" uuid PRIMARY KEY DEFAULT gen_random_uuid()`];for(let[a,o]of Object.entries(e.fields))if(a!==`id`){if(o.serial&&o.type!==`integer`){let i=sequenceName(e.name,a);n.push(`CREATE SEQUENCE IF NOT EXISTS ${i} ${sequenceRange(o.serial)}`),r.push(`ALTER SEQUENCE ${i} OWNED BY ${t}.${identifier(a)}`)}i.push(` ${columnDefinition(e.name,a,o)}`)}let a=Object.entries(e.indexes??{}).filter(([,e])=>e.unique).map(([n,r])=>`CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(e.name,n,`idx`)} ON ${t} (${r.fields.map(identifier).join(`, `)})`);return[...n,`CREATE TABLE IF NOT EXISTS ${t} (\n${i.join(`,
2
- `)}\n)`,...r,...a]}function generateSchemaDDL(e){return e.map(e=>generateTableDDL(e).map(e=>`${e};`).join(`
3
- `)).join(`
4
-
5
- `)}function templateLiteral(e){return`\`${e.replaceAll(`\\`,`\\\\`).replaceAll("`","\\`").replaceAll("${","\\${").replaceAll(`\r`,`\\r`)}\``}function generatePgliteSchemaModule(e,t){let n=e.map(({namespace:e,tables:t})=>` ${JSON.stringify(e)}: ${templateLiteral(generateSchemaDDL(t))},`);return[`/**`,` * Auto-generated PGlite schema for TailorDB tables.`," * Create a namespace's tables in a test with `pglite.exec(pgliteSchema[namespace])`.",` *`,` * DO NOT EDIT - This file is auto-generated by ${t.generatedBy}.`,` */`,``,`export const pgliteSchema = {`,...n,`} as const;`,``].join(`
6
- `)}function toDDLTables(e){return Object.values(e).map(e=>({name:e.name,fields:Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,t.config])),indexes:e.indexes}))}function generatePGliteSchemaModule(e){return generatePgliteSchemaModule(e.map(({namespace:e,tables:t})=>({namespace:e,tables:toDDLTables(t)})),{generatedBy:`the kysely-type plugin`})}function mapFieldTypeToColumnType(e,t=!1){switch(e){case`uuid`:case`string`:case`decimal`:return`string`;case`integer`:case`float`:return`number`;case`date`:return t?`TemporalDate`:`Timestamp`;case`datetime`:return t?`TemporalInstant`:`Timestamp`;case`time`:return t?`TemporalTime`:`string`;case`bool`:case`boolean`:return`boolean`;case`enum`:case`nested`:throw Error(`Field type "${e}" has no scalar column type; resolve it before mapping.`);default:return`string`}}const a=/* @__PURE__ */ new Map([[`Timestamp`,{select:`Date`,write:`Date | string`}],[`TemporalDate`,{select:`Temporal.PlainDate`,write:`Temporal.PlainDate | string`}],[`TemporalInstant`,{select:`Temporal.Instant`,write:`Temporal.Instant | string`}],[`TemporalTime`,{select:`Temporal.PlainTime`,write:`Temporal.PlainTime | string`}]]);function emptyUsedUtilityTypes(){return{Timestamp:!1,TemporalDate:!1,TemporalInstant:!1,TemporalTime:!1,Serial:!1,ObjectColumnType:!1,ArrayColumnType:!1}}function mergeUsedUtilityTypes(e,t){return{Timestamp:e.Timestamp||t.Timestamp,TemporalDate:e.TemporalDate||t.TemporalDate,TemporalInstant:e.TemporalInstant||t.TemporalInstant,TemporalTime:e.TemporalTime||t.TemporalTime,Serial:e.Serial||t.Serial,ObjectColumnType:e.ObjectColumnType||t.ObjectColumnType,ArrayColumnType:e.ArrayColumnType||t.ArrayColumnType}}function usesColumnTypeAlias(e){return e.Timestamp||e.TemporalDate||e.TemporalInstant||e.TemporalTime}function getEnumType(e){let t=e.allowedValues;return t&&Array.isArray(t)?t.map(e=>`"${typeof e==`string`?e:e.value}"`).join(` | `):`string`}function getNestedType(e,t){let n=e.fields;if(!n||typeof n!=`object`)return{type:`string`,usedUtilityTypes:emptyUsedUtilityTypes()};let r=Object.entries(n).map(([e,n])=>{let r=generateFieldType(n,t,!0);return{fieldType:`${e}${n.required===!0?``:`?`}: ${r.type}`,usedUtilityTypes:r.usedUtilityTypes}}),i=r.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),a=r.map(e=>e.fieldType),o=`{\n ${a.join(`;
7
- `)}${a.length>0?`;`:``}\n}`,s=Object.values(n).some(e=>e.required!==!0),c=Object.values(n).some(e=>e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0);return usesColumnTypeAlias(i)||s||c?{type:`ObjectColumnType<${o}>`,usedUtilityTypes:{...i,ObjectColumnType:!0}}:{type:o,usedUtilityTypes:i}}function getBaseType(e,t,n){let r=e.type,i=emptyUsedUtilityTypes();if(r===`enum`)return{type:getEnumType(e),usedUtilityTypes:i};if(r===`nested`)return getNestedType(e,t);let a=mapFieldTypeToColumnType(r,t&&!(n&&r===`time`));switch(a){case`Timestamp`:i.Timestamp=!0;break;case`TemporalDate`:i.TemporalDate=!0;break;case`TemporalInstant`:i.TemporalInstant=!0;break;case`TemporalTime`:i.TemporalTime=!0}return{type:a,usedUtilityTypes:i}}function generateFieldType(e,t,n=!1){let r=getBaseType(e,t,n),i={...r.usedUtilityTypes},o=e.array===!0,s=e.required!==!0,c=a.has(r.type),l=r.type;return o&&(c||l.startsWith(`ObjectColumnType<`)?(l=`ArrayColumnType<${r.type}>`,i.ArrayColumnType=!0):l=e.type===`enum`?`(${r.type})[]`:`${r.type}[]`),s&&(l=`${l} | null`),e.serial&&(i.Serial=!0,l=`Serial<${l}>`),(e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0)&&(l=`Generated<${l}>`),{type:l,usedUtilityTypes:i}}function generateTableInterface(t,n,r){let i=Object.entries(n).filter(([e])=>e!==`id`).map(([e,t])=>({fieldName:e,...generateFieldType(t,r)})),a=[`id: Generated<string>;`,...i.map(e=>`${e.fieldName}: ${e.type};`)],o=i.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes());return{typeDef:e`
8
- ${t}: {
9
- ${a.join(`
10
- `)}
11
- }
12
- `,usedUtilityTypes:o}}function processKyselyFields(e,t,n=!1){let r=generateTableInterface(e,t,n);return{name:e,typeDef:r.typeDef,usedUtilityTypes:r.usedUtilityTypes}}async function processKyselyType(e,t=!1){return processKyselyFields(e.name,Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,t.config])),t)}function generateUnifiedKyselyTypes(t,n=!1){if(t.length===0)return``;let r=t.flatMap(e=>e.types).reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),i=[`type Generated`];return r.Timestamp&&i.push(`type Timestamp`),r.TemporalDate&&i.push(`type TemporalDate`),r.TemporalInstant&&i.push(`type TemporalInstant`),r.TemporalTime&&i.push(`type TemporalTime`),r.ObjectColumnType&&i.push(`type ObjectColumnType`),r.ArrayColumnType&&i.push(`type ArrayColumnType`),r.Serial&&i.push(`type Serial`),[e`
13
- import {
14
- createGetDB,
15
- ${i.join(`,
16
- `)},
17
- type NamespaceDB,
18
- type NamespaceInsertable,
19
- type NamespaceSelectable,
20
- type NamespaceTable,
21
- type NamespaceTableName,
22
- type NamespaceTransaction,
23
- type NamespaceUpdateable,
24
- } from "@tailor-platform/sdk/kysely";
25
- `,`export interface Namespace {\n${t.map(({namespace:e,types:t})=>` "${e}": {\n${t.map(e=>e.typeDef.split(`
26
- `).map(e=>e.trim()?` ${e}`:``).join(`
27
- `)).join(`
28
-
29
- `)}\n }`).join(`,
30
- `)}\n}`,e`
31
- export const getDB = createGetDB<Namespace>(${n?`{ temporal: true }`:``});
32
-
33
- export type DB<N extends keyof Namespace = keyof Namespace> = NamespaceDB<Namespace, N>;
34
- `,e`
35
- export type Transaction<K extends keyof Namespace | DB = keyof Namespace> =
36
- NamespaceTransaction<Namespace, K>;
37
-
38
- type TableName = NamespaceTableName<Namespace>;
39
- export type Table<T extends TableName> = NamespaceTable<Namespace, T>;
40
-
41
- export type Insertable<T extends TableName> = NamespaceInsertable<Namespace, T>;
42
- export type Selectable<T extends TableName> = NamespaceSelectable<Namespace, T>;
43
- export type Updateable<T extends TableName> = NamespaceUpdateable<Namespace, T>;
44
- `].join(`
45
-
46
- `)+`
47
- `}const o=`@tailor-platform/kysely-type`,s=`./generated/tailordb.ts`;function kyselyTypePlugin(e){return{id:o,description:`Generates Kysely type definitions for TailorDB tables`,pluginConfig:e,async onTailorDBReady(e){let{distPath:n,pgliteSchemaPath:r,temporal:i}=e.pluginConfig;if(r&&t(n)===t(r))throw Error(`distPath and pgliteSchemaPath must resolve to different files.`);let a=[];for(let t of e.tailordb){let e=[];for(let n of Object.values(t.tables)){let t=await processKyselyType(n,i);e.push(t)}e.length!==0&&a.push({namespace:t.namespace,types:e})}let o=[];if(a.length>0){let t=generateUnifiedKyselyTypes(a,i);o.push({path:e.pluginConfig.distPath,content:t}),e.pluginConfig.pgliteSchemaPath&&o.push({path:e.pluginConfig.pgliteSchemaPath,content:generatePGliteSchemaModule(e.tailordb.filter(e=>Object.keys(e.tables).length>0))})}return{files:o}}}}export{processKyselyFields as a,generatePgliteSchemaModule as c,generateUnifiedKyselyTypes as i,o as n,a as o,kyselyTypePlugin as r,mapFieldTypeToColumnType as s,s as t};
48
- //# sourceMappingURL=kysely-type-BWMfV301.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"kysely-type-BWMfV301.mjs","names":["multiline","utf8","fieldType","name","hash","byte","value","suffix","tableName","memberName","kind","head","base","field","pgType","label","CURRENT_TIME_EXPRESSIONS","currentTime","v","groups","format","conversion","fieldName","range","serial","SERIAL_CONVERSIONS","nextval","sequence","number","width","zeroPad","prefix","column","parts","hasDefault","filledOnCreate","tableIdentifier","table","sequences","ownerships","columns","indexes","index","tables","statement","entries","namespaces","namespace","options","type","temporal","COLUMN_TYPE_ALIASES","a","b","usedUtilityTypes","allowedValues","fieldConfig","fields","fieldResults","config","result","aggregatedUtilityTypes","acc","fieldTypes","r","obj","hasOptionalFields","hasGeneratedFields","nested","baseTypeResult","isArray","isNullable","isColumnTypeBase","finalType","fieldLines","parsedField","namespaceData","globalUsedUtilityTypes","ns","utilityTypeImports","types","line","KyselyGeneratorID","DEFAULT_KYSELY_TYPES_DIST_PATH","ctx","pgliteSchemaPath","resolve","distPath","allNamespaceData","typeMetadataList","metadata","files","content"],"sources":["../src/utils/tailordb-ddl.ts","../src/plugin/builtin/kysely-type/pglite-schema.ts","../src/utils/field-column-type.ts","../src/plugin/builtin/kysely-type/type-processor.ts","../src/plugin/builtin/kysely-type/index.ts"],"sourcesContent":["/**\n * PostgreSQL DDL derived from TailorDB table definitions, for creating the\n * tables a PGlite-backed test needs. The columns match the flat shape the\n * Kysely type generators emit, not TailorDB's storage layout.\n */\n\n/** The field shape the DDL generator reads; parsed and snapshot field configs are both assignable. */\nexport interface DDLFieldConfig {\n type: string;\n required?: boolean;\n array?: boolean;\n unique?: boolean;\n serial?: { start: number; maxValue?: number; format?: string };\n scale?: number;\n default?: unknown;\n optionalOnCreate?: boolean;\n hooks?: { create?: unknown; update?: unknown };\n fields?: Record<string, DDLFieldConfig>;\n}\n\n/** A table to emit DDL for. */\nexport interface DDLTableConfig {\n name: string;\n fields: Record<string, DDLFieldConfig>;\n indexes?: Record<string, { fields: string[]; unique?: boolean }>;\n}\n\nconst MAX_IDENTIFIER_BYTES = 63;\n// The platform rounds decimals to their scale (6 unless configured); numeric\n// needs a precision to carry a scale, and the maximum leaves it unconstrained.\nconst DECIMAL_PRECISION = 1000;\nconst DEFAULT_DECIMAL_SCALE = 6;\nconst utf8 = new TextEncoder();\n\n/**\n * Map a TailorDB field type to the PostgreSQL column type PGlite tests use for it.\n * @param fieldType - TailorDB field type name\n * @returns The PostgreSQL type name\n * @throws If the type is not a TailorDB field type\n */\nexport function mapFieldTypeToPostgresType(fieldType: string): string {\n switch (fieldType) {\n case \"uuid\":\n return \"uuid\";\n case \"string\":\n case \"enum\":\n return \"text\";\n case \"boolean\":\n case \"bool\":\n return \"boolean\";\n case \"integer\":\n return \"integer\";\n case \"float\":\n return \"double precision\";\n case \"decimal\":\n return \"numeric\";\n case \"date\":\n return \"date\";\n case \"datetime\":\n return \"timestamptz\";\n case \"time\":\n return \"time\";\n case \"nested\":\n return \"jsonb\";\n default:\n throw new Error(`Field type \"${fieldType}\" has no PostgreSQL column type.`);\n }\n}\n\nfunction identifier(name: string): string {\n return `\"${name.replaceAll('\"', '\"\"')}\"`;\n}\n\nfunction fnv1aHex(value: string): string {\n let hash = 0x811c9dc5;\n for (const byte of utf8.encode(value)) {\n hash = Math.imul(hash ^ byte, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, \"0\");\n}\n\nfunction derivedIdentifier(tableName: string, memberName: string, kind: \"seq\" | \"idx\"): string {\n const suffix = `_${fnv1aHex(JSON.stringify([tableName, memberName, kind]))}_${kind}`;\n let head = `${tableName}_${memberName}`;\n while (utf8.encode(head + suffix).length > MAX_IDENTIFIER_BYTES) head = head.slice(0, -1);\n return identifier(head + suffix);\n}\n\nfunction stringLiteral(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction columnType(field: DDLFieldConfig): string {\n const base =\n field.type === \"decimal\"\n ? `numeric(${DECIMAL_PRECISION}, ${field.scale ?? DEFAULT_DECIMAL_SCALE})`\n : mapFieldTypeToPostgresType(field.type);\n return field.array && field.type !== \"nested\" ? `${base}[]` : base;\n}\n\nfunction scalarLiteral(value: unknown, field: DDLFieldConfig, label: string): string {\n const pgType = mapFieldTypeToPostgresType(field.type);\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new Error(`Default of field ${label} is an invalid Date.`);\n }\n return `${stringLiteral(value.toISOString())}::${pgType}`;\n }\n switch (typeof value) {\n case \"string\":\n return pgType === \"text\" ? stringLiteral(value) : `${stringLiteral(value)}::${pgType}`;\n case \"number\":\n if (!Number.isFinite(value)) {\n throw new Error(`Default of field ${label} is not a finite number.`);\n }\n return String(value);\n case \"boolean\":\n return value ? \"TRUE\" : \"FALSE\";\n default:\n throw new Error(`Default of field ${label} cannot be rendered as a SQL literal.`);\n }\n}\n\nconst CURRENT_TIME_EXPRESSIONS = new Map([\n [\"datetime\", \"now()\"],\n [\"date\", \"CURRENT_DATE\"],\n [\"time\", \"LOCALTIME\"],\n]);\n\nfunction defaultExpression(field: DDLFieldConfig, label: string): string {\n const value = field.default;\n const currentTime = CURRENT_TIME_EXPRESSIONS.get(field.type);\n if (value === \"now\" && currentTime !== undefined) {\n return currentTime;\n }\n if (field.array) {\n if (!Array.isArray(value)) {\n throw new Error(`Default of array field ${label} must be an array.`);\n }\n const pgType = columnType(field);\n if (value.length === 0) return `'{}'::${pgType}`;\n return `ARRAY[${value.map((v) => scalarLiteral(v, field, label)).join(\", \")}]::${pgType}`;\n }\n return scalarLiteral(value, field, label);\n}\n\ninterface SerialFormat {\n prefix: string;\n width: number;\n zeroPad: boolean;\n conversion: \"d\" | \"x\" | \"X\";\n suffix: string;\n}\n\n// printf-style with exactly one conversion specifier; octal has no Postgres\n// formatting function to stand in for it.\nfunction parseSerialFormat(format: string, label: string): SerialFormat {\n const match =\n /^(?<prefix>[^%]*)%(?<zero>0?)(?<width>\\d*)(?<conversion>[a-zA-Z])(?<suffix>[^%]*)$/.exec(\n format,\n );\n const groups = match?.groups;\n const conversion = groups?.conversion;\n if (!groups || (conversion !== \"d\" && conversion !== \"x\" && conversion !== \"X\")) {\n throw new Error(\n `Serial format \"${format}\" of field ${label} is not supported; use a single %d, %x, or %X specifier with an optional width (e.g. \"INV-%05d\").`,\n );\n }\n return {\n prefix: groups.prefix ?? \"\",\n zeroPad: groups.zero === \"0\",\n width: groups.width ? Number(groups.width) : 0,\n conversion,\n suffix: groups.suffix ?? \"\",\n };\n}\n\nfunction sequenceName(tableName: string, fieldName: string): string {\n return derivedIdentifier(tableName, fieldName, \"seq\");\n}\n\n// A sequence's minimum defaults to 1, which rejects a start of 0.\nfunction sequenceRange(serial: NonNullable<DDLFieldConfig[\"serial\"]>): string {\n const range = [`START WITH ${serial.start}`, `MINVALUE ${serial.start}`];\n if (serial.maxValue !== undefined) range.push(`MAXVALUE ${serial.maxValue}`);\n return range.join(\" \");\n}\n\nconst SERIAL_CONVERSIONS: Record<SerialFormat[\"conversion\"], (nextval: string) => string> = {\n d: (nextval) => nextval,\n x: (nextval) => `to_hex(${nextval})`,\n X: (nextval) => `upper(to_hex(${nextval}))`,\n};\n\nfunction serialStringDefault(sequence: string, format: string | undefined, label: string): string {\n const nextval = `nextval(${stringLiteral(sequence)})`;\n if (format === undefined) return `(${nextval}::text)`;\n const { prefix, width, zeroPad, conversion, suffix } = parseSerialFormat(format, label);\n const number = SERIAL_CONVERSIONS[conversion](nextval);\n let value = conversion === \"d\" ? `${number}::text` : number;\n if (width > 0) {\n value = `format('%${width}s', ${number})`;\n if (zeroPad) value = `translate(${value}, ' ', '0')`;\n }\n const parts = [\n ...(prefix ? [stringLiteral(prefix)] : []),\n value,\n ...(suffix ? [stringLiteral(suffix)] : []),\n ];\n return `(${parts.join(\" || \")})`;\n}\n\nfunction columnDefinition(tableName: string, fieldName: string, field: DDLFieldConfig): string {\n const column = identifier(fieldName);\n const label = `${identifier(tableName)}.${column}`;\n const parts = [column, columnType(field)];\n\n if (field.serial) {\n if (field.type === \"integer\") {\n parts.push(`GENERATED BY DEFAULT AS IDENTITY (${sequenceRange(field.serial)})`);\n if (field.unique) parts.push(\"UNIQUE\");\n return parts.join(\" \");\n }\n if (field.required) parts.push(\"NOT NULL\");\n if (field.unique) parts.push(\"UNIQUE\");\n parts.push(\n `DEFAULT ${serialStringDefault(sequenceName(tableName, fieldName), field.serial.format, label)}`,\n );\n return parts.join(\" \");\n }\n\n const hasDefault = field.default !== undefined;\n const filledOnCreate = field.hooks?.create !== undefined || field.optionalOnCreate === true;\n if (field.required && (hasDefault || !filledOnCreate)) parts.push(\"NOT NULL\");\n if (field.unique) parts.push(\"UNIQUE\");\n if (hasDefault) parts.push(`DEFAULT ${defaultExpression(field, label)}`);\n return parts.join(\" \");\n}\n\n/**\n * DDL statements that create one table: any sequences its string serial\n * fields draw from, the table, the sequences' ownership of their columns,\n * then its unique indexes. Every statement is `IF NOT EXISTS` or otherwise\n * idempotent, so re-applying the script on a database that already has the\n * table is a no-op. Owning a sequence makes `DROP TABLE` drop it and\n * `TRUNCATE ... RESTART IDENTITY` reset it to the configured start. Index\n * names end in `_idx` so they cannot take the `<table>_<column>_key` name\n * Postgres gives a UNIQUE column, which `IF NOT EXISTS` would otherwise\n * silently skip.\n * @param table - Table name, fields, and indexes\n * @returns Statements in execution order, without trailing semicolons\n * @throws If a field type, default, or serial format cannot be expressed\n */\nexport function generateTableDDL(table: DDLTableConfig): string[] {\n const tableIdentifier = identifier(table.name);\n const sequences: string[] = [];\n const ownerships: string[] = [];\n const columns = [` \"id\" uuid PRIMARY KEY DEFAULT gen_random_uuid()`];\n\n for (const [fieldName, field] of Object.entries(table.fields)) {\n if (fieldName === \"id\") continue;\n if (field.serial && field.type !== \"integer\") {\n const sequence = sequenceName(table.name, fieldName);\n sequences.push(`CREATE SEQUENCE IF NOT EXISTS ${sequence} ${sequenceRange(field.serial)}`);\n ownerships.push(\n `ALTER SEQUENCE ${sequence} OWNED BY ${tableIdentifier}.${identifier(fieldName)}`,\n );\n }\n columns.push(` ${columnDefinition(table.name, fieldName, field)}`);\n }\n\n const indexes = Object.entries(table.indexes ?? {})\n .filter(([, index]) => index.unique)\n .map(\n ([name, index]) =>\n `CREATE UNIQUE INDEX IF NOT EXISTS ${derivedIdentifier(table.name, name, \"idx\")} ON ${tableIdentifier} (${index.fields.map(identifier).join(\", \")})`,\n );\n\n return [\n ...sequences,\n `CREATE TABLE IF NOT EXISTS ${tableIdentifier} (\\n${columns.join(\",\\n\")}\\n)`,\n ...ownerships,\n ...indexes,\n ];\n}\n\n/**\n * A single SQL script creating every given table, for `pglite.exec()`.\n * @param tables - Tables in the order to create them\n * @returns The script, empty when there are no tables\n */\nexport function generateSchemaDDL(tables: readonly DDLTableConfig[]): string {\n return tables\n .map((table) =>\n generateTableDDL(table)\n .map((statement) => `${statement};`)\n .join(\"\\n\"),\n )\n .join(\"\\n\\n\");\n}\n\n/** One namespace's tables, as the schema module groups them. */\nexport interface PgliteSchemaNamespace {\n namespace: string;\n tables: readonly DDLTableConfig[];\n}\n\n/** Options for {@link generatePgliteSchemaModule}. */\nexport interface PgliteSchemaModuleOptions {\n /** Named in the generated header as the producer users must not edit around. */\n generatedBy: string;\n}\n\n// A template literal keeps line feeds but folds a carriage return into one.\nfunction templateLiteral(value: string): string {\n const escaped = value\n .replaceAll(\"\\\\\", \"\\\\\\\\\")\n .replaceAll(\"`\", \"\\\\`\")\n .replaceAll(\"${\", \"\\\\${\")\n .replaceAll(\"\\r\", \"\\\\r\");\n return `\\`${escaped}\\``;\n}\n\n/**\n * Render the module that exports each namespace's `CREATE TABLE` script for\n * `pglite.exec()`.\n * @param namespaces - Namespaces with the tables to create\n * @param options - Header wording\n * @returns TypeScript source of the schema module\n */\nexport function generatePgliteSchemaModule(\n namespaces: readonly PgliteSchemaNamespace[],\n options: PgliteSchemaModuleOptions,\n): string {\n const entries = namespaces.map(\n ({ namespace, tables }) =>\n ` ${JSON.stringify(namespace)}: ${templateLiteral(generateSchemaDDL(tables))},`,\n );\n return [\n \"/**\",\n \" * Auto-generated PGlite schema for TailorDB tables.\",\n \" * Create a namespace's tables in a test with `pglite.exec(pgliteSchema[namespace])`.\",\n \" *\",\n ` * DO NOT EDIT - This file is auto-generated by ${options.generatedBy}.`,\n \" */\",\n \"\",\n \"export const pgliteSchema = {\",\n ...entries,\n \"} as const;\",\n \"\",\n ].join(\"\\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","/** The Kysely column type a TailorDB field maps to, before array/null modifiers. */\nexport type FieldColumnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"Timestamp\"\n | \"TemporalDate\"\n | \"TemporalInstant\"\n | \"TemporalTime\";\n\n/**\n * Map a scalar TailorDB field type to the column type generated code uses for it.\n *\n * With `temporal: false` (the default), `date`/`datetime` resolve to `Timestamp` and\n * `time` to `string`, because that's what the function runtime hands back for them by\n * default. With `temporal: true`, `date`/`datetime`/`time` resolve to their\n * `Temporal.PlainDate`/`Temporal.Instant`/`Temporal.PlainTime` counterparts instead,\n * matching a `getDB` created with `createGetDB({ temporal: true })`.\n *\n * `enum` and `nested` carry their own shape, so each generator resolves them\n * before reaching here; passing either is a caller bug rather than a `string`\n * column.\n * @param fieldType - TailorDB scalar field type name\n * @param temporal - Whether to map date/datetime/time fields to their Temporal column\n * types instead of their `Date`/`string` defaults\n * @returns The column type for the field, defaulting to `string`\n * @throws If given `enum` or `nested`\n */\nexport function mapFieldTypeToColumnType(fieldType: string, temporal = false): FieldColumnType {\n switch (fieldType) {\n case \"uuid\":\n case \"string\":\n case \"decimal\":\n return \"string\";\n case \"integer\":\n case \"float\":\n return \"number\";\n case \"date\":\n return temporal ? \"TemporalDate\" : \"Timestamp\";\n case \"datetime\":\n return temporal ? \"TemporalInstant\" : \"Timestamp\";\n case \"time\":\n return temporal ? \"TemporalTime\" : \"string\";\n case \"bool\":\n case \"boolean\":\n return \"boolean\";\n case \"enum\":\n case \"nested\":\n throw new Error(\n `Field type \"${fieldType}\" has no scalar column type; resolve it before mapping.`,\n );\n default:\n return \"string\";\n }\n}\n\n/** The select and write types a `ColumnType`-shaped alias expands to. */\nexport type ColumnTypeAliasExpansion = {\n /** Type the alias reads back as. */\n readonly select: string;\n /** Type the alias accepts on insert and update. */\n readonly write: string;\n};\n\n/**\n * Column types whose alias expands to a `ColumnType`, mapped to that expansion.\n *\n * Kysely only unwraps a `ColumnType` at the top level of a table property, so an\n * array of one of these stays wrapped in `ArrayColumnType<...>` rather than taking\n * a `[]` suffix, which would nest the `ColumnType` out of Kysely's reach. Where a\n * generator has to spell out the slots itself, it reads the expansion from here\n * rather than inlining the alias, which would nest just the same.\n *\n * Both type generators track alias usage per alias to decide which declarations to\n * emit, so adding an entry here also means teaching them to report the new alias.\n */\nexport const COLUMN_TYPE_ALIASES: ReadonlyMap<string, ColumnTypeAliasExpansion> = new Map<\n FieldColumnType,\n ColumnTypeAliasExpansion\n>([\n [\"Timestamp\", { select: \"Date\", write: \"Date | string\" }],\n [\"TemporalDate\", { select: \"Temporal.PlainDate\", write: \"Temporal.PlainDate | string\" }],\n [\"TemporalInstant\", { select: \"Temporal.Instant\", write: \"Temporal.Instant | string\" }],\n [\"TemporalTime\", { select: \"Temporal.PlainTime\", write: \"Temporal.PlainTime | string\" }],\n]);\n","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 {\n Timestamp: false,\n TemporalDate: false,\n TemporalInstant: false,\n TemporalTime: false,\n Serial: false,\n ObjectColumnType: false,\n ArrayColumnType: false,\n };\n}\n\nfunction mergeUsedUtilityTypes(a: UsedUtilityTypes, b: UsedUtilityTypes): UsedUtilityTypes {\n return {\n Timestamp: a.Timestamp || b.Timestamp,\n TemporalDate: a.TemporalDate || b.TemporalDate,\n TemporalInstant: a.TemporalInstant || b.TemporalInstant,\n TemporalTime: a.TemporalTime || b.TemporalTime,\n Serial: a.Serial || b.Serial,\n ObjectColumnType: a.ObjectColumnType || b.ObjectColumnType,\n ArrayColumnType: a.ArrayColumnType || b.ArrayColumnType,\n };\n}\n\n/**\n * Whether a utility-type usage record uses any `ColumnType`-shaped alias.\n * @param usedUtilityTypes - Utility-type usage record to check\n * @returns Whether any `ColumnType`-shaped alias is used\n */\nfunction usesColumnTypeAlias(usedUtilityTypes: UsedUtilityTypes): boolean {\n return (\n usedUtilityTypes.Timestamp ||\n usedUtilityTypes.TemporalDate ||\n usedUtilityTypes.TemporalInstant ||\n usedUtilityTypes.TemporalTime\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 * @param temporal - Whether date/datetime/time fields resolve to their Temporal column\n * types instead of their `Date`/`string` defaults\n * @returns The nested type with used utility types\n */\nfunction getNestedType(fieldConfig: KyselyFieldConfig, temporal: boolean): 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, temporal, true);\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 (usesColumnTypeAlias(aggregatedUtilityTypes) || 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 * @param temporal - Whether date/datetime/time fields resolve to their Temporal column\n * types instead of their `Date`/`string` defaults\n * @param nested - Whether the field is inside an object\n * @returns The base type with used utility types\n */\nfunction getBaseType(\n fieldConfig: KyselyFieldConfig,\n temporal: boolean,\n nested: boolean,\n): 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, temporal);\n }\n\n const type = mapFieldTypeToColumnType(fieldType, temporal && !(nested && fieldType === \"time\"));\n switch (type) {\n case \"Timestamp\":\n usedUtilityTypes.Timestamp = true;\n break;\n case \"TemporalDate\":\n usedUtilityTypes.TemporalDate = true;\n break;\n case \"TemporalInstant\":\n usedUtilityTypes.TemporalInstant = true;\n break;\n case \"TemporalTime\":\n usedUtilityTypes.TemporalTime = true;\n break;\n case \"string\":\n case \"number\":\n case \"boolean\":\n break;\n }\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 * @param temporal - Whether date/datetime/time fields resolve to their Temporal column\n * types instead of their `Date`/`string` defaults\n * @param nested - Whether the field is inside an object\n * @returns The complete field type with used utility types\n */\nfunction generateFieldType(\n fieldConfig: KyselyFieldConfig,\n temporal: boolean,\n nested = false,\n): FieldTypeResult {\n const baseTypeResult = getBaseType(fieldConfig, temporal, nested);\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 * @param temporal - Whether date/datetime/time fields resolve to their Temporal column\n * types instead of their `Date`/`string` defaults\n * @returns The type definition and used utility types\n */\nfunction generateTableInterface(\n name: string,\n fields: Record<string, KyselyFieldConfig>,\n temporal: boolean,\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, temporal),\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 * @param temporal - Whether date/datetime/time fields resolve to their Temporal column\n * types instead of their `Date`/`string` defaults. Defaults to `false`.\n * @returns Generated Kysely type metadata\n */\nexport function processKyselyFields(\n name: string,\n fields: Record<string, KyselyFieldConfig>,\n temporal = false,\n): KyselyTypeMetadata {\n const result = generateTableInterface(name, fields, temporal);\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 * @param temporal - Whether date/datetime/time fields resolve to their Temporal column\n * types instead of their `Date`/`string` defaults. Defaults to `false`.\n * @returns Generated Kysely type metadata\n */\nexport async function processKyselyType(\n type: TailorDBType,\n temporal = false,\n): 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 temporal,\n );\n}\n\n/**\n * Generate unified types file from multiple namespaces.\n * @param namespaceData - Namespace metadata\n * @param temporal - Whether `kyselyTypePlugin` was configured with `{ temporal: true }`;\n * passed to `createGetDB` so the generated `getDB` always reads back the Temporal values\n * the tables above are typed with. Defaults to `false`.\n * @returns Generated types file contents\n */\nexport function generateUnifiedKyselyTypes(\n namespaceData: KyselyNamespaceMetadata[],\n temporal = false,\n): 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.TemporalDate) {\n utilityTypeImports.push(\"type TemporalDate\");\n }\n if (globalUsedUtilityTypes.TemporalInstant) {\n utilityTypeImports.push(\"type TemporalInstant\");\n }\n if (globalUsedUtilityTypes.TemporalTime) {\n utilityTypeImports.push(\"type TemporalTime\");\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>(${temporal ? \"{ temporal: true }\" : \"\"});\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 { 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 * When `true`, generated tables map date/datetime fields and top-level time fields to\n * `Temporal.PlainDate`/`Temporal.Instant`/`Temporal.PlainTime` columns instead of\n * their `Date`/`string` defaults, and the generated `getDB` reads them back as those\n * Temporal values. Nested time fields remain strings. Defaults to `false`.\n */\n temporal?: boolean;\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 * @param options.temporal - When `true`, generated tables map date/datetime fields and\n * top-level time fields to their `Temporal.PlainDate`/`Temporal.Instant`/\n * `Temporal.PlainTime` counterparts instead of `Date`/`string`. Nested time fields\n * remain strings. Defaults to `false`.\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, temporal } = 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, temporal);\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, temporal);\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":"6EA2BA,MAKMC,EAAO,IAAI,YAQjB,SAAgB,2BAA2B,EAA2B,CACpE,OAAQC,EAAR,CACE,IAAK,OACH,MAAO,OACT,IAAK,SACL,IAAK,OACH,MAAO,OACT,IAAK,UACL,IAAK,OACH,MAAO,UACT,IAAK,UACH,MAAO,UACT,IAAK,QACH,MAAO,mBACT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C3C,IAAMY,EAAW,MAAM,kBAAkBzC,EAAMC,CAAQ,EACvDuC,EAAiB,KAAKC,CAAQ,CAChC,CAEID,EAAiB,SAAW,GAEhCD,EAAiB,KAAK,CACpB,UAAWV,EAAG,UACd,MAAOW,CACT,CAAC,CACH,CAEA,IAAME,EAAkC,CAAC,EACzC,GAAIH,EAAiB,OAAS,EAAG,CAC/B,IAAMI,EAAU,2BAA2BJ,EAAkBtC,CAAQ,EACrEyC,EAAM,KAAK,CACT,KAAMP,EAAI,aAAa,SACvB,SACF,CAAC,EACGA,EAAI,aAAa,kBACnBO,EAAM,KAAK,CACT,KAAMP,EAAI,aAAa,iBACvB,QAAS,2BACPA,EAAI,SAAS,OAAQ,GAAO,OAAO,KAAKN,EAAG,MAAM,CAAC,CAAC,OAAS,CAAC,CAC/D,CACF,CAAC,CAEL,CAEA,MAAO,CAAE,OAAM,CACjB,CACF,CACF"}
@@ -1,2 +0,0 @@
1
- import{t as e}from"./schema-B6hJQWp6.mjs";import{t}from"./assert-WeXvmG4j.mjs";import{n,r,t as i}from"./guards-yDXyKC9F.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-Bk-7vkwd.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"manager-Bk-7vkwd.mjs","names":["db","getPluginGenerationDependencies","plugin","plugins","context","tableConfigRequired","output","error","message","importPath","assertDefined","kind","table","executor","results","pluginId","config","namespace","executorKey","tableKey","getRawPluginTableName","params","currentTable","rawTable","extendedTable","generatedTables","events","attachment","attachments","result","extendFields","tableName","id","info","hasGenerationHooks","tableGenerationResult","tableGenerator","outputDir","pluginExecutors","executorGenerator","sourceTableInfoMap","configPath","existingFieldNames","originalTable","existingFileNames","newFieldNames","duplicateFields","name","duplicateFiles","_id","fieldsWithoutId","pluralForm","extended","original","metadata","_pluralForm","features","indexDefs","def"],"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,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