@tailor-platform/sdk 2.10.0 → 2.12.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 +42 -0
- package/dist/application-BFTkaW6X.mjs +1 -0
- package/dist/{application-D2E3FDfF.mjs → application-D3HlhR3i.mjs} +32 -31
- package/dist/application-D3HlhR3i.mjs.map +1 -0
- package/dist/cli/commands/generate/seed/bundler.d.mts +2 -2
- package/dist/cli/commands/tailordb/migrate/bundler.d.mts +1 -1
- package/dist/cli/commands/workspace/user/remove.d.mts +1 -1
- package/dist/cli/commands/workspace/user/update.d.mts +1 -1
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/main.mjs +41 -41
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/script-executor.d.mts +2 -2
- package/dist/completion/zsh-worker.zsh +18 -2
- package/dist/idp-G_ojPBB5.mjs.map +1 -1
- package/dist/kysely-type-B-BOlXH7.mjs +43 -0
- package/dist/kysely-type-B-BOlXH7.mjs.map +1 -0
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
- package/dist/{register-ts-hook-D6aNriu3.mjs → register-ts-hook-rBH346V_.mjs} +63 -63
- package/dist/register-ts-hook-rBH346V_.mjs.map +1 -0
- package/dist/seed-CMkupmX8.mjs.map +1 -1
- package/dist/service-BzsSm2f6.mjs +7 -0
- package/dist/service-BzsSm2f6.mjs.map +1 -0
- package/dist/service-CmwD9bwv.mjs +1 -0
- package/dist/service_pb-CFVlGYdr.mjs +1 -0
- package/dist/{service_pb-BNxUPfP3.mjs → service_pb-CxHztLk1.mjs} +2 -2
- package/dist/{service_pb-BNxUPfP3.mjs.map → service_pb-CxHztLk1.mjs.map} +1 -1
- package/dist/tailor-proto/src/tailor/v1/auth_resource_pb.d.mts +10 -0
- package/dist/vitest/index.d.mts +3 -2
- package/dist/vitest/index.mjs +1 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/tailordb-pglite.d.mts +88 -0
- package/dist/vitest/pglite-kysely.d.mts +13 -5
- package/dist/workflow-Cs9ISw6j.mjs.map +1 -1
- package/dist/workspace_resource_pb-u9bj6p3i.mjs +2 -0
- package/dist/workspace_resource_pb-u9bj6p3i.mjs.map +1 -0
- package/docs/cli/user.md +43 -7
- package/docs/cli-reference.md +1 -0
- package/docs/plugin/custom.md +11 -0
- package/docs/plugin/index.md +5 -0
- package/docs/testing.md +78 -2
- package/package.json +7 -7
- package/dist/application-D2E3FDfF.mjs.map +0 -1
- package/dist/application-rySTKrFa.mjs +0 -1
- package/dist/kysely-type-CmvAz1Xj.mjs +0 -43
- package/dist/kysely-type-CmvAz1Xj.mjs.map +0 -1
- package/dist/register-ts-hook-D6aNriu3.mjs.map +0 -1
- package/dist/service-COC9whur.mjs +0 -1
- package/dist/service-DDon86tM.mjs +0 -7
- package/dist/service-DDon86tM.mjs.map +0 -1
- package/dist/service_pb-D-xFu9Ub.mjs +0 -1
- package/dist/workspace_resource_pb-B7S-zx4Z.mjs +0 -2
- package/dist/workspace_resource_pb-B7S-zx4Z.mjs.map +0 -1
|
@@ -63,10 +63,10 @@ interface ExecutionWaitResult {
|
|
|
63
63
|
*/
|
|
64
64
|
declare function waitForExecution(client: OperatorClient, workspaceId: string, executionId: string, pollInterval?: number): Promise<ExecutionWaitResult>;
|
|
65
65
|
/**
|
|
66
|
-
* Execute a script
|
|
66
|
+
* Execute a script and wait for completion
|
|
67
67
|
*
|
|
68
68
|
* This function:
|
|
69
|
-
* 1.
|
|
69
|
+
* 1. Starts the script execution
|
|
70
70
|
* 2. Polls getFunctionExecution until completion
|
|
71
71
|
* 3. Returns structured result with success/failure status
|
|
72
72
|
* @param {ScriptExecutionOptions} options - Execution options
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
# politty-completion-version: 1
|
|
2
|
-
# politty-bin-sig:
|
|
2
|
+
# politty-bin-sig: 1788439716
|
|
3
3
|
# politty-bin-path: /home/runner/work/sdk/sdk/node_modules/.bin/tailor
|
|
4
4
|
# program: tailor
|
|
5
5
|
# shell: zsh
|
|
@@ -530,6 +530,7 @@ __tailor_worker_opt_takes_value() {
|
|
|
530
530
|
api:--config|api:-c|api:--c) return 0 ;;
|
|
531
531
|
api:--body|api:-b|api:--b) return 0 ;;
|
|
532
532
|
api:--field|api:-f|api:--f) return 0 ;;
|
|
533
|
+
auth:status:--profile|auth:status:-p|auth:status:--p) return 0 ;;
|
|
533
534
|
auth:token:--profile|auth:token:-p|auth:token:--p) return 0 ;;
|
|
534
535
|
authconnection:authorize:--workspace-id|authconnection:authorize:--workspaceId|authconnection:authorize:-w|authconnection:authorize:--w) return 0 ;;
|
|
535
536
|
authconnection:authorize:--profile|authconnection:authorize:-p|authconnection:authorize:--p) return 0 ;;
|
|
@@ -871,6 +872,7 @@ __tailor_worker_is_subcmd() {
|
|
|
871
872
|
api:list) return 0 ;;
|
|
872
873
|
api:inspect) return 0 ;;
|
|
873
874
|
:api) return 0 ;;
|
|
875
|
+
auth:status) return 0 ;;
|
|
874
876
|
auth:token) return 0 ;;
|
|
875
877
|
:auth) return 0 ;;
|
|
876
878
|
authconnection:authorize) return 0 ;;
|
|
@@ -1141,6 +1143,19 @@ __tailor_worker_complete_api() {
|
|
|
1141
1143
|
fi
|
|
1142
1144
|
}
|
|
1143
1145
|
|
|
1146
|
+
__tailor_worker_complete_auth_status() {
|
|
1147
|
+
local -a _vals=()
|
|
1148
|
+
if __tailor_worker_opt_takes_value "auth:status" "${words[CURRENT-1]}"; then return 0; fi
|
|
1149
|
+
if (( _after_dd )); then return 0; fi
|
|
1150
|
+
if [[ "${words[CURRENT]}" == -* ]]; then
|
|
1151
|
+
local -a _opts=()
|
|
1152
|
+
__tailor_worker_not_used "--profile" "-p" "--p" && _opts+=("--profile:Workspace profile")
|
|
1153
|
+
__tailor_worker_not_used "--help" && _opts+=("--help:Show help")
|
|
1154
|
+
__tailor_worker_cdescribe 'options' _opts
|
|
1155
|
+
return 0
|
|
1156
|
+
fi
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1144
1159
|
__tailor_worker_complete_auth_token() {
|
|
1145
1160
|
local -a _vals=()
|
|
1146
1161
|
if __tailor_worker_opt_takes_value "auth:token" "${words[CURRENT-1]}"; then return 0; fi
|
|
@@ -1164,7 +1179,7 @@ __tailor_worker_complete_auth() {
|
|
|
1164
1179
|
__tailor_worker_cdescribe 'options' _opts
|
|
1165
1180
|
return 0
|
|
1166
1181
|
fi
|
|
1167
|
-
local -a _subs=("token:Print a valid Tailor Platform access token to stdout, refreshing it first if expired.")
|
|
1182
|
+
local -a _subs=("status:Show the active Tailor Platform authentication status without printing tokens." "token:Print a valid Tailor Platform access token to stdout, refreshing it first if expired.")
|
|
1168
1183
|
__tailor_worker_cdescribe 'subcommands' _subs
|
|
1169
1184
|
}
|
|
1170
1185
|
|
|
@@ -4202,6 +4217,7 @@ _tailor_worker_completions() {
|
|
|
4202
4217
|
api:list) __tailor_worker_complete_api_list ;;
|
|
4203
4218
|
api:inspect) __tailor_worker_complete_api_inspect ;;
|
|
4204
4219
|
api) __tailor_worker_complete_api ;;
|
|
4220
|
+
auth:status) __tailor_worker_complete_auth_status ;;
|
|
4205
4221
|
auth:token) __tailor_worker_complete_auth_token ;;
|
|
4206
4222
|
auth) __tailor_worker_complete_auth ;;
|
|
4207
4223
|
authconnection:authorize) __tailor_worker_complete_authconnection_authorize ;;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"idp-G_ojPBB5.mjs","names":[
|
|
1
|
+
{"version":3,"file":"idp-G_ojPBB5.mjs","names":[],"sources":["../src/runtime/idp.ts"],"sourcesContent":["/**\n * IDP (Identity Provider) utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.idp` runtime API.\n * At runtime this delegates to `globalThis.tailor.idp`. Use `mockIdp` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { idp } from \"@tailor-platform/sdk/runtime\";\n *\n * const client = new idp.Client({ namespace: \"my-namespace\" });\n * const { users } = await client.users({ first: 10 });\n */\n\n/** Configuration object for `idp.Client`. */\nexport interface ClientConfig {\n namespace: string;\n}\n\n/** User record returned by IDP operations. */\nexport interface User {\n id: string;\n name: string;\n disabled: boolean;\n createdAt?: string;\n /**\n * True when the user has at least one enrolled MFA second factor. False when\n * the namespace has MFA disabled or the user has not enrolled a factor.\n */\n mfaEnrolled: boolean;\n /**\n * Enrolled MFA second factor IDs. Pass an entry into\n * `idp.Client.unenrollMfa()` to remove that factor.\n */\n mfaFactorIds: string[];\n}\n\n/** Filter options for `idp.Client.users()`. */\nexport interface UserQuery {\n /** Filter by user IDs */\n ids?: string[];\n /** Filter by user names */\n names?: string[];\n}\n\n/** Pagination/filter options for `idp.Client.users()`. */\nexport interface ListUsersOptions {\n /** Maximum number of users to return */\n first?: number;\n /** Page token for pagination */\n after?: string;\n /** Query filter for users */\n query?: UserQuery;\n}\n\n/** Response shape for `idp.Client.users()`. */\nexport interface ListUsersResponse {\n users: User[];\n nextPageToken: string | null;\n totalCount: number;\n}\n\n/** Input for `idp.Client.createUser()`. */\nexport interface CreateUserInput {\n /** The user's name (typically email) */\n name: string;\n /** The user's password. If omitted, the user is created without a password (cannot log in with any password). */\n password?: string;\n /** Whether the user is disabled */\n disabled?: boolean;\n}\n\n/** Input for `idp.Client.updateUser()`. */\nexport interface UpdateUserInput {\n /** The user's ID */\n id: string;\n /** New name for the user */\n name?: string;\n /** New password for the user. Cannot be used with clearPassword. */\n password?: string;\n /** If true, remove the user's password. Cannot be used with password. */\n clearPassword?: boolean;\n /** New disabled status for the user */\n disabled?: boolean;\n}\n\n/** Input for `idp.Client.sendPasswordResetEmail()`. */\nexport interface SendPasswordResetEmailInput {\n /** The ID of the user */\n userId: string;\n /** The URI to redirect to after password reset */\n redirectUri: string;\n /** The sender display name. Defaults to 'Tailor Platform IdP'. */\n fromName?: string;\n /** The email subject line. Defaults to the localized default subject. */\n subject?: string;\n}\n\n/** Input for `idp.Client.unenrollMfa()`. */\nexport interface UnenrollMfaInput {\n /** The ID of the user whose factor will be unenrolled. */\n userId: string;\n /**\n * The ID of the factor to unenroll. Factor IDs are exposed on the user\n * record (see {@link User.mfaFactorIds}).\n */\n mfaFactorId: string;\n}\n\n/** Instance methods exposed by `tailor.idp.Client`. */\nexport interface IdpClientInstance {\n users(options?: ListUsersOptions): Promise<ListUsersResponse>;\n user(userId: string): Promise<User>;\n userByName(name: string): Promise<User>;\n createUser(input: CreateUserInput): Promise<User>;\n updateUser(input: UpdateUserInput): Promise<User>;\n deleteUser(userId: string): Promise<boolean>;\n sendPasswordResetEmail(input: SendPasswordResetEmailInput): Promise<boolean>;\n unenrollMfa(input: UnenrollMfaInput): Promise<boolean>;\n}\n\n/**\n * Constructor shape for `tailor.idp.Client`.\n * @internal\n */\nexport interface IdpClientConstructor {\n new (config: ClientConfig): IdpClientInstance;\n}\n\n/**\n * Platform API surface for `tailor.idp`. Describes the shape the platform\n * runtime injects on `globalThis.tailor.idp`.\n * @internal\n */\nexport interface TailorIdpAPI {\n Client: IdpClientConstructor;\n}\n\n/**\n * IDP Client for user management operations.\n *\n * Wraps the platform-provided `tailor.idp.Client` and exposes the same surface.\n */\nclass Client {\n #impl: IdpClientInstance;\n\n constructor(config: ClientConfig) {\n this.#impl = new (globalThis as unknown as { tailor: { idp: TailorIdpAPI } }).tailor.idp.Client(\n config,\n );\n }\n\n /**\n * List users in the namespace with optional filtering and pagination.\n * @param options - Pagination and filter options\n * @returns Page of users with `nextPageToken` and `totalCount`\n */\n users(options?: ListUsersOptions): Promise<ListUsersResponse> {\n return this.#impl.users(options);\n }\n\n /**\n * Get a user by ID.\n * @param userId - IDP user ID\n * @returns The matching user\n */\n user(userId: string): Promise<User> {\n return this.#impl.user(userId);\n }\n\n /**\n * Get a user by name.\n * @param name - IDP user name\n * @returns The matching user\n */\n userByName(name: string): Promise<User> {\n return this.#impl.userByName(name);\n }\n\n /**\n * Create a new user.\n * @param input - User attributes\n * @returns The newly created user\n */\n createUser(input: CreateUserInput): Promise<User> {\n return this.#impl.createUser(input);\n }\n\n /**\n * Update an existing user.\n * @param input - User ID plus attributes to update\n * @returns The updated user\n */\n updateUser(input: UpdateUserInput): Promise<User> {\n return this.#impl.updateUser(input);\n }\n\n /**\n * Delete a user by ID.\n * @param userId - IDP user ID\n * @returns `true` when the user was deleted\n */\n deleteUser(userId: string): Promise<boolean> {\n return this.#impl.deleteUser(userId);\n }\n\n /**\n * Send a password reset email to a user.\n * @param input - Target user ID and redirect URI\n * @returns `true` when the email was queued\n */\n sendPasswordResetEmail(input: SendPasswordResetEmailInput): Promise<boolean> {\n return this.#impl.sendPasswordResetEmail(input);\n }\n\n /**\n * Unenroll an MFA factor from a user.\n * @param input - Target user ID and factor ID (see {@link User.mfaFactorIds})\n * @returns `true` when the factor was removed\n */\n unenrollMfa(input: UnenrollMfaInput): Promise<boolean> {\n return this.#impl.unenrollMfa(input);\n }\n}\n\n// Keep the object typed to the public API so the private wrapper class does not leak into d.ts.\n/** Runtime API for `tailor.idp`. */\nexport const idp: TailorIdpAPI = { Client };\n"],"mappings":"AAkOA,MAAa,EAAoB,CAAE,YApFtB,CACX,GAEA,YAAY,EAAsB,CAChC,KAAK,GAAQ,IAAK,WAA4D,OAAO,IAAI,OACvF,CACF,CACF,CAOA,MAAM,EAAwD,CAC5D,OAAO,KAAK,GAAM,MAAM,CAAO,CACjC,CAOA,KAAK,EAA+B,CAClC,OAAO,KAAK,GAAM,KAAK,CAAM,CAC/B,CAOA,WAAW,EAA6B,CACtC,OAAO,KAAK,GAAM,WAAW,CAAI,CACnC,CAOA,WAAW,EAAuC,CAChD,OAAO,KAAK,GAAM,WAAW,CAAK,CACpC,CAOA,WAAW,EAAuC,CAChD,OAAO,KAAK,GAAM,WAAW,CAAK,CACpC,CAOA,WAAW,EAAkC,CAC3C,OAAO,KAAK,GAAM,WAAW,CAAM,CACrC,CAOA,uBAAuB,EAAsD,CAC3E,OAAO,KAAK,GAAM,uBAAuB,CAAK,CAChD,CAOA,YAAY,EAA2C,CACrD,OAAO,KAAK,GAAM,YAAY,CAAK,CACrC,CACF,CAI0C"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import{t as e}from"./multiline-EyzjEwn9.mjs";import{n as t,t as n}from"./field-column-type-QMtF6lUp.mjs";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 n=e.type,r=emptyUsedUtilityTypes();if(n===`enum`)return{type:getEnumType(e),usedUtilityTypes:r};if(n===`nested`)return getNestedType(e);let i=t(n);return r.Timestamp=i===`Timestamp`,{type:i,usedUtilityTypes:r}}function generateFieldType(e){let t=getBaseType(e),r={...t.usedUtilityTypes},i=e.array===!0,a=e.required!==!0,o=n.has(t.type),s=t.type;return i&&(o||s.startsWith(`ObjectColumnType<`)?(s=`ArrayColumnType<${t.type}>`,r.ArrayColumnType=!0):s=e.type===`enum`?`(${t.type})[]`:`${t.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
|
+
`}const r=`@tailor-platform/kysely-type`,i=`./generated/tailordb.ts`;function kyselyTypePlugin(e){return{id:r,description:`Generates Kysely type definitions for TailorDB tables`,pluginConfig:e,async onTailorDBReady(e){let t=[];for(let n of e.tailordb){let e=[];for(let t of Object.values(n.tables)){let n=await processKyselyType(t);e.push(n)}e.length!==0&&t.push({namespace:n.namespace,types:e})}let n=[];if(t.length>0){let r=generateUnifiedKyselyTypes(t);n.push({path:e.pluginConfig.distPath,content:r})}return{files:n}}}}export{processKyselyFields as a,generateUnifiedKyselyTypes as i,r as n,kyselyTypePlugin as r,i as t};
|
|
43
|
+
//# sourceMappingURL=kysely-type-B-BOlXH7.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-type-B-BOlXH7.mjs","names":[],"sources":["../src/plugin/builtin/kysely-type/type-processor.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 { 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};\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 * @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 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 }\n\n return { files };\n },\n };\n}\n"],"mappings":"yGAeA,SAAS,uBAA0C,CACjD,MAAO,CAAE,UAAW,GAAO,OAAQ,GAAO,iBAAkB,GAAO,gBAAiB,EAAM,CAC5F,CAEA,SAAS,sBAAsB,EAAqB,EAAuC,CACzF,MAAO,CACL,UAAW,EAAE,WAAa,EAAE,UAC5B,OAAQ,EAAE,QAAU,EAAE,OACtB,iBAAkB,EAAE,kBAAoB,EAAE,iBAC1C,gBAAiB,EAAE,iBAAmB,EAAE,eAC1C,CACF,CAOA,SAAS,YAAY,EAAwC,CAC3D,IAAM,EAAgB,EAAY,cAUlC,OARI,GAAiB,MA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,EAErD,IAAK,IAAM,KAAM,EAAI,SAAU,CAC7B,IAAM,EAAyC,CAAC,EAEhD,IAAK,IAAM,KAAQ,OAAO,OAAO,EAAG,MAAM,EAAG,CAC3C,IAAM,EAAW,MAAM,kBAAkB,CAAI,EAC7C,EAAiB,KAAK,CAAQ,CAChC,CAEI,EAAiB,SAAW,GAEhC,EAAiB,KAAK,CACpB,UAAW,EAAG,UACd,MAAO,CACT,CAAC,CACH,CAEA,IAAM,EAAkC,CAAC,EACzC,GAAI,EAAiB,OAAS,EAAG,CAC/B,IAAM,EAAU,2BAA2B,CAAgB,EAC3D,EAAM,KAAK,CACT,KAAM,EAAI,aAAa,SACvB,SACF,CAAC,CACH,CAEA,MAAO,CAAE,OAAM,CACjB,CACF,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"../../../kysely-type-
|
|
1
|
+
import{n as e,r as t,t as n}from"../../../kysely-type-B-BOlXH7.mjs";export{n as DEFAULT_KYSELY_TYPES_DIST_PATH,e as KyselyGeneratorID,t as kyselyTypePlugin};
|