@tailor-platform/sdk 2.3.0 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +171 -0
- package/README.md +1 -1
- package/dist/aigateway-DsWDjzk4.mjs +2 -0
- package/dist/{aigateway-DR4Kwuik.mjs.map → aigateway-DsWDjzk4.mjs.map} +1 -1
- package/dist/application-DFOUovmN.mjs +1 -0
- package/dist/application-D_4vg1KR.mjs +192 -0
- package/dist/application-D_4vg1KR.mjs.map +1 -0
- package/dist/assert-WeXvmG4j.mjs +2 -0
- package/dist/{assert-DBxo8jPo.mjs.map → assert-WeXvmG4j.mjs.map} +1 -1
- package/dist/authconnection-CynFBIv8.mjs +2 -0
- package/dist/{authconnection-CZvi9ANm.mjs.map → authconnection-CynFBIv8.mjs.map} +1 -1
- package/dist/brand-C8nMKhJC.mjs +2 -0
- package/dist/{brand-Eo4pLXPJ.mjs.map → brand-C8nMKhJC.mjs.map} +1 -1
- package/dist/cli/commands/deploy/deploy.d.mts +2 -2
- package/dist/cli/commands/deploy/deployment-target.d.mts +2 -0
- package/dist/cli/commands/deploy/event-subscriptions.d.mts +3 -0
- package/dist/cli/commands/deploy/tailordb/apply.d.mts +3 -0
- package/dist/cli/commands/deploy/tailordb/index.d.mts +3 -10
- package/dist/cli/commands/deploy/tailordb/migration-validation.d.mts +5 -0
- package/dist/cli/commands/deploy/tailordb/plan.d.mts +8 -0
- package/dist/cli/commands/executor/jobs.d.mts +1 -1
- package/dist/cli/commands/generate/seed/bundler.d.mts +2 -2
- package/dist/cli/commands/show.d.mts +1 -1
- package/dist/cli/commands/tailordb/migrate/diff-calculator.d.mts +15 -15
- package/dist/cli/commands/tailordb/migrate/generate.d.mts +7 -3
- package/dist/cli/commands/tailordb/migrate/rename-detection.d.mts +1 -1
- package/dist/cli/commands/tailordb/migrate/snapshot-comparison.d.mts +43 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-files.d.mts +62 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-local.d.mts +12 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-migrations.d.mts +12 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-remote.d.mts +1 -0
- package/dist/cli/commands/tailordb/migrate/snapshot-types.d.mts +3 -1
- package/dist/cli/commands/tailordb/migrate/snapshot.d.mts +5 -117
- package/dist/cli/commands/tailordb/truncate.d.mts +2 -2
- package/dist/cli/lib.d.mts +8 -4
- package/dist/cli/lib.mjs +1 -9
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +1170 -7686
- package/dist/cli/main.mjs.map +1 -1
- package/dist/cli/shared/seed-chunker.d.mts +5 -5
- package/dist/cli/ts-hook.mjs +3 -1
- package/dist/completion/zsh-worker.zsh +99 -18
- package/dist/configure/config/index.d.mts +2 -2
- package/dist/configure/config/types.d.mts +2 -2
- package/dist/configure/index.d.mts +49 -12
- package/dist/configure/index.mjs +1 -1267
- package/dist/configure/index.mjs.map +1 -1
- package/dist/configure/services/aigateway/index.d.mts +5 -4
- package/dist/configure/services/aigateway/types.d.mts +6 -1
- package/dist/configure/services/auth/types.d.mts +3 -3
- package/dist/configure/services/idp/types.d.mts +1 -1
- package/dist/configure/services/tailordb/permission.d.mts +1 -1
- package/dist/configure/services/tailordb/schema.d.mts +5 -9
- package/dist/configure/services/tailordb/types.d.mts +8 -5
- package/dist/configure/services/workflow/execution-policy.d.mts +3 -3
- package/dist/configure/services/workflow/job.d.mts +12 -2
- package/dist/configure/types/auth-namespace-name.d.mts +18 -0
- package/dist/configure/types/field.types.d.mts +1 -1
- package/dist/configure/types/permission-operand.types.d.mts +1 -1
- package/dist/context-D0QjfxzD.mjs +2 -0
- package/dist/{context-DYQVYWqZ.mjs.map → context-D0QjfxzD.mjs.map} +1 -1
- package/dist/crashreport-B-_HTKLr.mjs +42 -0
- package/dist/{crashreport-CIIfLnoO.mjs.map → crashreport-B-_HTKLr.mjs.map} +1 -1
- package/dist/crashreport-BmsRIdpy.mjs +1 -0
- package/dist/errors-DSEXKRVD.mjs +2 -0
- package/dist/errors-DSEXKRVD.mjs.map +1 -0
- package/dist/file-COPYfju_.mjs +2 -0
- package/dist/file-COPYfju_.mjs.map +1 -0
- package/dist/globals-CMHSnj4w.mjs +2 -0
- package/dist/{globals-B2nlxBrz.mjs.map → globals-CMHSnj4w.mjs.map} +1 -1
- package/dist/iconv-DlFMt2gW.mjs +2 -0
- package/dist/{iconv-QWaZh0TT.mjs.map → iconv-DlFMt2gW.mjs.map} +1 -1
- package/dist/idp-G_ojPBB5.mjs +2 -0
- package/dist/{idp-RA_swu-h.mjs.map → idp-G_ojPBB5.mjs.map} +1 -1
- package/dist/interceptor-DQg3cR_9.mjs +2 -0
- package/dist/{interceptor-e33JtsC-.mjs.map → interceptor-DQg3cR_9.mjs.map} +1 -1
- package/dist/kysely/index.mjs +1 -31
- package/dist/kysely/index.mjs.map +1 -1
- package/dist/kysely-type-BTi3BMtL.mjs +43 -0
- package/dist/kysely-type-BTi3BMtL.mjs.map +1 -0
- package/dist/logger-BcGy-u7G.mjs +9 -0
- package/dist/{logger-DSdExfor.mjs.map → logger-BcGy-u7G.mjs.map} +1 -1
- package/dist/logger-DP2BjQ93.mjs +2 -0
- package/dist/{logger-BtX0suGY.mjs.map → logger-DP2BjQ93.mjs.map} +1 -1
- package/dist/multiline-EyzjEwn9.mjs +3 -0
- package/dist/{multiline-sfHpTZZK.mjs.map → multiline-EyzjEwn9.mjs.map} +1 -1
- package/dist/node-builtins-oBl7EbyV.mjs +2 -0
- package/dist/{node-builtins-CmaL2Cbq.mjs.map → node-builtins-oBl7EbyV.mjs.map} +1 -1
- package/dist/package-json-C690ceex.mjs +2 -0
- package/dist/{package-json-8b0O9TlX.mjs.map → package-json-C690ceex.mjs.map} +1 -1
- package/dist/package-json-CmqhDJ__.mjs +1 -0
- package/dist/parser/service/tailordb/type-source.d.mts +5 -5
- package/dist/parser/service/tailordb/types.d.mts +4 -4
- package/dist/platform-serialize-DkiTdHOt.mjs +2 -0
- package/dist/{platform-serialize-RoRtBS0v.mjs.map → platform-serialize-DkiTdHOt.mjs.map} +1 -1
- package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
- package/dist/plugin/builtin/enum-constants/index.mjs +5 -114
- package/dist/plugin/builtin/enum-constants/index.mjs.map +1 -1
- package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
- package/dist/plugin/builtin/file-utils/index.mjs +22 -101
- package/dist/plugin/builtin/file-utils/index.mjs.map +1 -1
- package/dist/plugin/builtin/kysely-type/index.d.mts +9 -2
- package/dist/plugin/builtin/kysely-type/index.mjs +1 -275
- package/dist/plugin/builtin/seed/index.d.mts +5 -0
- package/dist/plugin/builtin/seed/index.mjs +1 -3
- package/dist/plugin/builtin/seed/seed-type-processor.d.mts +4 -6
- package/dist/plugin/get-generated-table.d.mts +16 -0
- package/dist/plugin/index.d.mts +3 -2
- package/dist/plugin/index.mjs +1 -251
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/plugin/types.d.mts +32 -25
- package/dist/plugin/with-context.d.mts +4 -4
- package/dist/register-ts-hook-Drnaproy.mjs +640 -0
- package/dist/register-ts-hook-Drnaproy.mjs.map +1 -0
- package/dist/registry-HlEaGvl5.mjs +2 -0
- package/dist/{registry-BIGVUrMB.mjs.map → registry-HlEaGvl5.mjs.map} +1 -1
- package/dist/repl-editor-BG1aDOfH.mjs +2 -0
- package/dist/{repl-editor-BCozyiNq.mjs.map → repl-editor-BG1aDOfH.mjs.map} +1 -1
- package/dist/runtime/aigateway.mjs +1 -3
- package/dist/runtime/authconnection.mjs +1 -3
- package/dist/runtime/context.mjs +1 -3
- package/dist/runtime/file.d.mts +28 -28
- package/dist/runtime/file.mjs +1 -3
- package/dist/runtime/globals.mjs +1 -1
- package/dist/runtime/iconv.mjs +1 -3
- package/dist/runtime/idp.mjs +1 -3
- package/dist/runtime/index.mjs +1 -11
- package/dist/runtime/logger.mjs +1 -3
- package/dist/runtime/secretmanager.mjs +1 -3
- package/dist/runtime/types.d.mts +1 -1
- package/dist/runtime/workflow.mjs +1 -3
- package/dist/schema-Ze_dI5VX.mjs +2 -0
- package/dist/schema-Ze_dI5VX.mjs.map +1 -0
- package/dist/secret-file-C9wp_FCX.mjs +2 -0
- package/dist/{secret-file-C3J4Gy8r.mjs.map → secret-file-C9wp_FCX.mjs.map} +1 -1
- package/dist/secretmanager-5olfnI1b.mjs +2 -0
- package/dist/{secretmanager-IY4UvinW.mjs.map → secretmanager-5olfnI1b.mjs.map} +1 -1
- package/dist/secretmanager-vHQoXdQz.mjs +2 -0
- package/dist/{secretmanager-CYlpffsz.mjs.map → secretmanager-vHQoXdQz.mjs.map} +1 -1
- package/dist/seed/index.d.mts +4 -4
- package/dist/seed/index.mjs +8 -244
- package/dist/seed/index.mjs.map +1 -1
- package/dist/seed-DwqRFdqP.mjs +207 -0
- package/dist/seed-DwqRFdqP.mjs.map +1 -0
- package/dist/service-BVe9u2Rt.mjs +7 -0
- package/dist/service-BVe9u2Rt.mjs.map +1 -0
- package/dist/service-CpZELSBa.mjs +1 -0
- package/dist/service-DlgaUO4V.mjs +2 -0
- package/dist/{service-hZskxZmg.mjs.map → service-DlgaUO4V.mjs.map} +1 -1
- package/dist/service_pb-DGKCLuAs.mjs +2 -0
- package/dist/{service_pb-BEWj1pOV.mjs.map → service_pb-DGKCLuAs.mjs.map} +1 -1
- package/dist/service_pb-_aeFE-Nv.mjs +1 -0
- package/dist/telemetry-Bklv9kQY.mjs +2 -0
- package/dist/{telemetry-BRVdwh14.mjs.map → telemetry-Bklv9kQY.mjs.map} +1 -1
- package/dist/telemetry-DXHP3VVi.mjs +1 -0
- package/dist/type-source--ZNcV8RJ.mjs +2 -0
- package/dist/type-source--ZNcV8RJ.mjs.map +1 -0
- package/dist/types/aigateway.generated.d.mts +2 -2
- package/dist/types/auth.generated.d.mts +3 -3
- package/dist/types/executor.generated.d.mts +2 -2
- package/dist/types/tailordb.generated.d.mts +12 -12
- package/dist/user-agent-vdHYF3QL.mjs +2 -0
- package/dist/{user-agent-Bgsszb5I.mjs.map → user-agent-vdHYF3QL.mjs.map} +1 -1
- package/dist/utils/test/index.d.mts +4 -4
- package/dist/utils/test/index.mjs +1 -109
- package/dist/utils/test/index.mjs.map +1 -1
- package/dist/vitest/environment.mjs +1 -41
- package/dist/vitest/environment.mjs.map +1 -1
- package/dist/vitest/index.mjs +1 -1980
- package/dist/vitest/index.mjs.map +1 -1
- package/dist/vitest/mocks/file.d.mts +8 -8
- package/dist/vitest/setup.mjs +1 -140
- package/dist/vitest/setup.mjs.map +1 -1
- package/dist/wait-point-invoker-eiP-IIux.mjs +2 -0
- package/dist/wait-point-invoker-eiP-IIux.mjs.map +1 -0
- package/dist/wait-point-registry-BrkwfyjS.mjs +2 -0
- package/dist/{wait-point-registry-TL99zotw.mjs.map → wait-point-registry-BrkwfyjS.mjs.map} +1 -1
- package/dist/workflow-Cs9ISw6j.mjs +2 -0
- package/dist/{workflow-Bamae_Yc.mjs.map → workflow-Cs9ISw6j.mjs.map} +1 -1
- package/dist/workspace_resource_pb--GeYQPXu.mjs +2 -0
- package/dist/{workspace_resource_pb-HNIL_Vfj.mjs.map → workspace_resource_pb--GeYQPXu.mjs.map} +1 -1
- package/docs/cli/application.md +3 -1
- package/docs/cli/function.md +77 -13
- package/docs/cli/setup.md +24 -14
- package/docs/cli/tailordb.md +32 -30
- package/docs/cli/workspace.md +2 -2
- package/docs/cli-reference.md +23 -22
- package/docs/configuration.md +2 -2
- package/docs/github-actions.md +10 -9
- package/docs/migration/v2.md +16 -4
- package/docs/migration/v3.md +123 -0
- package/docs/plugin/custom.md +130 -85
- package/docs/plugin/index.md +3 -3
- package/docs/quickstart.md +1 -1
- package/docs/services/aigateway.md +33 -9
- package/docs/services/executor.md +5 -1
- package/docs/services/tailordb-migration.md +68 -54
- package/docs/services/tailordb.md +7 -7
- package/docs/services/workflow.md +10 -9
- package/docs/testing.md +1 -1
- package/package.json +16 -16
- package/postinstall.mjs +1 -1
- package/dist/aigateway-DR4Kwuik.mjs +0 -9
- package/dist/application-BZfk4HKm.mjs +0 -3
- package/dist/application-F-nl107y.mjs +0 -6019
- package/dist/application-F-nl107y.mjs.map +0 -1
- package/dist/assert-DBxo8jPo.mjs +0 -9
- package/dist/authconnection-CZvi9ANm.mjs +0 -9
- package/dist/brand-Eo4pLXPJ.mjs +0 -36
- package/dist/context-DYQVYWqZ.mjs +0 -23
- package/dist/crashreport-CIIfLnoO.mjs +0 -423
- package/dist/crashreport-CINZ5dVN.mjs +0 -3
- package/dist/errors-BVb6vYGy.mjs +0 -89
- package/dist/errors-BVb6vYGy.mjs.map +0 -1
- package/dist/file-BUcmVIH2.mjs +0 -58
- package/dist/file-BUcmVIH2.mjs.map +0 -1
- package/dist/globals-B2nlxBrz.mjs +0 -126
- package/dist/iconv-QWaZh0TT.mjs +0 -38
- package/dist/idp-RA_swu-h.mjs +0 -82
- package/dist/interceptor-e33JtsC-.mjs +0 -33
- package/dist/logger-BtX0suGY.mjs +0 -48
- package/dist/logger-DSdExfor.mjs +0 -358
- package/dist/multiline-sfHpTZZK.mjs +0 -38
- package/dist/node-builtins-CmaL2Cbq.mjs +0 -36
- package/dist/package-json-8b0O9TlX.mjs +0 -17
- package/dist/package-json-Cv2Z-TqQ.mjs +0 -3
- package/dist/platform-serialize-RoRtBS0v.mjs +0 -46
- package/dist/plugin/builtin/kysely-type/index.mjs.map +0 -1
- package/dist/plugin/builtin/seed/types.d.mts +0 -2
- package/dist/plugin/get-generated-type.d.mts +0 -16
- package/dist/register-ts-hook-ClI226n2.mjs +0 -25543
- package/dist/register-ts-hook-ClI226n2.mjs.map +0 -1
- package/dist/registry-BIGVUrMB.mjs +0 -54
- package/dist/repl-editor-BCozyiNq.mjs +0 -251
- package/dist/schema--xYWRGfe.mjs +0 -639
- package/dist/schema--xYWRGfe.mjs.map +0 -1
- package/dist/secret-file-C3J4Gy8r.mjs +0 -64
- package/dist/secretmanager-CYlpffsz.mjs +0 -13
- package/dist/secretmanager-IY4UvinW.mjs +0 -131
- package/dist/seed-xqM9WIHP.mjs +0 -483
- package/dist/seed-xqM9WIHP.mjs.map +0 -1
- package/dist/service-C_WpbKHu.mjs +0 -898
- package/dist/service-C_WpbKHu.mjs.map +0 -1
- package/dist/service-D1RCdzIL.mjs +0 -3
- package/dist/service-hZskxZmg.mjs +0 -131
- package/dist/service_pb-BEWj1pOV.mjs +0 -167
- package/dist/service_pb-BjlhvK9E.mjs +0 -3
- package/dist/telemetry-BRVdwh14.mjs +0 -84
- package/dist/telemetry-CkbkeJxl.mjs +0 -3
- package/dist/type-source-DH_LH20p.mjs +0 -13
- package/dist/type-source-DH_LH20p.mjs.map +0 -1
- package/dist/user-agent-Bgsszb5I.mjs +0 -28
- package/dist/wait-point-invoker-__oE88_P.mjs +0 -148
- package/dist/wait-point-invoker-__oE88_P.mjs.map +0 -1
- package/dist/wait-point-registry-TL99zotw.mjs +0 -47
- package/dist/workflow-Bamae_Yc.mjs +0 -34
- package/dist/workspace_resource_pb-HNIL_Vfj.mjs +0 -860
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
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<
|
|
11
|
+
declare function defineAIGateway(name: string, config: Omit<AIGatewayServiceInput, "name">): {
|
|
11
12
|
readonly name: string;
|
|
12
13
|
readonly cors?: string[] | undefined;
|
|
13
|
-
readonly authNamespace
|
|
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
|
|
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
|
|
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;
|
|
@@ -165,4 +165,4 @@ type AuthServiceInputLoose = AuthServiceInput<any, any, any, string, any>;
|
|
|
165
165
|
type AuthOwnConfig = DefinedAuth<string, AuthServiceInputLoose>;
|
|
166
166
|
type AuthConfig = AuthOwnConfig | AuthExternalConfig;
|
|
167
167
|
//#endregion
|
|
168
|
-
export { AuthAttributeValue, AuthConfig, AuthConnectionTokenResult, AuthDefinitionBrand, AuthExternalConfig,
|
|
168
|
+
export { AuthAttributeValue, AuthConfig, AuthConnectionTokenResult, AuthDefinitionBrand, AuthExternalConfig, AuthOwnConfig, AuthServiceInput, BeforeLoginClaims, BeforeLoginHook, BeforeLoginHookArgs, DefinedAuth, FederatedIdentity, FederatedIdentityClaims, FederatedIdentityProvider, MachineUserName, MachineUserNameRegistry, OAuth2ClientGrantType, SCIMAttributeType, UserAttributeKey, UserAttributeListKey, UserAttributes, UsernameFieldKey, ValueOperand };
|
|
@@ -20,4 +20,4 @@ type IdPOwnConfigInput = Omit<IdPInput, "permission"> & {
|
|
|
20
20
|
type IdPOwnConfig = Omit<DefinedIdp<string, IdPOwnConfigInput, string>, "provider">;
|
|
21
21
|
type IdPConfig = IdPOwnConfig | IdPExternalConfig;
|
|
22
22
|
//#endregion
|
|
23
|
-
export {
|
|
23
|
+
export { IdPConfig, IdPExternalConfig, IdPOwnConfig, IdpDefinitionBrand };
|
|
@@ -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
|
|
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.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { FieldOptions, FieldOutput, FieldValidateInput, TailorFieldType, TailorToTs } from "../../types/field.types.mjs";
|
|
2
|
-
import { InferredAttributes
|
|
2
|
+
import { InferredAttributes } from "../../../runtime/types.mjs";
|
|
3
3
|
import { InferFieldsOutput, TypeLevelError, output } from "../../../types/helpers.mjs";
|
|
4
|
-
import { DBFieldMetadata, DefinedDBFieldMetadata, ExcludeDefaultedDBFields, ExcludeHookedDBFields, ExcludeNestedDBFields, Hook, IndexDef, RelationType, SerialConfig, TailorDBField as TailorDBField$1, TailorDBType as TailorDBType$1, TypeFeatures, TypeHook, TypeValidateFn } from "./types.mjs";
|
|
4
|
+
import { DBFieldMetadata, DefinedDBFieldMetadata, ExcludeDefaultedDBFields, ExcludeHookedDBFields, ExcludeNestedDBFields, Hook, IndexDef, RelationType, SerialConfig, TailorDBField as TailorDBField$1, TailorDBType as TailorDBType$1, TypeFeatures, TypeHook, TypeValidateFn, UpdateHookFn } from "./types.mjs";
|
|
5
5
|
import { AllowedValues, AllowedValuesOutput } from "../../types/field.mjs";
|
|
6
6
|
import { FieldParseArgs } from "../../../runtime/field-parse.mjs";
|
|
7
7
|
import { PluginConfigs } from "../../../plugin/types.mjs";
|
|
@@ -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
|
|
212
|
+
* Define a relation to another table.
|
|
213
213
|
*/
|
|
214
214
|
relation: DBFieldRelationMethod<Defined, Output, Nested>;
|
|
215
215
|
/**
|
|
@@ -443,6 +443,7 @@ declare function dbTable<const F extends {
|
|
|
443
443
|
declare function dbTable<const F extends {
|
|
444
444
|
id?: never;
|
|
445
445
|
} & Record<string, TailorAnyDBField>>(name: string | [string, string], description: string, fields: F): DBTable<F, WithDBTypeMetadata<DefinedDBTypeMetadata, "description">>;
|
|
446
|
+
type TimestampsUpdatedAtHookFn = UpdateHookFn<string | Date | null, string | Date>;
|
|
446
447
|
/** TailorDB schema builder utilities for defining tables and fields. */
|
|
447
448
|
declare const db: {
|
|
448
449
|
table: typeof dbTable;
|
|
@@ -472,12 +473,7 @@ declare const db: {
|
|
|
472
473
|
timestamps: () => {
|
|
473
474
|
createdAt: TailorDBField<WithDBFieldDescription<WithDBFieldDefault<DBFieldDefined<"datetime", FieldOptions>>>, string | Date, Record<string, TailorAnyDBField>>;
|
|
474
475
|
updatedAt: TailorDBField<WithDBFieldDescription<WithDBFieldHooks<WithDBFieldDefault<DBFieldDefined<"datetime", FieldOptions>>, {
|
|
475
|
-
readonly update:
|
|
476
|
-
input: string | Date | null;
|
|
477
|
-
oldValue: string | Date;
|
|
478
|
-
invoker: TailorPrincipal | null;
|
|
479
|
-
now: Date;
|
|
480
|
-
}) => string | Date;
|
|
476
|
+
readonly update: TimestampsUpdatedAtHookFn;
|
|
481
477
|
}>>, string | Date, Record<string, TailorAnyDBField>>;
|
|
482
478
|
};
|
|
483
479
|
};
|
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
201
|
+
* while an executor uses this table, an error will be thrown during apply.
|
|
199
202
|
*/
|
|
200
203
|
publishEvents?: boolean;
|
|
201
204
|
}
|
|
@@ -221,4 +224,4 @@ type TailorDBServiceInput = {
|
|
|
221
224
|
[namespace: string]: TailorDBServiceConfigInput | TailorDBExternalConfig;
|
|
222
225
|
};
|
|
223
226
|
//#endregion
|
|
224
|
-
export { DBFieldMetadata, DefinedDBFieldMetadata, ExcludeDefaultedDBFields, ExcludeHookedDBFields, ExcludeNestedDBFields,
|
|
227
|
+
export { DBFieldMetadata, DefinedDBFieldMetadata, ExcludeDefaultedDBFields, ExcludeHookedDBFields, ExcludeNestedDBFields, Hook, IndexDef, IsAutoFilledDBField, IsReadOnlyDBField, PluginAttachment, RawRelationConfig, RelationType, SerialConfig, TailorAnyDBField, TailorAnyDBType, TailorDBField, TailorDBInstance, TailorDBServiceInput, TailorDBType, TailorDBTypeMetadata, TypeFeatures, TypeHook, TypeValidateFn, UpdateHookFn };
|
|
@@ -57,11 +57,11 @@ declare function defineWorkflowExecutionPolicy<const N extends string, const D e
|
|
|
57
57
|
* }),
|
|
58
58
|
* }));
|
|
59
59
|
*
|
|
60
|
-
* // In a workflow job
|
|
61
|
-
* await
|
|
60
|
+
* // In a workflow job body:
|
|
61
|
+
* await worker.start(args, {
|
|
62
62
|
* executionPolicyKey: executionPolicies.premium.key,
|
|
63
63
|
* });
|
|
64
|
-
* await
|
|
64
|
+
* await worker.start(args, {
|
|
65
65
|
* executionPolicyKey: executionPolicies["tenant-api"].keyFor(input.tenantId),
|
|
66
66
|
* });
|
|
67
67
|
*/
|
|
@@ -29,6 +29,11 @@ interface WorkflowJob<Name extends string = string, Input = undefined, Output =
|
|
|
29
29
|
* Start this job with the given input and return the job's output value.
|
|
30
30
|
* Accepts an optional second argument to pass `executionPolicyKey` for
|
|
31
31
|
* platform-side concurrency enforcement.
|
|
32
|
+
*
|
|
33
|
+
* Must be called from within another job's `body` (a function defined
|
|
34
|
+
* inside `body` may call it too) — not from a function defined outside
|
|
35
|
+
* `body`. The build cannot see through that indirection to find the call,
|
|
36
|
+
* and fails instead of silently dropping it.
|
|
32
37
|
* @example
|
|
33
38
|
* body: async (input) => {
|
|
34
39
|
* const a = jobA.start({ id: input.id });
|
|
@@ -63,9 +68,14 @@ interface CreateWorkflowJobConfig<Name extends string, I, O> {
|
|
|
63
68
|
* Input and output must be JsonValue-compatible (primitives, plain objects, arrays).
|
|
64
69
|
* Functions and objects with a `toJSON` method are rejected at the type level;
|
|
65
70
|
* class instances exposing methods are rejected via the property walk.
|
|
71
|
+
* `name` and `body` must be written directly in this call — as a string literal and an
|
|
72
|
+
* inline function expression, respectively — not as a reference to a variable or the
|
|
73
|
+
* result of another function call. The build cannot see through that indirection to find
|
|
74
|
+
* the job, and fails instead of silently leaving it out.
|
|
66
75
|
* @param config - Job configuration with name and body function.
|
|
67
|
-
* @param config.name - Unique job name across the project.
|
|
68
|
-
* @param config.body - Function that processes the job input.
|
|
76
|
+
* @param config.name - Unique job name across the project. Must be a string literal.
|
|
77
|
+
* @param config.body - Function that processes the job input. Must be an inline function
|
|
78
|
+
* expression, not a reference to a separately-defined function.
|
|
69
79
|
* @returns A WorkflowJob that can be started from other jobs.
|
|
70
80
|
* @example
|
|
71
81
|
* // Simple job with async body:
|
|
@@ -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 };
|
|
@@ -67,4 +67,4 @@ interface TailorField<Defined extends DefinedFieldMetadata = DefinedFieldMetadat
|
|
|
67
67
|
}
|
|
68
68
|
type TailorAnyField = TailorField<any>;
|
|
69
69
|
//#endregion
|
|
70
|
-
export {
|
|
70
|
+
export { DefinedFieldMetadata, EnumValue, FieldMetadata, FieldOptions, FieldOutput, FieldValidateInput, TailorAnyField, TailorField, TailorFieldType, TailorToTs };
|
|
@@ -17,4 +17,4 @@ type UserBooleanArrayOperand<User extends object = InferredAttributes> = {
|
|
|
17
17
|
user: BooleanArrayFieldKeys<User>;
|
|
18
18
|
};
|
|
19
19
|
//#endregion
|
|
20
|
-
export {
|
|
20
|
+
export { BooleanFieldKeys, StringFieldKeys, UserBooleanArrayOperand, UserBooleanOperand, UserStringArrayOperand, UserStringOperand };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-
|
|
1
|
+
{"version":3,"file":"context-D0QjfxzD.mjs","names":[],"sources":["../src/runtime/context.ts"],"sourcesContent":["/**\n * Execution context utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.context` runtime API.\n * At runtime this delegates to `globalThis.tailor.context`.\n * @example\n * import { context } from \"@tailor-platform/sdk/runtime\";\n *\n * const invoker = context.getInvoker();\n * if (invoker) {\n * console.log(invoker.id, invoker.type, invoker.attributes, invoker.attributeList);\n * }\n */\n\nimport type { TailorPrincipal } from \"#/runtime/types\";\n\n/**\n * Information about the invoker of the current function execution.\n *\n * Matches the public `TailorPrincipal` shape — `attributes` is the attribute\n * map and `attributeList` is the array of attribute IDs.\n */\nexport type Invoker = TailorPrincipal;\n\n/**\n * Raw platform-side invoker payload returned by `tailor.context.getInvoker()`.\n * The wrapper normalizes this into {@link Invoker}.\n * @internal\n */\nexport interface ContextInvoker {\n /** The invoker's ID */\n id: string;\n /** The invoker's type */\n type: \"user\" | \"machine_user\";\n /** The workspace ID */\n workspaceId: string;\n /** The invoker's attribute IDs */\n attributes: string[];\n /** The invoker's attribute map */\n attributeMap: Record<string, unknown>;\n}\n\n/**\n * Platform API surface for `tailor.context`. Describes the shape the platform\n * runtime injects on `globalThis.tailor.context`.\n * @internal\n */\nexport interface PlatformContextAPI {\n getInvoker(): ContextInvoker | null;\n}\n\n/** Runtime wrapper API for execution context utilities. */\nexport interface TailorContextAPI {\n /**\n * Returns information about the current invoker.\n * @returns Invoker details, or `null` for anonymous invocations\n */\n getInvoker(): Invoker | null;\n}\n\n/**\n * Returns information about the invoker of the current function execution,\n * or `null` for anonymous invocations.\n * @returns Invoker details, or `null` when the call is anonymous\n */\nfunction getInvoker(): Invoker | null {\n const raw = (\n globalThis as unknown as { tailor: { context: PlatformContextAPI } }\n ).tailor.context.getInvoker();\n if (!raw) return null;\n return {\n id: raw.id,\n type: raw.type,\n workspaceId: raw.workspaceId,\n attributes: raw.attributeMap as Invoker[\"attributes\"],\n attributeList: raw.attributes as Invoker[\"attributeList\"],\n };\n}\n\n/** Runtime wrapper namespace for `tailor.context`. */\nexport const context = { getInvoker } as const satisfies TailorContextAPI;\n"],"mappings":"AAiEA,SAAS,YAA6B,CACpC,IAAM,EACJ,WACA,OAAO,QAAQ,WAAW,EAE5B,OADK,EACE,CACL,GAAI,EAAI,GACR,KAAM,EAAI,KACV,YAAa,EAAI,YACjB,WAAY,EAAI,aAChB,cAAe,EAAI,UACrB,EAPiB,IAQnB,CAGA,MAAa,EAAU,CAAE,UAAW"}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import{n as e}from"./logger-BcGy-u7G.mjs";import{t}from"./package-json-C690ceex.mjs";import{n}from"./user-agent-vdHYF3QL.mjs";import{r,t as i}from"./secret-file-C9wp_FCX.mjs";import*as a from"pathe";import*as o from"node:fs";import{parseYAML as s}from"confbox";import{xdgConfig as c}from"xdg-basedir";import*as l from"node:crypto";import{isCI as u}from"std-env";import*as d from"node:os";function parseCrashReportConfig(){if(u)return{localEnabled:!1,remoteEnabled:!1,localDir:``};let e=(process.env.TAILOR_CRASH_REPORTS_LOCAL??`on`).toLowerCase()!==`off`,t=(process.env.TAILOR_CRASH_REPORTS_REMOTE??`off`).toLowerCase()===`on`,n=c?a.join(c,`tailor-platform`,`crash-reports`):``;return{localEnabled:e&&n!==``,remoteEnabled:t,localDir:n}}const f=`--- JSON ---`,p=`.crash.log`;function formatCrashReport(e){return[`Crash Report: ${e.id}`,`Timestamp: ${e.timestamp}`,`Error Type: ${e.errorType}`,``,`--- Environment ---`,`SDK Version: ${e.sdkVersion}`,`Node Version: ${e.nodeVersion}`,`OS: ${e.osPlatform} ${e.osRelease}`,`Arch: ${e.arch}`,``,`--- Command ---`,`Command: ${e.command}`,`Arguments: ${JSON.stringify(e.argv)}`,``,`--- Error ---`,`Name: ${e.errorName}`,`Message: ${e.errorMessage}`,``,`--- Stack Trace ---`,e.stackTrace||`(no stack trace available)`,``,f,JSON.stringify(e),``].join(`
|
|
2
|
+
`)}function generateFilename(e){return`${e.timestamp.replace(/[:.]/g,`-`)}-${e.id.slice(0,8)}${p}`}function cleanupOldFiles(e){try{let t=o.readdirSync(e).filter(e=>e.endsWith(p)).toSorted().toReversed();for(let n of t.slice(10))o.unlinkSync(a.join(e,n))}catch{}}function writeCrashReport(e,t){try{i(t);let n=generateFilename(e),o=a.join(t,n),s=formatCrashReport(e);return r(o,s),cleanupOldFiles(t),o}catch{return}}async function sendCrashReport(e,t){try{let n=process.env.TAILOR_CRASH_REPORT_ENDPOINT||`https://sdk-error-tracking-926vh9t4cl.erp.dev/query`,r=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,"User-Agent":t},body:JSON.stringify({query:`
|
|
3
|
+
mutation SubmitCrashReport(
|
|
4
|
+
$id: String!
|
|
5
|
+
$timestamp: String!
|
|
6
|
+
$sdkVersion: String!
|
|
7
|
+
$nodeVersion: String!
|
|
8
|
+
$osPlatform: String!
|
|
9
|
+
$osRelease: String!
|
|
10
|
+
$arch: String!
|
|
11
|
+
$command: String!
|
|
12
|
+
$argv: [String]
|
|
13
|
+
$errorName: String!
|
|
14
|
+
$errorMessage: String!
|
|
15
|
+
$stackTrace: String
|
|
16
|
+
$errorType: String!
|
|
17
|
+
$userId: String
|
|
18
|
+
$userEmail: String
|
|
19
|
+
) {
|
|
20
|
+
submitCrashReport(
|
|
21
|
+
id: $id
|
|
22
|
+
timestamp: $timestamp
|
|
23
|
+
sdkVersion: $sdkVersion
|
|
24
|
+
nodeVersion: $nodeVersion
|
|
25
|
+
osPlatform: $osPlatform
|
|
26
|
+
osRelease: $osRelease
|
|
27
|
+
arch: $arch
|
|
28
|
+
command: $command
|
|
29
|
+
argv: $argv
|
|
30
|
+
errorName: $errorName
|
|
31
|
+
errorMessage: $errorMessage
|
|
32
|
+
stackTrace: $stackTrace
|
|
33
|
+
errorType: $errorType
|
|
34
|
+
userId: $userId
|
|
35
|
+
userEmail: $userEmail
|
|
36
|
+
) {
|
|
37
|
+
success
|
|
38
|
+
}
|
|
39
|
+
}`,variables:e}),signal:AbortSignal.timeout(5e3)});if(!r.ok)return!1;let i=await r.json();return!i.errors?.length&&i.data?.submitCrashReport.success===!0}catch{return!1}}const m=d.homedir(),h=/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,g=/\b[0-9a-fA-F]{32,}\b/g,_=/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/g,v=/(?:\/(?:[\w.@\- ]+\/)+[\w.@\- ]+)/g,y=/(?:[A-Za-z]:\\(?:[\w.@\- ]+\\)+[\w.@\- ]+)/g,b=/[?&][^?\s]*/g,x=/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/,S=/^[A-Za-z]:\\/,C=`packages/sdk/`;function lastSegment(e,t){return e.split(t).pop()??e}function sanitizeStackTrace(e){let t=e.search(/\n\s+at /),n;return n=t===-1?sanitizeMessage(e):sanitizeMessage(e.slice(0,t))+e.slice(t),n=n.replace(v,e=>{let t=e.indexOf(C);return t===-1?e.startsWith(m)?`~/<redacted>/${lastSegment(e,`/`)}`:`<external>/${lastSegment(e,`/`)}`:e.slice(t)}),n=n.replace(y,e=>{let t=e.replace(/\\/g,`/`),n=t.indexOf(C);return n===-1?`<external>/${lastSegment(e,`\\`)}`:t.slice(n)}),n}function sanitizeMessage(e){let t=e;return t=t.replace(/\nRequest:\s*[\s\S]*$/,`
|
|
40
|
+
Request: <redacted>`),t=t.replace(h,`<uuid>`),t=t.replace(g,`<redacted>`),t=t.replace(_,`<email>`),t=t.replace(b,`?<redacted>`),t=t.replace(v,e=>`<path>/${lastSegment(e,`/`)}`),t=t.replace(y,e=>`<path>/${lastSegment(e,`\\`)}`),t}function sanitizeArgv(e){let t=[],n=!1;for(let r of e){if(n){if(!r.startsWith(`-`)){t.push(`<redacted>`),n=!1;continue}n=!1}if(r.startsWith(`-`)){let e=r.indexOf(`=`);if(e!==-1){t.push(`${r.slice(0,e)}=<redacted>`);continue}t.push(r),n=!0;continue}if(r.startsWith(`/`)&&r.includes(`/`,1)){t.push(`<path>`);continue}if(S.test(r)){t.push(`<path>`);continue}if(x.test(r)){t.push(`<email>`);continue}t.push(r)}return t}function parseCommand(){let e=process.argv.slice(2),t=[];for(let n of e){if(n.startsWith(`-`)||t.length>=3)break;t.push(n)}return t.join(` `)||`<unknown>`}function buildCrashReport(e){let{error:t,sdkVersion:n,errorType:r}=e,i=t instanceof Error,a=i?t.message:String(t),o=i&&t.stack?t.stack:``,s=i?t.name:`UnknownError`,c=readCurrentUser();return{id:l.randomUUID(),timestamp:new Date().toISOString(),sdkVersion:n,nodeVersion:process.version,osPlatform:process.platform,osRelease:d.release(),arch:process.arch,command:sanitizeMessage(parseCommand()),argv:sanitizeArgv(process.argv),errorName:s,errorMessage:sanitizeMessage(a),stackTrace:sanitizeStackTrace(o),errorType:r,userId:c?.id??null,userEmail:c?.email??null}}function readCurrentUser(){try{if(!c)return null;let e=a.join(c,`tailor-platform`,`config.yaml`);if(!o.existsSync(e))return null;let t=s(o.readFileSync(e,`utf-8`)),n=t?.current_user??null;if(!n)return null;let r=t.users?.[n]?.email;return{id:n,email:typeof r==`string`?r:legacyEmail(n)}}catch{return null}}function legacyEmail(e){return e.includes(`@`)?e:null}async function reportCrash(r,i){try{let a=parseCrashReportConfig();if(!a.localEnabled&&!a.remoteEnabled)return;let o=(await t()).version??`unknown`,s=buildCrashReport({error:r,sdkVersion:o,errorType:i});if(a.localEnabled){let t=writeCrashReport(s,a.localDir);t&&e.log([``,`An unexpected error occurred. A crash report has been saved to:`,` ${t}`,``,`To submit this report:`,` tailor crashreport send --file "${t}"`].join(`
|
|
41
|
+
`))}a.remoteEnabled&&await sendCrashReport(s,n(o))}catch{}}function initCrashReporting(){let t=parseCrashReportConfig();if(!t.localEnabled&&!t.remoteEnabled)return;let handleFatal=(t,n)=>{let r=t instanceof Error?t.message:String(t);e.error(r),reportCrash(t,n).finally(()=>{process.exit(1)})};process.on(`uncaughtException`,e=>handleFatal(e,`uncaughtException`)),process.on(`unhandledRejection`,e=>handleFatal(e,`unhandledRejection`))}export{f as a,p as i,reportCrash as n,parseCrashReportConfig as o,sendCrashReport as r,initCrashReporting as t};
|
|
42
|
+
//# sourceMappingURL=crashreport-B-_HTKLr.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;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,IAA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,MAAM,SAAS,uBAAuB;EACtC,IAAI,CAAC,OAAO,gBAAgB,CAAC,OAAO,eAAe;EAGnD,MAAM,cAAa,MADO,gBAAgB,EACZ,CAAC,WAAW;EAE1C,MAAM,SAAS,iBAAiB;GAAE;GAAO;GAAY;EAAU,CAAC;EAEhE,IAAI,OAAO,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,eAET,MAAM,gBAAgB,QADX,qBAAqB,UACD,CAAC;CAEpC,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
|
+
{"version":3,"file":"crashreport-B-_HTKLr.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":"oYAiBA,SAAgB,wBAA4C,CAC1D,GAAI,EACF,MAAO,CACL,aAAc,GACd,cAAe,GACf,SAAU,EACZ,EAGF,IAAM,GAAgB,QAAQ,IAAI,4BAA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+1,2 @@
|
|
|
1
|
+
import{r as e}from"./logger-BcGy-u7G.mjs";function shellQuote(e){return process.platform===`win32`?/^[A-Za-z0-9_./:=@+\\-]+$/.test(e)?e:`"${e.replaceAll(`"`,`\\"`)}"`:/^[A-Za-z0-9_./:=@+-]+$/.test(e)?e:`'${e.replaceAll(`'`,`'"'"'`)}'`}function needsArgvRendering(e){return process.platform===`win32`&&e.some(e=>/[%$!]/.test(e))}function formatCopyableCommand(e){return needsArgvRendering(e)?`argv ${JSON.stringify(e)}`:e.map(shellQuote).join(` `)}function formatNextAction(e){let t=[e.command,...e.args],n=formatCopyableCommand(t);return needsArgvRendering(t)?`with ${n}`:`\`${n}\``}function formatError(t){let n=[e.error(`Error${t.code?` [${t.code}]`:``}: ${t.message}`)];return t.details&&n.push(`\n ${e.dim(`Details:`)} ${t.details}`),t.suggestion&&n.push(`\n ${e.info(`Suggestion:`)} ${t.suggestion}`),t.command&&n.push(`\n ${e.dim(`Help:`)} Run \`tailor ${t.command} --help\` for usage information.`),t.next&&n.push(`\n ${e.info(`Next:`)} Run ${formatNextAction(t.next)}.`),n.join(``)}function createCLIError(e){let t=Error(e.message);return t.name=`CLIError`,t.code=e.code,t.details=e.details,t.suggestion=e.suggestion,t.command=e.command,t.next=e.next,t.context=e.context,t.format=()=>formatError(t),t}function isCLIError(e){return e instanceof Error&&e.name===`CLIError`}function toError(e){return e instanceof Error?e:Error(String(e))}const t=/does not provide an export named '(?!default')([^']+)'/;function typeOnlyImportHint(e){if(!(e instanceof SyntaxError))return;let n=t.exec(e.message)?.[1];if(n)return`If '${n}' 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.`}export{toError as a,isCLIError as i,formatCopyableCommand as n,typeOnlyImportHint as o,formatNextAction as r,createCLIError as t};
|
|
2
|
+
//# sourceMappingURL=errors-DSEXKRVD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors-DSEXKRVD.mjs","names":[],"sources":["../src/cli/shared/errors.ts"],"sourcesContent":["import { styles } from \"./logger\";\n\n/**\n * Options for creating a CLI error\n */\ninterface 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/**\n * Convert a caught value into an Error, keeping Error instances as-is\n * @param value - Caught value\n * @returns The value itself when it is an Error, otherwise an Error of its string form\n */\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\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":"0CA6CA,SAAS,WAAW,EAAuB,CAMzC,OALI,QAAQ,WAAa,QACnB,2BAA2B,KAAK,CAAK,EAAU,EAC5C,IAAI,EAAM,WAAW,IAAK,KAAK,EAAE,GAEtC,yBAAyB,KAAK,CAAK,EAAU,EAC1C,IAAI,EAAM,WAAW,IAAK,OAAO,EAAE,EAC5C,CAEA,SAAS,mBAAmB,EAAkC,CAG5D,OAAO,QAAQ,WAAa,SAAW,EAAK,KAAM,GAAU,QAAQ,KAAK,CAAK,CAAC,CACjF,CAOA,SAAgB,sBAAsB,EAAiC,CAIrE,OAHI,mBAAmB,CAAI,EAClB,QAAQ,KAAK,UAAU,CAAI,IAE7B,EAAK,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG,CACtC,CAOA,SAAgB,iBAAiB,EAAkC,CACjE,IAAM,EAAO,CAAC,EAAK,QAAS,GAAG,EAAK,IAAI,EAClC,EAAW,sBAAsB,CAAI,EAC3C,OAAO,mBAAmB,CAAI,EAAI,QAAQ,IAAa,KAAK,EAAS,GACvE,CAOA,SAAS,YAAY,EAAyB,CAC5C,IAAM,EAAkB,CACtB,EAAO,MAAM,QAAQ,EAAM,KAAO,KAAK,EAAM,KAAK,GAAK,GAAG,IAAI,EAAM,SAAS,CAC/E,EAoBA,OAlBI,EAAM,SACR,EAAM,KAAK,OAAO,EAAO,IAAI,UAAU,EAAE,GAAG,EAAM,SAAS,EAGzD,EAAM,YACR,EAAM,KAAK,OAAO,EAAO,KAAK,aAAa,EAAE,GAAG,EAAM,YAAY,EAGhE,EAAM,SACR,EAAM,KACJ,OAAO,EAAO,IAAI,OAAO,EAAE,gBAAgB,EAAM,QAAQ,iCAC3D,EAGE,EAAM,MACR,EAAM,KAAK,OAAO,EAAO,KAAK,OAAO,EAAE,OAAO,iBAAiB,EAAM,IAAI,EAAE,EAAE,EAGxE,EAAM,KAAK,EAAE,CACtB,CAOA,SAAS,eAAe,EAAoC,CAC1D,IAAM,EAAY,MAAM,EAAQ,OAAO,EASvC,MARA,GAAM,KAAO,WACb,EAAM,KAAO,EAAQ,KACrB,EAAM,QAAU,EAAQ,QACxB,EAAM,WAAa,EAAQ,WAC3B,EAAM,QAAU,EAAQ,QACxB,EAAM,KAAO,EAAQ,KACrB,EAAM,QAAU,EAAQ,QACxB,EAAM,WAAe,YAAY,CAAK,EAC/B,CACT,CAOA,SAAgB,WAAW,EAAmC,CAC5D,OAAO,aAAiB,OAAS,EAAM,OAAS,UAClD,CAOA,SAAgB,QAAQ,EAAuB,CAC7C,OAAO,aAAiB,MAAQ,EAAY,MAAM,OAAO,CAAK,CAAC,CACjE,CAEA,MAAM,EAA+B,yDASrC,SAAgB,mBAAmB,EAAoC,CACrE,GAAI,EAAE,aAAiB,aAAc,OACrC,IAAM,EAAO,EAA6B,KAAK,EAAM,OAAO,CAAC,GAAG,GAC3D,KACL,MACE,OAAO,EAAK,mRAIhB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const api=()=>globalThis.tailordb.file,e={upload:(...e)=>api().upload(...e),download:(...e)=>api().download(...e),downloadAsBase64:(...e)=>api().downloadAsBase64(...e),delete:(...e)=>api().delete(...e),getMetadata:(...e)=>api().getMetadata(...e),downloadStream:(...e)=>api().downloadStream(...e),uploadStream:(...e)=>api().uploadStream(...e)};export{e as t};
|
|
2
|
+
//# sourceMappingURL=file-COPYfju_.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"file-COPYfju_.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 tableName - 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 tableName: 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 tableName - 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 tableName: 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 tableName - 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 tableName: 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 tableName - 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, tableName: string, fieldName: string, recordId: string): Promise<void>;\n\n /**\n * Get file metadata from TailorDB.\n * @param namespace - TailorDB namespace\n * @param tableName - 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 tableName: 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 tableName - 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 tableName: 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 tableName - 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 tableName: 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,QACH,WAAkE,SAAS,KAsDjE,EAAO,CAClB,QAhDyC,GAAG,IAAS,IAAI,CAAC,CAAC,OAAO,GAAG,CAAI,EAiDzE,UA1C6C,GAAG,IAAS,IAAI,CAAC,CAAC,SAAS,GAAG,CAAI,EA2C/E,kBApC6D,GAAG,IAChE,IAAI,CAAC,CAAC,iBAAiB,GAAG,CAAI,EAoC9B,QA7B6C,GAAG,IAAS,IAAI,CAAC,CAAC,OAAO,GAAG,CAAI,EA8B7E,aAvBmD,GAAG,IAAS,IAAI,CAAC,CAAC,YAAY,GAAG,CAAI,EAwBxF,gBAjByD,GAAG,IAC5D,IAAI,CAAC,CAAC,eAAe,GAAG,CAAI,EAiB5B,cAVqD,GAAG,IAAS,IAAI,CAAC,CAAC,aAAa,GAAG,CAAI,CAW7F"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./registry-HlEaGvl5.mjs";import{t}from"./platform-serialize-DkiTdHOt.mjs";function createDefaultWorkflowRuntime(){return{execJobFunction:e=>{throw Error(`No workflow job mock for "${e}". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`)},startWorkflow:async(n,r)=>(t(r),e),resumeWorkflowExecution:async e=>e,wait:e=>{throw Error(`No wait handler for "${e}". Acquire mockWorkflow() and call setWaitHandler(...).`)},resolve:async()=>{throw Error(`No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).`)}}}const n=`__tailorRuntimeActive`;var TailorErrorsMock=class extends Error{errors;constructor(e){if(!Array.isArray(e))throw TypeError(`TailorErrors: errors must be an array`);let t=e.map((e,t)=>{if(typeof e.message!=`string`)throw TypeError(`TailorErrors: errors[${t}].message must be a string`);if(!Array.isArray(e.path))throw TypeError(`TailorErrors: errors[${t}].path must be an array`);return{message:e.message,path:e.path}});super(`TailorErrors: ${JSON.stringify({errors:t})}`),this.name=`TailorErrors`,this.errors=t}},TailorDBFileErrorMock=class extends Error{code;cause;constructor(e,t,n){super(e),this.name=`TailorDBFileError`,this.code=t,this.cause=n}};function defaultGetInvoker(){return null}function noop(){}const r={debug:noop,info:noop,warn:noop,error:noop,setAttributes:noop};function installPlatformGlobals(e){let t=e;return t[n]=!0,t.tailor={context:{getInvoker:defaultGetInvoker},workflow:createDefaultWorkflowRuntime(),logger:{...r}},t.tailordb={},t.TailorErrors=TailorErrorsMock,t.TailorDBFileError=TailorDBFileErrorMock,{[Symbol.dispose](){cleanupPlatformGlobals(e)}}}function cleanupPlatformGlobals(e){let t=e;delete t.tailordb,delete t.tailor,delete t.TailorErrors,delete t.TailorDBFileError,delete t[n]}export{cleanupPlatformGlobals as n,installPlatformGlobals as r,n as t};
|
|
2
|
+
//# sourceMappingURL=globals-CMHSnj4w.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"globals-
|
|
1
|
+
{"version":3,"file":"globals-CMHSnj4w.mjs","names":[],"sources":["../src/vitest/workflow-runtime.ts","../src/vitest/globals.ts"],"sourcesContent":["// Default `tailor.workflow` runner installed by the `tailor-runtime` environment.\n// Must stay free of `vitest` (`vi`): it loads via `./globals` in the environment\n// realm where `vi` is unavailable, hence relative imports only (no `@/` alias).\nimport { START_DEFAULT } from \"../configure/services/workflow/registry\";\nimport { platformSerialize } from \"../utils/test/platform-serialize\";\nimport type { ExecJobFunctionOptions, StartWorkflowOptions } from \"../runtime/workflow\";\n\nexport interface DefaultWorkflowRuntime {\n execJobFunction: (name: string, args?: unknown, options?: ExecJobFunctionOptions) => unknown;\n startWorkflow: (name: string, args?: unknown, options?: StartWorkflowOptions) => Promise<string>;\n resumeWorkflowExecution: (executionId: string) => Promise<string>;\n wait: (key: string, payload?: unknown) => unknown;\n resolve: (\n executionId: string,\n key: string,\n callback: (payload: unknown) => unknown,\n ) => Promise<void>;\n}\n\nexport function createDefaultWorkflowRuntime(): DefaultWorkflowRuntime {\n const execJobFunction: DefaultWorkflowRuntime[\"execJobFunction\"] = (name) => {\n throw new Error(\n `No workflow job mock for \"${name}\". Acquire mockWorkflow() and call setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`,\n );\n };\n const startWorkflow: DefaultWorkflowRuntime[\"startWorkflow\"] = async (_name, args) => {\n platformSerialize(args);\n return START_DEFAULT;\n };\n const resumeWorkflowExecution: DefaultWorkflowRuntime[\"resumeWorkflowExecution\"] = async (\n executionId,\n ) => executionId;\n return {\n execJobFunction,\n startWorkflow,\n resumeWorkflowExecution,\n wait: (key: string): unknown => {\n throw new Error(\n `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n );\n },\n resolve: async (): Promise<void> => {\n throw new Error(\n \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n );\n },\n };\n}\n","/**\n * Base platform globals for the tailor-runtime test environment.\n *\n * This module is intentionally free of any `vitest` (`vi`) dependency so it can\n * be imported from the Vitest *environment* module (which runs in a realm where\n * `vi` is not available). It installs only the always-present structural pieces:\n *\n * - `globalThis.tailor` / `globalThis.tailordb` container objects\n * - `globalThis.tailor.context.getInvoker` default stub\n * - the platform error classes (`TailorErrors`,\n * `TailorDBFileError`)\n * - the `__tailorRuntimeActive` sentinel flag\n *\n * The per-namespace mock behavior (TailorDB client, workflow, secretmanager, …)\n * is installed on demand by the `xMock()` factories in `./mock`, which run in\n * test context where `vi` *is* available.\n */\n\nimport { createDefaultWorkflowRuntime } from \"./workflow-runtime\";\nimport type { ContextInvoker } from \"../runtime/context\";\nimport type { TailorDBFileErrorCode } from \"../runtime/file\";\n\n// Sentinel set when the tailor-runtime environment is active. setup.ts reads it\n// to decide whether to run its blocked-globals lifecycle and config-secret\n// loading.\nexport const RUNTIME_FLAG_KEY = \"__tailorRuntimeActive\";\n\n// ---------------------------------------------------------------------------\n// Error class mocks\n// ---------------------------------------------------------------------------\n\ninterface TailorErrorItem {\n message: string;\n path: (string | number)[];\n}\n\nclass TailorErrorsMock extends Error {\n errors: TailorErrorItem[];\n\n constructor(errors: TailorErrorItem[]) {\n if (!Array.isArray(errors)) {\n throw new TypeError(\"TailorErrors: errors must be an array\");\n }\n const validated = errors.map((e, i) => {\n if (typeof e.message !== \"string\") {\n throw new TypeError(`TailorErrors: errors[${i}].message must be a string`);\n }\n if (!Array.isArray(e.path)) {\n throw new TypeError(`TailorErrors: errors[${i}].path must be an array`);\n }\n return { message: e.message, path: e.path };\n });\n // Match the PF runtime's TailorErrors serialization, which prefixes the\n // JSON payload with \"TailorErrors: \". Other SDK code (e.g. apply\n // integration fixtures) strips this prefix before JSON.parse.\n super(`TailorErrors: ${JSON.stringify({ errors: validated })}`);\n this.name = \"TailorErrors\";\n this.errors = validated;\n }\n}\n\nclass TailorDBFileErrorMock extends Error {\n code?: TailorDBFileErrorCode;\n override cause: unknown;\n\n constructor(message: string, code?: TailorDBFileErrorCode, cause?: unknown) {\n super(message);\n this.name = \"TailorDBFileError\";\n this.code = code;\n this.cause = cause;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Base install / cleanup\n// ---------------------------------------------------------------------------\n\n// Stub-only injection. SDK consumers configure invokers at the body level\n// (resolver/executor/workflow `.body()` `invoker` arg) or, for bundled tests,\n// via `vi.spyOn(globalThis.tailor.context, \"getInvoker\")`.\nfunction defaultGetInvoker(): ContextInvoker | null {\n return null;\n}\n\n// No-op logger stub so `tailor.logger.*` calls in code under test don't throw\n// without an explicit `mockLogger()`. `mockLogger()` overlays vi.fn spies and\n// restores this on dispose.\nfunction noop(): void {}\nconst defaultLogger = {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n setAttributes: noop,\n};\n\n/**\n * Install the always-present base platform globals (containers, context stub,\n * error classes, runtime flag). Per-namespace mocks are layered on top by the\n * `xMock()` factories in `./mock`.\n *\n * Acquire with a `using` declaration and the globals are removed when the\n * scope exits; alternatively call `cleanupPlatformGlobals` yourself.\n * @param global - The global object to install into (typically `globalThis`)\n * @returns A `Disposable` that removes the installed globals\n */\nexport function installPlatformGlobals(global: typeof globalThis): Disposable {\n const g = global as Record<string, unknown>;\n\n g[RUNTIME_FLAG_KEY] = true;\n\n // Containers. Namespace mocks (secretmanager, …) are added to these by the\n // corresponding `xMock()` on acquisition. `workflow` carries a default\n // runner: job/wait/resolve calls throw a helpful error, and workflow starts\n // return a placeholder execution id, unless overlaid by `mockWorkflow()` or\n // `runWorkflowLocally()`.\n g.tailor = {\n context: { getInvoker: defaultGetInvoker },\n workflow: createDefaultWorkflowRuntime(),\n logger: { ...defaultLogger },\n };\n g.tailordb = {};\n\n g.TailorErrors = TailorErrorsMock;\n g.TailorDBFileError = TailorDBFileErrorMock;\n\n return {\n [Symbol.dispose]() {\n cleanupPlatformGlobals(global);\n },\n };\n}\n\n/**\n * Remove the base platform globals (and anything the namespace mocks layered on\n * top, since they live under the same containers).\n * @param global - The global object to clean up (typically `globalThis`)\n */\nexport function cleanupPlatformGlobals(global: typeof globalThis): void {\n const g = global as Record<string, unknown>;\n delete g.tailordb;\n delete g.tailor;\n delete g.TailorErrors;\n delete g.TailorDBFileError;\n delete g[RUNTIME_FLAG_KEY];\n}\n"],"mappings":"6FAmBA,SAAgB,8BAAuD,CAarE,MAAO,CACL,gBAbkE,GAAS,CAC3E,MAAU,MACR,6BAA6B,EAAK,uIACpC,CACF,EAUE,oBAToE,EAAO,KAC3E,EAAkB,CAAI,EACf,GAQP,6BALA,IACG,EAKH,KAAO,GAAyB,CAC9B,MAAU,MACR,wBAAwB,EAAI,wDAC9B,CACF,EACA,QAAS,SAA2B,CAClC,MAAU,MACR,6EACF,CACF,CACF,CACF,CCtBA,MAAa,EAAmB,wBAWhC,IAAM,iBAAN,cAA+B,KAAM,CACnC,OAEA,YAAY,EAA2B,CACrC,GAAI,CAAC,MAAM,QAAQ,CAAM,EACvB,MAAU,UAAU,uCAAuC,EAE7D,IAAM,EAAY,EAAO,KAAK,EAAG,IAAM,CACrC,GAAI,OAAO,EAAE,SAAY,SACvB,MAAU,UAAU,wBAAwB,EAAE,2BAA2B,EAE3E,GAAI,CAAC,MAAM,QAAQ,EAAE,IAAI,EACvB,MAAU,UAAU,wBAAwB,EAAE,wBAAwB,EAExE,MAAO,CAAE,QAAS,EAAE,QAAS,KAAM,EAAE,IAAK,CAC5C,CAAC,EAID,MAAM,iBAAiB,KAAK,UAAU,CAAE,OAAQ,CAAU,CAAC,GAAG,EAC9D,KAAK,KAAO,eACZ,KAAK,OAAS,CAChB,CACF,EAEM,sBAAN,cAAoC,KAAM,CACxC,KACA,MAEA,YAAY,EAAiB,EAA8B,EAAiB,CAC1E,MAAM,CAAO,EACb,KAAK,KAAO,oBACZ,KAAK,KAAO,EACZ,KAAK,MAAQ,CACf,CACF,EASA,SAAS,mBAA2C,CAClD,OAAO,IACT,CAKA,SAAS,MAAa,CAAC,CACvB,MAAM,EAAgB,CACpB,MAAO,KACP,KAAM,KACN,KAAM,KACN,MAAO,KACP,cAAe,IACjB,EAYA,SAAgB,uBAAuB,EAAuC,CAC5E,IAAM,EAAI,EAmBV,MAjBA,GAAE,GAAoB,GAOtB,EAAE,OAAS,CACT,QAAS,CAAE,WAAY,iBAAkB,EACzC,SAAU,6BAA6B,EACvC,OAAQ,CAAE,GAAG,CAAc,CAC7B,EACA,EAAE,SAAW,CAAC,EAEd,EAAE,aAAe,iBACjB,EAAE,kBAAoB,sBAEf,CACL,CAAC,OAAO,UAAW,CACjB,uBAAuB,CAAM,CAC/B,CACF,CACF,CAOA,SAAgB,uBAAuB,EAAiC,CACtE,IAAM,EAAI,EACV,OAAO,EAAE,SACT,OAAO,EAAE,OACT,OAAO,EAAE,aACT,OAAO,EAAE,kBACT,OAAO,EAAE,EACX"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const api=()=>globalThis.tailor.iconv,e={convert:(...e)=>api().convert(...e),convertBuffer:(...e)=>api().convertBuffer(...e),decode:(...e)=>api().decode(...e),encode:(...e)=>api().encode(...e),encodings:()=>api().encodings(),Iconv:class{impl;constructor(e,t){this.impl=new(api()).Iconv(e,t)}convert(e){return this.impl.convert(e)}}};export{e as t};
|
|
2
|
+
//# sourceMappingURL=iconv-DlFMt2gW.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"iconv-
|
|
1
|
+
{"version":3,"file":"iconv-DlFMt2gW.mjs","names":[],"sources":["../src/runtime/iconv.ts"],"sourcesContent":["/**\n * Character encoding conversion utilities.\n *\n * Thin typed wrapper around the platform-provided `tailor.iconv` runtime API.\n * At runtime this delegates to `globalThis.tailor.iconv`, which is provided by\n * the Tailor Platform Function runtime. Use `mockIconv` from\n * `@tailor-platform/sdk/vitest` to mock these calls in unit tests.\n * @example\n * import { iconv } from \"@tailor-platform/sdk/runtime\";\n *\n * const utf8 = iconv.convert(sjisBuffer, \"Shift_JIS\", \"UTF-8\"); // string\n * const sjis = iconv.convert(\"こんにちは\", \"UTF-8\", \"Shift_JIS\"); // Uint8Array\n *\n * const conv = new iconv.Iconv(\"Shift_JIS\", \"UTF-8\");\n * const out = conv.convert(sjisBuffer);\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** Instance methods exposed by `tailor.iconv.Iconv`. */\nexport interface IconvInstance {\n convert(input: string | Uint8Array | ArrayBuffer): string | Uint8Array;\n}\n\n/** Constructor shape for `tailor.iconv.Iconv`. */\nexport interface IconvConstructor {\n new (fromEncoding: string, toEncoding: string): IconvInstance;\n}\n\n/**\n * Platform API surface for `tailor.iconv`. Describes the shape the platform\n * runtime injects on `globalThis.tailor.iconv` so the wrapper and ambient\n * globals stay in sync.\n */\nexport interface TailorIconvAPI {\n /**\n * Convert a string or buffer between encodings.\n * @param str - Input data to convert\n * @param fromEncoding - Source encoding name\n * @param toEncoding - Target encoding name\n * @returns `string` when `toEncoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\n convert<T extends string>(\n str: string | Uint8Array | ArrayBuffer,\n fromEncoding: string,\n toEncoding: T,\n ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array;\n\n /**\n * Convert a buffer between encodings.\n * @param buffer - Input bytes to convert\n * @param fromEncoding - Source encoding name\n * @param toEncoding - Target encoding name\n * @returns `string` when `toEncoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\n convertBuffer<T extends string>(\n buffer: Uint8Array | ArrayBuffer,\n fromEncoding: string,\n toEncoding: T,\n ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array;\n\n /**\n * Decode a buffer to a UTF-8 string using the given source encoding.\n * @param buffer - Input bytes\n * @param encoding - Source encoding name\n * @returns Decoded UTF-8 string\n */\n decode(buffer: Uint8Array | ArrayBuffer, encoding: string): string;\n\n /**\n * Encode a UTF-8 string into the given target encoding.\n * @param str - Input string\n * @param encoding - Target encoding name\n * @returns `string` when `encoding` is `\"UTF8\"` or `\"UTF-8\"`, otherwise `Uint8Array`.\n */\n encode<T extends string>(\n str: string,\n encoding: T,\n ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array;\n\n /**\n * Returns the list of supported encoding names.\n * @returns Array of encoding names supported by the platform iconv runtime\n */\n encodings(): string[];\n\n /** Constructor for the stateful converter. */\n Iconv: IconvConstructor;\n}\n\nconst api = (): TailorIconvAPI =>\n (globalThis as unknown as { tailor: { iconv: TailorIconvAPI } }).tailor.iconv;\n\nconst convert: TailorIconvAPI[\"convert\"] = (...args) => api().convert(...args);\n\nconst convertBuffer: TailorIconvAPI[\"convertBuffer\"] = (...args) => api().convertBuffer(...args);\n\nconst decode: TailorIconvAPI[\"decode\"] = (...args) => api().decode(...args);\n\nconst encode: TailorIconvAPI[\"encode\"] = (...args) => api().encode(...args);\n\nconst encodings: TailorIconvAPI[\"encodings\"] = () => api().encodings();\n\n/**\n * Stateful converter for repeated conversions between a fixed encoding pair.\n * Compatible with the `node-iconv` API surface.\n */\nclass Iconv {\n private impl: IconvInstance;\n\n constructor(fromEncoding: string, toEncoding: string) {\n this.impl = new (api().Iconv)(fromEncoding, toEncoding);\n }\n\n /**\n * Convert input using this converter's fixed encoding pair.\n * @param input - Bytes or string to convert\n * @returns Encoded output (string for UTF-8 targets, otherwise `Uint8Array`).\n */\n convert(input: string | Uint8Array | ArrayBuffer): string | Uint8Array {\n return this.impl.convert(input);\n }\n}\n\n// Keep the object typed to the public API so the private wrapper class does not leak into d.ts.\n/** Runtime API for `tailor.iconv`. */\nexport const iconv: TailorIconvAPI = {\n convert,\n convertBuffer,\n decode,\n encode,\n encodings,\n Iconv,\n};\n"],"mappings":"AA0FA,MAAM,QACH,WAAgE,OAAO,MAmC7D,EAAwB,CACnC,SAlC0C,GAAG,IAAS,IAAI,CAAC,CAAC,QAAQ,GAAG,CAAI,EAmC3E,eAjCsD,GAAG,IAAS,IAAI,CAAC,CAAC,cAAc,GAAG,CAAI,EAkC7F,QAhCwC,GAAG,IAAS,IAAI,CAAC,CAAC,OAAO,GAAG,CAAI,EAiCxE,QA/BwC,GAAG,IAAS,IAAI,CAAC,CAAC,OAAO,GAAG,CAAI,EAgCxE,cA9BmD,IAAI,CAAC,CAAC,UAAU,EA+BnE,WAzBU,CACV,KAEA,YAAY,EAAsB,EAAoB,CACpD,KAAK,KAAO,IAAK,IAAI,EAAA,CAAE,MAAO,EAAc,CAAU,CACxD,CAOA,QAAQ,EAA+D,CACrE,OAAO,KAAK,KAAK,QAAQ,CAAK,CAChC,CACF,CAWA"}
|