@tailor-platform/sdk 2.25.0 → 2.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +106 -0
- package/dist/application-DFeuELRo.mjs +200 -0
- package/dist/application-DFeuELRo.mjs.map +1 -0
- package/dist/application-nT_4a5HO.mjs +1 -0
- package/dist/cli/commands/deploy/deploy.d.mts +2 -0
- package/dist/cli/commands/deploy/tailordb/migration-validation.d.mts +2 -1
- package/dist/cli/commands/tailordb/migrate/bundler.d.mts +7 -6
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +12 -0
- package/dist/cli/commands/tailordb/migrate/remote-state.d.mts +1 -0
- package/dist/cli/lib.d.mts +2 -2
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +43 -43
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/workspace-name.d.mts +2 -0
- package/dist/completion/zsh-worker.zsh +4 -2
- package/dist/configure/config/types.d.mts +11 -0
- package/dist/configure/index.d.mts +6 -6
- package/dist/configure/index.mjs +1 -1
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/auth/types.d.mts +6 -1
- package/dist/configure/services/executor/trigger/event.d.mts +1 -1
- package/dist/configure/services/executor/trigger/webhook.d.mts +1 -1
- package/dist/configure/services/idp/permission.d.mts +2 -2
- package/dist/configure/services/resolver/resolver.d.mts +1 -1
- package/dist/configure/services/tailordb/schema.d.mts +1 -1
- package/dist/configure/services/tailordb/types.d.mts +1 -1
- package/dist/configure/services/workflow/job.d.mts +1 -1
- package/dist/configure/types/field.types.d.mts +48 -11
- package/dist/configure/types/type.d.mts +1 -1
- package/dist/date-CgP7gMG_.mjs +2 -0
- package/dist/date-CgP7gMG_.mjs.map +1 -0
- package/dist/{secretmanager-5olfnI1b.mjs → date-representation-Cr7W7Pn2.mjs} +2 -2
- package/dist/date-representation-Cr7W7Pn2.mjs.map +1 -0
- package/dist/{field-parse-DhnFs9WG.mjs → field-parse-C41e3UAF.mjs} +2 -2
- package/dist/{field-parse-DhnFs9WG.mjs.map → field-parse-C41e3UAF.mjs.map} +1 -1
- package/dist/idp-G_ojPBB5.mjs.map +1 -1
- package/dist/kysely/index.d.mts +47 -15
- package/dist/kysely/index.mjs +1 -1
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/kysely-type-RDX59E1j.mjs +48 -0
- package/dist/kysely-type-RDX59E1j.mjs.map +1 -0
- package/dist/{manager-8-JOvuLl.mjs → manager-Bk-7vkwd.mjs} +2 -2
- package/dist/{manager-8-JOvuLl.mjs.map → manager-Bk-7vkwd.mjs.map} +1 -1
- package/dist/migration-steps-C6F3zNdQ.mjs +3 -0
- package/dist/migration-steps-C6F3zNdQ.mjs.map +1 -0
- package/dist/plugin/builtin/kysely-type/index.d.mts +11 -0
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/register-ts-hook-D6KXrGrB.mjs +1009 -0
- package/dist/register-ts-hook-D6KXrGrB.mjs.map +1 -0
- package/dist/runtime/idp.d.mts +6 -0
- package/dist/runtime/index.d.mts +8 -0
- package/dist/runtime/index.mjs +1 -1
- package/dist/runtime/types.d.mts +5 -0
- package/dist/{schema-CRtAmDcl.mjs → schema-B6hJQWp6.mjs} +2 -2
- package/dist/{schema-CRtAmDcl.mjs.map → schema-B6hJQWp6.mjs.map} +1 -1
- package/dist/seed/index.d.mts +3 -1
- package/dist/seed/index.mjs +7 -9
- package/dist/seed/index.mjs.map +1 -1
- package/dist/service-Cc7OY0Oh.mjs +7 -0
- package/dist/service-Cc7OY0Oh.mjs.map +1 -0
- package/dist/service-sH2MZ4_W.mjs +1 -0
- package/dist/service_pb-Dw2ilc1O.mjs +2 -0
- package/dist/{service_pb-ZClWtj1X.mjs.map → service_pb-Dw2ilc1O.mjs.map} +1 -1
- package/dist/service_pb-GDOqfwb6.mjs +1 -0
- package/dist/types/field.generated.d.mts +2 -2
- package/dist/utils/test/index.mjs +1 -1
- package/dist/vitest/date-representation.d.mts +23 -0
- package/dist/vitest/index.d.mts +5 -2
- package/dist/vitest/index.mjs +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/migration-steps.d.mts +45 -0
- package/dist/vitest/mocks/file.d.mts +1 -1
- package/dist/vitest/mocks/idp.d.mts +1 -0
- package/dist/vitest/mocks/tailordb-pglite.d.mts +1 -0
- package/dist/vitest/pglite-kysely.d.mts +14 -1
- package/dist/vitest/pglite-temporal.d.mts +9 -0
- package/dist/vitest/setup.d.mts +3 -1
- package/dist/vitest/setup.mjs +1 -1
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/{workspace_resource_pb-CxR_6fyN.mjs → workspace_resource_pb-ChWejcj0.mjs} +2 -2
- package/dist/workspace_resource_pb-ChWejcj0.mjs.map +1 -0
- package/docs/cli/application.md +24 -16
- package/docs/cli/function.md +2 -0
- package/docs/cli/workspace.md +1 -1
- package/docs/configuration.md +19 -6
- package/docs/github-actions.md +124 -58
- package/docs/plugin/custom.md +2 -1
- package/docs/services/auth.md +20 -0
- package/docs/services/executor.md +2 -2
- package/docs/services/idp.md +6 -1
- package/docs/services/resolver.md +4 -2
- package/docs/services/staticwebsite.md +5 -5
- package/docs/services/tailordb-migration.md +159 -35
- package/docs/services/tailordb.md +2 -2
- package/docs/testing.md +5 -1
- package/package.json +12 -12
- package/dist/application-ChqHuhZW.mjs +0 -1
- package/dist/application-DS0XKBtK.mjs +0 -200
- package/dist/application-DS0XKBtK.mjs.map +0 -1
- package/dist/date-Dri6Yas-.mjs +0 -2
- package/dist/date-Dri6Yas-.mjs.map +0 -1
- package/dist/kysely-type-C-iyFFH7.mjs +0 -43
- package/dist/kysely-type-C-iyFFH7.mjs.map +0 -1
- package/dist/register-ts-hook-DPAW0Z4M.mjs +0 -924
- package/dist/register-ts-hook-DPAW0Z4M.mjs.map +0 -1
- package/dist/secretmanager-5olfnI1b.mjs.map +0 -1
- package/dist/service-Bx-7Lz06.mjs +0 -1
- package/dist/service-CL1Bp4It.mjs +0 -7
- package/dist/service-CL1Bp4It.mjs.map +0 -1
- package/dist/service_pb-ZClWtj1X.mjs +0 -2
- package/dist/service_pb-dB3RrGeh.mjs +0 -1
- package/dist/tailordb-ddl-DqInYupv.mjs +0 -7
- package/dist/tailordb-ddl-DqInYupv.mjs.map +0 -1
- package/dist/workspace_resource_pb-CxR_6fyN.mjs.map +0 -1
package/dist/date-Dri6Yas-.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function getTemporal(){let e=globalThis.Temporal;if(!e)throw ReferenceError(`Temporal is unavailable. Use the Tailor Platform runtime or the SDK tailor-runtime Vitest environment.`);return e}const e={get PlainDate(){return getTemporal().PlainDate},get PlainTime(){return getTemporal().PlainTime},get PlainDateTime(){return getTemporal().PlainDateTime},get PlainYearMonth(){return getTemporal().PlainYearMonth},get PlainMonthDay(){return getTemporal().PlainMonthDay},get ZonedDateTime(){return getTemporal().ZonedDateTime},get Duration(){return getTemporal().Duration},get Instant(){return getTemporal().Instant},get Now(){return getTemporal().Now}};function formatDate(e){return formatDateTime(e).slice(0,10)}function formatDateTime(e){let t=e.getUTCFullYear();if(!Number.isFinite(t)||t<0||t>9999){let n=Number.isNaN(e.getTime())?`an invalid Date`:`year ${t}`;throw RangeError(`Expected a Date with a 4-digit year (0000-9999), but received ${n}`)}return e.toISOString()}function formatHoursMinutes(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function formatTime(e){if(!Number.isFinite(e.getTime()))throw RangeError(`Expected a valid Date, but received an invalid Date`);return formatHoursMinutes(e.getUTCHours(),e.getUTCMinutes())}function formatTemporal(e){let t=getTemporal();if(e instanceof t.PlainTime)return formatHoursMinutes(e.hour,e.minute);let n=e.toString({calendarName:`never`});if(!/^\d{4}-/.test(n)){let r=e instanceof t.Instant;throw RangeError(`Expected a Temporal.${r?`Instant`:`PlainDate`} with a 4-digit ${r?`UTC `:``}year (0000-9999), but received ${n}`)}return n}function serialize(e,t,n){if(e.metadata.array){if(!Array.isArray(t))return t;let r=t.map((t,r)=>serializeValue(e,t,`${n}[${r}]`));return r.every((e,n)=>e===t[n])?t:r}return serializeValue(e,t,n)}function describePathTarget(e){return e||`the top-level value`}function truncateForDescription(e){return e.length>100?`${e.slice(0,100)}...`:e}function describeReceivedValue(e){if(Array.isArray(e)){let t=e.slice(0,100),n=[...new Set(Array.from(t,e=>typeof e))];return n.length>0?`an array of ${n.join(`/`)}`:`an empty array`}if(typeof e==`string`)return`a string (${JSON.stringify(truncateForDescription(e))})`;let t=typeof e;return t===`object`?`an object`:t===`function`?`a function`:`a ${t} (${truncateForDescription(String(e))})`}function dateRepresentationOf(e,t){return(e===`date`||e===`datetime`||e===`time`)&&(t===`date`||t===`temporal`)?t:void 0}function isDateRepresentationField(e,t){let n=dateRepresentationOf(e.type,e.metadata.as);return n!==void 0&&(t===void 0||n===t)}function throwInvalidDate(e,t){let n=e instanceof Error?e.message:String(e);throw RangeError(`Invalid date at ${describePathTarget(t)}: ${n}`,{cause:e})}function serializeAsDate(e,t,n){if(!(t instanceof Date))throw TypeError(`Expected a Date instance at ${describePathTarget(n)}, but received ${describeReceivedValue(t)}`);try{return e===`datetime`?formatDateTime(t):e===`time`?formatTime(t):formatDate(t)}catch(e){return throwInvalidDate(e,n)}}function serializeAsTemporal(e,t,n){let r=getTemporal(),i=e===`date`?r.PlainDate:e===`datetime`?r.Instant:r.PlainTime;if(!(t instanceof i))throw TypeError(`Expected a Temporal.${i.name} instance at ${describePathTarget(n)}, but received ${describeReceivedValue(t)}`);try{return formatTemporal(t)}catch(e){return throwInvalidDate(e,n)}}const t={date:globalThis.process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE?void 0:serializeAsDate,temporal:globalThis.process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL?void 0:serializeAsTemporal};function serializeValue(e,n,r){if(n==null)return n;let{type:i}=e,a=dateRepresentationOf(i,e.metadata.as);if(a){let e=t[a];if(!e)throw Error(`Serializing fields declared with as: "${a}" is not included in this bundle.`);return e(i,n,r)}if(i!==`nested`||typeof n!=`object`||Array.isArray(n))return n;let o=n,s=o;for(let[t,n]of Object.entries(e.fields)){let e=serialize(n,o[t],r?`${r}.${t}`:t);e!==o[t]&&(s===o&&(s={...o}),Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}))}return s}function hasDateRepresentationFields(e,t){return isDateRepresentationField(e,t)||Object.values(e.fields).some(e=>hasDateRepresentationFields(e,t))}function serializeDateFields(e,t){return serialize(e,t,``)}export{e as a,serializeDateFields as i,formatDate as n,getTemporal as o,hasDateRepresentationFields as r,dateRepresentationOf as t};
|
|
2
|
-
//# sourceMappingURL=date-Dri6Yas-.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"date-Dri6Yas-.mjs","names":["temporal","Temporal","date","year","received","hour","minute","value","iso","isInstant","field","converted","item","path","index","text","sample","elementTypes","type","as","representation","reason","error","expected","dateSerializers","serializeAs","record","result","key","child"],"sources":["../src/runtime/temporal.ts","../src/runtime/date.ts"],"sourcesContent":["import type { Temporal as TemporalTypes } from \"temporal-spec\";\n\n/**\n * Get the host Temporal implementation when a value is needed.\n * @returns Host Temporal implementation\n * @internal\n */\nexport function getTemporal(): typeof TemporalTypes {\n const temporal = (globalThis as unknown as { Temporal?: typeof TemporalTypes }).Temporal;\n if (!temporal) {\n throw new ReferenceError(\n \"Temporal is unavailable. Use the Tailor Platform runtime or the SDK tailor-runtime Vitest environment.\",\n );\n }\n return temporal;\n}\n\n/**\n * Typed access to the runtime's Temporal API, without installing a polyfill.\n * Constructors are resolved on access so configuration files can load in Node.js.\n * @example\n * import { Temporal } from \"@tailor-platform/sdk/runtime\";\n * const tomorrow: Temporal.PlainDate = Temporal.Now.plainDateISO().add({ days: 1 });\n */\nexport const Temporal: typeof TemporalTypes = {\n get PlainDate() {\n return getTemporal().PlainDate;\n },\n get PlainTime() {\n return getTemporal().PlainTime;\n },\n get PlainDateTime() {\n return getTemporal().PlainDateTime;\n },\n get PlainYearMonth() {\n return getTemporal().PlainYearMonth;\n },\n get PlainMonthDay() {\n return getTemporal().PlainMonthDay;\n },\n get ZonedDateTime() {\n return getTemporal().ZonedDateTime;\n },\n get Duration() {\n return getTemporal().Duration;\n },\n get Instant() {\n return getTemporal().Instant;\n },\n get Now() {\n return getTemporal().Now;\n },\n};\n\n/** Temporal instance types supplied by the SDK, independent of TypeScript's lib settings. */\n// Type-only merging supports Temporal.PlainDate annotations on the value import.\n// oxlint-disable-next-line typescript/no-namespace\nexport declare namespace Temporal {\n /** The runtime Temporal.PlainDate instance. */\n type PlainDate = TemporalTypes.PlainDate;\n /** The runtime Temporal.PlainTime instance. */\n type PlainTime = TemporalTypes.PlainTime;\n /** The runtime Temporal.PlainDateTime instance. */\n type PlainDateTime = TemporalTypes.PlainDateTime;\n /** The runtime Temporal.PlainYearMonth instance. */\n type PlainYearMonth = TemporalTypes.PlainYearMonth;\n /** The runtime Temporal.PlainMonthDay instance. */\n type PlainMonthDay = TemporalTypes.PlainMonthDay;\n /** The runtime Temporal.ZonedDateTime instance. */\n type ZonedDateTime = TemporalTypes.ZonedDateTime;\n /** The runtime Temporal.Duration instance. */\n type Duration = TemporalTypes.Duration;\n /** The runtime Temporal.Instant instance. */\n type Instant = TemporalTypes.Instant;\n}\n","import { getTemporal } from \"./temporal\";\nimport type { FieldMetadata, TailorFieldType } from \"#/configure/types/field.types\";\nimport type { Temporal } from \"temporal-spec\";\n\n/**\n * Format a Date using its UTC calendar date.\n * @param date - Date to format\n * @returns Date string in YYYY-MM-DD format\n */\nexport function formatDate(date: Date): string {\n return formatDateTime(date).slice(0, 10);\n}\n\nfunction formatDateTime(date: Date): string {\n const year = date.getUTCFullYear();\n if (!Number.isFinite(year) || year < 0 || year > 9999) {\n const received = Number.isNaN(date.getTime()) ? \"an invalid Date\" : `year ${year}`;\n throw new RangeError(\n `Expected a Date with a 4-digit year (0000-9999), but received ${received}`,\n );\n }\n return date.toISOString();\n}\n\nfunction formatHoursMinutes(hour: number, minute: number): string {\n return `${String(hour).padStart(2, \"0\")}:${String(minute).padStart(2, \"0\")}`;\n}\n\nfunction formatTime(date: Date): string {\n if (!Number.isFinite(date.getTime())) {\n throw new RangeError(\"Expected a valid Date, but received an invalid Date\");\n }\n return formatHoursMinutes(date.getUTCHours(), date.getUTCMinutes());\n}\n\nfunction formatTemporal(value: Temporal.PlainDate | Temporal.Instant | Temporal.PlainTime): string {\n const Temporal = getTemporal();\n if (value instanceof Temporal.PlainTime) return formatHoursMinutes(value.hour, value.minute);\n const iso = value.toString({ calendarName: \"never\" });\n if (!/^\\d{4}-/.test(iso)) {\n const isInstant = value instanceof Temporal.Instant;\n throw new RangeError(\n `Expected a Temporal.${isInstant ? \"Instant\" : \"PlainDate\"} with a 4-digit ${isInstant ? \"UTC \" : \"\"}year (0000-9999), but received ${iso}`,\n );\n }\n return iso;\n}\n\ntype DateField = {\n readonly type: TailorFieldType;\n readonly metadata: FieldMetadata;\n readonly fields: Record<string, DateField>;\n};\n\ntype DateRepresentationField = {\n readonly type: TailorFieldType;\n readonly metadata: Pick<FieldMetadata, \"as\">;\n readonly fields: Record<string, DateRepresentationField>;\n};\n\nfunction serialize(field: DateField, value: unknown, path: string): unknown {\n if (field.metadata.array) {\n if (!Array.isArray(value)) return value;\n const converted = value.map((item, index) => serializeValue(field, item, `${path}[${index}]`));\n return converted.every((item, index) => item === value[index]) ? value : converted;\n }\n return serializeValue(field, value, path);\n}\n\nfunction describePathTarget(path: string): string {\n return path || \"the top-level value\";\n}\n\nconst MAX_DESCRIBED_VALUE_LENGTH = 100;\nconst MAX_DESCRIBED_ARRAY_SAMPLE = 100;\n\nfunction truncateForDescription(text: string): string {\n return text.length > MAX_DESCRIBED_VALUE_LENGTH\n ? `${text.slice(0, MAX_DESCRIBED_VALUE_LENGTH)}...`\n : text;\n}\n\nfunction describeReceivedValue(value: unknown): string {\n if (Array.isArray(value)) {\n const sample = value.slice(0, MAX_DESCRIBED_ARRAY_SAMPLE);\n const elementTypes = [...new Set(Array.from(sample, (item) => typeof item))];\n return elementTypes.length > 0 ? `an array of ${elementTypes.join(\"/\")}` : \"an empty array\";\n }\n if (typeof value === \"string\")\n return `a string (${JSON.stringify(truncateForDescription(value))})`;\n const type = typeof value;\n if (type === \"object\") return \"an object\";\n if (type === \"function\") return \"a function\";\n return `a ${type} (${truncateForDescription(String(value))})`;\n}\n\ntype DateRepresentation = \"date\" | \"temporal\";\n\n/**\n * Get the Date or Temporal representation a field converts its values to.\n * @param type - Field type\n * @param as - The field's `as` option\n * @returns The representation, or undefined when values stay strings\n * @internal\n */\nexport function dateRepresentationOf(\n type: TailorFieldType,\n as: FieldMetadata[\"as\"],\n): DateRepresentation | undefined {\n return (type === \"date\" || type === \"datetime\" || type === \"time\") &&\n (as === \"date\" || as === \"temporal\")\n ? as\n : undefined;\n}\n\nfunction isDateRepresentationField(\n field: DateRepresentationField,\n representation?: DateRepresentation,\n): boolean {\n const as = dateRepresentationOf(field.type, field.metadata.as);\n return as !== undefined && (representation === undefined || as === representation);\n}\n\ntype DateSerializer = (type: TailorFieldType, value: unknown, path: string) => string;\n\nfunction throwInvalidDate(error: unknown, path: string): never {\n const reason = error instanceof Error ? error.message : String(error);\n throw new RangeError(`Invalid date at ${describePathTarget(path)}: ${reason}`, {\n cause: error,\n });\n}\n\nfunction serializeAsDate(type: TailorFieldType, value: unknown, path: string): string {\n if (!(value instanceof Date)) {\n throw new TypeError(\n `Expected a Date instance at ${describePathTarget(path)}, but received ${describeReceivedValue(value)}`,\n );\n }\n try {\n if (type === \"datetime\") return formatDateTime(value);\n if (type === \"time\") return formatTime(value);\n return formatDate(value);\n } catch (error) {\n return throwInvalidDate(error, path);\n }\n}\n\nfunction serializeAsTemporal(type: TailorFieldType, value: unknown, path: string): string {\n const Temporal = getTemporal();\n const expected =\n type === \"date\"\n ? Temporal.PlainDate\n : type === \"datetime\"\n ? Temporal.Instant\n : Temporal.PlainTime;\n if (!(value instanceof expected)) {\n throw new TypeError(\n `Expected a Temporal.${expected.name} instance at ${describePathTarget(path)}, but received ${describeReceivedValue(value)}`,\n );\n }\n try {\n return formatTemporal(value);\n } catch (error) {\n return throwInvalidDate(error, path);\n }\n}\n\ntype MaybeProcessGlobal = { process?: { env: Record<string, string | undefined> } };\n\nconst dateSerializers: Record<DateRepresentation, DateSerializer | undefined> = {\n date: (globalThis as MaybeProcessGlobal).process?.env.__TAILOR_PLATFORM_BUNDLE_WITHOUT_DATE\n ? undefined\n : serializeAsDate,\n temporal: (globalThis as MaybeProcessGlobal).process?.env\n .__TAILOR_PLATFORM_BUNDLE_WITHOUT_TEMPORAL\n ? undefined\n : serializeAsTemporal,\n};\n\nfunction serializeValue(field: DateField, value: unknown, path: string): unknown {\n if (value === null || value === undefined) return value;\n const { type } = field;\n const as = dateRepresentationOf(type, field.metadata.as);\n if (as) {\n const serializeAs = dateSerializers[as];\n if (!serializeAs) {\n throw new Error(\n `Serializing fields declared with as: \"${as}\" is not included in this bundle.`,\n );\n }\n return serializeAs(type, value, path);\n }\n if (type !== \"nested\" || typeof value !== \"object\" || Array.isArray(value)) return value;\n const record = value as Record<string, unknown>;\n let result = record;\n for (const [key, child] of Object.entries(field.fields)) {\n const converted = serialize(child, record[key], path ? `${path}.${key}` : key);\n if (converted !== record[key]) {\n if (result === record) result = { ...record };\n Object.defineProperty(result, key, {\n value: converted,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n }\n return result;\n}\n\n/**\n * Check whether a field or any of its nested fields uses a Date or Temporal representation.\n * @param field - Field to inspect\n * @param representation - Only match fields using this representation\n * @returns Whether serializeDateFields would convert any value of the field\n * @internal\n */\nexport function hasDateRepresentationFields(\n field: DateRepresentationField,\n representation?: DateRepresentation,\n): boolean {\n return (\n isDateRepresentationField(field, representation) ||\n Object.values(field.fields).some((child) => hasDateRepresentationFields(child, representation))\n );\n}\n\n/**\n * Convert fields using Date or Temporal representations to date, datetime, or time strings.\n * @param field - Field defining the value's shape\n * @param value - Value to serialize\n * @returns Value with Date and Temporal fields converted to strings\n * @internal\n */\nexport function serializeDateFields(field: DateField, value: unknown): unknown {\n return serialize(field, value, \"\");\n}\n"],"mappings":"AAOA,SAAgB,aAAoC,CAClD,IAAMA,EAAY,WAA8D,SAChF,GAAI,CAACA,EACH,MAAU,eACR,wGACF,EAEF,OAAOA,CACT,CASA,MAAaC,EAAiC,CAC5C,IAAI,WAAY,CACd,OAAO,YAAY,CAAC,CAAC,SACvB,EACA,IAAI,WAAY,CACd,OAAO,YAAY,CAAC,CAAC,SACvB,EACA,IAAI,eAAgB,CAClB,OAAO,YAAY,CAAC,CAAC,aACvB,EACA,IAAI,gBAAiB,CACnB,OAAO,YAAY,CAAC,CAAC,cACvB,EACA,IAAI,eAAgB,CAClB,OAAO,YAAY,CAAC,CAAC,aACvB,EACA,IAAI,eAAgB,CAClB,OAAO,YAAY,CAAC,CAAC,aACvB,EACA,IAAI,UAAW,CACb,OAAO,YAAY,CAAC,CAAC,QACvB,EACA,IAAI,SAAU,CACZ,OAAO,YAAY,CAAC,CAAC,OACvB,EACA,IAAI,KAAM,CACR,OAAO,YAAY,CAAC,CAAC,GACvB,CACF,EC3CA,SAAgB,WAAW,EAAoB,CAC7C,OAAO,eAAeC,CAAI,CAAC,CAAC,MAAM,EAAG,EAAE,CACzC,CAEA,SAAS,eAAe,EAAoB,CAC1C,IAAMC,EAAOD,EAAK,eAAe,EACjC,GAAI,CAAC,OAAO,SAASC,CAAI,GAAKA,EAAO,GAAKA,EAAO,KAAM,CACrD,IAAMC,EAAW,OAAO,MAAMF,EAAK,QAAQ,CAAC,EAAI,kBAAoB,QAAQC,IAC5E,MAAU,WACR,iEAAiEC,GACnE,CACF,CACA,OAAOF,EAAK,YAAY,CAC1B,CAEA,SAAS,mBAAmB,EAAc,EAAwB,CAChE,MAAO,GAAG,OAAOG,CAAI,CAAC,CAAC,SAAS,EAAG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BjB,EAAOU,CAAc,GAC/C,OAAO,OAAOV,EAAM,MAAM,CAAC,CAAC,KAAM,GAAU,4BAA4BmB,EAAOT,CAAc,CAAC,CAElG,CASA,SAAgB,oBAAoB,EAAkB,EAAyB,CAC7E,OAAO,UAAUV,EAAOH,EAAO,EAAE,CACnC"}
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./multiline-EyzjEwn9.mjs";import{n as t,r as n,t as r}from"./tailordb-ddl-DqInYupv.mjs";import{resolve as i}from"pathe";function emptyUsedUtilityTypes(){return{Timestamp:!1,Serial:!1,ObjectColumnType:!1,ArrayColumnType:!1}}function mergeUsedUtilityTypes(e,t){return{Timestamp:e.Timestamp||t.Timestamp,Serial:e.Serial||t.Serial,ObjectColumnType:e.ObjectColumnType||t.ObjectColumnType,ArrayColumnType:e.ArrayColumnType||t.ArrayColumnType}}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){let t=e.fields;if(!t||typeof t!=`object`)return{type:`string`,usedUtilityTypes:emptyUsedUtilityTypes()};let n=Object.entries(t).map(([e,t])=>{let n=generateFieldType(t);return{fieldType:`${e}${t.required===!0?``:`?`}: ${n.type}`,usedUtilityTypes:n.usedUtilityTypes}}),r=n.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),i=n.map(e=>e.fieldType),a=`{\n ${i.join(`;
|
|
2
|
-
`)}${i.length>0?`;`:``}\n}`,o=Object.values(t).some(e=>e.required!==!0),s=Object.values(t).some(e=>e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0);return r.Timestamp||o||s?{type:`ObjectColumnType<${a}>`,usedUtilityTypes:{...r,ObjectColumnType:!0}}:{type:a,usedUtilityTypes:r}}function getBaseType(e){let t=e.type,r=emptyUsedUtilityTypes();if(t===`enum`)return{type:getEnumType(e),usedUtilityTypes:r};if(t===`nested`)return getNestedType(e);let i=n(t);return r.Timestamp=i===`Timestamp`,{type:i,usedUtilityTypes:r}}function generateFieldType(e){let n=getBaseType(e),r={...n.usedUtilityTypes},i=e.array===!0,a=e.required!==!0,o=t.has(n.type),s=n.type;return i&&(o||s.startsWith(`ObjectColumnType<`)?(s=`ArrayColumnType<${n.type}>`,r.ArrayColumnType=!0):s=e.type===`enum`?`(${n.type})[]`:`${n.type}[]`),a&&(s=`${s} | null`),e.serial&&(r.Serial=!0,s=`Serial<${s}>`),(e.hooks?.create||e.default!==void 0||e.optionalOnCreate===!0)&&(s=`Generated<${s}>`),{type:s,usedUtilityTypes:r}}function generateTableInterface(t,n){let r=Object.entries(n).filter(([e])=>e!==`id`).map(([e,t])=>({fieldName:e,...generateFieldType(t)})),i=[`id: Generated<string>;`,...r.map(e=>`${e.fieldName}: ${e.type};`)],a=r.reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes());return{typeDef:e`
|
|
3
|
-
${t}: {
|
|
4
|
-
${i.join(`
|
|
5
|
-
`)}
|
|
6
|
-
}
|
|
7
|
-
`,usedUtilityTypes:a}}function processKyselyFields(e,t){let n=generateTableInterface(e,t);return{name:e,typeDef:n.typeDef,usedUtilityTypes:n.usedUtilityTypes}}async function processKyselyType(e){return processKyselyFields(e.name,Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,t.config])))}function generateUnifiedKyselyTypes(t){if(t.length===0)return``;let n=t.flatMap(e=>e.types).reduce((e,t)=>mergeUsedUtilityTypes(e,t.usedUtilityTypes),emptyUsedUtilityTypes()),r=[`type Generated`];return n.Timestamp&&r.push(`type Timestamp`),n.ObjectColumnType&&r.push(`type ObjectColumnType`),n.ArrayColumnType&&r.push(`type ArrayColumnType`),n.Serial&&r.push(`type Serial`),[e`
|
|
8
|
-
import {
|
|
9
|
-
createGetDB,
|
|
10
|
-
${r.join(`,
|
|
11
|
-
`)},
|
|
12
|
-
type NamespaceDB,
|
|
13
|
-
type NamespaceInsertable,
|
|
14
|
-
type NamespaceSelectable,
|
|
15
|
-
type NamespaceTable,
|
|
16
|
-
type NamespaceTableName,
|
|
17
|
-
type NamespaceTransaction,
|
|
18
|
-
type NamespaceUpdateable,
|
|
19
|
-
} from "@tailor-platform/sdk/kysely";
|
|
20
|
-
`,`export interface Namespace {\n${t.map(({namespace:e,types:t})=>` "${e}": {\n${t.map(e=>e.typeDef.split(`
|
|
21
|
-
`).map(e=>e.trim()?` ${e}`:``).join(`
|
|
22
|
-
`)).join(`
|
|
23
|
-
|
|
24
|
-
`)}\n }`).join(`,
|
|
25
|
-
`)}\n}`,e`
|
|
26
|
-
export const getDB = createGetDB<Namespace>();
|
|
27
|
-
|
|
28
|
-
export type DB<N extends keyof Namespace = keyof Namespace> = NamespaceDB<Namespace, N>;
|
|
29
|
-
`,e`
|
|
30
|
-
export type Transaction<K extends keyof Namespace | DB = keyof Namespace> =
|
|
31
|
-
NamespaceTransaction<Namespace, K>;
|
|
32
|
-
|
|
33
|
-
type TableName = NamespaceTableName<Namespace>;
|
|
34
|
-
export type Table<T extends TableName> = NamespaceTable<Namespace, T>;
|
|
35
|
-
|
|
36
|
-
export type Insertable<T extends TableName> = NamespaceInsertable<Namespace, T>;
|
|
37
|
-
export type Selectable<T extends TableName> = NamespaceSelectable<Namespace, T>;
|
|
38
|
-
export type Updateable<T extends TableName> = NamespaceUpdateable<Namespace, T>;
|
|
39
|
-
`].join(`
|
|
40
|
-
|
|
41
|
-
`)+`
|
|
42
|
-
`}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 r(e.map(({namespace:e,tables:t})=>({namespace:e,tables:toDDLTables(t)})),{generatedBy:`the kysely-type plugin`})}const a=`@tailor-platform/kysely-type`,o=`./generated/tailordb.ts`;function kyselyTypePlugin(e){return{id:a,description:`Generates Kysely type definitions for TailorDB tables`,pluginConfig:e,async onTailorDBReady(e){let{distPath:t,pgliteSchemaPath:n}=e.pluginConfig;if(n&&i(t)===i(n))throw Error(`distPath and pgliteSchemaPath must resolve to different files.`);let r=[];for(let t of e.tailordb){let e=[];for(let n of Object.values(t.tables)){let t=await processKyselyType(n);e.push(t)}e.length!==0&&r.push({namespace:t.namespace,types:e})}let a=[];if(r.length>0){let t=generateUnifiedKyselyTypes(r);a.push({path:e.pluginConfig.distPath,content:t}),e.pluginConfig.pgliteSchemaPath&&a.push({path:e.pluginConfig.pgliteSchemaPath,content:generatePGliteSchemaModule(e.tailordb.filter(e=>Object.keys(e.tables).length>0))})}return{files:a}}}}export{processKyselyFields as a,generateUnifiedKyselyTypes as i,a as n,kyselyTypePlugin as r,o as t};
|
|
43
|
-
//# sourceMappingURL=kysely-type-C-iyFFH7.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-type-C-iyFFH7.mjs","names":["multiline","COLUMN_TYPE_ALIASES","mapFieldTypeToColumnType","generatePgliteSchemaModule","a","b","allowedValues","fieldConfig","v","fields","fieldResults","fieldName","config","result","aggregatedUtilityTypes","acc","fieldTypes","r","obj","hasOptionalFields","hasGeneratedFields","fieldType","usedUtilityTypes","type","baseTypeResult","isArray","isNullable","isColumnTypeBase","finalType","fieldLines","name","parsedField","namespaceData","globalUsedUtilityTypes","ns","utilityTypeImports","namespace","types","line","tables","field","namespaces","KyselyGeneratorID","DEFAULT_KYSELY_TYPES_DIST_PATH","options","ctx","pgliteSchemaPath","resolve","distPath","allNamespaceData","typeMetadataList","metadata","files","content"],"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,CAAE,UAAW,GAAO,OAAQ,GAAO,iBAAkB,GAAO,gBAAiB,EAAM,CAC5F,CAEA,SAAS,sBAAsB,EAAqB,EAAuC,CACzF,MAAO,CACL,UAAWI,EAAE,WAAaC,EAAE,UAC5B,OAAQD,EAAE,QAAUC,EAAE,OACtB,iBAAkBD,EAAE,kBAAoBC,EAAE,iBAC1C,gBAAiBD,EAAE,iBAAmBC,EAAE,eAC1C,CACF,CAOA,SAAS,YAAY,EAAwC,CAC3D,IAAMC,EAAgBC,EAAY,cAUlC,OARID,GAAiB,MAAM,QAAQA,CAAa,EACvCA,EACJ,IAAK,GAEG,IADO,OAAOE,GAAM,SAAWA,EAAIA,EAAE,MAC3B,EAClB,CAAC,CACD,KAAK,KAAK,EAER,QACT,CAOA,SAAS,cAAc,EAAiD,CACtE,IAAMC,EAASF,EAAY,OAC3B,GAAI,CAACE,GAAU,OAAOA,GAAW,SAC/B,MAAO,CACL,KAAM,SACN,iBAAkB,sBAAsB,CAC1C,EAGF,IAAMC,EAAe,OAAO,QAAQD,CAAM,CAAC,CAAC,KAAK,CAACE,EAAWC,KAAY,CACvE,IAAMC,EAAS,kBAAkBD,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