@tailor-platform/sdk 1.74.0 → 1.74.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/{application-DwmoI6ZQ.mjs → application-BsH6tkZC.mjs} +43 -5
- package/dist/application-BsH6tkZC.mjs.map +1 -0
- package/dist/application-CSUhZMb5.mjs +3 -0
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +1 -16
- package/dist/cli/index.mjs +22 -33
- package/dist/cli/index.mjs.map +1 -1
- package/dist/cli/lib.d.mts +2 -2
- package/dist/cli/lib.mjs +3 -3
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/completion/zsh-worker.zsh +1 -1
- package/dist/configure/index.mjs +2 -2
- package/dist/configure/services/tailordb/schema.d.mts +5 -19
- package/dist/configure/types/field-runtime.d.mts +17 -0
- package/dist/configure/types/type.d.mts +1 -18
- package/dist/field-runtime-9bfXBAOK.mjs +183 -0
- package/dist/field-runtime-9bfXBAOK.mjs.map +1 -0
- package/dist/plugin/builtin/seed/index.mjs +1 -1
- package/dist/{runtime-Zkg3SUwi.mjs → runtime-DV1EnfMs.mjs} +229 -394
- package/dist/runtime-DV1EnfMs.mjs.map +1 -0
- package/dist/{schema-DAdZSFOd.mjs → schema-Dl_y0m9e.mjs} +8 -167
- package/dist/schema-Dl_y0m9e.mjs.map +1 -0
- package/dist/secretmanager-Bd45j7an.mjs +98 -0
- package/dist/secretmanager-Bd45j7an.mjs.map +1 -0
- package/dist/{seed-DoMTMLcm.mjs → seed-fm0LeYP2.mjs} +14 -3
- package/dist/seed-fm0LeYP2.mjs.map +1 -0
- package/dist/types-BwzB2okW.mjs +199 -0
- package/dist/types-BwzB2okW.mjs.map +1 -0
- package/dist/types-KlawuVKa.mjs +4 -0
- package/dist/vitest/index.d.mts +8 -1
- package/dist/vitest/index.mjs +776 -1
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mock.d.mts +8 -363
- package/dist/vitest/mocks/aigateway.d.mts +30 -0
- package/dist/vitest/mocks/authconnection.d.mts +28 -0
- package/dist/vitest/mocks/file.d.mts +41 -0
- package/dist/vitest/mocks/iconv.d.mts +27 -0
- package/dist/vitest/mocks/idp.d.mts +44 -0
- package/dist/vitest/mocks/secretmanager.d.mts +33 -0
- package/dist/vitest/mocks/tailordb.d.mts +71 -0
- package/dist/vitest/mocks/workflow.d.mts +115 -0
- package/dist/vitest/setup.mjs +1 -1
- package/package.json +8 -8
- package/dist/application-BndtMTFY.mjs +0 -3
- package/dist/application-DwmoI6ZQ.mjs.map +0 -1
- package/dist/field-DOsJCPFa.mjs +0 -22
- package/dist/field-DOsJCPFa.mjs.map +0 -1
- package/dist/mock-Ce1GCi4-.mjs +0 -871
- package/dist/mock-Ce1GCi4-.mjs.map +0 -1
- package/dist/runtime-Zkg3SUwi.mjs.map +0 -1
- package/dist/schema-DAdZSFOd.mjs.map +0 -1
- package/dist/seed-DoMTMLcm.mjs.map +0 -1
- package/dist/types-qhFZ8y9B.mjs +0 -4
- package/dist/types-ywCGpzDZ.mjs +0 -360
- package/dist/types-ywCGpzDZ.mjs.map +0 -1
package/dist/cli/lib.d.mts
CHANGED
|
@@ -9,7 +9,7 @@ import { OperatorClient, initOperatorClient } from "./shared/client.mjs";
|
|
|
9
9
|
import { NormalizedSchemaSnapshot, SchemaSnapshot, SnapshotFieldConfig, TailorDBSnapshotType } from "./commands/tailordb/migrate/snapshot-types.mjs";
|
|
10
10
|
import { BreakingChangeInfo, MigrationDiff, formatDiffSummary, formatMigrationDiff, hasChanges } from "./commands/tailordb/migrate/diff-calculator.mjs";
|
|
11
11
|
import { MIGRATION_LABEL_KEY } from "./commands/tailordb/migrate/types.mjs";
|
|
12
|
-
import { DB_TYPES_FILE_NAME, DIFF_FILE_NAME, INITIAL_SCHEMA_NUMBER, MIGRATE_FILE_NAME,
|
|
12
|
+
import { DB_TYPES_FILE_NAME, DIFF_FILE_NAME, INITIAL_SCHEMA_NUMBER, MIGRATE_FILE_NAME, SCHEMA_FILE_NAME, compareLocalTypesWithSnapshot, compareSnapshots, createSnapshotFromLocalTypes, getLatestMigrationNumber, getMigrationDirPath, getMigrationFilePath, getMigrationFiles, getNextMigrationNumber, reconstructSnapshotFromMigrations } from "./commands/tailordb/migrate/snapshot.mjs";
|
|
13
13
|
import { DeployOptions, deploy } from "./commands/deploy/deploy.mjs";
|
|
14
14
|
import { AggregateArgs, CodeGenerator, DependencyKind, ExecutorGenerator, ExecutorInput, FullCodeGenerator, FullInput, GeneratorResult, ResolverGenerator, ResolverInput, TailorDBGenerator, TailorDBInput, TailorDBResolverGenerator } from "./commands/generate/types.mjs";
|
|
15
15
|
import { GenerateOptions } from "./commands/generate/options.mjs";
|
|
@@ -77,4 +77,4 @@ import { ChunkSeedDataOptions, SeedChunk, chunkSeedData } from "./shared/seed-ch
|
|
|
77
77
|
import { SeedBundleResult, bundleSeedScript } from "./commands/generate/seed/bundler.mjs";
|
|
78
78
|
import { MigrationBundleResult, bundleMigrationScript } from "./commands/tailordb/migrate/bundler.mjs";
|
|
79
79
|
import { ExecutionWaitResult, ScriptExecutionOptions, ScriptExecutionResult, executeScript, waitForExecution } from "./shared/script-executor.mjs";
|
|
80
|
-
export { type AggregateArgs, type ApiCallOptions, type ApiCallResult, type AppHealthInfo, type AppInfo, type ApplicationInfo, type DeployOptions as ApplyOptions, type AuthInvoker, type BreakingChangeInfo, type BundledScripts, type ChunkSeedDataOptions, type CodeGenerator, type CreateFolderOptions, type CreateWorkspaceOptions, DB_TYPES_FILE_NAME, DIFF_FILE_NAME, type DeleteFolderOptions, type DeleteWorkspaceOptions, type DependencyKind, type DeployOptions, type ExecutionWaitResult, type Executor, type ExecutorGenerator, type ExecutorInfo, type ExecutorInput, type ExecutorJobAttemptInfo, type ExecutorJobDetailInfo, type ExecutorJobInfo, type ExecutorJobListInfo, type ExecutorListInfo, type FolderInfo, type FolderListInfo, type FullCodeGenerator, type FullInput, type FunctionRegistryInfo, type GenerateOptions, type GeneratorResult, type HealthOptions as GetAppHealthOptions, type GetExecutorJobOptions, type GetExecutorJobTypedOptions, type GetExecutorOptions, type GetExecutorTypedOptions, type GetFolderOptions, type GetFunctionRegistryOptions, type GetMachineUserTokenOptions, type GetOAuth2ClientOptions, type GetOrganizationOptions, type GetWorkflowExecutionOptions, type GetWorkflowExecutionResult, type GetWorkflowOptions, type GetWorkflowTypedOptions, type GetWorkspaceOptions, INITIAL_SCHEMA_NUMBER, type InviteUserOptions, type ListAppsOptions, type ListExecutorJobsOptions, type ListExecutorJobsTypedOptions, type ListExecutorsOptions, type ListFoldersOptions, type ListFunctionRegistriesOptions, type ListMachineUsersOptions, type ListOAuth2ClientsOptions, type ListOrganizationsOptions, type ListUsersOptions, type ListWebhookExecutorsOptions, type ListWorkflowExecutionsOptions, type ListWorkflowExecutionsTypedOptions, type ListWorkflowsOptions, type ListWorkspacesOptions, type LoadedConfig, MIGRATE_FILE_NAME, MIGRATION_LABEL_KEY, type MachineUserInfo, type MachineUserTokenInfo, type GenerateOptions$1 as MigrateGenerateOptions, type MigrationBundleResult, type MigrationDiff, type
|
|
80
|
+
export { type AggregateArgs, type ApiCallOptions, type ApiCallResult, type AppHealthInfo, type AppInfo, type ApplicationInfo, type DeployOptions as ApplyOptions, type AuthInvoker, type BreakingChangeInfo, type BundledScripts, type ChunkSeedDataOptions, type CodeGenerator, type CreateFolderOptions, type CreateWorkspaceOptions, DB_TYPES_FILE_NAME, DIFF_FILE_NAME, type DeleteFolderOptions, type DeleteWorkspaceOptions, type DependencyKind, type DeployOptions, type ExecutionWaitResult, type Executor, type ExecutorGenerator, type ExecutorInfo, type ExecutorInput, type ExecutorJobAttemptInfo, type ExecutorJobDetailInfo, type ExecutorJobInfo, type ExecutorJobListInfo, type ExecutorListInfo, type FolderInfo, type FolderListInfo, type FullCodeGenerator, type FullInput, type FunctionRegistryInfo, type GenerateOptions, type GeneratorResult, type HealthOptions as GetAppHealthOptions, type GetExecutorJobOptions, type GetExecutorJobTypedOptions, type GetExecutorOptions, type GetExecutorTypedOptions, type GetFolderOptions, type GetFunctionRegistryOptions, type GetMachineUserTokenOptions, type GetOAuth2ClientOptions, type GetOrganizationOptions, type GetWorkflowExecutionOptions, type GetWorkflowExecutionResult, type GetWorkflowOptions, type GetWorkflowTypedOptions, type GetWorkspaceOptions, INITIAL_SCHEMA_NUMBER, type InviteUserOptions, type ListAppsOptions, type ListExecutorJobsOptions, type ListExecutorJobsTypedOptions, type ListExecutorsOptions, type ListFoldersOptions, type ListFunctionRegistriesOptions, type ListMachineUsersOptions, type ListOAuth2ClientsOptions, type ListOrganizationsOptions, type ListUsersOptions, type ListWebhookExecutorsOptions, type ListWorkflowExecutionsOptions, type ListWorkflowExecutionsTypedOptions, type ListWorkflowsOptions, type ListWorkspacesOptions, type LoadedConfig, MIGRATE_FILE_NAME, MIGRATION_LABEL_KEY, type MachineUserInfo, type MachineUserTokenInfo, type GenerateOptions$1 as MigrateGenerateOptions, type MigrationBundleResult, type MigrationDiff, type NamespaceWithMigrations, type NormalizedSchemaSnapshot, type OAuth2ClientCredentials, type OAuth2ClientInfo, type OperatorClient, type OrganizationInfo, type OrganizationTreeOptions, type PluginAttachment, type RemoveOptions, type RemoveUserOptions, type Resolver, type ResolverGenerator, type ResolverInput, type RestoreWorkspaceOptions, type ResumeWorkflowOptions, type ResumeWorkflowResultWithWait, SCHEMA_FILE_NAME, type SchemaSnapshot, type ScriptExecutionOptions, type ScriptExecutionResult, type SeedBundleResult, type SeedChunk, type ShowOptions, type SnapshotFieldConfig, type StartWorkflowOptions, type StartWorkflowResultWithWait, type StartWorkflowTypedOptions, type TailorDBGenerator, type TailorDBInput, type TailorDBResolverGenerator, type TailorDBSnapshotType, type TailorDBType, type TriggerExecutorOptions, type TriggerExecutorResult, type TriggerExecutorTypedOptions, type TruncateOptions, type TypeSourceInfoEntry, type UpdateFolderOptions, type UpdateOrganizationOptions, type UpdateUserOptions, type UserInfo, type UserOrganizationInfo, type WaitOptions, type WaitWorkflowExecutionOptions, type WatchExecutorJobOptions, type WatchExecutorJobResult, type WatchExecutorJobTypedOptions, type WebhookExecutorInfo, type WorkflowExecutionInfo, type WorkflowExecutionWaitInfo, type WorkflowInfo, type WorkflowJobExecutionInfo, type WorkflowListInfo, type WorkflowWaitOutput, type WorkflowWaitResult, type WorkspaceDetails, type WorkspaceInfo, apiCall, deploy as apply, bundleMigrationScript, bundleSeedScript, chunkSeedData, compareLocalTypesWithSnapshot, compareSnapshots, createFolder, createSnapshotFromLocalTypes, createWorkspace, deleteFolder, deleteWorkspace, deploy, enumConstantsPlugin, executeScript, fileUtilsPlugin, formatDiffSummary, formatMigrationDiff, generate, generateUserTypes, getAppHealth, getExecutor, getExecutorJob, getExecutorWaitFailureMessage, getFolder, getFunctionRegistry, getLatestMigrationNumber, getMachineUserToken, getMigrationDirPath, getMigrationFilePath, getMigrationFiles, getNamespacesWithMigrations, getNextMigrationNumber, getOAuth2Client, getOrganization, getWorkflow, getWorkflowExecution, getWorkspace, hasChanges, initOperatorClient, inviteUser, kyselyTypePlugin, listApps, listExecutorJobs, listExecutors, listFolders, listFunctionRegistries, listMachineUsers, listOAuth2Clients, listOrganizations, listUsers, listWebhookExecutors, listWorkflowExecutions, listWorkflows, listWorkspaces, loadAccessToken, loadConfig, loadWorkspaceId, generate$1 as migrateGenerate, organizationTree, query, reconstructSnapshotFromMigrations, remove, removeUser, restoreWorkspace, resumeWorkflow, seedPlugin, show, startWorkflow, triggerExecutor, truncate, updateFolder, updateOrganization, updateUser, waitForExecution, waitWorkflowExecution, watchExecutorJob };
|
package/dist/cli/lib.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { t as assertDefined } from "../assert-DBxo8jPo.mjs";
|
|
2
|
-
import { $ as getOrganization, At as getExecutorWaitFailureMessage, B as show, Bt as listWorkflowExecutions, Cn as hasChanges, Ct as listWebhookExecutors, D as waitWorkflowExecution, Et as triggerExecutor, Ft as startWorkflow, Gt as deploy, J as organizationTree, Jt as waitForExecution, Lt as getWorkflow, M as truncate, Mt as listExecutorJobs, Nt as watchExecutorJob, On as generateUserTypes, Ot as listExecutors, P as generate$1, S as listApps, Sn as formatMigrationDiff, St as getFunctionRegistry, W as remove, Wt as getExecutor, Xt as MIGRATION_LABEL_KEY, Yt as bundleMigrationScript, Z as listOrganizations, _ as getWorkspace, _t as listMachineUsers, a as updateUser, an as MIGRATE_FILE_NAME, at as getFolder, bt as listFunctionRegistries, cn as compareLocalTypesWithSnapshot, d as inviteUser, dn as getLatestMigrationNumber, dt as listOAuth2Clients, fn as getMigrationDirPath, h as listWorkspaces, hn as getNextMigrationNumber, in as INITIAL_SCHEMA_NUMBER, j as listWorkflows, jn as apiCall, k as resumeWorkflow, kt as getExecutorJob, l as listUsers, ln as compareSnapshots, lt as createFolder, mn as getMigrationFiles, mt as getMachineUserToken, n as query, nn as DB_TYPES_FILE_NAME, on as SCHEMA_FILE_NAME, p as restoreWorkspace, pn as getMigrationFilePath, pt as getOAuth2Client, q as updateOrganization, qt as executeScript, rn as DIFF_FILE_NAME, rt as listFolders, s as removeUser, st as deleteFolder, t as isNativeTypeScriptRuntime, tt as updateFolder, un as createSnapshotFromLocalTypes, vn as reconstructSnapshotFromMigrations, vt as generate, w as getAppHealth, wn as getNamespacesWithMigrations, x as createWorkspace, xn as formatDiffSummary, y as deleteWorkspace, zt as getWorkflowExecution } from "../runtime-
|
|
3
|
-
import { C as getDistDir, E as loadConfig, L as loadWorkspaceId,
|
|
2
|
+
import { $ as getOrganization, At as getExecutorWaitFailureMessage, B as show, Bt as listWorkflowExecutions, Cn as hasChanges, Ct as listWebhookExecutors, D as waitWorkflowExecution, Et as triggerExecutor, Ft as startWorkflow, Gt as deploy, J as organizationTree, Jt as waitForExecution, Lt as getWorkflow, M as truncate, Mt as listExecutorJobs, Nt as watchExecutorJob, On as generateUserTypes, Ot as listExecutors, P as generate$1, S as listApps, Sn as formatMigrationDiff, St as getFunctionRegistry, W as remove, Wt as getExecutor, Xt as MIGRATION_LABEL_KEY, Yt as bundleMigrationScript, Z as listOrganizations, _ as getWorkspace, _t as listMachineUsers, a as updateUser, an as MIGRATE_FILE_NAME, at as getFolder, bt as listFunctionRegistries, cn as compareLocalTypesWithSnapshot, d as inviteUser, dn as getLatestMigrationNumber, dt as listOAuth2Clients, fn as getMigrationDirPath, h as listWorkspaces, hn as getNextMigrationNumber, in as INITIAL_SCHEMA_NUMBER, j as listWorkflows, jn as apiCall, k as resumeWorkflow, kt as getExecutorJob, l as listUsers, ln as compareSnapshots, lt as createFolder, mn as getMigrationFiles, mt as getMachineUserToken, n as query, nn as DB_TYPES_FILE_NAME, on as SCHEMA_FILE_NAME, p as restoreWorkspace, pn as getMigrationFilePath, pt as getOAuth2Client, q as updateOrganization, qt as executeScript, rn as DIFF_FILE_NAME, rt as listFolders, s as removeUser, st as deleteFolder, t as isNativeTypeScriptRuntime, tt as updateFolder, un as createSnapshotFromLocalTypes, vn as reconstructSnapshotFromMigrations, vt as generate, w as getAppHealth, wn as getNamespacesWithMigrations, x as createWorkspace, xn as formatDiffSummary, y as deleteWorkspace, zt as getWorkflowExecution } from "../runtime-DV1EnfMs.mjs";
|
|
3
|
+
import { C as getDistDir, E as loadConfig, L as loadWorkspaceId, g as platformBundleDefinePlugin, j as loadAccessToken, nt as initOperatorClient } from "../application-BsH6tkZC.mjs";
|
|
4
4
|
import { n as enumConstantsPlugin } from "../enum-constants-j9QBF0cB.mjs";
|
|
5
5
|
import { t as multiline } from "../multiline-sfHpTZZK.mjs";
|
|
6
6
|
import { n as fileUtilsPlugin } from "../file-utils-DcyIPFQh.mjs";
|
|
7
7
|
import { n as kyselyTypePlugin } from "../kysely-type-D-zflMGf.mjs";
|
|
8
|
-
import { n as seedPlugin } from "../seed-
|
|
8
|
+
import { n as seedPlugin } from "../seed-fm0LeYP2.mjs";
|
|
9
9
|
import * as fs from "node:fs";
|
|
10
10
|
import * as path from "pathe";
|
|
11
11
|
import { resolveTSConfig } from "pkg-types";
|
package/dist/cli/lib.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lib.mjs","names":[],"sources":["../../src/cli/shared/seed-chunker.ts","../../src/cli/commands/generate/seed/bundler.ts","../../src/cli/lib.ts"],"sourcesContent":["/**\n * Seed data chunker for splitting large seed data into manageable message sizes.\n *\n * When seed data exceeds the gRPC message size limit, this module splits the data\n * into multiple chunks at type boundaries (or record boundaries for large types).\n */\n\nimport { assertDefined } from \"#/utils/assert\";\n\n/**\n * Seed data keyed by type name, with an array of records per type.\n */\nexport type SeedData = Record<string, Record<string, unknown>[]>;\n\n/**\n * A single chunk of seed data with metadata for ordered execution.\n */\nexport type SeedChunk = {\n data: SeedData;\n order: string[];\n index: number;\n total: number;\n};\n\n/**\n * Options for chunking seed data.\n */\nexport type ChunkSeedDataOptions = {\n /** Seed data keyed by type name */\n data: SeedData;\n /** Ordered list of type names (dependency order) */\n order: string[];\n /** Byte size of the bundled seed script code */\n codeByteSize: number;\n /** Maximum gRPC message size in bytes (default: 3.5MB) */\n maxMessageSize?: number;\n};\n\n/** Default maximum message size: 3.5MB (conservative limit for gRPC) */\nexport const DEFAULT_MAX_MESSAGE_SIZE = 3.5 * 1024 * 1024;\n\n/** Reserved bytes for message metadata overhead */\nconst METADATA_OVERHEAD = 1024;\n\n/**\n * Split seed data into chunks that fit within the gRPC message size limit.\n *\n * Algorithm:\n * 1. Calculate the available budget for the arg field (maxMessageSize - codeByteSize - overhead)\n * 2. If all data fits in one message, return a single chunk\n * 3. Otherwise, iterate through types in dependency order:\n * - If a type fits in the current chunk, add it\n * - If adding a type would exceed the budget, finalize the current chunk and start a new one\n * - If a single type exceeds the budget, split its records across multiple chunks\n * - If a single record exceeds the budget, throw an error\n * @param options - Chunking options\n * @returns Array of seed chunks\n */\nexport function chunkSeedData(options: ChunkSeedDataOptions): SeedChunk[] {\n const { data, order, codeByteSize, maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE } = options;\n\n const argBudget = maxMessageSize - codeByteSize - METADATA_OVERHEAD;\n if (argBudget <= 0) {\n throw new Error(\n `Code size (${codeByteSize} bytes) exceeds the message size limit (${maxMessageSize} bytes). ` +\n `No space left for seed data.`,\n );\n }\n\n // Filter to types that have data\n const typesWithData = order.filter((type) => (data[type]?.length ?? 0) > 0);\n\n if (typesWithData.length === 0) {\n return [];\n }\n\n // Check if all data fits in a single message\n const fullArg = JSON.stringify({ data, order });\n if (byteSize(fullArg) <= argBudget) {\n return [{ data, order, index: 0, total: 1 }];\n }\n\n // Split into multiple chunks\n const chunks: Omit<SeedChunk, \"total\">[] = [];\n let currentData: SeedData = {};\n let currentOrder: string[] = [];\n\n for (const type of typesWithData) {\n const typeRecords = assertDefined(data[type], `seed data missing for type: ${type}`);\n\n // Check if the type fits in the current chunk\n if (currentOrder.length > 0) {\n const testData = { ...currentData, [type]: typeRecords };\n const testOrder = [...currentOrder, type];\n if (byteSize(JSON.stringify({ data: testData, order: testOrder })) > argBudget) {\n // Finalize the current chunk\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n }\n\n // Check if the entire type fits in an empty chunk\n if (byteSize(JSON.stringify({ data: { [type]: typeRecords }, order: [type] })) <= argBudget) {\n currentData[type] = typeRecords;\n currentOrder.push(type);\n continue;\n }\n\n // Type is too large — split by records\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n\n let recordBatch: Record<string, unknown>[] = [];\n for (const record of typeRecords) {\n if (byteSize(JSON.stringify({ data: { [type]: [record] }, order: [type] })) > argBudget) {\n const singleRecordSize = byteSize(JSON.stringify(record));\n throw new Error(\n `A single record in type \"${type}\" (${singleRecordSize} bytes) exceeds the message size budget ` +\n `(${argBudget} bytes). Consider increasing maxMessageSize or reducing the record size.`,\n );\n }\n\n const testBatch = [...recordBatch, record];\n const testData = { ...currentData, [type]: testBatch };\n const testOrder = currentOrder.includes(type) ? currentOrder : [...currentOrder, type];\n const testSize = byteSize(JSON.stringify({ data: testData, order: testOrder }));\n\n if (testSize > argBudget && recordBatch.length > 0) {\n // Finalize current chunk with accumulated records\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n recordBatch = [record];\n } else {\n recordBatch = testBatch;\n }\n }\n\n // Add remaining records\n if (recordBatch.length > 0) {\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n }\n }\n\n // Finalize the last chunk\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n }\n\n const total = chunks.length;\n return chunks.map((chunk) => ({ ...chunk, total }));\n}\n\nfunction byteSize(str: string): number {\n return new TextEncoder().encode(str).length;\n}\n","/**\n * Seed script bundler for TailorDB seed data\n *\n * Bundles seed scripts to be executed via TestExecScript API\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport ml from \"#/utils/multiline\";\n\nexport type SeedBundleResult = {\n namespace: string;\n bundledCode: string;\n typesIncluded: string[];\n};\n\nconst BATCH_SIZE = 100;\n\n/**\n * Generate seed script content for server-side execution\n * @param namespace - TailorDB namespace\n * @returns Generated seed script content\n */\nfunction generateSeedScriptContent(namespace: string): string {\n return ml /* ts */ `\n import { Kysely, TailordbDialect } from \"@tailor-platform/sdk/kysely\";\n\n type SeedInput = {\n data: Record<string, Record<string, unknown>[]>;\n order: string[];\n selfRefTypes: string[];\n };\n\n type SeedResult = {\n success: boolean;\n processed: Record<string, number>;\n errors: string[];\n };\n\n function getDB(namespace: string) {\n const client = new tailordb.Client({ namespace });\n return new Kysely<Record<string, Record<string, unknown>>>({\n dialect: new TailordbDialect(client),\n });\n }\n\n export async function main(input: SeedInput): Promise<SeedResult> {\n const db = getDB(\"${namespace}\");\n const processed: Record<string, number> = {};\n const errors: string[] = [];\n const BATCH_SIZE = ${String(BATCH_SIZE)};\n\n for (const typeName of input.order) {\n const records = input.data[typeName];\n if (!records || records.length === 0) {\n console.log(\\`[${namespace}] \\${typeName}: skipped (no data)\\`);\n continue;\n }\n\n processed[typeName] = 0;\n const hasSelfRef = (input.selfRefTypes || []).includes(typeName);\n\n try {\n if (hasSelfRef) {\n // Insert one-by-one to respect self-referencing foreign key order\n for (const record of records) {\n await db.insertInto(typeName).values(record).execute();\n processed[typeName] += 1;\n }\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length} (one-by-one)\\`);\n } else {\n for (let i = 0; i < records.length; i += BATCH_SIZE) {\n const batch = records.slice(i, i + BATCH_SIZE);\n await db.insertInto(typeName).values(batch).execute();\n processed[typeName] += batch.length;\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length}\\`);\n }\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`\\${typeName}: \\${message}\\`);\n console.error(\\`[${namespace}] \\${typeName}: failed - \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n processed,\n errors,\n };\n }\n `;\n}\n\n/**\n * Bundle a seed script for server-side execution\n *\n * Creates an entry that:\n * 1. Defines getDB() function inline\n * 2. Processes data in batches using Kysely\n * 3. Reports progress via console.log\n * 4. Exports as main() for TestExecScript\n * @param namespace - TailorDB namespace\n * @param typeNames - List of type names to include in the seed\n * @returns Bundled seed script result\n */\nexport async function bundleSeedScript(\n namespace: string,\n typeNames: string[],\n): Promise<SeedBundleResult> {\n // Output directory in .tailor-sdk (relative to project root)\n const outputDir = path.resolve(getDistDir(), \"seed\");\n fs.mkdirSync(outputDir, { recursive: true });\n\n // Entry file in output directory\n const entryPath = path.join(outputDir, `seed_${namespace}.entry.ts`);\n\n // Generate seed script content\n const entryContent = generateSeedScriptContent(namespace);\n fs.writeFileSync(entryPath, entryContent);\n\n let tsconfig: string | undefined;\n try {\n tsconfig = await resolveTSConfig();\n } catch {\n tsconfig = undefined;\n }\n\n // Bundle with tree-shaking (write: false to avoid unnecessary disk I/O)\n const result = await rolldown.build({\n plugins: [platformBundleDefinePlugin],\n input: entryPath,\n write: false,\n output: {\n format: \"esm\",\n sourcemap: false,\n minify: false,\n codeSplitting: false,\n globals: {\n tailordb: \"tailordb\",\n },\n },\n external: [\"tailordb\"],\n resolve: {\n conditionNames: [\"node\", \"import\"],\n },\n tsconfig,\n treeshake: {\n moduleSideEffects: false,\n annotations: true,\n unknownGlobalSideEffects: false,\n },\n logLevel: \"silent\",\n } as rolldown.BuildOptions);\n\n const bundledCode = result.output[0].code;\n\n return {\n namespace,\n bundledCode,\n typesIncluded: typeNames,\n };\n}\n","// CLI API exports for programmatic usage\nimport { isNativeTypeScriptRuntime } from \"./shared/runtime\";\n\n// Register tsx to handle TypeScript files when using CLI API programmatically.\n// Bun and Deno handle TypeScript natively, so registration is skipped.\n// tsx's own register() picks `module.registerHooks` on Node ≥ 24.11.1 / 25.1 / 26\n// (avoiding the DEP0205 deprecation) and falls back to `module.register` on older runtimes.\nif (!isNativeTypeScriptRuntime()) {\n const { register } = await import(\"tsx/esm/api\");\n register();\n}\n\nexport { deploy, deploy as apply } from \"./commands/deploy/deploy\";\nexport type { DeployOptions, DeployOptions as ApplyOptions } from \"./commands/deploy/deploy\";\nexport type { BundledScripts } from \"./commands/deploy/function-registry\";\nexport { generate } from \"./commands/generate/service\";\nexport type { GenerateOptions } from \"./commands/generate/options\";\nexport { loadConfig, type LoadedConfig } from \"./shared/config-loader\";\nexport { generateUserTypes } from \"./shared/type-generator\";\nexport type {\n CodeGenerator,\n TailorDBGenerator,\n ResolverGenerator,\n ExecutorGenerator,\n TailorDBResolverGenerator,\n FullCodeGenerator,\n TailorDBInput,\n ResolverInput,\n ExecutorInput,\n FullInput,\n AggregateArgs,\n GeneratorResult,\n DependencyKind,\n PluginAttachment,\n TypeSourceInfoEntry,\n} from \"./commands/generate/types\";\nexport type { TailorDBType } from \"#/parser/service/tailordb/types\";\nexport type { Resolver } from \"#/types/resolver.generated\";\nexport type { Executor } from \"#/types/executor.generated\";\n\n/** @deprecated Import from '@tailor-platform/sdk/plugin/kysely-type' instead */\nexport { kyselyTypePlugin } from \"#/plugin/builtin/kysely-type/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/enum-constants' instead */\nexport { enumConstantsPlugin } from \"#/plugin/builtin/enum-constants/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/file-utils' instead */\nexport { fileUtilsPlugin } from \"#/plugin/builtin/file-utils/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/seed' instead */\nexport { seedPlugin } from \"#/plugin/builtin/seed/index\";\n\nexport { show, type ShowOptions, type ApplicationInfo } from \"./commands/show\";\nexport { remove, type RemoveOptions } from \"./commands/remove\";\nexport { createWorkspace, type CreateWorkspaceOptions } from \"./commands/workspace/create\";\nexport { listWorkspaces, type ListWorkspacesOptions } from \"./commands/workspace/list\";\nexport { deleteWorkspace, type DeleteWorkspaceOptions } from \"./commands/workspace/delete\";\nexport { getWorkspace, type GetWorkspaceOptions } from \"./commands/workspace/get\";\nexport { restoreWorkspace, type RestoreWorkspaceOptions } from \"./commands/workspace/restore\";\nexport type { WorkspaceInfo, WorkspaceDetails } from \"./commands/workspace/transform\";\nexport { listUsers, type ListUsersOptions } from \"./commands/workspace/user/list\";\nexport { inviteUser, type InviteUserOptions } from \"./commands/workspace/user/invite\";\nexport { updateUser, type UpdateUserOptions } from \"./commands/workspace/user/update\";\nexport { removeUser, type RemoveUserOptions } from \"./commands/workspace/user/remove\";\nexport type { UserInfo } from \"./commands/workspace/user/transform\";\nexport { listApps, type ListAppsOptions } from \"./commands/workspace/app/list\";\nexport {\n getAppHealth,\n type HealthOptions as GetAppHealthOptions,\n} from \"./commands/workspace/app/health\";\nexport type { AppInfo, AppHealthInfo } from \"./commands/workspace/app/transform\";\nexport { getFunctionRegistry, type GetFunctionRegistryOptions } from \"./commands/function/get\";\nexport {\n listFunctionRegistries,\n type ListFunctionRegistriesOptions,\n} from \"./commands/function/list\";\nexport type { FunctionRegistryInfo } from \"./commands/function/transform\";\nexport {\n listMachineUsers,\n type ListMachineUsersOptions,\n type MachineUserInfo,\n} from \"./commands/machineuser/list\";\nexport {\n getMachineUserToken,\n type GetMachineUserTokenOptions,\n type MachineUserTokenInfo,\n} from \"./commands/machineuser/token\";\nexport { getOAuth2Client, type GetOAuth2ClientOptions } from \"./commands/oauth2client/get\";\nexport { listOAuth2Clients, type ListOAuth2ClientsOptions } from \"./commands/oauth2client/list\";\nexport type { OAuth2ClientInfo, OAuth2ClientCredentials } from \"./commands/oauth2client/transform\";\nexport { listWorkflows, type ListWorkflowsOptions } from \"./commands/workflow/list\";\nexport {\n getWorkflow,\n type GetWorkflowOptions,\n type GetWorkflowTypedOptions,\n} from \"./commands/workflow/get\";\nexport {\n startWorkflow,\n type StartWorkflowOptions,\n type StartWorkflowTypedOptions,\n type StartWorkflowResultWithWait,\n type WaitOptions,\n} from \"./commands/workflow/start\";\nexport {\n listWorkflowExecutions,\n getWorkflowExecution,\n type ListWorkflowExecutionsOptions,\n type ListWorkflowExecutionsTypedOptions,\n type GetWorkflowExecutionOptions,\n type GetWorkflowExecutionResult,\n type WorkflowExecutionWaitInfo,\n} from \"./commands/workflow/executions\";\nexport { waitWorkflowExecution, type WorkflowWaitOutput } from \"./commands/workflow/wait\";\nexport type { WaitWorkflowExecutionOptions, WorkflowWaitResult } from \"./commands/workflow/waiter\";\nexport {\n resumeWorkflow,\n type ResumeWorkflowOptions,\n type ResumeWorkflowResultWithWait,\n} from \"./commands/workflow/resume\";\nexport type {\n WorkflowListInfo,\n WorkflowInfo,\n WorkflowExecutionInfo,\n WorkflowJobExecutionInfo,\n} from \"./commands/workflow/transform\";\nexport {\n triggerExecutor,\n type TriggerExecutorOptions,\n type TriggerExecutorTypedOptions,\n type TriggerExecutorResult,\n} from \"./commands/executor/trigger\";\nexport {\n listExecutorJobs,\n getExecutorJob,\n getExecutorWaitFailureMessage,\n watchExecutorJob,\n type ListExecutorJobsOptions,\n type ListExecutorJobsTypedOptions,\n type GetExecutorJobOptions,\n type GetExecutorJobTypedOptions,\n type WatchExecutorJobOptions,\n type WatchExecutorJobTypedOptions,\n type ExecutorJobDetailInfo,\n type WatchExecutorJobResult,\n} from \"./commands/executor/jobs\";\nexport { listExecutors, type ListExecutorsOptions } from \"./commands/executor/list\";\nexport {\n getExecutor,\n type GetExecutorOptions,\n type GetExecutorTypedOptions,\n} from \"./commands/executor/get\";\nexport {\n listWebhookExecutors,\n type ListWebhookExecutorsOptions,\n type WebhookExecutorInfo,\n} from \"./commands/executor/webhook\";\nexport type {\n ExecutorJobListInfo,\n ExecutorJobInfo,\n ExecutorJobAttemptInfo,\n ExecutorListInfo,\n ExecutorInfo,\n} from \"./commands/executor/transform\";\nexport { listOrganizations, type ListOrganizationsOptions } from \"./commands/organization/list\";\nexport { getOrganization, type GetOrganizationOptions } from \"./commands/organization/get\";\nexport { updateOrganization, type UpdateOrganizationOptions } from \"./commands/organization/update\";\nexport { organizationTree, type OrganizationTreeOptions } from \"./commands/organization/tree\";\nexport type {\n UserOrganizationInfo,\n OrganizationInfo,\n FolderListInfo,\n FolderInfo,\n} from \"./commands/organization/transform\";\nexport { listFolders, type ListFoldersOptions } from \"./commands/organization/folder/list\";\nexport { getFolder, type GetFolderOptions } from \"./commands/organization/folder/get\";\nexport { createFolder, type CreateFolderOptions } from \"./commands/organization/folder/create\";\nexport { updateFolder, type UpdateFolderOptions } from \"./commands/organization/folder/update\";\nexport { deleteFolder, type DeleteFolderOptions } from \"./commands/organization/folder/delete\";\nexport { loadAccessToken, loadWorkspaceId } from \"./shared/context\";\nexport { apiCall, type ApiCallOptions, type ApiCallResult } from \"./commands/api\";\nexport { query } from \"./query\";\nexport { truncate, type TruncateOptions } from \"./commands/tailordb/truncate\";\n\n// Migration exports\nexport {\n generate as migrateGenerate,\n type GenerateOptions as MigrateGenerateOptions,\n} from \"./commands/tailordb/migrate/generate\";\nexport {\n createSnapshotFromLocalTypes,\n reconstructSnapshotFromMigrations,\n compareSnapshots,\n getNextMigrationNumber,\n getLatestMigrationNumber,\n getMigrationFiles,\n compareLocalTypesWithSnapshot,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport {\n getNamespacesWithMigrations,\n type NamespaceWithMigrations,\n} from \"./commands/tailordb/migrate/config\";\nexport {\n hasChanges,\n formatMigrationDiff,\n formatDiffSummary,\n type MigrationDiff,\n type BreakingChangeInfo,\n} from \"./commands/tailordb/migrate/diff-calculator\";\nexport {\n SCHEMA_FILE_NAME,\n DIFF_FILE_NAME,\n MIGRATE_FILE_NAME,\n DB_TYPES_FILE_NAME,\n INITIAL_SCHEMA_NUMBER,\n getMigrationDirPath,\n getMigrationFilePath,\n type SchemaSnapshot,\n type NormalizedSchemaSnapshot,\n type TailorDBSnapshotType,\n type SnapshotFieldConfig,\n type MigrationInfo,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport { MIGRATION_LABEL_KEY } from \"./commands/tailordb/migrate/types\";\n\n// Seed exports\nexport { chunkSeedData, type SeedChunk, type ChunkSeedDataOptions } from \"./shared/seed-chunker\";\nexport { bundleSeedScript, type SeedBundleResult } from \"./commands/generate/seed/bundler\";\nexport {\n bundleMigrationScript,\n type MigrationBundleResult,\n} from \"./commands/tailordb/migrate/bundler\";\nexport {\n executeScript,\n waitForExecution,\n type ScriptExecutionOptions,\n type ScriptExecutionResult,\n type ExecutionWaitResult,\n} from \"./shared/script-executor\";\nexport { initOperatorClient, type OperatorClient } from \"./shared/client\";\nexport type { AuthInvoker } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,2BAA2B,MAAM,OAAO;;AAGrD,MAAM,oBAAoB;;;;;;;;;;;;;;;A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;;;;;;;;AClJA,MAAM,aAAa;;;;;;AAOnB,SAAS,0BAA0B,WAA2B;CAC5D,OAAO,SAAY;;;;;;;;;;;;;;;;;;;;;;;0BAuBK,UAAU;;;2BAGT,OAAO,UAAU,EAAE;;;;;2BAKnB,UAAU;;;;;;;;;;;;;;6BAcR,UAAU;;;;;;+BAMR,UAAU;;;;;;6BAMZ,UAAU;;;;;;;;;;;AAWvC;;;;;;;;;;;;;AAcA,eAAsB,iBACpB,WACA,WAC2B;CAE3B,MAAM,YAAY,KAAK,QAAQ,WAAW,GAAG,MAAM;CACnD,GAAG,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CAG3C,MAAM,YAAY,KAAK,KAAK,WAAW,QAAQ,UAAU,UAAU;CAGnE,MAAM,eAAe,0BAA0B,SAAS;CACxD,GAAG,cAAc,WAAW,YAAY;CAExC,IAAI;CACJ,IAAI;EACF,WAAW,MAAM,gBAAgB;CACnC,QAAQ;EACN,WAAW;CACb;CA+BA,OAAO;EACL;EACA,cAJkB,MA1BC,SAAS,MAAM;GAClC,SAAS,CAAC,0BAA0B;GACpC,OAAO;GACP,OAAO;GACP,QAAQ;IACN,QAAQ;IACR,WAAW;IACX,QAAQ;IACR,eAAe;IACf,SAAS,EACP,UAAU,WACZ;GACF;GACA,UAAU,CAAC,UAAU;GACrB,SAAS,EACP,gBAAgB,CAAC,QAAQ,QAAQ,EACnC;GACA;GACA,WAAW;IACT,mBAAmB;IACnB,aAAa;IACb,0BAA0B;GAC5B;GACA,UAAU;EACZ,CAA0B,EAEA,CAAC,OAAO,EAAE,CAAC;EAKnC,eAAe;CACjB;AACF;;;;AC/JA,IAAI,CAAC,0BAA0B,GAAG;CAChC,MAAM,EAAE,aAAa,MAAM,OAAO;CAClC,SAAS;AACX"}
|
|
1
|
+
{"version":3,"file":"lib.mjs","names":[],"sources":["../../src/cli/shared/seed-chunker.ts","../../src/cli/commands/generate/seed/bundler.ts","../../src/cli/lib.ts"],"sourcesContent":["/**\n * Seed data chunker for splitting large seed data into manageable message sizes.\n *\n * When seed data exceeds the gRPC message size limit, this module splits the data\n * into multiple chunks at type boundaries (or record boundaries for large types).\n */\n\nimport { assertDefined } from \"#/utils/assert\";\n\n/**\n * Seed data keyed by type name, with an array of records per type.\n */\nexport type SeedData = Record<string, Record<string, unknown>[]>;\n\n/**\n * A single chunk of seed data with metadata for ordered execution.\n */\nexport type SeedChunk = {\n data: SeedData;\n order: string[];\n index: number;\n total: number;\n};\n\n/**\n * Options for chunking seed data.\n */\nexport type ChunkSeedDataOptions = {\n /** Seed data keyed by type name */\n data: SeedData;\n /** Ordered list of type names (dependency order) */\n order: string[];\n /** Byte size of the bundled seed script code */\n codeByteSize: number;\n /** Maximum gRPC message size in bytes (default: 3.5MB) */\n maxMessageSize?: number;\n};\n\n/** Default maximum message size: 3.5MB (conservative limit for gRPC) */\nexport const DEFAULT_MAX_MESSAGE_SIZE = 3.5 * 1024 * 1024;\n\n/** Reserved bytes for message metadata overhead */\nconst METADATA_OVERHEAD = 1024;\n\n/**\n * Split seed data into chunks that fit within the gRPC message size limit.\n *\n * Algorithm:\n * 1. Calculate the available budget for the arg field (maxMessageSize - codeByteSize - overhead)\n * 2. If all data fits in one message, return a single chunk\n * 3. Otherwise, iterate through types in dependency order:\n * - If a type fits in the current chunk, add it\n * - If adding a type would exceed the budget, finalize the current chunk and start a new one\n * - If a single type exceeds the budget, split its records across multiple chunks\n * - If a single record exceeds the budget, throw an error\n * @param options - Chunking options\n * @returns Array of seed chunks\n */\nexport function chunkSeedData(options: ChunkSeedDataOptions): SeedChunk[] {\n const { data, order, codeByteSize, maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE } = options;\n\n const argBudget = maxMessageSize - codeByteSize - METADATA_OVERHEAD;\n if (argBudget <= 0) {\n throw new Error(\n `Code size (${codeByteSize} bytes) exceeds the message size limit (${maxMessageSize} bytes). ` +\n `No space left for seed data.`,\n );\n }\n\n // Filter to types that have data\n const typesWithData = order.filter((type) => (data[type]?.length ?? 0) > 0);\n\n if (typesWithData.length === 0) {\n return [];\n }\n\n // Check if all data fits in a single message\n const fullArg = JSON.stringify({ data, order });\n if (byteSize(fullArg) <= argBudget) {\n return [{ data, order, index: 0, total: 1 }];\n }\n\n // Split into multiple chunks\n const chunks: Omit<SeedChunk, \"total\">[] = [];\n let currentData: SeedData = {};\n let currentOrder: string[] = [];\n\n for (const type of typesWithData) {\n const typeRecords = assertDefined(data[type], `seed data missing for type: ${type}`);\n\n // Check if the type fits in the current chunk\n if (currentOrder.length > 0) {\n const testData = { ...currentData, [type]: typeRecords };\n const testOrder = [...currentOrder, type];\n if (byteSize(JSON.stringify({ data: testData, order: testOrder })) > argBudget) {\n // Finalize the current chunk\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n }\n\n // Check if the entire type fits in an empty chunk\n if (byteSize(JSON.stringify({ data: { [type]: typeRecords }, order: [type] })) <= argBudget) {\n currentData[type] = typeRecords;\n currentOrder.push(type);\n continue;\n }\n\n // Type is too large — split by records\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n }\n\n let recordBatch: Record<string, unknown>[] = [];\n for (const record of typeRecords) {\n if (byteSize(JSON.stringify({ data: { [type]: [record] }, order: [type] })) > argBudget) {\n const singleRecordSize = byteSize(JSON.stringify(record));\n throw new Error(\n `A single record in type \"${type}\" (${singleRecordSize} bytes) exceeds the message size budget ` +\n `(${argBudget} bytes). Consider increasing maxMessageSize or reducing the record size.`,\n );\n }\n\n const testBatch = [...recordBatch, record];\n const testData = { ...currentData, [type]: testBatch };\n const testOrder = currentOrder.includes(type) ? currentOrder : [...currentOrder, type];\n const testSize = byteSize(JSON.stringify({ data: testData, order: testOrder }));\n\n if (testSize > argBudget && recordBatch.length > 0) {\n // Finalize current chunk with accumulated records\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n currentData = {};\n currentOrder = [];\n recordBatch = [record];\n } else {\n recordBatch = testBatch;\n }\n }\n\n // Add remaining records\n if (recordBatch.length > 0) {\n currentData[type] = recordBatch;\n if (!currentOrder.includes(type)) {\n currentOrder.push(type);\n }\n }\n }\n\n // Finalize the last chunk\n if (currentOrder.length > 0) {\n chunks.push({ data: currentData, order: currentOrder, index: chunks.length });\n }\n\n const total = chunks.length;\n return chunks.map((chunk) => ({ ...chunk, total }));\n}\n\nfunction byteSize(str: string): number {\n return new TextEncoder().encode(str).length;\n}\n","/**\n * Seed script bundler for TailorDB seed data\n *\n * Bundles seed scripts to be executed via TestExecScript API\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { resolveTSConfig } from \"pkg-types\";\nimport * as rolldown from \"rolldown\";\nimport { getDistDir } from \"#/cli/shared/dist-dir\";\nimport { platformBundleDefinePlugin } from \"#/cli/shared/platform-bundle-plugin\";\nimport ml from \"#/utils/multiline\";\n\nexport type SeedBundleResult = {\n namespace: string;\n bundledCode: string;\n typesIncluded: string[];\n};\n\nconst BATCH_SIZE = 100;\n\n/**\n * Generate seed script content for server-side execution\n * @param namespace - TailorDB namespace\n * @returns Generated seed script content\n */\nfunction generateSeedScriptContent(namespace: string): string {\n return ml /* ts */ `\n import { Kysely, TailordbDialect } from \"@tailor-platform/sdk/kysely\";\n\n type SeedInput = {\n data: Record<string, Record<string, unknown>[]>;\n order: string[];\n selfRefTypes: string[];\n };\n\n type SeedResult = {\n success: boolean;\n processed: Record<string, number>;\n errors: string[];\n };\n\n function getDB(namespace: string) {\n const client = new tailordb.Client({ namespace });\n return new Kysely<Record<string, Record<string, unknown>>>({\n dialect: new TailordbDialect(client),\n });\n }\n\n export async function main(input: SeedInput): Promise<SeedResult> {\n const db = getDB(\"${namespace}\");\n const processed: Record<string, number> = {};\n const errors: string[] = [];\n const BATCH_SIZE = ${String(BATCH_SIZE)};\n\n for (const typeName of input.order) {\n const records = input.data[typeName];\n if (!records || records.length === 0) {\n console.log(\\`[${namespace}] \\${typeName}: skipped (no data)\\`);\n continue;\n }\n\n processed[typeName] = 0;\n const hasSelfRef = (input.selfRefTypes || []).includes(typeName);\n\n try {\n if (hasSelfRef) {\n // Insert one-by-one to respect self-referencing foreign key order\n for (const record of records) {\n await db.insertInto(typeName).values(record).execute();\n processed[typeName] += 1;\n }\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length} (one-by-one)\\`);\n } else {\n for (let i = 0; i < records.length; i += BATCH_SIZE) {\n const batch = records.slice(i, i + BATCH_SIZE);\n await db.insertInto(typeName).values(batch).execute();\n processed[typeName] += batch.length;\n console.log(\\`[${namespace}] \\${typeName}: \\${processed[typeName]}/\\${records.length}\\`);\n }\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n errors.push(\\`\\${typeName}: \\${message}\\`);\n console.error(\\`[${namespace}] \\${typeName}: failed - \\${message}\\`);\n }\n }\n\n return {\n success: errors.length === 0,\n processed,\n errors,\n };\n }\n `;\n}\n\n/**\n * Bundle a seed script for server-side execution\n *\n * Creates an entry that:\n * 1. Defines getDB() function inline\n * 2. Processes data in batches using Kysely\n * 3. Reports progress via console.log\n * 4. Exports as main() for TestExecScript\n * @param namespace - TailorDB namespace\n * @param typeNames - List of type names to include in the seed\n * @returns Bundled seed script result\n */\nexport async function bundleSeedScript(\n namespace: string,\n typeNames: string[],\n): Promise<SeedBundleResult> {\n // Output directory in .tailor-sdk (relative to project root)\n const outputDir = path.resolve(getDistDir(), \"seed\");\n fs.mkdirSync(outputDir, { recursive: true });\n\n // Entry file in output directory\n const entryPath = path.join(outputDir, `seed_${namespace}.entry.ts`);\n\n // Generate seed script content\n const entryContent = generateSeedScriptContent(namespace);\n fs.writeFileSync(entryPath, entryContent);\n\n let tsconfig: string | undefined;\n try {\n tsconfig = await resolveTSConfig();\n } catch {\n tsconfig = undefined;\n }\n\n // Bundle with tree-shaking (write: false to avoid unnecessary disk I/O)\n const result = await rolldown.build({\n plugins: [platformBundleDefinePlugin],\n input: entryPath,\n write: false,\n output: {\n format: \"esm\",\n sourcemap: false,\n minify: false,\n codeSplitting: false,\n globals: {\n tailordb: \"tailordb\",\n },\n },\n external: [\"tailordb\"],\n resolve: {\n conditionNames: [\"node\", \"import\"],\n },\n tsconfig,\n treeshake: {\n moduleSideEffects: false,\n annotations: true,\n unknownGlobalSideEffects: false,\n },\n logLevel: \"silent\",\n } as rolldown.BuildOptions);\n\n const bundledCode = result.output[0].code;\n\n return {\n namespace,\n bundledCode,\n typesIncluded: typeNames,\n };\n}\n","// CLI API exports for programmatic usage\nimport { isNativeTypeScriptRuntime } from \"./shared/runtime\";\n\n// Register tsx to handle TypeScript files when using CLI API programmatically.\n// Bun and Deno handle TypeScript natively, so registration is skipped.\n// tsx's own register() picks `module.registerHooks` on Node ≥ 24.11.1 / 25.1 / 26\n// (avoiding the DEP0205 deprecation) and falls back to `module.register` on older runtimes.\nif (!isNativeTypeScriptRuntime()) {\n const { register } = await import(\"tsx/esm/api\");\n register();\n}\n\nexport { deploy, deploy as apply } from \"./commands/deploy/deploy\";\nexport type { DeployOptions, DeployOptions as ApplyOptions } from \"./commands/deploy/deploy\";\nexport type { BundledScripts } from \"./commands/deploy/function-registry\";\nexport { generate } from \"./commands/generate/service\";\nexport type { GenerateOptions } from \"./commands/generate/options\";\nexport { loadConfig, type LoadedConfig } from \"./shared/config-loader\";\nexport { generateUserTypes } from \"./shared/type-generator\";\nexport type {\n CodeGenerator,\n TailorDBGenerator,\n ResolverGenerator,\n ExecutorGenerator,\n TailorDBResolverGenerator,\n FullCodeGenerator,\n TailorDBInput,\n ResolverInput,\n ExecutorInput,\n FullInput,\n AggregateArgs,\n GeneratorResult,\n DependencyKind,\n PluginAttachment,\n TypeSourceInfoEntry,\n} from \"./commands/generate/types\";\nexport type { TailorDBType } from \"#/parser/service/tailordb/types\";\nexport type { Resolver } from \"#/types/resolver.generated\";\nexport type { Executor } from \"#/types/executor.generated\";\n\n/** @deprecated Import from '@tailor-platform/sdk/plugin/kysely-type' instead */\nexport { kyselyTypePlugin } from \"#/plugin/builtin/kysely-type/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/enum-constants' instead */\nexport { enumConstantsPlugin } from \"#/plugin/builtin/enum-constants/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/file-utils' instead */\nexport { fileUtilsPlugin } from \"#/plugin/builtin/file-utils/index\";\n/** @deprecated Import from '@tailor-platform/sdk/plugin/seed' instead */\nexport { seedPlugin } from \"#/plugin/builtin/seed/index\";\n\nexport { show, type ShowOptions, type ApplicationInfo } from \"./commands/show\";\nexport { remove, type RemoveOptions } from \"./commands/remove\";\nexport { createWorkspace, type CreateWorkspaceOptions } from \"./commands/workspace/create\";\nexport { listWorkspaces, type ListWorkspacesOptions } from \"./commands/workspace/list\";\nexport { deleteWorkspace, type DeleteWorkspaceOptions } from \"./commands/workspace/delete\";\nexport { getWorkspace, type GetWorkspaceOptions } from \"./commands/workspace/get\";\nexport { restoreWorkspace, type RestoreWorkspaceOptions } from \"./commands/workspace/restore\";\nexport type { WorkspaceInfo, WorkspaceDetails } from \"./commands/workspace/transform\";\nexport { listUsers, type ListUsersOptions } from \"./commands/workspace/user/list\";\nexport { inviteUser, type InviteUserOptions } from \"./commands/workspace/user/invite\";\nexport { updateUser, type UpdateUserOptions } from \"./commands/workspace/user/update\";\nexport { removeUser, type RemoveUserOptions } from \"./commands/workspace/user/remove\";\nexport type { UserInfo } from \"./commands/workspace/user/transform\";\nexport { listApps, type ListAppsOptions } from \"./commands/workspace/app/list\";\nexport {\n getAppHealth,\n type HealthOptions as GetAppHealthOptions,\n} from \"./commands/workspace/app/health\";\nexport type { AppInfo, AppHealthInfo } from \"./commands/workspace/app/transform\";\nexport { getFunctionRegistry, type GetFunctionRegistryOptions } from \"./commands/function/get\";\nexport {\n listFunctionRegistries,\n type ListFunctionRegistriesOptions,\n} from \"./commands/function/list\";\nexport type { FunctionRegistryInfo } from \"./commands/function/transform\";\nexport {\n listMachineUsers,\n type ListMachineUsersOptions,\n type MachineUserInfo,\n} from \"./commands/machineuser/list\";\nexport {\n getMachineUserToken,\n type GetMachineUserTokenOptions,\n type MachineUserTokenInfo,\n} from \"./commands/machineuser/token\";\nexport { getOAuth2Client, type GetOAuth2ClientOptions } from \"./commands/oauth2client/get\";\nexport { listOAuth2Clients, type ListOAuth2ClientsOptions } from \"./commands/oauth2client/list\";\nexport type { OAuth2ClientInfo, OAuth2ClientCredentials } from \"./commands/oauth2client/transform\";\nexport { listWorkflows, type ListWorkflowsOptions } from \"./commands/workflow/list\";\nexport {\n getWorkflow,\n type GetWorkflowOptions,\n type GetWorkflowTypedOptions,\n} from \"./commands/workflow/get\";\nexport {\n startWorkflow,\n type StartWorkflowOptions,\n type StartWorkflowTypedOptions,\n type StartWorkflowResultWithWait,\n type WaitOptions,\n} from \"./commands/workflow/start\";\nexport {\n listWorkflowExecutions,\n getWorkflowExecution,\n type ListWorkflowExecutionsOptions,\n type ListWorkflowExecutionsTypedOptions,\n type GetWorkflowExecutionOptions,\n type GetWorkflowExecutionResult,\n type WorkflowExecutionWaitInfo,\n} from \"./commands/workflow/executions\";\nexport { waitWorkflowExecution, type WorkflowWaitOutput } from \"./commands/workflow/wait\";\nexport type { WaitWorkflowExecutionOptions, WorkflowWaitResult } from \"./commands/workflow/waiter\";\nexport {\n resumeWorkflow,\n type ResumeWorkflowOptions,\n type ResumeWorkflowResultWithWait,\n} from \"./commands/workflow/resume\";\nexport type {\n WorkflowListInfo,\n WorkflowInfo,\n WorkflowExecutionInfo,\n WorkflowJobExecutionInfo,\n} from \"./commands/workflow/transform\";\nexport {\n triggerExecutor,\n type TriggerExecutorOptions,\n type TriggerExecutorTypedOptions,\n type TriggerExecutorResult,\n} from \"./commands/executor/trigger\";\nexport {\n listExecutorJobs,\n getExecutorJob,\n getExecutorWaitFailureMessage,\n watchExecutorJob,\n type ListExecutorJobsOptions,\n type ListExecutorJobsTypedOptions,\n type GetExecutorJobOptions,\n type GetExecutorJobTypedOptions,\n type WatchExecutorJobOptions,\n type WatchExecutorJobTypedOptions,\n type ExecutorJobDetailInfo,\n type WatchExecutorJobResult,\n} from \"./commands/executor/jobs\";\nexport { listExecutors, type ListExecutorsOptions } from \"./commands/executor/list\";\nexport {\n getExecutor,\n type GetExecutorOptions,\n type GetExecutorTypedOptions,\n} from \"./commands/executor/get\";\nexport {\n listWebhookExecutors,\n type ListWebhookExecutorsOptions,\n type WebhookExecutorInfo,\n} from \"./commands/executor/webhook\";\nexport type {\n ExecutorJobListInfo,\n ExecutorJobInfo,\n ExecutorJobAttemptInfo,\n ExecutorListInfo,\n ExecutorInfo,\n} from \"./commands/executor/transform\";\nexport { listOrganizations, type ListOrganizationsOptions } from \"./commands/organization/list\";\nexport { getOrganization, type GetOrganizationOptions } from \"./commands/organization/get\";\nexport { updateOrganization, type UpdateOrganizationOptions } from \"./commands/organization/update\";\nexport { organizationTree, type OrganizationTreeOptions } from \"./commands/organization/tree\";\nexport type {\n UserOrganizationInfo,\n OrganizationInfo,\n FolderListInfo,\n FolderInfo,\n} from \"./commands/organization/transform\";\nexport { listFolders, type ListFoldersOptions } from \"./commands/organization/folder/list\";\nexport { getFolder, type GetFolderOptions } from \"./commands/organization/folder/get\";\nexport { createFolder, type CreateFolderOptions } from \"./commands/organization/folder/create\";\nexport { updateFolder, type UpdateFolderOptions } from \"./commands/organization/folder/update\";\nexport { deleteFolder, type DeleteFolderOptions } from \"./commands/organization/folder/delete\";\nexport { loadAccessToken, loadWorkspaceId } from \"./shared/context\";\nexport { apiCall, type ApiCallOptions, type ApiCallResult } from \"./commands/api\";\nexport { query } from \"./query\";\nexport { truncate, type TruncateOptions } from \"./commands/tailordb/truncate\";\n\n// Migration exports\nexport {\n generate as migrateGenerate,\n type GenerateOptions as MigrateGenerateOptions,\n} from \"./commands/tailordb/migrate/generate\";\nexport {\n createSnapshotFromLocalTypes,\n reconstructSnapshotFromMigrations,\n compareSnapshots,\n getNextMigrationNumber,\n getLatestMigrationNumber,\n getMigrationFiles,\n compareLocalTypesWithSnapshot,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport {\n getNamespacesWithMigrations,\n type NamespaceWithMigrations,\n} from \"./commands/tailordb/migrate/config\";\nexport {\n hasChanges,\n formatMigrationDiff,\n formatDiffSummary,\n type MigrationDiff,\n type BreakingChangeInfo,\n} from \"./commands/tailordb/migrate/diff-calculator\";\nexport {\n SCHEMA_FILE_NAME,\n DIFF_FILE_NAME,\n MIGRATE_FILE_NAME,\n DB_TYPES_FILE_NAME,\n INITIAL_SCHEMA_NUMBER,\n getMigrationDirPath,\n getMigrationFilePath,\n type SchemaSnapshot,\n type NormalizedSchemaSnapshot,\n type TailorDBSnapshotType,\n type SnapshotFieldConfig,\n} from \"./commands/tailordb/migrate/snapshot\";\nexport { MIGRATION_LABEL_KEY } from \"./commands/tailordb/migrate/types\";\n\n// Seed exports\nexport { chunkSeedData, type SeedChunk, type ChunkSeedDataOptions } from \"./shared/seed-chunker\";\nexport { bundleSeedScript, type SeedBundleResult } from \"./commands/generate/seed/bundler\";\nexport {\n bundleMigrationScript,\n type MigrationBundleResult,\n} from \"./commands/tailordb/migrate/bundler\";\nexport {\n executeScript,\n waitForExecution,\n type ScriptExecutionOptions,\n type ScriptExecutionResult,\n type ExecutionWaitResult,\n} from \"./shared/script-executor\";\nexport { initOperatorClient, type OperatorClient } from \"./shared/client\";\nexport type { AuthInvoker } from \"@tailor-platform/tailor-proto/auth_resource_pb\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,MAAa,2BAA2B,MAAM,OAAO;;AAGrD,MAAM,oBAAoB;;;;;;;;;;;;;;;AAgB1B,SAAgB,cAAc,SAA4C;CACxE,MAAM,EAAE,MAAM,OAAO,cAAc,iBAAiB,6BAA6B;CAEjF,MAAM,YAAY,iBAAiB,eAAe;CAClD,IAAI,aAAa,GACf,MAAM,IAAI,MACR,cAAc,aAAa,0CAA0C,eAAe,sCAEtF;C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R,UAAU;;;;;;+BAMR,UAAU;;;;;;6BAMZ,UAAU;;;;;;;;;;;AAWvC;;;;;;;;;;;;;AAcA,eAAsB,iBACpB,WACA,WAC2B;CAE3B,MAAM,YAAY,KAAK,QAAQ,WAAW,GAAG,MAAM;CACnD,GAAG,UAAU,WAAW,EAAE,WAAW,KAAK,CAAC;CAG3C,MAAM,YAAY,KAAK,KAAK,WAAW,QAAQ,UAAU,UAAU;CAGnE,MAAM,eAAe,0BAA0B,SAAS;CACxD,GAAG,cAAc,WAAW,YAAY;CAExC,IAAI;CACJ,IAAI;EACF,WAAW,MAAM,gBAAgB;CACnC,QAAQ;EACN,WAAW;CACb;CA+BA,OAAO;EACL;EACA,cAJkB,MA1BC,SAAS,MAAM;GAClC,SAAS,CAAC,0BAA0B;GACpC,OAAO;GACP,OAAO;GACP,QAAQ;IACN,QAAQ;IACR,WAAW;IACX,QAAQ;IACR,eAAe;IACf,SAAS,EACP,UAAU,WACZ;GACF;GACA,UAAU,CAAC,UAAU;GACrB,SAAS,EACP,gBAAgB,CAAC,QAAQ,QAAQ,EACnC;GACA;GACA,WAAW;IACT,mBAAmB;IACnB,aAAa;IACb,0BAA0B;GAC5B;GACA,UAAU;EACZ,CAA0B,EAEA,CAAC,OAAO,EAAE,CAAC;EAKnC,eAAe;CACjB;AACF;;;;AC/JA,IAAI,CAAC,0BAA0B,GAAG;CAChC,MAAM,EAAE,aAAa,MAAM,OAAO;CAClC,SAAS;AACX"}
|
package/dist/configure/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as t$1 } from "../types-
|
|
1
|
+
import { t as t$1 } from "../types-BwzB2okW.mjs";
|
|
2
2
|
import { t as brandValue } from "../brand-Eo4pLXPJ.mjs";
|
|
3
|
-
import { t as db } from "../schema-
|
|
3
|
+
import { t as db } from "../schema-Dl_y0m9e.mjs";
|
|
4
4
|
import { r as dispatchTriggerWorkflow, s as registerWorkflow, u as WORKFLOW_TEST_ENV_KEY } from "../registry-BozuxbPp.mjs";
|
|
5
5
|
import { t as createWorkflowJob } from "../job-CtU73PGa.mjs";
|
|
6
6
|
|
|
@@ -3,6 +3,7 @@ import { InferFieldsOutput, TypeLevelError, output } from "../../../types/helper
|
|
|
3
3
|
import { FieldOptions, FieldOutput, FieldValidateInput, TailorFieldType, TailorToTs, Validators } from "../../types/field.types.mjs";
|
|
4
4
|
import { DBFieldMetadata, DefinedDBFieldMetadata, ExcludeNestedDBFields, Hook, Hooks, IndexDef, RelationType, SerialConfig, TailorDBField as TailorDBField$1, TailorDBType as TailorDBType$1, TypeFeatures } from "./types.mjs";
|
|
5
5
|
import { AllowedValues, AllowedValuesOutput } from "../../types/field.mjs";
|
|
6
|
+
import { FieldParseArgs, FieldParseInternalArgs } from "../../types/field-runtime.mjs";
|
|
6
7
|
import { PluginConfigs } from "../../../plugin/types.mjs";
|
|
7
8
|
import { TailorTypeGqlPermission, TailorTypePermission } from "./permission.mjs";
|
|
8
9
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
@@ -76,7 +77,7 @@ type WithDBFieldSerial<Defined> = Defined & {
|
|
|
76
77
|
update: false;
|
|
77
78
|
};
|
|
78
79
|
};
|
|
79
|
-
type WithDBFieldCloneOptions<Defined extends DefinedDBFieldMetadata, NewOpt extends FieldOptions> = Omit<Defined, "array"> & {
|
|
80
|
+
type WithDBFieldCloneOptions<Defined extends DefinedDBFieldMetadata, NewOpt extends FieldOptions> = IsAny<Defined> extends true ? Defined : Omit<Defined, "array"> & {
|
|
80
81
|
array: NewOpt extends {
|
|
81
82
|
array: true;
|
|
82
83
|
} ? true : Defined["array"];
|
|
@@ -101,12 +102,12 @@ type DBFieldRelationMethod<Defined extends DefinedDBFieldMetadata, Output> = IsA
|
|
|
101
102
|
} ? TypeLevelError<".relation() has already been set"> : DBFieldRelationFn<Defined, Output>;
|
|
102
103
|
type DBFieldIndexMethod<Defined extends DefinedDBFieldMetadata, Output> = IsAny<Defined> extends true ? DBFieldIndexFn<Defined, Output> : Defined extends {
|
|
103
104
|
index: unknown;
|
|
104
|
-
} ? TypeLevelError<".index() has already been set"> : Defined extends {
|
|
105
|
+
} ? TypeLevelError<".index() has already been set"> : boolean extends Defined["array"] ? DBFieldIndexFn<Defined, Output> | TypeLevelError<"index cannot be set on array fields"> : Defined extends {
|
|
105
106
|
array: true;
|
|
106
107
|
} ? TypeLevelError<"index cannot be set on array fields"> : DBFieldIndexFn<Defined, Output>;
|
|
107
108
|
type DBFieldUniqueMethod<Defined extends DefinedDBFieldMetadata, Output> = IsAny<Defined> extends true ? DBFieldUniqueFn<Defined, Output> : Defined extends {
|
|
108
109
|
unique: unknown;
|
|
109
|
-
} ? TypeLevelError<".unique() has already been set"> : Defined extends {
|
|
110
|
+
} ? TypeLevelError<".unique() has already been set"> : boolean extends Defined["array"] ? DBFieldUniqueFn<Defined, Output> | TypeLevelError<"unique cannot be set on array fields"> : Defined extends {
|
|
110
111
|
array: true;
|
|
111
112
|
} ? TypeLevelError<"unique cannot be set on array fields"> : DBFieldUniqueFn<Defined, Output>;
|
|
112
113
|
type DBFieldVectorMethod<Defined extends DefinedDBFieldMetadata, Output> = IsAny<Defined> extends true ? DBFieldVectorFn<Defined, Output> : Defined extends {
|
|
@@ -213,11 +214,7 @@ interface TailorDBType<Fields extends Record<string, TailorAnyDBField> = any, Us
|
|
|
213
214
|
gqlPermission<U extends object = User, P extends TailorTypeGqlPermission<U> = TailorTypeGqlPermission<U>>(permission: P): TailorDBType<Fields, U>;
|
|
214
215
|
description(description: string): TailorDBType<Fields, User>;
|
|
215
216
|
pickFields<K extends keyof Fields>(keys: K[]): Pick<Fields, K>;
|
|
216
|
-
pickFields<K extends keyof Fields, const Opt extends FieldOptions>(keys: K[], options: Opt): { [P in K]: Fields[P] extends TailorDBField<infer D, infer _O> ? TailorDBField<
|
|
217
|
-
array: Opt extends {
|
|
218
|
-
array: true;
|
|
219
|
-
} ? true : D["array"];
|
|
220
|
-
}, FieldOutput<TailorToTs[D["type"]], Opt>> : never };
|
|
217
|
+
pickFields<K extends keyof Fields, const Opt extends FieldOptions>(keys: K[], options: Opt): { [P in K]: Fields[P] extends TailorDBField<infer D, infer _O> ? TailorDBField<WithDBFieldCloneOptions<D, Opt>, FieldOutput<TailorToTs[D["type"]], Opt>> : never };
|
|
221
218
|
omitFields<K extends keyof Fields>(keys: K[]): Omit<Fields, K>;
|
|
222
219
|
plugin<P extends keyof PluginConfigs<keyof Fields & string>>(config: { [K in P]: PluginConfigs<keyof Fields & string>[K] }): TailorDBType<Fields, User>;
|
|
223
220
|
}
|
|
@@ -240,17 +237,6 @@ type RelationSelfConfig = {
|
|
|
240
237
|
};
|
|
241
238
|
backward?: string;
|
|
242
239
|
};
|
|
243
|
-
type FieldParseArgs = {
|
|
244
|
-
value: unknown;
|
|
245
|
-
data: unknown;
|
|
246
|
-
user: TailorUser;
|
|
247
|
-
};
|
|
248
|
-
type FieldParseInternalArgs = {
|
|
249
|
-
value: any;
|
|
250
|
-
data: unknown;
|
|
251
|
-
user: TailorUser;
|
|
252
|
-
pathArray: string[];
|
|
253
|
-
};
|
|
254
240
|
type DBFieldDefined<T extends TailorFieldType, Opt extends FieldOptions> = {
|
|
255
241
|
type: T;
|
|
256
242
|
array: Opt extends {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { TailorUser } from "../../runtime/types.mjs";
|
|
2
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
3
|
+
|
|
4
|
+
//#region src/configure/types/field-runtime.d.ts
|
|
5
|
+
type FieldParseArgs = {
|
|
6
|
+
value: unknown;
|
|
7
|
+
data: unknown;
|
|
8
|
+
user: TailorUser;
|
|
9
|
+
};
|
|
10
|
+
type FieldParseInternalArgs = {
|
|
11
|
+
value: unknown;
|
|
12
|
+
data: unknown;
|
|
13
|
+
user: TailorUser;
|
|
14
|
+
pathArray: string[];
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
export { FieldParseArgs, FieldParseInternalArgs };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { TailorUser } from "../../runtime/types.mjs";
|
|
2
1
|
import { TypeLevelError } from "../../types/helpers.mjs";
|
|
3
2
|
import { DefinedFieldMetadata, FieldMetadata, FieldValidateInput, TailorField as TailorField$1, TailorFieldType } from "./field.types.mjs";
|
|
3
|
+
import { FieldParseArgs, FieldParseInternalArgs } from "./field-runtime.mjs";
|
|
4
4
|
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
5
5
|
|
|
6
6
|
//#region src/configure/types/type.d.ts
|
|
@@ -78,22 +78,5 @@ interface TailorField<Defined extends DefinedFieldMetadata = DefinedFieldMetadat
|
|
|
78
78
|
*/
|
|
79
79
|
_parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<Output>;
|
|
80
80
|
}
|
|
81
|
-
type FieldParseArgs = {
|
|
82
|
-
value: unknown;
|
|
83
|
-
data: unknown;
|
|
84
|
-
user: TailorUser;
|
|
85
|
-
};
|
|
86
|
-
type FieldParseInternalArgs = {
|
|
87
|
-
value: any;
|
|
88
|
-
data: unknown;
|
|
89
|
-
user: TailorUser;
|
|
90
|
-
pathArray: string[];
|
|
91
|
-
};
|
|
92
|
-
/**
|
|
93
|
-
* Create a UUID field for resolver input/output.
|
|
94
|
-
* @param options - Field configuration options
|
|
95
|
-
* @returns A UUID field
|
|
96
|
-
* @example t.uuid()
|
|
97
|
-
*/
|
|
98
81
|
//#endregion
|
|
99
82
|
export { TailorAnyField, TailorField };
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
//#region src/configure/types/field.ts
|
|
2
|
+
/**
|
|
3
|
+
* Normalize allowed values into EnumValue objects with descriptions.
|
|
4
|
+
* @param values - Allowed values as strings or EnumValue objects
|
|
5
|
+
* @returns Normalized allowed values
|
|
6
|
+
*/
|
|
7
|
+
function mapAllowedValues(values) {
|
|
8
|
+
return values.map((value) => {
|
|
9
|
+
if (typeof value === "string") return {
|
|
10
|
+
value,
|
|
11
|
+
description: ""
|
|
12
|
+
};
|
|
13
|
+
return {
|
|
14
|
+
...value,
|
|
15
|
+
description: value.description ?? ""
|
|
16
|
+
};
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
//#endregion
|
|
21
|
+
//#region src/configure/types/field-runtime.ts
|
|
22
|
+
const regex = {
|
|
23
|
+
uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
|
|
24
|
+
date: /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/,
|
|
25
|
+
time: /^(?<hour>\d{2}):(?<minute>\d{2})$/,
|
|
26
|
+
datetime: /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2})(.(?<millisec>\d{3}))?Z$/,
|
|
27
|
+
decimal: /^-?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/
|
|
28
|
+
};
|
|
29
|
+
function validateValue(args) {
|
|
30
|
+
const { field, value, data, user, pathArray } = args;
|
|
31
|
+
const issues = [];
|
|
32
|
+
const path = pathArray.length > 0 ? pathArray : void 0;
|
|
33
|
+
switch (field.type) {
|
|
34
|
+
case "string":
|
|
35
|
+
if (typeof value !== "string") issues.push({
|
|
36
|
+
message: `Expected a string: received ${String(value)}`,
|
|
37
|
+
path
|
|
38
|
+
});
|
|
39
|
+
break;
|
|
40
|
+
case "integer":
|
|
41
|
+
if (typeof value !== "number" || !Number.isInteger(value)) issues.push({
|
|
42
|
+
message: `Expected an integer: received ${String(value)}`,
|
|
43
|
+
path
|
|
44
|
+
});
|
|
45
|
+
break;
|
|
46
|
+
case "float":
|
|
47
|
+
if (typeof value !== "number" || !Number.isFinite(value)) issues.push({
|
|
48
|
+
message: `Expected a number: received ${String(value)}`,
|
|
49
|
+
path
|
|
50
|
+
});
|
|
51
|
+
break;
|
|
52
|
+
case "boolean":
|
|
53
|
+
if (typeof value !== "boolean") issues.push({
|
|
54
|
+
message: `Expected a boolean: received ${String(value)}`,
|
|
55
|
+
path
|
|
56
|
+
});
|
|
57
|
+
break;
|
|
58
|
+
case "uuid":
|
|
59
|
+
if (typeof value !== "string" || !regex.uuid.test(value)) issues.push({
|
|
60
|
+
message: `Expected a valid UUID: received ${String(value)}`,
|
|
61
|
+
path
|
|
62
|
+
});
|
|
63
|
+
break;
|
|
64
|
+
case "date":
|
|
65
|
+
if (typeof value !== "string" || !regex.date.test(value)) issues.push({
|
|
66
|
+
message: `Expected to match "yyyy-MM-dd" format: received ${String(value)}`,
|
|
67
|
+
path
|
|
68
|
+
});
|
|
69
|
+
break;
|
|
70
|
+
case "datetime":
|
|
71
|
+
if (typeof value !== "string" || !regex.datetime.test(value)) issues.push({
|
|
72
|
+
message: `Expected to match ISO format: received ${String(value)}`,
|
|
73
|
+
path
|
|
74
|
+
});
|
|
75
|
+
break;
|
|
76
|
+
case "time":
|
|
77
|
+
if (typeof value !== "string" || !regex.time.test(value)) issues.push({
|
|
78
|
+
message: `Expected to match "HH:mm" format: received ${String(value)}`,
|
|
79
|
+
path
|
|
80
|
+
});
|
|
81
|
+
break;
|
|
82
|
+
case "decimal":
|
|
83
|
+
if (typeof value !== "string" || !regex.decimal.test(value)) issues.push({
|
|
84
|
+
message: `Expected a decimal string: received ${String(value)}`,
|
|
85
|
+
path
|
|
86
|
+
});
|
|
87
|
+
break;
|
|
88
|
+
case "enum":
|
|
89
|
+
if (field._metadata.allowedValues) {
|
|
90
|
+
const allowedValues = field._metadata.allowedValues.map((v) => v.value);
|
|
91
|
+
if (typeof value !== "string" || !allowedValues.includes(value)) issues.push({
|
|
92
|
+
message: `Must be one of [${allowedValues.join(", ")}]: received ${String(value)}`,
|
|
93
|
+
path
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
break;
|
|
97
|
+
case "nested":
|
|
98
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || value instanceof Date) issues.push({
|
|
99
|
+
message: `Expected an object: received ${String(value)}`,
|
|
100
|
+
path
|
|
101
|
+
});
|
|
102
|
+
else if (Object.keys(field.fields).length > 0) for (const [fieldName, nestedField] of Object.entries(field.fields)) {
|
|
103
|
+
const fieldValue = value[fieldName];
|
|
104
|
+
const result = nestedField._parseInternal({
|
|
105
|
+
value: fieldValue,
|
|
106
|
+
data,
|
|
107
|
+
user,
|
|
108
|
+
pathArray: pathArray.concat(fieldName)
|
|
109
|
+
});
|
|
110
|
+
if (result.issues) issues.push(...result.issues);
|
|
111
|
+
}
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
const validateFns = field._metadata.validate;
|
|
115
|
+
if (validateFns && validateFns.length > 0) for (const validateInput of validateFns) {
|
|
116
|
+
const { fn, message } = typeof validateInput === "function" ? {
|
|
117
|
+
fn: validateInput,
|
|
118
|
+
message: "Validation failed"
|
|
119
|
+
} : {
|
|
120
|
+
fn: validateInput[0],
|
|
121
|
+
message: validateInput[1]
|
|
122
|
+
};
|
|
123
|
+
if (!fn({
|
|
124
|
+
value,
|
|
125
|
+
data,
|
|
126
|
+
user
|
|
127
|
+
})) issues.push({
|
|
128
|
+
message,
|
|
129
|
+
path
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
return issues;
|
|
133
|
+
}
|
|
134
|
+
function parseInternal(args) {
|
|
135
|
+
const { field, value, data, user, pathArray } = args;
|
|
136
|
+
const issues = [];
|
|
137
|
+
const path = pathArray.length > 0 ? pathArray : void 0;
|
|
138
|
+
const isNullOrUndefined = value === null || value === void 0;
|
|
139
|
+
if (field._metadata.required && isNullOrUndefined) {
|
|
140
|
+
issues.push({
|
|
141
|
+
message: "Required field is missing",
|
|
142
|
+
path
|
|
143
|
+
});
|
|
144
|
+
return { issues };
|
|
145
|
+
}
|
|
146
|
+
if (!field._metadata.required && isNullOrUndefined) return { value: value ?? null };
|
|
147
|
+
if (field._metadata.array) {
|
|
148
|
+
if (!Array.isArray(value)) {
|
|
149
|
+
issues.push({
|
|
150
|
+
message: "Expected an array",
|
|
151
|
+
path
|
|
152
|
+
});
|
|
153
|
+
return { issues };
|
|
154
|
+
}
|
|
155
|
+
for (let i = 0; i < value.length; i++) {
|
|
156
|
+
const elementValue = value[i];
|
|
157
|
+
const elementIssues = validateValue({
|
|
158
|
+
field,
|
|
159
|
+
value: elementValue,
|
|
160
|
+
data,
|
|
161
|
+
user,
|
|
162
|
+
pathArray: pathArray.concat(`[${i}]`)
|
|
163
|
+
});
|
|
164
|
+
if (elementIssues.length > 0) issues.push(...elementIssues);
|
|
165
|
+
}
|
|
166
|
+
if (issues.length > 0) return { issues };
|
|
167
|
+
return { value };
|
|
168
|
+
}
|
|
169
|
+
const valueIssues = validateValue({
|
|
170
|
+
field,
|
|
171
|
+
value,
|
|
172
|
+
data,
|
|
173
|
+
user,
|
|
174
|
+
pathArray
|
|
175
|
+
});
|
|
176
|
+
issues.push(...valueIssues);
|
|
177
|
+
if (issues.length > 0) return { issues };
|
|
178
|
+
return { value };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
//#endregion
|
|
182
|
+
export { mapAllowedValues as n, parseInternal as t };
|
|
183
|
+
//# sourceMappingURL=field-runtime-9bfXBAOK.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"field-runtime-9bfXBAOK.mjs","names":[],"sources":["../src/configure/types/field.ts","../src/configure/types/field-runtime.ts"],"sourcesContent":["import type { EnumValue } from \"#/configure/types/field.types\";\n\nexport type AllowedValues = readonly [string | EnumValue, ...(string | EnumValue)[]];\n\n/**\n * Normalize allowed values into EnumValue objects with descriptions.\n * @param values - Allowed values as strings or EnumValue objects\n * @returns Normalized allowed values\n */\nexport function mapAllowedValues(values: AllowedValues): EnumValue[] {\n return values.map((value) => {\n if (typeof value === \"string\") {\n return { value, description: \"\" };\n }\n return { ...value, description: value.description ?? \"\" };\n });\n}\n\nexport type AllowedValuesOutput<V extends AllowedValues> = V[number] extends infer T\n ? T extends string\n ? T\n : T extends { value: infer K }\n ? K\n : never\n : never;\n","import type { FieldMetadata, TailorFieldType } from \"#/configure/types/field.types\";\nimport type { TailorUser } from \"#/runtime/types\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nconst regex = {\n uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n date: /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$/,\n time: /^(?<hour>\\d{2}):(?<minute>\\d{2})$/,\n datetime:\n /^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})T(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(.(?<millisec>\\d{3}))?Z$/,\n decimal: /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][+-]?\\d+)?$/,\n} as const;\n\nexport type FieldParseArgs = {\n value: unknown;\n data: unknown;\n user: TailorUser;\n};\n\nexport type FieldParseInternalArgs = {\n value: unknown;\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\nexport type FieldRuntime<T extends TailorFieldType = TailorFieldType> = {\n readonly type: T;\n readonly fields: Record<string, FieldRuntime>;\n _metadata: FieldMetadata;\n _parseInternal(args: FieldParseInternalArgs): StandardSchemaV1.Result<unknown>;\n};\n\ntype FieldValidateValueArgs<T extends TailorFieldType> = {\n field: FieldRuntime<T>;\n value: unknown;\n data: unknown;\n user: TailorUser;\n pathArray: string[];\n};\n\ntype FieldParseRuntimeArgs<T extends TailorFieldType> = FieldParseInternalArgs & {\n field: FieldRuntime<T>;\n};\n\nfunction validateValue<T extends TailorFieldType>(\n args: FieldValidateValueArgs<T>,\n): StandardSchemaV1.Issue[] {\n const { field, value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n switch (field.type) {\n case \"string\":\n if (typeof value !== \"string\") {\n issues.push({\n message: `Expected a string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n issues.push({\n message: `Expected an integer: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"float\":\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n issues.push({\n message: `Expected a number: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n issues.push({\n message: `Expected a boolean: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"uuid\":\n if (typeof value !== \"string\" || !regex.uuid.test(value)) {\n issues.push({\n message: `Expected a valid UUID: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"date\":\n if (typeof value !== \"string\" || !regex.date.test(value)) {\n issues.push({\n message: `Expected to match \"yyyy-MM-dd\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"datetime\":\n if (typeof value !== \"string\" || !regex.datetime.test(value)) {\n issues.push({\n message: `Expected to match ISO format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"time\":\n if (typeof value !== \"string\" || !regex.time.test(value)) {\n issues.push({\n message: `Expected to match \"HH:mm\" format: received ${String(value)}`,\n path,\n });\n }\n break;\n case \"decimal\":\n if (typeof value !== \"string\" || !regex.decimal.test(value)) {\n issues.push({\n message: `Expected a decimal string: received ${String(value)}`,\n path,\n });\n }\n break;\n\n case \"enum\":\n if (field._metadata.allowedValues) {\n const allowedValues = field._metadata.allowedValues.map((v) => v.value);\n if (typeof value !== \"string\" || !allowedValues.includes(value)) {\n issues.push({\n message: `Must be one of [${allowedValues.join(\", \")}]: received ${String(value)}`,\n path,\n });\n }\n }\n break;\n\n case \"nested\":\n // Runtime input may not match the declared field type.\n // oxlint-disable typescript/no-unnecessary-condition\n if (\n typeof value !== \"object\" ||\n value === null ||\n Array.isArray(value) ||\n value instanceof Date\n ) {\n // oxlint-enable typescript/no-unnecessary-condition\n issues.push({\n message: `Expected an object: received ${String(value)}`,\n path,\n });\n } else if (Object.keys(field.fields).length > 0) {\n for (const [fieldName, nestedField] of Object.entries(field.fields)) {\n const fieldValue = (value as Record<string, unknown>)[fieldName];\n const result = nestedField._parseInternal({\n value: fieldValue,\n data,\n user,\n pathArray: pathArray.concat(fieldName),\n });\n if (result.issues) {\n issues.push(...result.issues);\n }\n }\n }\n break;\n }\n\n const validateFns = field._metadata.validate;\n if (validateFns && validateFns.length > 0) {\n for (const validateInput of validateFns) {\n const { fn, message } =\n typeof validateInput === \"function\"\n ? { fn: validateInput, message: \"Validation failed\" }\n : { fn: validateInput[0], message: validateInput[1] };\n\n if (!fn({ value, data, user })) {\n issues.push({\n message,\n path,\n });\n }\n }\n }\n\n return issues;\n}\n\nexport function parseInternal<T extends TailorFieldType, Output>(\n args: FieldParseRuntimeArgs<T>,\n): StandardSchemaV1.Result<Output> {\n const { field, value, data, user, pathArray } = args;\n const issues: StandardSchemaV1.Issue[] = [];\n const path = pathArray.length > 0 ? pathArray : undefined;\n\n const isNullOrUndefined = value === null || value === undefined;\n if (field._metadata.required && isNullOrUndefined) {\n issues.push({\n message: \"Required field is missing\",\n path,\n });\n return { issues };\n }\n\n if (!field._metadata.required && isNullOrUndefined) {\n return { value: (value ?? null) as Output };\n }\n\n if (field._metadata.array) {\n if (!Array.isArray(value)) {\n issues.push({\n message: \"Expected an array\",\n path,\n });\n return { issues };\n }\n\n for (let i = 0; i < value.length; i++) {\n const elementValue = value[i];\n const elementPath = pathArray.concat(`[${i}]`);\n\n const elementIssues = validateValue({\n field,\n value: elementValue,\n data,\n user,\n pathArray: elementPath,\n });\n if (elementIssues.length > 0) {\n issues.push(...elementIssues);\n }\n }\n\n if (issues.length > 0) {\n return { issues };\n }\n return { value: value as Output };\n }\n\n const valueIssues = validateValue({ field, value, data, user, pathArray });\n issues.push(...valueIssues);\n\n if (issues.length > 0) {\n return { issues };\n }\n\n return { value: value as Output };\n}\n"],"mappings":";;;;;;AASA,SAAgB,iBAAiB,QAAoC;CACnE,OAAO,OAAO,KAAK,UAAU;EAC3B,IAAI,OAAO,UAAU,UACnB,OAAO;GAAE;GAAO,aAAa;EAAG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