@tailor-platform/sdk 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/README.md +1 -1
  3. package/dist/{application-BpLeawBg.mjs → application-C8a0UJ-z.mjs} +312 -166
  4. package/dist/application-C8a0UJ-z.mjs.map +1 -0
  5. package/dist/application-D4zOiLLa.mjs +3 -0
  6. package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +47 -24
  7. package/dist/cli/commands/tailordb/migrate/generate.d.mts +6 -0
  8. package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +22 -0
  9. package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +1 -1
  10. package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +30 -11
  11. package/dist/cli/commands/tailordb/truncate.d.mts +2 -2
  12. package/dist/cli/lib.mjs +2 -2
  13. package/dist/cli/lib.mjs.map +1 -1
  14. package/dist/cli/main.mjs +366 -137
  15. package/dist/cli/main.mjs.map +1 -1
  16. package/dist/cli/ts-hook.mjs +55 -8
  17. package/dist/completion/zsh-worker.zsh +38 -10
  18. package/dist/configure/config/index.d.mts +1 -1
  19. package/dist/configure/index.d.mts +3 -2
  20. package/dist/configure/index.mjs +92 -25
  21. package/dist/configure/index.mjs.map +1 -1
  22. package/dist/configure/services/aigateway/index.d.mts +5 -4
  23. package/dist/configure/services/aigateway/types.d.mts +6 -1
  24. package/dist/configure/services/auth/types.d.mts +2 -2
  25. package/dist/configure/services/index.d.mts +2 -2
  26. package/dist/configure/services/tailordb/permission.d.mts +1 -1
  27. package/dist/configure/services/tailordb/schema.d.mts +1 -1
  28. package/dist/configure/services/tailordb/types.d.mts +7 -4
  29. package/dist/configure/services/workflow/index.d.mts +2 -2
  30. package/dist/configure/services/workflow/wait-point.d.mts +72 -13
  31. package/dist/configure/types/auth-namespace-name.d.mts +18 -0
  32. package/dist/{crashreport-CINZ5dVN.mjs → crashreport-Cd4TqfZq.mjs} +1 -1
  33. package/dist/{crashreport-CIIfLnoO.mjs → crashreport-Q0pDAlrj.mjs} +8 -4
  34. package/dist/{crashreport-CIIfLnoO.mjs.map → crashreport-Q0pDAlrj.mjs.map} +1 -1
  35. package/dist/{errors-CWj21238.mjs → errors-Bxut5_Sy.mjs} +17 -3
  36. package/dist/{errors-CWj21238.mjs.map → errors-Bxut5_Sy.mjs.map} +1 -1
  37. package/dist/file-BUcmVIH2.mjs.map +1 -1
  38. package/dist/kysely/index.d.mts +2 -1
  39. package/dist/kysely/index.mjs +2 -1
  40. package/dist/kysely/index.mjs.map +1 -1
  41. package/dist/{logger-DSdExfor.mjs → logger-D0bEznPv.mjs} +9 -5
  42. package/dist/{logger-DSdExfor.mjs.map → logger-D0bEznPv.mjs.map} +1 -1
  43. package/dist/package-json-8b0O9TlX.mjs.map +1 -1
  44. package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
  45. package/dist/plugin/builtin/enum-constants/index.mjs +5 -5
  46. package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
  47. package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
  48. package/dist/plugin/builtin/file-utils/index.mjs +14 -11
  49. package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
  50. package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
  51. package/dist/plugin/builtin/kysely-type/index.mjs +9 -9
  52. package/dist/plugin/builtin/kysely-type/index.mjs.map +1 -1
  53. package/dist/plugin/builtin/seed/index.mjs +1 -1
  54. package/dist/plugin/builtin/seed/seed-type-processor.d.mts +4 -4
  55. package/dist/plugin/get-generated-type.d.mts +4 -4
  56. package/dist/plugin/index.mjs +13 -13
  57. package/dist/plugin/index.mjs.map +1 -1
  58. package/dist/plugin/types.d.mts +2 -2
  59. package/dist/plugin/with-context.d.mts +1 -1
  60. package/dist/{register-ts-hook-CTth1eqj.mjs → register-ts-hook-Vqjza10T.mjs} +2516 -857
  61. package/dist/register-ts-hook-Vqjza10T.mjs.map +1 -0
  62. package/dist/{repl-editor-BCozyiNq.mjs → repl-editor-F9LotMNx.mjs} +3 -2
  63. package/dist/{repl-editor-BCozyiNq.mjs.map → repl-editor-F9LotMNx.mjs.map} +1 -1
  64. package/dist/runtime/file.d.mts +14 -14
  65. package/dist/{schema--xYWRGfe.mjs → schema-D4TC4BC3.mjs} +4 -3
  66. package/dist/schema-D4TC4BC3.mjs.map +1 -0
  67. package/dist/seed/index.d.mts +4 -4
  68. package/dist/seed/index.mjs +3 -3
  69. package/dist/seed/index.mjs.map +1 -1
  70. package/dist/{seed-xqM9WIHP.mjs → seed-Cibjmtry.mjs} +46 -40
  71. package/dist/seed-Cibjmtry.mjs.map +1 -0
  72. package/dist/{service-goqlJJgA.mjs → service-2grcAOCJ.mjs} +61 -27
  73. package/dist/service-2grcAOCJ.mjs.map +1 -0
  74. package/dist/service-CaBPNDIZ.mjs +3 -0
  75. package/dist/{service-CCwl3Avt.mjs → service-LTfp03ZZ.mjs} +7 -5
  76. package/dist/{service-CCwl3Avt.mjs.map → service-LTfp03ZZ.mjs.map} +1 -1
  77. package/dist/types/aigateway.generated.d.mts +2 -2
  78. package/dist/types/auth.generated.d.mts +3 -3
  79. package/dist/types/executor.generated.d.mts +1 -1
  80. package/dist/types/tailordb.generated.d.mts +12 -12
  81. package/dist/utils/test/index.d.mts +4 -4
  82. package/dist/utils/test/index.mjs +4 -4
  83. package/dist/utils/test/index.mjs.map +1 -1
  84. package/dist/vitest/index.mjs +95 -7
  85. package/dist/vitest/index.mjs.map +1 -1
  86. package/dist/vitest/mocks/workflow.d.mts +13 -1
  87. package/dist/wait-point-invoker-__oE88_P.mjs +148 -0
  88. package/dist/wait-point-invoker-__oE88_P.mjs.map +1 -0
  89. package/dist/wait-point-registry-TL99zotw.mjs +47 -0
  90. package/dist/wait-point-registry-TL99zotw.mjs.map +1 -0
  91. package/docs/cli/application.md +3 -1
  92. package/docs/cli/function.md +17 -13
  93. package/docs/cli/setup.md +14 -1
  94. package/docs/cli/tailordb.md +30 -27
  95. package/docs/cli/workspace.md +2 -2
  96. package/docs/cli-reference.md +23 -22
  97. package/docs/configuration.md +2 -2
  98. package/docs/github-actions.md +73 -28
  99. package/docs/migration/v2.md +58 -4
  100. package/docs/migration/v3.md +41 -0
  101. package/docs/quickstart.md +1 -1
  102. package/docs/services/aigateway.md +33 -9
  103. package/docs/services/executor.md +5 -1
  104. package/docs/services/tailordb-migration.md +146 -44
  105. package/docs/services/tailordb.md +7 -7
  106. package/docs/services/workflow.md +52 -2
  107. package/docs/testing.md +13 -1
  108. package/package.json +8 -8
  109. package/dist/application-BpLeawBg.mjs.map +0 -1
  110. package/dist/application-BxLLiLsr.mjs +0 -3
  111. package/dist/register-ts-hook-CTth1eqj.mjs.map +0 -1
  112. package/dist/schema--xYWRGfe.mjs.map +0 -1
  113. package/dist/seed-xqM9WIHP.mjs.map +0 -1
  114. package/dist/service-_XmjSEGr.mjs +0 -3
  115. package/dist/service-goqlJJgA.mjs.map +0 -1
  116. package/dist/test-env-key-D7UkZp99.mjs +0 -75
  117. package/dist/test-env-key-D7UkZp99.mjs.map +0 -1
@@ -1,5 +1,6 @@
1
- import { AIGatewayInput } from "../../../types/aigateway.generated.mjs";
2
- import { AIGatewayConfig, AIGatewayDefinitionBrand } from "./types.mjs";
1
+ import { AuthNamespaceName } from "../../types/auth-namespace-name.mjs";
2
+ import { AIGatewayConfig, AIGatewayDefinitionBrand, AIGatewayServiceInput } from "./types.mjs";
3
+ import "../../index.mjs";
3
4
  //#region src/configure/services/aigateway/index.d.ts
4
5
  /**
5
6
  * Define an AI Gateway configuration for the Tailor SDK.
@@ -7,10 +8,10 @@ import { AIGatewayConfig, AIGatewayDefinitionBrand } from "./types.mjs";
7
8
  * @param config - AI Gateway configuration
8
9
  * @returns Defined AI Gateway
9
10
  */
10
- declare function defineAIGateway(name: string, config: Omit<AIGatewayInput, "name">): {
11
+ declare function defineAIGateway(name: string, config: Omit<AIGatewayServiceInput, "name">): {
11
12
  readonly name: string;
12
13
  readonly cors?: string[] | undefined;
13
- readonly authNamespace: string;
14
+ readonly authNamespace?: AuthNamespaceName;
14
15
  } & AIGatewayDefinitionBrand;
15
16
  //#endregion
16
17
  export { type AIGatewayConfig, defineAIGateway };
@@ -1,10 +1,15 @@
1
+ import { AuthNamespaceName } from "../../types/auth-namespace-name.mjs";
1
2
  import { AIGatewayInput } from "../../../types/aigateway.generated.mjs";
2
3
  //#region src/configure/services/aigateway/types.d.ts
3
4
  declare const aiGatewayDefinitionBrand: unique symbol;
4
5
  type AIGatewayDefinitionBrand = {
5
6
  readonly [aiGatewayDefinitionBrand]: true;
6
7
  };
8
+ /** AI Gateway configuration accepted by `defineAIGateway()`. */
9
+ type AIGatewayServiceInput = Omit<AIGatewayInput, "authNamespace"> & {
10
+ authNamespace?: AuthNamespaceName;
11
+ };
7
12
  /** Type accepted by `AppConfig.aiGateways`. Only values returned by `defineAIGateway()` satisfy this. */
8
13
  type AIGatewayConfig = AIGatewayInput & AIGatewayDefinitionBrand;
9
14
  //#endregion
10
- export { AIGatewayConfig, AIGatewayDefinitionBrand };
15
+ export { AIGatewayConfig, AIGatewayDefinitionBrand, AIGatewayServiceInput };
@@ -49,10 +49,10 @@ type AttributeListToTuple<User extends TailorDBInstance, AttributeList extends r
49
49
  type SelectedAttributeKeys<User extends TailorDBInstance, Attributes extends UserAttributes<User>> = Extract<{ [K in keyof Attributes]-?: undefined extends Attributes[K] ? never : K; }[keyof Attributes], UserAttributeKey<User>>;
50
50
  type UserProfile<User extends TailorDBInstance, Attributes extends UserAttributes<User>, AttributeList extends UserAttributeListKey<User>[]> = {
51
51
  /**
52
- * TailorDB namespace where the user type is defined.
52
+ * TailorDB namespace where the user table is defined.
53
53
  *
54
54
  * Usually auto-resolved, so you don't need to specify this.
55
- * Required only when multiple TailorDBs exist and the type is in an external TailorDB.
55
+ * Required only when multiple TailorDBs exist and the table is in an external TailorDB.
56
56
  */
57
57
  namespace?: string;
58
58
  type: User;
@@ -30,7 +30,7 @@ import { Trigger } from "./executor/trigger/index.mjs";
30
30
  import { createExecutor } from "./executor/executor.mjs";
31
31
  import "./executor/index.mjs";
32
32
  import { defineWorkflowExecutionPolicies, defineWorkflowExecutionPolicy } from "./workflow/execution-policy.mjs";
33
- import { WaitPointInstance, createWaitPoint, createWaitPoints } from "./workflow/wait-point.mjs";
33
+ import { ParameterizedWaitPointInstance, WaitPointInstance, createWaitPoint, createWaitPoints } from "./workflow/wait-point.mjs";
34
34
  import "./workflow/index.mjs";
35
35
  import { defineStaticWebSite } from "./staticwebsite/index.mjs";
36
36
  import { defineAIGateway } from "./aigateway/index.mjs";
@@ -38,4 +38,4 @@ import { defineIdp } from "./idp/index.mjs";
38
38
  import { defineSecretManager } from "./secrets/index.mjs";
39
39
  import { HttpAdapter, HttpAdapterGraphQLQuery, HttpAdapterGraphQLRequest, HttpAdapterGraphQLResponse, HttpAdapterInput, HttpAdapterInputFn, HttpAdapterOutputFn, HttpAdapterRequest, HttpAdapterResponse, HttpAdapterTypedDocumentNode, createHttpAdapter } from "./http-adapter/http-adapter.mjs";
40
40
  import "./http-adapter/index.mjs";
41
- export { type AIGatewayConfig, AuthAccessTokenArgs, AuthAccessTokenIssuedArgs, AuthAccessTokenRefreshedArgs, AuthAccessTokenRevokedArgs, AuthAccessTokenTrigger, type AuthConfig, type AuthConnectionConfig, type AuthConnectionOAuth2Config, type AuthConnectionTokenResult, type AuthExternalConfig, type AuthOwnConfig, type AuthServiceInput, type BeforeLoginClaims, type BeforeLoginHookArgs, type BuiltinIdP, type ConcurrencyPolicy, type DefinedAuth, type ExecutionPolicyConcurrency, type ExecutionPolicyDefInput, type ExecutionPolicyExactInstance, type ExecutionPolicyGroupOptions, type ExecutionPolicyInstance, type ExecutionPolicyWildcardInstance, type ExecutorServiceConfig, type ExecutorServiceInput, type FederatedIdentity, type FederatedIdentityClaims, type FederatedIdentityProvider, FunctionOperation, GqlOperation, HttpAdapter, HttpAdapterGraphQLQuery, HttpAdapterGraphQLRequest, HttpAdapterGraphQLResponse, HttpAdapterInput, HttpAdapterInputFn, HttpAdapterOutputFn, HttpAdapterRequest, HttpAdapterResponse, HttpAdapterTypedDocumentNode, type IDToken, type IdPConfig, type IdPEmailConfig, type IdPExternalConfig, type IdPGqlOperations, type IdPGqlOperationsInput as IdPGqlOperationsConfig, type IdPPermission, type IdPPermissionCondition, type IdProvider as IdProviderConfig, IdpUserArgs, IdpUserCreatedArgs, IdpUserDeletedArgs, IdpUserTrigger, IdpUserUpdatedArgs, IncomingWebhookArgs, IncomingWebhookRequest, IncomingWebhookResponse, IncomingWebhookResponseConfig, IncomingWebhookTrigger, IncomingWebhookTriggerOptions, type IsAutoFilledDBField, type IsReadOnlyDBField, type OAuth2ClientInput as OAuth2Client, type OAuth2ClientGrantType, type OIDC, Operation, type PermissionCondition, type QueryType, RecordCreatedArgs, RecordDeletedArgs, RecordUpdatedArgs, type ResolvedExecutionPolicyInstance, type Resolver, ResolverExecutedArgs, ResolverExecutedTrigger, type ResolverExternalConfig, type ResolverPermission, type ResolverPermissionCondition, type ResolverPermissionPolicy, type ResolverServiceConfig, type ResolverServiceInput, type RetryPolicy, type SAML, type SCIMAttribute, type SCIMAttributeMapping, type SCIMAttributeType, type SCIMAuthorization, type SCIMConfig, type SCIMResource, ScheduleArgs, ScheduleTrigger, type SecretsConfig, type StaticWebsiteConfig, type TailorAnyDBField, type TailorAnyDBType, type TailorDBField, type TailorDBInstance, TailorDBTrigger, type TailorDBType, type TailorTypeGqlPermission, type TailorTypePermission, type TenantProvider as TenantProviderConfig, Trigger, type UserAttributeKey, type UserAttributeListKey, type UserAttributes, type UsernameFieldKey, type ValueOperand, WaitPointInstance, WebhookOperation, Workflow, WorkflowConfig, WorkflowExecutionArgs, WorkflowExecutionCompletedArgs, WorkflowExecutionResumedArgs, WorkflowExecutionRetriedArgs, WorkflowExecutionStartedArgs, WorkflowExecutionTrigger, WorkflowExecutionWaitResolvedArgs, WorkflowExecutionWaitStartedArgs, WorkflowJob, WorkflowJobContext, WorkflowJobExecutionArgs, WorkflowJobExecutionCompletedArgs, WorkflowJobExecutionStartedArgs, WorkflowJobExecutionTrigger, WorkflowJobExecutionWaitResolvedArgs, WorkflowJobExecutionWaitStartedArgs, WorkflowOperation, type WorkflowServiceConfig, type WorkflowServiceInput, authAccessTokenIssuedTrigger, authAccessTokenRefreshedTrigger, authAccessTokenRevokedTrigger, authAccessTokenTrigger, createExecutor, createHttpAdapter, createResolver, createWaitPoint, createWaitPoints, createWorkflow, createWorkflowJob, db, defineAIGateway, defineAuth, defineIdp, defineSecretManager, defineStaticWebSite, defineWorkflowExecutionPolicies, defineWorkflowExecutionPolicy, idpUserCreatedTrigger, idpUserDeletedTrigger, idpUserTrigger, idpUserUpdatedTrigger, incomingWebhookTrigger, recordCreatedTrigger, recordDeletedTrigger, recordTrigger, recordUpdatedTrigger, resolverExecutedTrigger, scheduleTrigger, unsafeAllowAllGqlPermission, unsafeAllowAllIdPPermission, unsafeAllowAllTypePermission, workflowExecutionCompletedTrigger, workflowExecutionResumedTrigger, workflowExecutionRetriedTrigger, workflowExecutionStartedTrigger, workflowExecutionTrigger, workflowExecutionWaitResolvedTrigger, workflowExecutionWaitStartedTrigger, workflowJobExecutionCompletedTrigger, workflowJobExecutionStartedTrigger, workflowJobExecutionTrigger, workflowJobExecutionWaitResolvedTrigger, workflowJobExecutionWaitStartedTrigger };
41
+ export { type AIGatewayConfig, AuthAccessTokenArgs, AuthAccessTokenIssuedArgs, AuthAccessTokenRefreshedArgs, AuthAccessTokenRevokedArgs, AuthAccessTokenTrigger, type AuthConfig, type AuthConnectionConfig, type AuthConnectionOAuth2Config, type AuthConnectionTokenResult, type AuthExternalConfig, type AuthOwnConfig, type AuthServiceInput, type BeforeLoginClaims, type BeforeLoginHookArgs, type BuiltinIdP, type ConcurrencyPolicy, type DefinedAuth, type ExecutionPolicyConcurrency, type ExecutionPolicyDefInput, type ExecutionPolicyExactInstance, type ExecutionPolicyGroupOptions, type ExecutionPolicyInstance, type ExecutionPolicyWildcardInstance, type ExecutorServiceConfig, type ExecutorServiceInput, type FederatedIdentity, type FederatedIdentityClaims, type FederatedIdentityProvider, FunctionOperation, GqlOperation, HttpAdapter, HttpAdapterGraphQLQuery, HttpAdapterGraphQLRequest, HttpAdapterGraphQLResponse, HttpAdapterInput, HttpAdapterInputFn, HttpAdapterOutputFn, HttpAdapterRequest, HttpAdapterResponse, HttpAdapterTypedDocumentNode, type IDToken, type IdPConfig, type IdPEmailConfig, type IdPExternalConfig, type IdPGqlOperations, type IdPGqlOperationsInput as IdPGqlOperationsConfig, type IdPPermission, type IdPPermissionCondition, type IdProvider as IdProviderConfig, IdpUserArgs, IdpUserCreatedArgs, IdpUserDeletedArgs, IdpUserTrigger, IdpUserUpdatedArgs, IncomingWebhookArgs, IncomingWebhookRequest, IncomingWebhookResponse, IncomingWebhookResponseConfig, IncomingWebhookTrigger, IncomingWebhookTriggerOptions, type IsAutoFilledDBField, type IsReadOnlyDBField, type OAuth2ClientInput as OAuth2Client, type OAuth2ClientGrantType, type OIDC, Operation, ParameterizedWaitPointInstance, type PermissionCondition, type QueryType, RecordCreatedArgs, RecordDeletedArgs, RecordUpdatedArgs, type ResolvedExecutionPolicyInstance, type Resolver, ResolverExecutedArgs, ResolverExecutedTrigger, type ResolverExternalConfig, type ResolverPermission, type ResolverPermissionCondition, type ResolverPermissionPolicy, type ResolverServiceConfig, type ResolverServiceInput, type RetryPolicy, type SAML, type SCIMAttribute, type SCIMAttributeMapping, type SCIMAttributeType, type SCIMAuthorization, type SCIMConfig, type SCIMResource, ScheduleArgs, ScheduleTrigger, type SecretsConfig, type StaticWebsiteConfig, type TailorAnyDBField, type TailorAnyDBType, type TailorDBField, type TailorDBInstance, TailorDBTrigger, type TailorDBType, type TailorTypeGqlPermission, type TailorTypePermission, type TenantProvider as TenantProviderConfig, Trigger, type UserAttributeKey, type UserAttributeListKey, type UserAttributes, type UsernameFieldKey, type ValueOperand, WaitPointInstance, WebhookOperation, Workflow, WorkflowConfig, WorkflowExecutionArgs, WorkflowExecutionCompletedArgs, WorkflowExecutionResumedArgs, WorkflowExecutionRetriedArgs, WorkflowExecutionStartedArgs, WorkflowExecutionTrigger, WorkflowExecutionWaitResolvedArgs, WorkflowExecutionWaitStartedArgs, WorkflowJob, WorkflowJobContext, WorkflowJobExecutionArgs, WorkflowJobExecutionCompletedArgs, WorkflowJobExecutionStartedArgs, WorkflowJobExecutionTrigger, WorkflowJobExecutionWaitResolvedArgs, WorkflowJobExecutionWaitStartedArgs, WorkflowOperation, type WorkflowServiceConfig, type WorkflowServiceInput, authAccessTokenIssuedTrigger, authAccessTokenRefreshedTrigger, authAccessTokenRevokedTrigger, authAccessTokenTrigger, createExecutor, createHttpAdapter, createResolver, createWaitPoint, createWaitPoints, createWorkflow, createWorkflowJob, db, defineAIGateway, defineAuth, defineIdp, defineSecretManager, defineStaticWebSite, defineWorkflowExecutionPolicies, defineWorkflowExecutionPolicy, idpUserCreatedTrigger, idpUserDeletedTrigger, idpUserTrigger, idpUserUpdatedTrigger, incomingWebhookTrigger, recordCreatedTrigger, recordDeletedTrigger, recordTrigger, recordUpdatedTrigger, resolverExecutedTrigger, scheduleTrigger, unsafeAllowAllGqlPermission, unsafeAllowAllIdPPermission, unsafeAllowAllTypePermission, workflowExecutionCompletedTrigger, workflowExecutionResumedTrigger, workflowExecutionRetriedTrigger, workflowExecutionStartedTrigger, workflowExecutionTrigger, workflowExecutionWaitResolvedTrigger, workflowExecutionWaitStartedTrigger, workflowJobExecutionCompletedTrigger, workflowJobExecutionStartedTrigger, workflowJobExecutionTrigger, workflowJobExecutionWaitResolvedTrigger, workflowJobExecutionWaitStartedTrigger };
@@ -2,7 +2,7 @@ import { InferredAttributes } from "../../../runtime/types.mjs";
2
2
  import { UserBooleanArrayOperand, UserBooleanOperand, UserStringArrayOperand, UserStringOperand } from "../../types/permission-operand.types.mjs";
3
3
  //#region src/configure/services/tailordb/permission.d.ts
4
4
  /**
5
- * Record-level permission configuration for a TailorDB type.
5
+ * Record-level permission configuration for a TailorDB table.
6
6
  * Defines create, read, update, and delete permissions.
7
7
  *
8
8
  * Prefer object format with explicit `conditions` and `permit` for readability.
@@ -209,7 +209,7 @@ interface TailorDBField<Defined extends DefinedDBFieldMetadata = DefinedDBFieldM
209
209
  */
210
210
  description: DBFieldDescriptionMethod<Defined, Output, Nested>;
211
211
  /**
212
- * Define a relation to another type.
212
+ * Define a relation to another table.
213
213
  */
214
214
  relation: DBFieldRelationMethod<Defined, Output, Nested>;
215
215
  /**
@@ -185,17 +185,20 @@ type ExcludeDefaultedDBFields<T extends Record<string, TailorAnyDBField>> = { [K
185
185
  default: true;
186
186
  }, any> ? never : T[K]; };
187
187
  interface TypeFeatures {
188
+ /** Custom plural form of the table name for GraphQL */
188
189
  pluralForm?: string;
190
+ /** Enable aggregation queries for this table */
189
191
  aggregation?: true;
192
+ /** Enable bulk upsert mutation for this table */
190
193
  bulkUpsert?: true;
191
- /** Configure GraphQL operations for this type. Use "query" for read-only mode, or an object for granular control. */
194
+ /** Configure GraphQL operations for this table. Use "query" for read-only mode, or an object for granular control. */
192
195
  gqlOperations?: GqlOperationsConfig;
193
196
  /**
194
- * Enable publishing events for this type.
197
+ * Enable publishing events for this table.
195
198
  * When enabled, record creation/update/deletion events are published.
196
- * If not specified, this is automatically set to true when an executor uses this type
199
+ * If not specified, this is automatically set to true when an executor uses this table
197
200
  * with recordCreated/recordUpdated/recordDeleted triggers. If explicitly set to false
198
- * while an executor uses this type, an error will be thrown during apply.
201
+ * while an executor uses this table, an error will be thrown during apply.
199
202
  */
200
203
  publishEvents?: boolean;
201
204
  }
@@ -4,6 +4,6 @@ import { ConcurrencyPolicy, RetryPolicy } from "../../../types/workflow.generate
4
4
  import { WorkflowJob, WorkflowJobContext, createWorkflowJob } from "./job.mjs";
5
5
  import { Workflow, WorkflowConfig, createWorkflow } from "./workflow.mjs";
6
6
  import { defineWorkflowExecutionPolicies, defineWorkflowExecutionPolicy } from "./execution-policy.mjs";
7
- import { WaitPointInstance, createWaitPoint, createWaitPoints } from "./wait-point.mjs";
7
+ import { ParameterizedWaitPointInstance, WaitPointInstance, createWaitPoint, createWaitPoints } from "./wait-point.mjs";
8
8
  import "./types.mjs";
9
- export { type ConcurrencyPolicy, type ExecutionPolicyConcurrency, type ExecutionPolicyDefInput, type ExecutionPolicyExactInstance, type ExecutionPolicyGroupOptions, type ExecutionPolicyInstance, type ExecutionPolicyWildcardInstance, type ResolvedExecutionPolicyInstance, type RetryPolicy, WaitPointInstance, Workflow, WorkflowConfig, WorkflowJob, WorkflowJobContext, type WorkflowServiceConfig, type WorkflowServiceInput, createWaitPoint, createWaitPoints, createWorkflow, createWorkflowJob, defineWorkflowExecutionPolicies, defineWorkflowExecutionPolicy };
9
+ export { type ConcurrencyPolicy, type ExecutionPolicyConcurrency, type ExecutionPolicyDefInput, type ExecutionPolicyExactInstance, type ExecutionPolicyGroupOptions, type ExecutionPolicyInstance, type ExecutionPolicyWildcardInstance, ParameterizedWaitPointInstance, type ResolvedExecutionPolicyInstance, type RetryPolicy, WaitPointInstance, Workflow, WorkflowConfig, WorkflowJob, WorkflowJobContext, type WorkflowServiceConfig, type WorkflowServiceInput, createWaitPoint, createWaitPoints, createWorkflow, createWorkflowJob, defineWorkflowExecutionPolicies, defineWorkflowExecutionPolicy };
@@ -1,4 +1,4 @@
1
- import { JsonCompatible, TypeLevelError } from "../../../types/helpers.mjs";
1
+ import { JsonCompatible, Prettify, TypeLevelError } from "../../../types/helpers.mjs";
2
2
  //#region src/configure/services/workflow/wait-point.d.ts
3
3
  /**
4
4
  * A single wait point instance with typed `.wait()` and `.resolve()` methods.
@@ -14,24 +14,79 @@ interface WaitPointInstance<Payload = undefined, Result = undefined> {
14
14
  resolve: (executionId: string, callback: (payload: [Payload] extends [undefined] ? undefined : Payload) => Result | Promise<Result>) => Promise<void>;
15
15
  }
16
16
  /**
17
- * The type produced by `define<Payload, Result>()` / `createWaitPoint<Payload, Result>(key)`.
18
- * Resolves to `WaitPointInstance<Payload, Result>` when both types are JsonValue-compatible,
17
+ * A wait point whose key carries `$params`, so the runtime key is built per call.
18
+ *
19
+ * `.with(params)` substitutes the params into the declared key and returns the
20
+ * same two-method surface as an unparameterized wait point.
21
+ */
22
+ interface ParameterizedWaitPointInstance<Params extends object, Payload = undefined, Result = undefined> {
23
+ /**
24
+ * Bind runtime values to the key's `$params`.
25
+ * @param params - One value per `$param` in the declared key
26
+ * @returns A wait point bound to the resulting key
27
+ * @throws If a param value is empty, contains characters outside `[a-z0-9-]`,
28
+ * starts or ends with `-`, or makes the resulting key exceed 63 characters
29
+ */
30
+ with(params: Params): WaitPointInstance<Payload, Result>;
31
+ }
32
+ type NonEmptyString = `${string & {}}${string}`;
33
+ type KeySegments<Key extends string> = Key extends `${infer Head}-${infer Tail}` ? Head | KeySegments<Tail> : Key;
34
+ type KeySegmentList<Key extends string> = Key extends `${infer Head}-${infer Tail}` ? [Head, ...KeySegmentList<Tail>] : [Key];
35
+ type ParamSegments<Key extends string> = Extract<KeySegments<Key>, `$${NonEmptyString}`>;
36
+ type ParamName<Segment extends string> = Segment extends `$${infer Name}` ? Name : never;
37
+ type KeyParams<Key extends string> = [ParamSegments<Key>] extends [never] ? undefined : Prettify<{ [Name in ParamName<ParamSegments<Key>>]: string; }>;
38
+ type HasLiteralSegment<Segments extends readonly string[]> = Segments extends readonly [infer Head extends string, ...infer Tail extends readonly string[]] ? Head extends `$${string}` ? HasLiteralSegment<Tail> : true : false;
39
+ type HasDuplicateParam<Segments extends readonly string[]> = Segments extends readonly [infer Head extends string, ...infer Tail extends readonly string[]] ? Head extends `$${string}` ? Head extends Tail[number] ? true : HasDuplicateParam<Tail> : HasDuplicateParam<Tail> : false;
40
+ /**
41
+ * Resolves to `Instance` when both `Payload` and `Result` are JsonValue-compatible,
19
42
  * or to a type-level error that surfaces at the call site.
20
43
  */
21
- type WaitPointDef<Payload, Result> = [null] extends [Payload] ? TypeLevelError<"Payload cannot be null at the top level"> : [undefined] extends [Result] ? TypeLevelError<"Result cannot be (or include) undefined (resolve callback must return a value)"> : [Payload] extends [undefined] ? [Result] extends [JsonCompatible<Result>] ? WaitPointInstance<Payload, Result> : TypeLevelError<"Result must be JsonValue-compatible (plain objects/arrays; no class instances or functions)"> : [undefined] extends [Payload] ? TypeLevelError<"Payload cannot include undefined at the top level"> : [Payload] extends [JsonCompatible<Payload>] ? [Result] extends [JsonCompatible<Result>] ? WaitPointInstance<Payload, Result> : TypeLevelError<"Result must be JsonValue-compatible (plain objects/arrays; no class instances or functions)"> : TypeLevelError<"Payload must be JsonValue-compatible (plain objects/arrays; no class instances or functions)">;
44
+ type ValidatedWaitPoint<Payload, Result, Instance> = [null] extends [Payload] ? TypeLevelError<"Payload cannot be null at the top level"> : [undefined] extends [Result] ? TypeLevelError<"Result cannot be (or include) undefined (resolve callback must return a value)"> : [Payload] extends [undefined] ? [Result] extends [JsonCompatible<Result>] ? Instance : TypeLevelError<"Result must be JsonValue-compatible (plain objects/arrays; no class instances or functions)"> : [undefined] extends [Payload] ? TypeLevelError<"Payload cannot include undefined at the top level"> : [Payload] extends [JsonCompatible<Payload>] ? [Result] extends [JsonCompatible<Result>] ? Instance : TypeLevelError<"Result must be JsonValue-compatible (plain objects/arrays; no class instances or functions)"> : TypeLevelError<"Payload must be JsonValue-compatible (plain objects/arrays; no class instances or functions)">;
45
+ /**
46
+ * The type produced by `define<Payload, Result>()` (the no-key form inside `createWaitPoints`).
47
+ */
48
+ type WaitPointDef<Payload, Result> = ValidatedWaitPoint<Payload, Result, WaitPointInstance<Payload, Result>>;
49
+ /**
50
+ * The type produced by `define(key)<Payload, Result>()`. Keys containing
51
+ * `$params` resolve to a {@link ParameterizedWaitPointInstance}; plain keys
52
+ * resolve to a {@link WaitPointInstance}, so the same call shape covers both.
53
+ */
54
+ type WaitPointKeyDef<Key extends string, Payload, Result> = string extends Key ? TypeLevelError<"Wait point key must be a string literal"> : HasDuplicateParam<KeySegmentList<Key>> extends true ? TypeLevelError<"Wait point key repeats a $param name"> : HasLiteralSegment<KeySegmentList<Key>> extends false ? TypeLevelError<"Wait point key needs at least one literal segment alongside its $params"> : [KeyParams<Key>] extends [undefined] ? ValidatedWaitPoint<Payload, Result, WaitPointInstance<Payload, Result>> : KeyParams<Key> extends (infer Params extends object) ? ValidatedWaitPoint<Payload, Result, ParameterizedWaitPointInstance<Params, Payload, Result>> : never;
55
+ /**
56
+ * The factory returned when a key is passed before the type arguments.
57
+ * Calling it yields the wait point the key describes.
58
+ */
59
+ type WaitPointFactory<Key extends string> = <Payload = undefined, Result = undefined>() => WaitPointKeyDef<Key, Payload, Result>;
22
60
  /**
23
61
  * The `define` function passed to the `createWaitPoints` builder callback.
24
- * Returns an actual WaitPointInstance (not a phantom marker) so that the
25
- * builder's return type can flow through as-is, preserving JSDoc comments
26
- * on each property for IDE autocompletion.
62
+ *
63
+ * Called with no arguments, the property name becomes the key. Called with a
64
+ * key, that key is used verbatim — and any `$params` in it become the argument
65
+ * of `.with()`. The key comes first so TypeScript can infer it as a literal;
66
+ * `Payload` / `Result` follow on the returned factory.
27
67
  *
28
68
  * JSON validation is encoded in the return type rather than in type-parameter
29
69
  * constraints, because tsgo rejects self-referential constraints like
30
70
  * `Payload extends JsonCompatible<Payload>` as circular.
31
71
  */
32
- type DefineFn = <Payload = undefined, Result = undefined>() => WaitPointDef<Payload, Result>;
72
+ type DefineFn = {
73
+ <Payload = undefined, Result = undefined>(): WaitPointDef<Payload, Result>;
74
+ /**
75
+ * Use a key of your own instead of the property name — the only way to give
76
+ * a key `$params`, since the key has to be read as a literal type and giving
77
+ * `Payload` / `Result` explicitly would stop that.
78
+ * @param key - The wait point key
79
+ * @returns A factory taking the type arguments
80
+ */
81
+ for<const Key extends string>(key: Key): WaitPointFactory<Key>;
82
+ };
33
83
  /**
34
- * Create a single typed wait point with an explicit key.
84
+ * Create a single typed wait point with a fixed key.
85
+ *
86
+ * The key must match `[a-z0-9-]` (3-63 characters, starting and ending with
87
+ * `[a-z0-9]`), which `deploy` reports on. For a key with `$params`, use
88
+ * {@link createWaitPoints}: binding params needs the key inferred as a literal
89
+ * type, which only its `define` offers.
35
90
  *
36
91
  * `Payload` and `Result` must be JsonValue-compatible.
37
92
  * Functions and objects with a `toJSON` method are rejected at the type level;
@@ -46,7 +101,9 @@ type DefineFn = <Payload = undefined, Result = undefined>() => WaitPointDef<Payl
46
101
  declare function createWaitPoint<Payload = undefined, Result = undefined>(key: string): WaitPointDef<Payload, Result>;
47
102
  /**
48
103
  * Create a group of typed wait points for human-in-the-loop workflows.
49
- * Property names become the wait point keys.
104
+ * Property names become the wait point keys, so they must match
105
+ * `[a-z0-9-]`, which `deploy` reports on — pass an explicit key to `define`
106
+ * when they do not.
50
107
  *
51
108
  * The return type is the same as the builder's return type, so JSDoc on each
52
109
  * property is preserved and visible in IDE autocompletion.
@@ -60,13 +117,15 @@ declare function createWaitPoint<Payload = undefined, Result = undefined>(key: s
60
117
  * export const waitPoints = createWaitPoints(define => ({
61
118
  * // Preceding JSDoc on this property is shown in IDE autocompletion
62
119
  * approval: define<{ message: string }, { approved: boolean }>(),
120
+ * // A key with $params is bound per call through `.with()`
121
+ * lineApproval: define.for("line-approval-$lineId")<{ message: string }, { approved: boolean }>(),
63
122
  * }));
64
123
  *
65
- * // IDE shows the JSDoc when typing `waitPoints.`
66
124
  * await waitPoints.approval.wait({ message: "Please approve" });
125
+ * await waitPoints.lineApproval.with({ lineId: line.id }).wait({ message: "Please approve" });
67
126
  *
68
127
  * // For 2-level access, use destructured export with JSDoc attached to the export itself.
69
128
  */
70
- declare function createWaitPoints<T extends Record<string, WaitPointInstance<any, any>>>(builder: (define: DefineFn) => T): T;
129
+ declare function createWaitPoints<T extends Record<string, WaitPointInstance<any, any> | ParameterizedWaitPointInstance<any, any, any>>>(builder: (define: DefineFn) => T): T;
71
130
  //#endregion
72
- export { WaitPointInstance, createWaitPoint, createWaitPoints };
131
+ export { ParameterizedWaitPointInstance, WaitPointInstance, createWaitPoint, createWaitPoints };
@@ -0,0 +1,18 @@
1
+ //#region src/configure/types/auth-namespace-name.d.ts
2
+ interface AuthNamespaceNameRegistry {}
3
+ /**
4
+ * Auth namespace name.
5
+ *
6
+ * When `tailor.d.ts` is generated (via `tailor deploy`/`generate`), this is narrowed
7
+ * to the application's own auth namespace name (from `defineAuth()`, local or
8
+ * external) — the common case, since an `AIGatewayConfig` usually authenticates
9
+ * against its own app's auth. When no auth namespace is registered yet, falls back
10
+ * to `string` to avoid blocking editing before the first generate run.
11
+ *
12
+ * To authenticate against an auth namespace owned by a different application in the
13
+ * workspace, extend the registry: `declare module "@tailor-platform/sdk" { interface
14
+ * AuthNamespaceNameRegistry { "other-app-auth": true } }`.
15
+ */
16
+ type AuthNamespaceName = keyof AuthNamespaceNameRegistry extends never ? string : keyof AuthNamespaceNameRegistry & string;
17
+ //#endregion
18
+ export { AuthNamespaceName, AuthNamespaceNameRegistry };
@@ -1,3 +1,3 @@
1
- import { n as reportCrash, t as initCrashReporting } from "./crashreport-CIIfLnoO.mjs";
1
+ import { n as reportCrash, t as initCrashReporting } from "./crashreport-Q0pDAlrj.mjs";
2
2
 
3
3
  export { reportCrash };
@@ -1,4 +1,4 @@
1
- import { n as logger } from "./logger-DSdExfor.mjs";
1
+ import { n as logger } from "./logger-D0bEznPv.mjs";
2
2
  import { t as readPackageJson } from "./package-json-8b0O9TlX.mjs";
3
3
  import { n as userAgentFromVersion } from "./user-agent-Bgsszb5I.mjs";
4
4
  import { r as writeSecretFile, t as ensureSecretDir } from "./secret-file-C3J4Gy8r.mjs";
@@ -106,7 +106,8 @@ function writeCrashReport(report, dir) {
106
106
  ensureSecretDir(dir);
107
107
  const filename = generateFilename(report);
108
108
  const filePath = path.join(dir, filename);
109
- writeSecretFile(filePath, formatCrashReport(report));
109
+ const content = formatCrashReport(report);
110
+ writeSecretFile(filePath, content);
110
111
  cleanupOldFiles(dir);
111
112
  return filePath;
112
113
  } catch {
@@ -396,7 +397,10 @@ async function reportCrash(error, errorType) {
396
397
  ` tailor crashreport send --file "${filePath}"`
397
398
  ].join("\n"));
398
399
  }
399
- if (config.remoteEnabled) await sendCrashReport(report, userAgentFromVersion(sdkVersion));
400
+ if (config.remoteEnabled) {
401
+ const ua = userAgentFromVersion(sdkVersion);
402
+ await sendCrashReport(report, ua);
403
+ }
400
404
  } catch {}
401
405
  }
402
406
  /**
@@ -420,4 +424,4 @@ function initCrashReporting() {
420
424
 
421
425
  //#endregion
422
426
  export { JSON_FOOTER_MARKER as a, CRASH_LOG_EXTENSION as i, reportCrash as n, parseCrashReportConfig as o, sendCrashReport as r, initCrashReporting as t };
423
- //# sourceMappingURL=crashreport-CIIfLnoO.mjs.map
427
+ //# sourceMappingURL=crashreport-Q0pDAlrj.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"crashreport-CIIfLnoO.mjs","names":[],"sources":["../src/cli/crashreport/config.ts","../src/cli/crashreport/writer.ts","../src/cli/crashreport/sender.ts","../src/cli/crashreport/sanitize.ts","../src/cli/crashreport/report.ts","../src/cli/crashreport/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { ensureSecretDir, writeSecretFile } from \"#/cli/shared/secret-file\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .toSorted()\n .toReversed();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n ensureSecretDir(dir);\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n writeSecretFile(filePath, content);\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { sanitizeArgv, sanitizeMessage, sanitizeStackTrace } from \"./sanitize\";\n\nexport type ErrorType = \"uncaughtException\" | \"unhandledRejection\" | \"handledError\";\n\nexport interface CrashReport {\n id: string;\n timestamp: string;\n sdkVersion: string;\n nodeVersion: string;\n osPlatform: string;\n osRelease: string;\n arch: string;\n command: string;\n argv: string[];\n errorName: string;\n errorMessage: string;\n stackTrace: string;\n errorType: ErrorType;\n userId: string | null;\n userEmail: string | null;\n}\n\ninterface BuildCrashReportOptions {\n error: unknown;\n sdkVersion: string;\n errorType: ErrorType;\n}\n\n// Maximum subcommand depth to keep (e.g., \"tailordb migrate generate\" = 3 tokens).\n// Positional arguments beyond this are potentially sensitive user input.\n// Accepted trade-off: plain-text positional args that don't match known patterns\n// (UUIDs, hex tokens, emails, paths) pass through to `command` and `argv`.\n// Full redaction would require embedding the CLI command tree here, which is fragile.\nconst MAX_COMMAND_TOKENS = 3;\n\n/**\n * Parse the command name from process.argv.\n * Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.\n * @returns Parsed command string\n */\nfunction parseCommand(): string {\n const args = process.argv.slice(2);\n const commandParts: string[] = [];\n for (const arg of args) {\n if (arg.startsWith(\"-\") || commandParts.length >= MAX_COMMAND_TOKENS) break;\n commandParts.push(arg);\n }\n return commandParts.join(\" \") || \"<unknown>\";\n}\n\n/**\n * Build a CrashReport data structure from an error and context.\n * All sensitive data is sanitized before inclusion.\n * @param options - Error, SDK version, and crash type\n * @returns Sanitized crash report\n */\nexport function buildCrashReport(options: BuildCrashReportOptions): CrashReport {\n const { error, sdkVersion, errorType } = options;\n\n const isError = error instanceof Error;\n const rawMessage = isError ? error.message : String(error);\n const rawStack = isError && error.stack ? error.stack : \"\";\n const errorName = isError ? error.name : \"UnknownError\";\n\n const currentUser = readCurrentUser();\n\n return {\n id: crypto.randomUUID(),\n timestamp: new Date().toISOString(),\n sdkVersion,\n nodeVersion: process.version,\n osPlatform: process.platform,\n osRelease: os.release(),\n arch: process.arch,\n command: sanitizeMessage(parseCommand()),\n argv: sanitizeArgv(process.argv),\n errorName,\n errorMessage: sanitizeMessage(rawMessage),\n stackTrace: sanitizeStackTrace(rawStack),\n errorType,\n userId: currentUser?.id ?? null,\n userEmail: currentUser?.email ?? null,\n };\n}\n\ntype CurrentUser = {\n id: string;\n email: string | null;\n};\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user ID and email, or null if unavailable\n */\nfunction readCurrentUser(): CurrentUser | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as {\n current_user?: string | null;\n users?: Record<string, { email?: unknown } | undefined>;\n };\n // parseYAML returns null for empty documents\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n const currentUser = raw?.current_user ?? null;\n if (!currentUser) return null;\n const email = raw.users?.[currentUser]?.email;\n return {\n id: currentUser,\n email: typeof email === \"string\" ? email : legacyEmail(currentUser),\n };\n } catch {\n return null;\n }\n}\n\nfunction legacyEmail(user: string): string | null {\n return user.includes(\"@\") ? user : null;\n}\n","import { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\nimport { userAgentFromVersion } from \"#/cli/shared/user-agent\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor crashreport send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n const ua = userAgentFromVersion(sdkVersion);\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;CAC1D,IAAI,MACF,OAAO;EACL,cAAc;EACd,eAAe;EACf,UAAU;CACZ;CAGF,MAAM,gBAAgB,QAAQ,IAAI,8BAA8B,KAAI,CAAE,YAAY,MAAM;CACxF,MAAM,iBAAiB,QAAQ,IAAI,+BAA+B,MAAK,CAAE,YAAY,MAAM;CAC3F,MAAM,WAAW,YAAY,KAAK,KAAK,WAAW,mBAAmB,eAAe,IAAI;CAExF,OAAO;EACL,cAAc,gBAAgB,aAAa;EAC3C;EACA;CACF;AACF;;;;AC9BA,MAAM,kBAAkB;;AAGxB,MAAa,qBAAqB;;AAGlC,MAAa,sBAAsB;;;;;;AAOnC,SAAgB,kBAAkB,QAA6B;CA2B7D,OAAO;EAzBL,iBAAiB,OAAO;EACxB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB;EACA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.mjs","names":[],"sources":["../src/cli/crashreport/config.ts","../src/cli/crashreport/writer.ts","../src/cli/crashreport/sender.ts","../src/cli/crashreport/sanitize.ts","../src/cli/crashreport/report.ts","../src/cli/crashreport/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport { ensureSecretDir, writeSecretFile } from \"#/cli/shared/secret-file\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .toSorted()\n .toReversed();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n ensureSecretDir(dir);\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n writeSecretFile(filePath, content);\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { sanitizeArgv, sanitizeMessage, sanitizeStackTrace } from \"./sanitize\";\n\nexport type ErrorType = \"uncaughtException\" | \"unhandledRejection\" | \"handledError\";\n\nexport interface CrashReport {\n id: string;\n timestamp: string;\n sdkVersion: string;\n nodeVersion: string;\n osPlatform: string;\n osRelease: string;\n arch: string;\n command: string;\n argv: string[];\n errorName: string;\n errorMessage: string;\n stackTrace: string;\n errorType: ErrorType;\n userId: string | null;\n userEmail: string | null;\n}\n\ninterface BuildCrashReportOptions {\n error: unknown;\n sdkVersion: string;\n errorType: ErrorType;\n}\n\n// Maximum subcommand depth to keep (e.g., \"tailordb migrate generate\" = 3 tokens).\n// Positional arguments beyond this are potentially sensitive user input.\n// Accepted trade-off: plain-text positional args that don't match known patterns\n// (UUIDs, hex tokens, emails, paths) pass through to `command` and `argv`.\n// Full redaction would require embedding the CLI command tree here, which is fragile.\nconst MAX_COMMAND_TOKENS = 3;\n\n/**\n * Parse the command name from process.argv.\n * Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.\n * @returns Parsed command string\n */\nfunction parseCommand(): string {\n const args = process.argv.slice(2);\n const commandParts: string[] = [];\n for (const arg of args) {\n if (arg.startsWith(\"-\") || commandParts.length >= MAX_COMMAND_TOKENS) break;\n commandParts.push(arg);\n }\n return commandParts.join(\" \") || \"<unknown>\";\n}\n\n/**\n * Build a CrashReport data structure from an error and context.\n * All sensitive data is sanitized before inclusion.\n * @param options - Error, SDK version, and crash type\n * @returns Sanitized crash report\n */\nexport function buildCrashReport(options: BuildCrashReportOptions): CrashReport {\n const { error, sdkVersion, errorType } = options;\n\n const isError = error instanceof Error;\n const rawMessage = isError ? error.message : String(error);\n const rawStack = isError && error.stack ? error.stack : \"\";\n const errorName = isError ? error.name : \"UnknownError\";\n\n const currentUser = readCurrentUser();\n\n return {\n id: crypto.randomUUID(),\n timestamp: new Date().toISOString(),\n sdkVersion,\n nodeVersion: process.version,\n osPlatform: process.platform,\n osRelease: os.release(),\n arch: process.arch,\n command: sanitizeMessage(parseCommand()),\n argv: sanitizeArgv(process.argv),\n errorName,\n errorMessage: sanitizeMessage(rawMessage),\n stackTrace: sanitizeStackTrace(rawStack),\n errorType,\n userId: currentUser?.id ?? null,\n userEmail: currentUser?.email ?? null,\n };\n}\n\ntype CurrentUser = {\n id: string;\n email: string | null;\n};\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user ID and email, or null if unavailable\n */\nfunction readCurrentUser(): CurrentUser | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as {\n current_user?: string | null;\n users?: Record<string, { email?: unknown } | undefined>;\n };\n // parseYAML returns null for empty documents\n // oxlint-disable-next-line typescript/no-unnecessary-condition\n const currentUser = raw?.current_user ?? null;\n if (!currentUser) return null;\n const email = raw.users?.[currentUser]?.email;\n return {\n id: currentUser,\n email: typeof email === \"string\" ? email : legacyEmail(currentUser),\n };\n } catch {\n return null;\n }\n}\n\nfunction legacyEmail(user: string): string | null {\n return user.includes(\"@\") ? user : null;\n}\n","import { logger } from \"#/cli/shared/logger\";\nimport { readPackageJson } from \"#/cli/shared/package-json\";\nimport { userAgentFromVersion } from \"#/cli/shared/user-agent\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor crashreport send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n const ua = userAgentFromVersion(sdkVersion);\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;CAC1D,IAAI,MACF,OAAO;EACL,cAAc;EACd,eAAe;EACf,UAAU;CACZ;CAGF,MAAM,gBAAgB,QAAQ,IAAI,8BAA8B,KAAI,CAAE,YAAY,MAAM;CACxF,MAAM,iBAAiB,QAAQ,IAAI,+BAA+B,MAAK,CAAE,YAAY,MAAM;CAC3F,MAAM,WAAW,YAAY,KAAK,KAAK,WAAW,mBAAmB,eAAe,IAAI;CAExF,OAAO;EACL,cAAc,gBAAgB,aAAa;EAC3C;EACA;CACF;AACF;;;;AC9BA,MAAM,kBAAkB;;AAGxB,MAAa,qBAAqB;;AAGlC,MAAa,sBAAsB;;;;;;AAOnC,SAAgB,kBAAkB,QAA6B;CA2B7D,OAAO;EAzBL,iBAAiB,OAAO;EACxB,cAAc,OAAO;EACrB,eAAe,OAAO;EACtB;EACA;EACA,gBAAgB,OAAO;EACvB,iBAAiB,OAAO;EACxB,OAAO,OAAO,WAAW,GAAG,OAAO;EACnC,SAAS,OAAO;EAChB;EACA;EACA,YAAY,OAAO;EACnB,cAAc,KAAK,UAAU,OAAO,IAAI;EACxC;EACA;EACA,SAAS,OAAO;EAChB,YAAY,OAAO;EACnB;EACA;EACA,OAAO,cAAc;EACrB;EACA;EACA,KAAK,UAAU,MAAM;EACrB;CAES,CAAC,CAAC,KAAK,IAAI;AACxB;;;;;;;AAQA,SAAS,iBAAiB,QAA6B;CAGrD,OAAO,GAFe,OAAO,UAAU,QAAQ,SAAS,GAElC,EAAE,GADR,OAAO,GAAG,MAAM,GAAG,CACF,IAAI;AACvC;;;;;AAMA,SAAS,gBAAgB,KAAmB;CAC1C,IAAI;EACF,MAAM,QAAQ,GACX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AO,cAAc;GACvB,MAAM,WAAW,iBAAiB,QAAQ,OAAO,QAAQ;GACzD,IAAI,UACF,OAAO,IACL;IACE;IACA;IACA,KAAK;IACL;IACA;IACA,qCAAqC,SAAS;GAChD,CAAC,CAAC,KAAK,IAAI,CACb;EAEJ;EAEA,IAAI,OAAO,eAAe;GACxB,MAAM,KAAK,qBAAqB,UAAU;GAC1C,MAAM,gBAAgB,QAAQ,EAAE;EAClC;CACF,QAAQ,CAER;AACF;;;;;;AAOA,SAAgB,qBAA2B;CACzC,MAAM,SAAS,uBAAuB;CACtC,IAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,eAAe;CAEnD,MAAM,eAAe,OAAgB,cAAyB;EAC5D,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EACrE,OAAO,MAAM,OAAO;EACpB,AAAK,YAAY,OAAO,SAAS,CAAC,CAAC,cAAc;GAC/C,QAAQ,KAAK,CAAC;EAChB,CAAC;CACH;CAEA,QAAQ,GAAG,sBAAsB,UAAU,YAAY,OAAO,mBAAmB,CAAC;CAClF,QAAQ,GAAG,uBAAuB,WAAW,YAAY,QAAQ,oBAAoB,CAAC;AACxF"}
@@ -1,4 +1,4 @@
1
- import { r as styles } from "./logger-DSdExfor.mjs";
1
+ import { r as styles } from "./logger-D0bEznPv.mjs";
2
2
 
3
3
  //#region src/cli/shared/errors.ts
4
4
  function shellQuote(value) {
@@ -69,7 +69,21 @@ function createCLIError(options) {
69
69
  function isCLIError(error) {
70
70
  return error instanceof Error && error.name === "CLIError";
71
71
  }
72
+ const MISSING_NAMED_EXPORT_PATTERN = /does not provide an export named '(?!default')([^']+)'/;
73
+ /**
74
+ * Suggest `import type` when importing user code fails on a missing named
75
+ * export. The CLI strips types from each file in isolation, so a type-only
76
+ * export does not exist at runtime and a plain import of it fails to link.
77
+ * @param error - Error thrown while importing user modules
78
+ * @returns Suggestion text, or undefined when the error is not that failure
79
+ */
80
+ function typeOnlyImportHint(error) {
81
+ if (!(error instanceof SyntaxError)) return void 0;
82
+ const name = MISSING_NAMED_EXPORT_PATTERN.exec(error.message)?.[1];
83
+ if (!name) return void 0;
84
+ return `If '${name}' is a type, import it with \`import type\` (or the inline \`type\` modifier). The CLI runs TypeScript by stripping types from each file in isolation, so type-only exports do not exist at runtime. Set "verbatimModuleSyntax": true in tsconfig.json to catch this at typecheck.`;
85
+ }
72
86
 
73
87
  //#endregion
74
- export { isCLIError as i, formatCopyableCommand as n, formatNextAction as r, createCLIError as t };
75
- //# sourceMappingURL=errors-CWj21238.mjs.map
88
+ export { typeOnlyImportHint as a, isCLIError as i, formatCopyableCommand as n, formatNextAction as r, createCLIError as t };
89
+ //# sourceMappingURL=errors-Bxut5_Sy.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors-CWj21238.mjs","names":[],"sources":["../src/cli/shared/errors.ts"],"sourcesContent":["import { styles } from \"./logger\";\n\n/**\n * Options for creating a CLI error\n */\nexport interface CLIErrorOptions {\n message: string;\n details?: string;\n suggestion?: string;\n command?: string;\n code?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, unknown>>;\n}\n\nexport interface CLIErrorNextAction {\n /** Executable name, such as `tailor`. */\n command: string;\n /** Arguments passed directly to the executable. */\n args: readonly string[];\n}\n\n/**\n * CLI error interface with formatted output\n */\nexport interface CLIError extends Error {\n readonly code?: string;\n readonly details?: string;\n readonly suggestion?: string;\n readonly command?: string;\n readonly next?: CLIErrorNextAction;\n readonly context?: Readonly<Record<string, unknown>>;\n format(): string;\n}\n\ntype CLIErrorInternal = Error & {\n code?: string;\n details?: string;\n suggestion?: string;\n command?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, unknown>>;\n format(): string;\n};\n\nfunction shellQuote(value: string): string {\n if (process.platform === \"win32\") {\n if (/^[A-Za-z0-9_./:=@+\\\\-]+$/.test(value)) return value;\n return `\"${value.replaceAll('\"', '\\\\\"')}\"`;\n }\n if (/^[A-Za-z0-9_./:=@+-]+$/.test(value)) return value;\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction needsArgvRendering(argv: readonly string[]): boolean {\n // cmd.exe/PowerShell expand %, $, and ! even inside double quotes, so no\n // quoting can keep such values literal on Windows.\n return process.platform === \"win32\" && argv.some((value) => /[%$!]/.test(value));\n}\n\n/**\n * Render an argv array as a copyable command line for the current platform's shell\n * @param {readonly string[]} argv - Executable name followed by its arguments\n * @returns {string} A shell-quoted command line, or an `argv [...]` JSON rendering when the platform shell cannot keep a value literal\n */\nexport function formatCopyableCommand(argv: readonly string[]): string {\n if (needsArgvRendering(argv)) {\n return `argv ${JSON.stringify(argv)}`;\n }\n return argv.map(shellQuote).join(\" \");\n}\n\n/**\n * Format an executable and argv as a shell-safe user-facing command.\n * @param next - Executable and arguments to format\n * @returns Shell command, or an argv representation when shell quoting is unsafe\n */\nexport function formatNextAction(next: CLIErrorNextAction): string {\n const argv = [next.command, ...next.args];\n const rendered = formatCopyableCommand(argv);\n return needsArgvRendering(argv) ? `with ${rendered}` : `\\`${rendered}\\``;\n}\n\n/**\n * Format CLI error for output\n * @param error - CLIError instance to format\n * @returns Formatted error message\n */\nfunction formatError(error: CLIError): string {\n const parts: string[] = [\n styles.error(`Error${error.code ? ` [${error.code}]` : \"\"}: ${error.message}`),\n ];\n\n if (error.details) {\n parts.push(`\\n ${styles.dim(\"Details:\")} ${error.details}`);\n }\n\n if (error.suggestion) {\n parts.push(`\\n ${styles.info(\"Suggestion:\")} ${error.suggestion}`);\n }\n\n if (error.command) {\n parts.push(\n `\\n ${styles.dim(\"Help:\")} Run \\`tailor ${error.command} --help\\` for usage information.`,\n );\n }\n\n if (error.next) {\n parts.push(`\\n ${styles.info(\"Next:\")} Run ${formatNextAction(error.next)}.`);\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Create a CLI error with formatted output\n * @param options - Options to construct a CLIError\n * @returns Constructed CLIError instance\n */\nfunction createCLIError(options: CLIErrorOptions): CLIError {\n const error = new Error(options.message) as CLIErrorInternal;\n error.name = \"CLIError\";\n error.code = options.code;\n error.details = options.details;\n error.suggestion = options.suggestion;\n error.command = options.command;\n error.next = options.next;\n error.context = options.context;\n error.format = () => formatError(error);\n return error;\n}\n\n/**\n * Type guard to check if an error is a CLIError\n * @param error - Error to check\n * @returns True if the error is a CLIError\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\n// Re-export createCLIError as CLIError for backward compatibility\nexport { createCLIError as CLIError };\n"],"mappings":";;;AA6CA,SAAS,WAAW,OAAuB;CACzC,IAAI,QAAQ,aAAa,SAAS;EAChC,IAAI,2BAA2B,KAAK,KAAK,GAAG,OAAO;EACnD,OAAO,IAAI,MAAM,WAAW,MAAK,MAAK,EAAE;CAC1C;CACA,IAAI,yBAAyB,KAAK,KAAK,GAAG,OAAO;CACjD,OAAO,IAAI,MAAM,WAAW,KAAK,OAAO,EAAE;AAC5C;AAEA,SAAS,mBAAmB,MAAkC;CAG5D,OAAO,QAAQ,aAAa,WAAW,KAAK,MAAM,UAAU,QAAQ,KAAK,KAAK,CAAC;AACjF;;;;;;AAOA,SAAgB,sBAAsB,MAAiC;CACrE,IAAI,mBAAmB,IAAI,GACzB,OAAO,QAAQ,KAAK,UAAU,IAAI;CAEpC,OAAO,KAAK,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG;AACtC;;;;;;AAOA,SAAgB,iBAAiB,MAAkC;CACjE,MAAM,OAAO,CAAC,KAAK,SAAS,GAAG,KAAK,IAAI;CACxC,MAAM,WAAW,sBAAsB,IAAI;CAC3C,OAAO,mBAAmB,IAAI,IAAI,QAAQ,aAAa,KAAK,SAAS;AACvE;;;;;;AAOA,SAAS,YAAY,OAAyB;CAC5C,MAAM,QAAkB,CACtB,OAAO,MAAM,QAAQ,MAAM,OAAO,KAAK,MAAM,KAAK,KAAK,GAAG,IAAI,MAAM,SAAS,CAC/E;CAEA,IAAI,MAAM,SACR,MAAM,KAAK,OAAO,OAAO,IAAI,UAAU,EAAE,GAAG,MAAM,SAAS;CAG7D,IAAI,MAAM,YACR,MAAM,KAAK,OAAO,OAAO,KAAK,aAAa,EAAE,GAAG,MAAM,YAAY;CAGpE,IAAI,MAAM,SACR,MAAM,KACJ,OAAO,OAAO,IAAI,OAAO,EAAE,gBAAgB,MAAM,QAAQ,iCAC3D;CAGF,IAAI,MAAM,MACR,MAAM,KAAK,OAAO,OAAO,KAAK,OAAO,EAAE,OAAO,iBAAiB,MAAM,IAAI,EAAE,EAAE;CAG/E,OAAO,MAAM,KAAK,EAAE;AACtB;;;;;;AAOA,SAAS,eAAe,SAAoC;CAC1D,MAAM,QAAQ,IAAI,MAAM,QAAQ,OAAO;CACvC,MAAM,OAAO;CACb,MAAM,OAAO,QAAQ;CACrB,MAAM,UAAU,QAAQ;CACxB,MAAM,aAAa,QAAQ;CAC3B,MAAM,UAAU,QAAQ;CACxB,MAAM,OAAO,QAAQ;CACrB,MAAM,UAAU,QAAQ;CACxB,MAAM,eAAe,YAAY,KAAK;CACtC,OAAO;AACT;;;;;;AAOA,SAAgB,WAAW,OAAmC;CAC5D,OAAO,iBAAiB,SAAS,MAAM,SAAS;AAClD"}
1
+ {"version":3,"file":"errors-Bxut5_Sy.mjs","names":[],"sources":["../src/cli/shared/errors.ts"],"sourcesContent":["import { styles } from \"./logger\";\n\n/**\n * Options for creating a CLI error\n */\nexport interface CLIErrorOptions {\n message: string;\n details?: string;\n suggestion?: string;\n command?: string;\n code?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, unknown>>;\n}\n\nexport interface CLIErrorNextAction {\n /** Executable name, such as `tailor`. */\n command: string;\n /** Arguments passed directly to the executable. */\n args: readonly string[];\n}\n\n/**\n * CLI error interface with formatted output\n */\nexport interface CLIError extends Error {\n readonly code?: string;\n readonly details?: string;\n readonly suggestion?: string;\n readonly command?: string;\n readonly next?: CLIErrorNextAction;\n readonly context?: Readonly<Record<string, unknown>>;\n format(): string;\n}\n\ntype CLIErrorInternal = Error & {\n code?: string;\n details?: string;\n suggestion?: string;\n command?: string;\n next?: CLIErrorNextAction;\n context?: Readonly<Record<string, unknown>>;\n format(): string;\n};\n\nfunction shellQuote(value: string): string {\n if (process.platform === \"win32\") {\n if (/^[A-Za-z0-9_./:=@+\\\\-]+$/.test(value)) return value;\n return `\"${value.replaceAll('\"', '\\\\\"')}\"`;\n }\n if (/^[A-Za-z0-9_./:=@+-]+$/.test(value)) return value;\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction needsArgvRendering(argv: readonly string[]): boolean {\n // cmd.exe/PowerShell expand %, $, and ! even inside double quotes, so no\n // quoting can keep such values literal on Windows.\n return process.platform === \"win32\" && argv.some((value) => /[%$!]/.test(value));\n}\n\n/**\n * Render an argv array as a copyable command line for the current platform's shell\n * @param {readonly string[]} argv - Executable name followed by its arguments\n * @returns {string} A shell-quoted command line, or an `argv [...]` JSON rendering when the platform shell cannot keep a value literal\n */\nexport function formatCopyableCommand(argv: readonly string[]): string {\n if (needsArgvRendering(argv)) {\n return `argv ${JSON.stringify(argv)}`;\n }\n return argv.map(shellQuote).join(\" \");\n}\n\n/**\n * Format an executable and argv as a shell-safe user-facing command.\n * @param next - Executable and arguments to format\n * @returns Shell command, or an argv representation when shell quoting is unsafe\n */\nexport function formatNextAction(next: CLIErrorNextAction): string {\n const argv = [next.command, ...next.args];\n const rendered = formatCopyableCommand(argv);\n return needsArgvRendering(argv) ? `with ${rendered}` : `\\`${rendered}\\``;\n}\n\n/**\n * Format CLI error for output\n * @param error - CLIError instance to format\n * @returns Formatted error message\n */\nfunction formatError(error: CLIError): string {\n const parts: string[] = [\n styles.error(`Error${error.code ? ` [${error.code}]` : \"\"}: ${error.message}`),\n ];\n\n if (error.details) {\n parts.push(`\\n ${styles.dim(\"Details:\")} ${error.details}`);\n }\n\n if (error.suggestion) {\n parts.push(`\\n ${styles.info(\"Suggestion:\")} ${error.suggestion}`);\n }\n\n if (error.command) {\n parts.push(\n `\\n ${styles.dim(\"Help:\")} Run \\`tailor ${error.command} --help\\` for usage information.`,\n );\n }\n\n if (error.next) {\n parts.push(`\\n ${styles.info(\"Next:\")} Run ${formatNextAction(error.next)}.`);\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Create a CLI error with formatted output\n * @param options - Options to construct a CLIError\n * @returns Constructed CLIError instance\n */\nfunction createCLIError(options: CLIErrorOptions): CLIError {\n const error = new Error(options.message) as CLIErrorInternal;\n error.name = \"CLIError\";\n error.code = options.code;\n error.details = options.details;\n error.suggestion = options.suggestion;\n error.command = options.command;\n error.next = options.next;\n error.context = options.context;\n error.format = () => formatError(error);\n return error;\n}\n\n/**\n * Type guard to check if an error is a CLIError\n * @param error - Error to check\n * @returns True if the error is a CLIError\n */\nexport function isCLIError(error: unknown): error is CLIError {\n return error instanceof Error && error.name === \"CLIError\";\n}\n\nconst MISSING_NAMED_EXPORT_PATTERN = /does not provide an export named '(?!default')([^']+)'/;\n\n/**\n * Suggest `import type` when importing user code fails on a missing named\n * export. The CLI strips types from each file in isolation, so a type-only\n * export does not exist at runtime and a plain import of it fails to link.\n * @param error - Error thrown while importing user modules\n * @returns Suggestion text, or undefined when the error is not that failure\n */\nexport function typeOnlyImportHint(error: unknown): string | undefined {\n if (!(error instanceof SyntaxError)) return undefined;\n const name = MISSING_NAMED_EXPORT_PATTERN.exec(error.message)?.[1];\n if (!name) return undefined;\n return (\n `If '${name}' is a type, import it with \\`import type\\` (or the inline \\`type\\` modifier). ` +\n \"The CLI runs TypeScript by stripping types from each file in isolation, so type-only exports do not exist at runtime. \" +\n 'Set \"verbatimModuleSyntax\": true in tsconfig.json to catch this at typecheck.'\n );\n}\n\n// Re-export createCLIError as CLIError for backward compatibility\nexport { createCLIError as CLIError };\n"],"mappings":";;;AA6CA,SAAS,WAAW,OAAuB;CACzC,IAAI,QAAQ,aAAa,SAAS;EAChC,IAAI,2BAA2B,KAAK,KAAK,GAAG,OAAO;EACnD,OAAO,IAAI,MAAM,WAAW,MAAK,MAAK,E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;CACrB,MAAM,UAAU,QAAQ;CACxB,MAAM,aAAa,QAAQ;CAC3B,MAAM,UAAU,QAAQ;CACxB,MAAM,OAAO,QAAQ;CACrB,MAAM,UAAU,QAAQ;CACxB,MAAM,eAAe,YAAY,KAAK;CACtC,OAAO;AACT;;;;;;AAOA,SAAgB,WAAW,OAAmC;CAC5D,OAAO,iBAAiB,SAAS,MAAM,SAAS;AAClD;AAEA,MAAM,+BAA+B;;;;;;;;AASrC,SAAgB,mBAAmB,OAAoC;CACrE,IAAI,EAAE,iBAAiB,cAAc,OAAO;CAC5C,MAAM,OAAO,6BAA6B,KAAK,MAAM,OAAO,CAAC,GAAG;CAChE,IAAI,CAAC,MAAM,OAAO;CAClB,OACE,OAAO,KAAK;AAIhB"}
@@ -1 +1 @@
1
- {"version":3,"file":"file-BUcmVIH2.mjs","names":[],"sources":["../src/runtime/file.ts"],"sourcesContent":["/**\n * TailorDB file (BLOB) utilities.\n *\n * Thin typed wrapper around the platform-provided `tailordb.file` runtime API.\n * At runtime this delegates to `globalThis.tailordb.file`. Use `mockFile` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { file } from \"@tailor-platform/sdk/runtime\";\n *\n * const { metadata } = await file.upload(\n * \"my-namespace\",\n * \"Document\",\n * \"attachment\",\n * recordId,\n * bytes,\n * );\n */\n\n/** Upload response metadata. */\nexport interface UploadMetadata {\n fileSize: number;\n sha256sum: string;\n}\n\n/** Download response metadata. */\nexport interface DownloadMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n lastUploadedAt: string;\n}\n\n/** File metadata (for {@link TailorDBFileAPI.getMetadata}). */\nexport interface FileMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n urlPath: string;\n lastUploadedAt?: string;\n}\n\n/** Upload options. */\nexport interface FileUploadOptions {\n contentType?: string;\n}\n\n/** Upload stream options. */\nexport interface FileUploadStreamOptions {\n contentType?: string;\n fileSize?: number;\n}\n\n/** Upload response. */\nexport interface FileUploadResponse {\n metadata: UploadMetadata;\n}\n\n/** Download response. */\nexport interface FileDownloadResponse {\n data: Uint8Array;\n metadata: DownloadMetadata;\n}\n\n/** Download-as-Base64 response. */\nexport interface FileDownloadAsBase64Response {\n data: string;\n metadata: DownloadMetadata;\n}\n\n/** Download stream response. */\nexport interface FileDownloadStreamResponse {\n body: ReadableStream<Uint8Array>;\n metadata: DownloadMetadata;\n}\n\n/** Error code emitted by {@link TailorDBFileError}. */\nexport type TailorDBFileErrorCode =\n | \"INVALID_PARAMS\"\n | \"INVALID_DATA_TYPE\"\n | \"OPERATION_FAILED\"\n | \"DELETE_FAILED\"\n | \"STREAM_OPEN_FAILED\"\n | \"STREAM_READ_ERROR\"\n | \"STREAM_ERROR\"\n | \"FILE_TOO_LARGE\";\n\n/**\n * Type-only shape of the `TailorDBFileError` runtime class. The class itself\n * is provided by the platform runtime (and by `injectMocks` in tests); this\n * interface mirrors it so callers can `import type { TailorDBFileError }` from\n * the wrapper module without depending on any ambient declaration.\n */\nexport interface TailorDBFileError extends Error {\n name: \"TailorDBFileError\";\n code?: TailorDBFileErrorCode;\n cause?: unknown;\n}\n\n/**\n * Platform API surface for `tailordb.file`. Describes the shape the platform\n * runtime injects on `globalThis.tailordb.file`.\n */\nexport interface TailorDBFileAPI {\n /**\n * Upload a file to TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @param data - File contents\n * @param options - Upload options (e.g. `contentType`)\n * @returns Upload response containing the file metadata\n */\n upload(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n data: string | ArrayBuffer | Uint8Array | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse>;\n\n /**\n * Download a file from TailorDB.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Bytes and metadata for the file\n */\n download(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadResponse>;\n\n /**\n * Download a file from TailorDB as a Base64-encoded string.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Base64-encoded contents and metadata for the file\n */\n downloadAsBase64(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadAsBase64Response>;\n\n /**\n * Delete a file from TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Resolves once the file has been deleted\n */\n delete(namespace: string, typeName: string, fieldName: string, recordId: string): Promise<void>;\n\n /**\n * Get file metadata from TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns Metadata for the stored file\n */\n getMetadata(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileMetadata>;\n\n /**\n * Download a file as a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @returns ReadableStream body and metadata for the file\n */\n downloadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadStreamResponse>;\n\n /**\n * Upload a file using a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB type name\n * @param fieldName - File field name on the type\n * @param recordId - Record ID owning the field\n * @param readableStream - ReadableStream providing the file data\n * @param options - Upload stream options (e.g. `contentType`, `fileSize`)\n * @returns Upload response containing the file metadata\n */\n uploadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n readableStream: ReadableStream<Uint8Array | ArrayBuffer>,\n options?: FileUploadStreamOptions,\n ): Promise<FileUploadResponse>;\n}\n\nconst api = (): TailorDBFileAPI =>\n (globalThis as unknown as { tailordb: { file: TailorDBFileAPI } }).tailordb.file;\n\n/**\n * See {@link TailorDBFileAPI.upload}.\n * @param args - Forwarded to {@link TailorDBFileAPI.upload}\n * @returns Upload response containing the file metadata\n */\nconst upload: TailorDBFileAPI[\"upload\"] = (...args) => api().upload(...args);\n\n/**\n * See {@link TailorDBFileAPI.download}.\n * @param args - Forwarded to {@link TailorDBFileAPI.download}\n * @returns Bytes and metadata for the file\n */\nconst download: TailorDBFileAPI[\"download\"] = (...args) => api().download(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadAsBase64}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadAsBase64}\n * @returns Base64-encoded contents and metadata for the file\n */\nconst downloadAsBase64: TailorDBFileAPI[\"downloadAsBase64\"] = (...args) =>\n api().downloadAsBase64(...args);\n\n/**\n * See {@link TailorDBFileAPI.delete}.\n * @param args - Forwarded to {@link TailorDBFileAPI.delete}\n * @returns Resolves once the file has been deleted\n */\nconst deleteFile: TailorDBFileAPI[\"delete\"] = (...args) => api().delete(...args);\n\n/**\n * See {@link TailorDBFileAPI.getMetadata}.\n * @param args - Forwarded to {@link TailorDBFileAPI.getMetadata}\n * @returns Metadata for the stored file\n */\nconst getMetadata: TailorDBFileAPI[\"getMetadata\"] = (...args) => api().getMetadata(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadStream}\n * @returns ReadableStream body and metadata for the file\n */\nconst downloadStream: TailorDBFileAPI[\"downloadStream\"] = (...args) =>\n api().downloadStream(...args);\n\n/**\n * See {@link TailorDBFileAPI.uploadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.uploadStream}\n * @returns Upload response containing the file metadata\n */\nconst uploadStream: TailorDBFileAPI[\"uploadStream\"] = (...args) => api().uploadStream(...args);\n\n/** Runtime wrapper namespace for `tailordb.file`. */\nexport const file = {\n upload,\n download,\n downloadAsBase64,\n delete: deleteFile,\n getMetadata,\n downloadStream,\n uploadStream,\n} as const satisfies TailorDBFileAPI;\n"],"mappings":";AA0NA,MAAM,YACH,WAAkE,SAAS;;;;;;AAO9E,MAAM,UAAqC,GAAG,SAAS,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI;;;;;;AAO3E,MAAM,YAAyC,GAAG,SAAS,IAAI,CAAC,CAAC,SAAS,GAAG,IAAI;;;;;;AAOjF,MAAM,oBAAyD,GAAG,SAChE,IAAI,CAAC,CAAC,iBAAiB,GAAG,IAAI;;;;;;AAOhC,MAAM,cAAyC,GAAG,SAAS,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI;;;;;;AAO/E,MAAM,eAA+C,GAAG,SAAS,IAAI,CAAC,CAAC,YAAY,GAAG,IAAI;;;;;;AAO1F,MAAM,kBAAqD,GAAG,SAC5D,IAAI,CAAC,CAAC,eAAe,GAAG,IAAI;;;;;;AAO9B,MAAM,gBAAiD,GAAG,SAAS,IAAI,CAAC,CAAC,aAAa,GAAG,IAAI;;AAG7F,MAAa,OAAO;CAClB;CACA;CACA;CACA,QAAQ;CACR;CACA;CACA;AACF"}
1
+ {"version":3,"file":"file-BUcmVIH2.mjs","names":[],"sources":["../src/runtime/file.ts"],"sourcesContent":["/**\n * TailorDB file (BLOB) utilities.\n *\n * Thin typed wrapper around the platform-provided `tailordb.file` runtime API.\n * At runtime this delegates to `globalThis.tailordb.file`. Use `mockFile` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { file } from \"@tailor-platform/sdk/runtime\";\n *\n * const { metadata } = await file.upload(\n * \"my-namespace\",\n * \"Document\",\n * \"attachment\",\n * recordId,\n * bytes,\n * );\n */\n\n/** Upload response metadata. */\nexport interface UploadMetadata {\n fileSize: number;\n sha256sum: string;\n}\n\n/** Download response metadata. */\nexport interface DownloadMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n lastUploadedAt: string;\n}\n\n/** File metadata (for {@link TailorDBFileAPI.getMetadata}). */\nexport interface FileMetadata {\n contentType: string;\n fileSize: number;\n sha256sum: string;\n urlPath: string;\n lastUploadedAt?: string;\n}\n\n/** Upload options. */\nexport interface FileUploadOptions {\n contentType?: string;\n}\n\n/** Upload stream options. */\nexport interface FileUploadStreamOptions {\n contentType?: string;\n fileSize?: number;\n}\n\n/** Upload response. */\nexport interface FileUploadResponse {\n metadata: UploadMetadata;\n}\n\n/** Download response. */\nexport interface FileDownloadResponse {\n data: Uint8Array;\n metadata: DownloadMetadata;\n}\n\n/** Download-as-Base64 response. */\nexport interface FileDownloadAsBase64Response {\n data: string;\n metadata: DownloadMetadata;\n}\n\n/** Download stream response. */\nexport interface FileDownloadStreamResponse {\n body: ReadableStream<Uint8Array>;\n metadata: DownloadMetadata;\n}\n\n/** Error code emitted by {@link TailorDBFileError}. */\nexport type TailorDBFileErrorCode =\n | \"INVALID_PARAMS\"\n | \"INVALID_DATA_TYPE\"\n | \"OPERATION_FAILED\"\n | \"DELETE_FAILED\"\n | \"STREAM_OPEN_FAILED\"\n | \"STREAM_READ_ERROR\"\n | \"STREAM_ERROR\"\n | \"FILE_TOO_LARGE\";\n\n/**\n * Type-only shape of the `TailorDBFileError` runtime class. The class itself\n * is provided by the platform runtime (and by `injectMocks` in tests); this\n * interface mirrors it so callers can `import type { TailorDBFileError }` from\n * the wrapper module without depending on any ambient declaration.\n */\nexport interface TailorDBFileError extends Error {\n name: \"TailorDBFileError\";\n code?: TailorDBFileErrorCode;\n cause?: unknown;\n}\n\n/**\n * Platform API surface for `tailordb.file`. Describes the shape the platform\n * runtime injects on `globalThis.tailordb.file`.\n */\nexport interface TailorDBFileAPI {\n /**\n * Upload a file to TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB table name\n * @param fieldName - File field name on the table\n * @param recordId - Record ID owning the field\n * @param data - File contents\n * @param options - Upload options (e.g. `contentType`)\n * @returns Upload response containing the file metadata\n */\n upload(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n data: string | ArrayBuffer | Uint8Array | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse>;\n\n /**\n * Download a file from TailorDB.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB table name\n * @param fieldName - File field name on the table\n * @param recordId - Record ID owning the field\n * @returns Bytes and metadata for the file\n */\n download(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadResponse>;\n\n /**\n * Download a file from TailorDB as a Base64-encoded string.\n *\n * Throws `TailorDBFileError` with code `FILE_TOO_LARGE` when the file\n * exceeds 10MB — use {@link downloadStream} for large files.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB table name\n * @param fieldName - File field name on the table\n * @param recordId - Record ID owning the field\n * @returns Base64-encoded contents and metadata for the file\n */\n downloadAsBase64(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadAsBase64Response>;\n\n /**\n * Delete a file from TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB table name\n * @param fieldName - File field name on the table\n * @param recordId - Record ID owning the field\n * @returns Resolves once the file has been deleted\n */\n delete(namespace: string, typeName: string, fieldName: string, recordId: string): Promise<void>;\n\n /**\n * Get file metadata from TailorDB.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB table name\n * @param fieldName - File field name on the table\n * @param recordId - Record ID owning the field\n * @returns Metadata for the stored file\n */\n getMetadata(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileMetadata>;\n\n /**\n * Download a file as a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB table name\n * @param fieldName - File field name on the table\n * @param recordId - Record ID owning the field\n * @returns ReadableStream body and metadata for the file\n */\n downloadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n ): Promise<FileDownloadStreamResponse>;\n\n /**\n * Upload a file using a ReadableStream.\n * @param namespace - TailorDB namespace\n * @param typeName - TailorDB table name\n * @param fieldName - File field name on the table\n * @param recordId - Record ID owning the field\n * @param readableStream - ReadableStream providing the file data\n * @param options - Upload stream options (e.g. `contentType`, `fileSize`)\n * @returns Upload response containing the file metadata\n */\n uploadStream(\n namespace: string,\n typeName: string,\n fieldName: string,\n recordId: string,\n readableStream: ReadableStream<Uint8Array | ArrayBuffer>,\n options?: FileUploadStreamOptions,\n ): Promise<FileUploadResponse>;\n}\n\nconst api = (): TailorDBFileAPI =>\n (globalThis as unknown as { tailordb: { file: TailorDBFileAPI } }).tailordb.file;\n\n/**\n * See {@link TailorDBFileAPI.upload}.\n * @param args - Forwarded to {@link TailorDBFileAPI.upload}\n * @returns Upload response containing the file metadata\n */\nconst upload: TailorDBFileAPI[\"upload\"] = (...args) => api().upload(...args);\n\n/**\n * See {@link TailorDBFileAPI.download}.\n * @param args - Forwarded to {@link TailorDBFileAPI.download}\n * @returns Bytes and metadata for the file\n */\nconst download: TailorDBFileAPI[\"download\"] = (...args) => api().download(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadAsBase64}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadAsBase64}\n * @returns Base64-encoded contents and metadata for the file\n */\nconst downloadAsBase64: TailorDBFileAPI[\"downloadAsBase64\"] = (...args) =>\n api().downloadAsBase64(...args);\n\n/**\n * See {@link TailorDBFileAPI.delete}.\n * @param args - Forwarded to {@link TailorDBFileAPI.delete}\n * @returns Resolves once the file has been deleted\n */\nconst deleteFile: TailorDBFileAPI[\"delete\"] = (...args) => api().delete(...args);\n\n/**\n * See {@link TailorDBFileAPI.getMetadata}.\n * @param args - Forwarded to {@link TailorDBFileAPI.getMetadata}\n * @returns Metadata for the stored file\n */\nconst getMetadata: TailorDBFileAPI[\"getMetadata\"] = (...args) => api().getMetadata(...args);\n\n/**\n * See {@link TailorDBFileAPI.downloadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.downloadStream}\n * @returns ReadableStream body and metadata for the file\n */\nconst downloadStream: TailorDBFileAPI[\"downloadStream\"] = (...args) =>\n api().downloadStream(...args);\n\n/**\n * See {@link TailorDBFileAPI.uploadStream}.\n * @param args - Forwarded to {@link TailorDBFileAPI.uploadStream}\n * @returns Upload response containing the file metadata\n */\nconst uploadStream: TailorDBFileAPI[\"uploadStream\"] = (...args) => api().uploadStream(...args);\n\n/** Runtime wrapper namespace for `tailordb.file`. */\nexport const file = {\n upload,\n download,\n downloadAsBase64,\n delete: deleteFile,\n getMetadata,\n downloadStream,\n uploadStream,\n} as const satisfies TailorDBFileAPI;\n"],"mappings":";AA0NA,MAAM,YACH,WAAkE,SAAS;;;;;;AAO9E,MAAM,UAAqC,GAAG,SAAS,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI;;;;;;AAO3E,MAAM,YAAyC,GAAG,SAAS,IAAI,CAAC,CAAC,SAAS,GAAG,IAAI;;;;;;AAOjF,MAAM,oBAAyD,GAAG,SAChE,IAAI,CAAC,CAAC,iBAAiB,GAAG,IAAI;;;;;;AAOhC,MAAM,cAAyC,GAAG,SAAS,IAAI,CAAC,CAAC,OAAO,GAAG,IAAI;;;;;;AAO/E,MAAM,eAA+C,GAAG,SAAS,IAAI,CAAC,CAAC,YAAY,GAAG,IAAI;;;;;;AAO1F,MAAM,kBAAqD,GAAG,SAC5D,IAAI,CAAC,CAAC,eAAe,GAAG,IAAI;;;;;;AAO9B,MAAM,gBAAiD,GAAG,SAAS,IAAI,CAAC,CAAC,aAAa,GAAG,IAAI;;AAG7F,MAAa,OAAO;CAClB;CACA;CACA;CACA,QAAQ;CACR;CACA;CACA;AACF"}
@@ -10,7 +10,8 @@ type ResolveUpdate<T> = T extends ColumnType$1<unknown, unknown, infer U> ? U :
10
10
  type ObjectColumnType<T> = ColumnType$1<{ [K in keyof T]-?: Exclude<ResolveSelect<T[K]>, undefined>; }, { [K in keyof T]: ResolveInsert<T[K]>; }, { [K in keyof T]: ResolveUpdate<T[K]>; }>;
11
11
  type ArrayColumnType<T> = ColumnType$1<ResolveSelect<T>[], ResolveInsert<T>[], ResolveUpdate<T>[]>;
12
12
  type Generated<T> = T extends ColumnType$1<infer S, infer I, infer U> ? ColumnType$1<S, I | undefined, U> : ColumnType$1<T, T | undefined, T>;
13
- type Serial<T = string | number> = ColumnType$1<T, TypeLevelError<"assigned by .serial(); remove it from the input"> | undefined, TypeLevelError<"assigned by .serial(); remove it from the input"> | undefined>;
13
+ type SerialColumnMustBeOmitted = TypeLevelError<"assigned by .serial(); remove it from the input">;
14
+ type Serial<T = string | number> = ColumnType$1<T, SerialColumnMustBeOmitted | undefined, SerialColumnMustBeOmitted | undefined>;
14
15
  type FlattenColumns<T> = { [K in keyof T]: T[K]; } & {};
15
16
  type TailordbKysely<DB> = Kysely$1<DB>;
16
17
  type NamespaceDB<NS, N extends keyof NS = keyof NS> = TailordbKysely<NS[N]>;
@@ -20,8 +20,9 @@ import { Kysely, Kysely as Kysely$1, sql } from "kysely";
20
20
  */
21
21
  function createGetDB() {
22
22
  return function getDB(namespace, config) {
23
+ const client = new tailordb.Client({ namespace });
23
24
  return new Kysely$1({
24
- dialect: new TailordbDialect$1(new tailordb.Client({ namespace })),
25
+ dialect: new TailordbDialect$1(client),
25
26
  ...config
26
27
  });
27
28
  };