@polyester/sdk 0.6.0 → 0.8.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 +28 -0
- package/dist/gen/auth/v1/address_book_pb.d.ts +8 -0
- package/dist/gen/auth/v1/address_book_pb.d.ts.map +1 -1
- package/dist/gen/auth/v1/address_book_pb.js +1 -1
- package/dist/gen/auth/v1/address_book_pb.js.map +1 -1
- package/dist/gen/auth/v1/api_keys_pb.d.ts +1 -1
- package/dist/gen/auth/v1/api_keys_pb.js.map +1 -1
- package/dist/gen/auth/v1/auth_pb.d.ts +7 -1
- package/dist/gen/auth/v1/auth_pb.d.ts.map +1 -1
- package/dist/gen/auth/v1/auth_pb.js +7 -1
- package/dist/gen/auth/v1/auth_pb.js.map +1 -1
- package/dist/gen/auth/v1/policies_pb.d.ts +47 -337
- package/dist/gen/auth/v1/policies_pb.d.ts.map +1 -1
- package/dist/gen/auth/v1/policies_pb.js +49 -73
- package/dist/gen/auth/v1/policies_pb.js.map +1 -1
- package/dist/gen/orders/v1/orders_pb.d.ts +32 -1
- package/dist/gen/orders/v1/orders_pb.d.ts.map +1 -1
- package/dist/gen/orders/v1/orders_pb.js +25 -1
- package/dist/gen/orders/v1/orders_pb.js.map +1 -1
- package/dist/gen/triggers/v1/triggers_pb.d.ts +22 -2
- package/dist/gen/triggers/v1/triggers_pb.d.ts.map +1 -1
- package/dist/gen/triggers/v1/triggers_pb.js +7 -1
- package/dist/gen/triggers/v1/triggers_pb.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/services/address-book/address-book.d.ts +1 -1
- package/dist/services/address-book/address-book.js +1 -1
- package/dist/services/address-book/address-book.js.map +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts +27 -4
- package/dist/services/address-book/address-book.schemas.d.ts.map +1 -1
- package/dist/services/address-book/address-book.schemas.js +11 -5
- package/dist/services/address-book/address-book.schemas.js.map +1 -1
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +42 -42
- package/dist/services/orders/order-errors.schemas.d.ts +1 -1
- package/dist/services/orders/orders-batch.schemas.d.ts +20 -20
- package/dist/services/orders/orders-input.schemas.d.ts +4 -4
- package/dist/services/orders/orders-modify.schemas.d.ts +3 -2
- package/dist/services/orders/orders-modify.schemas.d.ts.map +1 -1
- package/dist/services/orders/orders-modify.schemas.js +5 -3
- package/dist/services/orders/orders-modify.schemas.js.map +1 -1
- package/dist/services/orders/orders-output.schemas.d.ts +6 -6
- package/dist/services/orders/orders.d.ts +1 -1
- package/dist/services/orders/orders.js +1 -1
- package/dist/services/orders/orders.js.map +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.d.ts +2 -2
- package/dist/services/policies/api-key-policies/api-key-policies.js +2 -2
- package/dist/services/policies/api-key-policies/api-key-policies.js.map +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +15 -140
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts.map +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.js +5 -53
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.js.map +1 -1
- package/dist/services/policies/shared.codecs.js +4 -12
- package/dist/services/policies/shared.codecs.js.map +1 -1
- package/dist/services/policies/shared.d.ts +1 -1
- package/dist/services/policies/shared.d.ts.map +1 -1
- package/dist/services/policies/shared.js +3 -11
- package/dist/services/policies/shared.js.map +1 -1
- package/dist/services/policies/subaccount-policies/subaccount-policies.d.ts +1 -1
- package/dist/services/policies/subaccount-policies/subaccount-policies.js +1 -1
- package/dist/services/policies/subaccount-policies/subaccount-policies.js.map +1 -1
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts +10 -206
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts.map +1 -1
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js +9 -115
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js.map +1 -1
- package/dist/services/social-verification/social-verification.schemas.d.ts +10 -2
- package/dist/services/social-verification/social-verification.schemas.d.ts.map +1 -1
- package/dist/services/social-verification/social-verification.schemas.js +4 -2
- package/dist/services/social-verification/social-verification.schemas.js.map +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +5 -5
- package/dist/services/triggers/trigger-input.schemas.d.ts +14 -7
- package/dist/services/triggers/trigger-input.schemas.d.ts.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.js +13 -3
- package/dist/services/triggers/trigger-input.schemas.js.map +1 -1
- package/dist/services/triggers/triggers-output.schemas.d.ts +15 -15
- package/dist/services/triggers/triggers.codecs.js +6 -3
- package/dist/services/triggers/triggers.codecs.js.map +1 -1
- package/dist/services/triggers/triggers.d.ts +2 -2
- package/dist/services/triggers/triggers.js +2 -2
- package/dist/services/triggers/triggers.js.map +1 -1
- package/dist/services/triggers/triggers.types.d.ts +3 -3
- package/dist/shared/connect-error-mapping.d.ts.map +1 -1
- package/dist/shared/connect-error-mapping.js +1 -0
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/schemas.js +2 -2
- package/dist/shared/schemas.js.map +1 -1
- package/dist/shared/transports.js +6 -1
- package/dist/shared/transports.js.map +1 -1
- package/dist/shared/wire-bounds.js +3 -1
- package/dist/shared/wire-bounds.js.map +1 -1
- package/dist/utils/numbers.js +1 -10
- package/dist/utils/numbers.js.map +1 -1
- package/package.json +1 -1
|
@@ -31,62 +31,62 @@ declare const CreateTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSche
|
|
|
31
31
|
type CreateTriggerResult = v.InferOutput<typeof CreateTriggerResultSchema>;
|
|
32
32
|
declare const CancelTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
33
33
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
34
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
34
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused">]>;
|
|
35
35
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
36
36
|
}, undefined>, v.TransformAction<{
|
|
37
37
|
triggerId: string;
|
|
38
|
-
status: "unspecified" | "
|
|
38
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
39
39
|
tsNs: bigint;
|
|
40
40
|
}, {
|
|
41
41
|
ts: number;
|
|
42
42
|
tsNs: string;
|
|
43
43
|
triggerId: string;
|
|
44
|
-
status: "unspecified" | "
|
|
44
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
45
45
|
}>]>;
|
|
46
46
|
type CancelTriggerResult = v.InferOutput<typeof CancelTriggerResultSchema>;
|
|
47
47
|
declare const ModifyTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
48
48
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
49
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
49
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused">]>;
|
|
50
50
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
51
51
|
}, undefined>, v.TransformAction<{
|
|
52
52
|
triggerId: string;
|
|
53
|
-
status: "unspecified" | "
|
|
53
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
54
54
|
tsNs: bigint;
|
|
55
55
|
}, {
|
|
56
56
|
ts: number;
|
|
57
57
|
tsNs: string;
|
|
58
58
|
triggerId: string;
|
|
59
|
-
status: "unspecified" | "
|
|
59
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
60
60
|
}>]>;
|
|
61
61
|
type ModifyTriggerResult = v.InferOutput<typeof ModifyTriggerResultSchema>;
|
|
62
62
|
declare const PauseTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
63
63
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
64
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
64
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused">]>;
|
|
65
65
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
66
66
|
}, undefined>, v.TransformAction<{
|
|
67
67
|
triggerId: string;
|
|
68
|
-
status: "unspecified" | "
|
|
68
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
69
69
|
tsNs: bigint;
|
|
70
70
|
}, {
|
|
71
71
|
ts: number;
|
|
72
72
|
tsNs: string;
|
|
73
73
|
triggerId: string;
|
|
74
|
-
status: "unspecified" | "
|
|
74
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
75
75
|
}>]>;
|
|
76
76
|
type PauseTriggerResult = v.InferOutput<typeof PauseTriggerResultSchema>;
|
|
77
77
|
declare const ResumeTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
78
78
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
79
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
79
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused">]>;
|
|
80
80
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
81
81
|
}, undefined>, v.TransformAction<{
|
|
82
82
|
triggerId: string;
|
|
83
|
-
status: "unspecified" | "
|
|
83
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
84
84
|
tsNs: bigint;
|
|
85
85
|
}, {
|
|
86
86
|
ts: number;
|
|
87
87
|
tsNs: string;
|
|
88
88
|
triggerId: string;
|
|
89
|
-
status: "unspecified" | "
|
|
89
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
90
90
|
}>]>;
|
|
91
91
|
type ResumeTriggerResult = v.InferOutput<typeof ResumeTriggerResultSchema>;
|
|
92
92
|
type StopDetailsOutput = {
|
|
@@ -507,7 +507,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
507
507
|
subaccountId: string;
|
|
508
508
|
symbolId: number;
|
|
509
509
|
symbol: string;
|
|
510
|
-
status: "unspecified" | "
|
|
510
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
511
511
|
parentOrderId: string | undefined;
|
|
512
512
|
qty: string;
|
|
513
513
|
feeAsset: "unspecified" | "quote" | "base";
|
|
@@ -670,8 +670,8 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
670
670
|
triggerId: string;
|
|
671
671
|
subaccountId: string;
|
|
672
672
|
symbolId: number;
|
|
673
|
-
triggerType: "unspecified" | "
|
|
674
|
-
eventType: "unspecified" | "updated" | "fired" | "canceled";
|
|
673
|
+
triggerType: "unspecified" | "stop_loss" | "take_profit" | "trailing_stop" | "twap" | "ladder";
|
|
674
|
+
eventType: "unspecified" | "failed" | "updated" | "fired" | "canceled";
|
|
675
675
|
ts: number;
|
|
676
676
|
childSeq: number;
|
|
677
677
|
childOrderId: string | undefined;
|
|
@@ -21,7 +21,8 @@ const TRIGGER_STATUS_FILTER_VALUES = [
|
|
|
21
21
|
const TRIGGER_EVENT_TYPE_VALUES = [
|
|
22
22
|
"fired",
|
|
23
23
|
"canceled",
|
|
24
|
-
"updated"
|
|
24
|
+
"updated",
|
|
25
|
+
"failed"
|
|
25
26
|
];
|
|
26
27
|
const TriggerTypeCodec = {
|
|
27
28
|
inputToProto: {
|
|
@@ -65,13 +66,15 @@ const TriggerEventTypeCodec = {
|
|
|
65
66
|
inputToProto: {
|
|
66
67
|
fired: 1,
|
|
67
68
|
canceled: 2,
|
|
68
|
-
updated: 3
|
|
69
|
+
updated: 3,
|
|
70
|
+
failed: 4
|
|
69
71
|
},
|
|
70
72
|
protoToOutput: {
|
|
71
73
|
[0]: "unspecified",
|
|
72
74
|
[1]: "fired",
|
|
73
75
|
[2]: "canceled",
|
|
74
|
-
[3]: "updated"
|
|
76
|
+
[3]: "updated",
|
|
77
|
+
[4]: "failed"
|
|
75
78
|
}
|
|
76
79
|
};
|
|
77
80
|
const TriggerDirectionCodec = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"triggers.codecs.js","names":[],"sources":["../../../src/services/triggers/triggers.codecs.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport * as ProtoOrders from \"../../gen/orders/v1/orders_pb.js\";\nimport type { InputToProto, ProtoToOutput } from \"../../utils/types.js\";\nexport {\n FEE_ASSET_VALUES,\n FeeAssetCodec,\n type FeeAssetValue,\n ORDER_SIDE_VALUES as TRIGGER_SIDE_VALUES,\n ORDER_TYPE_VALUES,\n OrderSideCodec as TriggerSideCodec,\n type OrderSideValue as TriggerSideValue,\n OrderTypeCodec,\n type OrderTypeValue,\n SELF_TRADE_PREVENTION_MODE_VALUES,\n SelfTradePreventionModeCodec,\n type SelfTradePreventionModeValue,\n TIME_IN_FORCE_OUTPUT_VALUES,\n TIME_IN_FORCE_VALUES,\n TimeInForceCodec,\n type TimeInForceOutputValue,\n type TimeInForceValue,\n TRIGGER_PRICE_SOURCE_VALUES,\n TriggerPriceSourceCodec,\n type TriggerPriceSourceValue,\n} from \"../orders/order-enums.codecs.js\";\n\nexport const TRIGGER_TYPE_VALUES = [\n \"stop_loss\",\n \"take_profit\",\n \"trailing_stop\",\n \"twap\",\n \"ladder\",\n] as const;\nexport type TriggerTypeValue = (typeof TRIGGER_TYPE_VALUES)[number];\n\nexport const TRIGGER_TYPE_LABEL_VALUES = TRIGGER_TYPE_VALUES;\nexport type TriggerTypeLabelValue = (typeof TRIGGER_TYPE_LABEL_VALUES)[number];\n\nexport const TRIGGER_STATUS_FILTER_VALUES = [\n \"created\",\n \"armed\",\n \"running\",\n \"completed\",\n \"cancelled\",\n \"failed\",\n \"paused\",\n] as const;\nexport type TriggerStatusFilterValue = (typeof TRIGGER_STATUS_FILTER_VALUES)[number];\n\nexport const TRIGGER_STATUS_LABEL_VALUES = TRIGGER_STATUS_FILTER_VALUES;\nexport type TriggerStatusLabelValue = (typeof TRIGGER_STATUS_LABEL_VALUES)[number];\n\nexport const TRIGGER_EVENT_TYPE_VALUES = [\"fired\", \"canceled\", \"updated\"] as const;\nexport type TriggerEventTypeValue = (typeof TRIGGER_EVENT_TYPE_VALUES)[number];\n\nexport const TRIGGER_EVENT_TYPE_LABEL_VALUES = TRIGGER_EVENT_TYPE_VALUES;\nexport type TriggerEventTypeLabelValue = (typeof TRIGGER_EVENT_TYPE_LABEL_VALUES)[number];\n\nexport const TRIGGER_DIRECTION_VALUES = [\"above\", \"below\"] as const;\nexport type TriggerDirectionValue = (typeof TRIGGER_DIRECTION_VALUES)[number];\n\nexport const LADDER_DISTRIBUTION_VALUES = [\"linear\"] as const;\nexport type LadderDistributionValue = (typeof LADDER_DISTRIBUTION_VALUES)[number];\n\nexport const LADDER_DISTRIBUTION_LABEL_VALUES = [\n \"linear\",\n \"geometric\",\n \"weighted_favorable\",\n] as const;\nexport type LadderDistributionLabelValue = (typeof LADDER_DISTRIBUTION_LABEL_VALUES)[number];\n\nexport const TriggerTypeCodec = {\n inputToProto: {\n stop_loss: Proto.TriggerType.STOP_LOSS,\n take_profit: Proto.TriggerType.TAKE_PROFIT,\n trailing_stop: Proto.TriggerType.TRAILING_STOP,\n twap: Proto.TriggerType.TWAP,\n ladder: Proto.TriggerType.LADDER,\n } satisfies InputToProto<TriggerTypeValue, Proto.TriggerType>,\n protoToOutput: {\n [Proto.TriggerType.TRIGGER_TYPE_UNSPECIFIED]: \"unspecified\",\n [Proto.TriggerType.STOP_LOSS]: \"stop_loss\",\n [Proto.TriggerType.TAKE_PROFIT]: \"take_profit\",\n [Proto.TriggerType.TRAILING_STOP]: \"trailing_stop\",\n [Proto.TriggerType.TWAP]: \"twap\",\n [Proto.TriggerType.LADDER]: \"ladder\",\n } satisfies ProtoToOutput<Proto.TriggerType, TriggerTypeLabelValue>,\n} as const;\n\nexport const TriggerStatusCodec = {\n inputToProto: {\n created: Proto.TriggerStatus.STATUS_CREATED,\n armed: Proto.TriggerStatus.STATUS_ARMED,\n running: Proto.TriggerStatus.STATUS_RUNNING,\n completed: Proto.TriggerStatus.STATUS_COMPLETED,\n cancelled: Proto.TriggerStatus.STATUS_CANCELED,\n failed: Proto.TriggerStatus.STATUS_FAILED,\n paused: Proto.TriggerStatus.STATUS_PAUSED,\n } satisfies InputToProto<TriggerStatusFilterValue, Proto.TriggerStatus>,\n protoToOutput: {\n [Proto.TriggerStatus.STATUS_UNSPECIFIED]: \"unspecified\",\n [Proto.TriggerStatus.STATUS_CREATED]: \"created\",\n [Proto.TriggerStatus.STATUS_ARMED]: \"armed\",\n [Proto.TriggerStatus.STATUS_RUNNING]: \"running\",\n [Proto.TriggerStatus.STATUS_COMPLETED]: \"completed\",\n [Proto.TriggerStatus.STATUS_CANCELED]: \"cancelled\",\n [Proto.TriggerStatus.STATUS_FAILED]: \"failed\",\n [Proto.TriggerStatus.STATUS_PAUSED]: \"paused\",\n } satisfies ProtoToOutput<Proto.TriggerStatus, TriggerStatusLabelValue>,\n} as const;\n\nexport const TriggerEventTypeCodec = {\n inputToProto: {\n fired: Proto.TriggerEventType.EVENT_FIRED,\n canceled: Proto.TriggerEventType.EVENT_CANCELED,\n updated: Proto.TriggerEventType.EVENT_UPDATED,\n } satisfies InputToProto<TriggerEventTypeValue, Proto.TriggerEventType>,\n protoToOutput: {\n [Proto.TriggerEventType.EVENT_UNSPECIFIED]: \"unspecified\",\n [Proto.TriggerEventType.EVENT_FIRED]: \"fired\",\n [Proto.TriggerEventType.EVENT_CANCELED]: \"canceled\",\n [Proto.TriggerEventType.EVENT_UPDATED]: \"updated\",\n } satisfies ProtoToOutput<Proto.TriggerEventType, TriggerEventTypeLabelValue>,\n} as const;\n\nexport const TriggerDirectionCodec = {\n inputToProto: {\n above: ProtoOrders.TriggerDirection.ABOVE,\n below: ProtoOrders.TriggerDirection.BELOW,\n } satisfies InputToProto<TriggerDirectionValue, ProtoOrders.TriggerDirection>,\n protoToOutput: {\n [ProtoOrders.TriggerDirection.TRIGGER_DIRECTION_UNSPECIFIED]: \"unspecified\",\n [ProtoOrders.TriggerDirection.ABOVE]: \"above\",\n [ProtoOrders.TriggerDirection.BELOW]: \"below\",\n } satisfies ProtoToOutput<ProtoOrders.TriggerDirection, TriggerDirectionValue>,\n} as const;\n\nexport const LadderDistributionCodec = {\n inputToProto: {\n linear: Proto.LadderDistribution.LINEAR,\n } satisfies InputToProto<LadderDistributionValue, Proto.LadderDistribution>,\n protoToOutput: {\n [Proto.LadderDistribution.LADDER_DISTRIBUTION_UNSPECIFIED]: \"unspecified\",\n [Proto.LadderDistribution.LINEAR]: \"linear\",\n [Proto.LadderDistribution.GEOMETRIC]: \"geometric\",\n [Proto.LadderDistribution.WEIGHTED_FAVORABLE]: \"weighted_favorable\",\n } satisfies ProtoToOutput<Proto.LadderDistribution, LadderDistributionLabelValue>,\n} as const;\n"],"mappings":";;;;AA0BA,MAAa,sBAAsB;CAC/B;CACA;CACA;CACA;CACA;AACJ;AAMA,MAAa,+BAA+B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;AAMA,MAAa,4BAA4B;CAAC;CAAS;CAAY;
|
|
1
|
+
{"version":3,"file":"triggers.codecs.js","names":[],"sources":["../../../src/services/triggers/triggers.codecs.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport * as ProtoOrders from \"../../gen/orders/v1/orders_pb.js\";\nimport type { InputToProto, ProtoToOutput } from \"../../utils/types.js\";\nexport {\n FEE_ASSET_VALUES,\n FeeAssetCodec,\n type FeeAssetValue,\n ORDER_SIDE_VALUES as TRIGGER_SIDE_VALUES,\n ORDER_TYPE_VALUES,\n OrderSideCodec as TriggerSideCodec,\n type OrderSideValue as TriggerSideValue,\n OrderTypeCodec,\n type OrderTypeValue,\n SELF_TRADE_PREVENTION_MODE_VALUES,\n SelfTradePreventionModeCodec,\n type SelfTradePreventionModeValue,\n TIME_IN_FORCE_OUTPUT_VALUES,\n TIME_IN_FORCE_VALUES,\n TimeInForceCodec,\n type TimeInForceOutputValue,\n type TimeInForceValue,\n TRIGGER_PRICE_SOURCE_VALUES,\n TriggerPriceSourceCodec,\n type TriggerPriceSourceValue,\n} from \"../orders/order-enums.codecs.js\";\n\nexport const TRIGGER_TYPE_VALUES = [\n \"stop_loss\",\n \"take_profit\",\n \"trailing_stop\",\n \"twap\",\n \"ladder\",\n] as const;\nexport type TriggerTypeValue = (typeof TRIGGER_TYPE_VALUES)[number];\n\nexport const TRIGGER_TYPE_LABEL_VALUES = TRIGGER_TYPE_VALUES;\nexport type TriggerTypeLabelValue = (typeof TRIGGER_TYPE_LABEL_VALUES)[number];\n\nexport const TRIGGER_STATUS_FILTER_VALUES = [\n \"created\",\n \"armed\",\n \"running\",\n \"completed\",\n \"cancelled\",\n \"failed\",\n \"paused\",\n] as const;\nexport type TriggerStatusFilterValue = (typeof TRIGGER_STATUS_FILTER_VALUES)[number];\n\nexport const TRIGGER_STATUS_LABEL_VALUES = TRIGGER_STATUS_FILTER_VALUES;\nexport type TriggerStatusLabelValue = (typeof TRIGGER_STATUS_LABEL_VALUES)[number];\n\nexport const TRIGGER_EVENT_TYPE_VALUES = [\"fired\", \"canceled\", \"updated\", \"failed\"] as const;\nexport type TriggerEventTypeValue = (typeof TRIGGER_EVENT_TYPE_VALUES)[number];\n\nexport const TRIGGER_EVENT_TYPE_LABEL_VALUES = TRIGGER_EVENT_TYPE_VALUES;\nexport type TriggerEventTypeLabelValue = (typeof TRIGGER_EVENT_TYPE_LABEL_VALUES)[number];\n\nexport const TRIGGER_DIRECTION_VALUES = [\"above\", \"below\"] as const;\nexport type TriggerDirectionValue = (typeof TRIGGER_DIRECTION_VALUES)[number];\n\nexport const LADDER_DISTRIBUTION_VALUES = [\"linear\"] as const;\nexport type LadderDistributionValue = (typeof LADDER_DISTRIBUTION_VALUES)[number];\n\nexport const LADDER_DISTRIBUTION_LABEL_VALUES = [\n \"linear\",\n \"geometric\",\n \"weighted_favorable\",\n] as const;\nexport type LadderDistributionLabelValue = (typeof LADDER_DISTRIBUTION_LABEL_VALUES)[number];\n\nexport const TriggerTypeCodec = {\n inputToProto: {\n stop_loss: Proto.TriggerType.STOP_LOSS,\n take_profit: Proto.TriggerType.TAKE_PROFIT,\n trailing_stop: Proto.TriggerType.TRAILING_STOP,\n twap: Proto.TriggerType.TWAP,\n ladder: Proto.TriggerType.LADDER,\n } satisfies InputToProto<TriggerTypeValue, Proto.TriggerType>,\n protoToOutput: {\n [Proto.TriggerType.TRIGGER_TYPE_UNSPECIFIED]: \"unspecified\",\n [Proto.TriggerType.STOP_LOSS]: \"stop_loss\",\n [Proto.TriggerType.TAKE_PROFIT]: \"take_profit\",\n [Proto.TriggerType.TRAILING_STOP]: \"trailing_stop\",\n [Proto.TriggerType.TWAP]: \"twap\",\n [Proto.TriggerType.LADDER]: \"ladder\",\n } satisfies ProtoToOutput<Proto.TriggerType, TriggerTypeLabelValue>,\n} as const;\n\nexport const TriggerStatusCodec = {\n inputToProto: {\n created: Proto.TriggerStatus.STATUS_CREATED,\n armed: Proto.TriggerStatus.STATUS_ARMED,\n running: Proto.TriggerStatus.STATUS_RUNNING,\n completed: Proto.TriggerStatus.STATUS_COMPLETED,\n cancelled: Proto.TriggerStatus.STATUS_CANCELED,\n failed: Proto.TriggerStatus.STATUS_FAILED,\n paused: Proto.TriggerStatus.STATUS_PAUSED,\n } satisfies InputToProto<TriggerStatusFilterValue, Proto.TriggerStatus>,\n protoToOutput: {\n [Proto.TriggerStatus.STATUS_UNSPECIFIED]: \"unspecified\",\n [Proto.TriggerStatus.STATUS_CREATED]: \"created\",\n [Proto.TriggerStatus.STATUS_ARMED]: \"armed\",\n [Proto.TriggerStatus.STATUS_RUNNING]: \"running\",\n [Proto.TriggerStatus.STATUS_COMPLETED]: \"completed\",\n [Proto.TriggerStatus.STATUS_CANCELED]: \"cancelled\",\n [Proto.TriggerStatus.STATUS_FAILED]: \"failed\",\n [Proto.TriggerStatus.STATUS_PAUSED]: \"paused\",\n } satisfies ProtoToOutput<Proto.TriggerStatus, TriggerStatusLabelValue>,\n} as const;\n\nexport const TriggerEventTypeCodec = {\n inputToProto: {\n fired: Proto.TriggerEventType.EVENT_FIRED,\n canceled: Proto.TriggerEventType.EVENT_CANCELED,\n updated: Proto.TriggerEventType.EVENT_UPDATED,\n failed: Proto.TriggerEventType.EVENT_FAILED,\n } satisfies InputToProto<TriggerEventTypeValue, Proto.TriggerEventType>,\n protoToOutput: {\n [Proto.TriggerEventType.EVENT_UNSPECIFIED]: \"unspecified\",\n [Proto.TriggerEventType.EVENT_FIRED]: \"fired\",\n [Proto.TriggerEventType.EVENT_CANCELED]: \"canceled\",\n [Proto.TriggerEventType.EVENT_UPDATED]: \"updated\",\n [Proto.TriggerEventType.EVENT_FAILED]: \"failed\",\n } satisfies ProtoToOutput<Proto.TriggerEventType, TriggerEventTypeLabelValue>,\n} as const;\n\nexport const TriggerDirectionCodec = {\n inputToProto: {\n above: ProtoOrders.TriggerDirection.ABOVE,\n below: ProtoOrders.TriggerDirection.BELOW,\n } satisfies InputToProto<TriggerDirectionValue, ProtoOrders.TriggerDirection>,\n protoToOutput: {\n [ProtoOrders.TriggerDirection.TRIGGER_DIRECTION_UNSPECIFIED]: \"unspecified\",\n [ProtoOrders.TriggerDirection.ABOVE]: \"above\",\n [ProtoOrders.TriggerDirection.BELOW]: \"below\",\n } satisfies ProtoToOutput<ProtoOrders.TriggerDirection, TriggerDirectionValue>,\n} as const;\n\nexport const LadderDistributionCodec = {\n inputToProto: {\n linear: Proto.LadderDistribution.LINEAR,\n } satisfies InputToProto<LadderDistributionValue, Proto.LadderDistribution>,\n protoToOutput: {\n [Proto.LadderDistribution.LADDER_DISTRIBUTION_UNSPECIFIED]: \"unspecified\",\n [Proto.LadderDistribution.LINEAR]: \"linear\",\n [Proto.LadderDistribution.GEOMETRIC]: \"geometric\",\n [Proto.LadderDistribution.WEIGHTED_FAVORABLE]: \"weighted_favorable\",\n } satisfies ProtoToOutput<Proto.LadderDistribution, LadderDistributionLabelValue>,\n} as const;\n"],"mappings":";;;;AA0BA,MAAa,sBAAsB;CAC/B;CACA;CACA;CACA;CACA;AACJ;AAMA,MAAa,+BAA+B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;AAMA,MAAa,4BAA4B;CAAC;CAAS;CAAY;CAAW;AAAQ;AAmBlF,MAAa,mBAAmB;CAC5B,cAAc;EACV,WAAA;EACA,aAAA;EACA,eAAA;EACA,MAAA;EACA,QAAA;CACJ;CACA,eAAe;GACmC,IAAA;GACf,IAAA;GACE,IAAA;GACE,IAAA;GACT,IAAA;GACE,IAAA;CAChC;AACJ;AAEA,MAAa,qBAAqB;CAC9B,cAAc;EACV,SAAA;EACA,OAAA;EACA,SAAA;EACA,WAAA;EACA,WAAA;EACA,QAAA;EACA,QAAA;CACJ;CACA,eAAe;GAC+B,IAAA;GACJ,IAAA;GACF,IAAA;GACE,IAAA;GACE,IAAA;GACD,IAAA;GACF,IAAA;GACA,IAAA;CACzC;AACJ;AAEA,MAAa,wBAAwB;CACjC,cAAc;EACV,OAAA;EACA,UAAA;EACA,SAAA;EACA,QAAA;CACJ;CACA,eAAe;GACiC,IAAA;GACN,IAAA;GACG,IAAA;GACD,IAAA;GACD,IAAA;CAC3C;AACJ;AAEA,MAAa,wBAAwB;CACjC,cAAc;EACV,OAAA;EACA,OAAA;CACJ;CACA,eAAe;GACmD,IAAA;GACxB,IAAA;GACA,IAAA;CAC1C;AACJ;AAEA,MAAa,0BAA0B;CACnC,cAAc,EACV,QAAA,EACJ;CACA,eAAe;GACiD,IAAA;GACzB,IAAA;GACG,IAAA;GACS,IAAA;CACnD;AACJ"}
|
|
@@ -42,7 +42,7 @@ declare class TriggersService {
|
|
|
42
42
|
*/
|
|
43
43
|
cancel(input: CancelTriggerInput, options?: PolyesterMutationOptions): Promise<CancelTriggerResult>;
|
|
44
44
|
/**
|
|
45
|
-
* Applies a limited patch to an existing trigger
|
|
45
|
+
* Applies a limited patch to an existing trigger. The symbol ID routes policy checks for exposure-increasing changes.
|
|
46
46
|
*/
|
|
47
47
|
modify(input: ModifyTriggerInput, options?: PolyesterMutationOptions): Promise<ModifyTriggerResult>;
|
|
48
48
|
/**
|
|
@@ -50,7 +50,7 @@ declare class TriggersService {
|
|
|
50
50
|
*/
|
|
51
51
|
pause(input: PauseTriggerInput, options?: PolyesterMutationOptions): Promise<PauseTriggerResult>;
|
|
52
52
|
/**
|
|
53
|
-
* Resumes a paused trigger.
|
|
53
|
+
* Resumes a paused trigger using its symbol ID for policy checks.
|
|
54
54
|
*/
|
|
55
55
|
resume(input: ResumeTriggerInput, options?: PolyesterMutationOptions): Promise<ResumeTriggerResult>;
|
|
56
56
|
/**
|
|
@@ -84,7 +84,7 @@ var TriggersService = class {
|
|
|
84
84
|
return parse(CancelTriggerResultSchema, res);
|
|
85
85
|
}
|
|
86
86
|
/**
|
|
87
|
-
* Applies a limited patch to an existing trigger
|
|
87
|
+
* Applies a limited patch to an existing trigger. The symbol ID routes policy checks for exposure-increasing changes.
|
|
88
88
|
*/
|
|
89
89
|
async modify(input, options) {
|
|
90
90
|
await this.#scales.ready();
|
|
@@ -103,7 +103,7 @@ var TriggersService = class {
|
|
|
103
103
|
return parse(PauseTriggerResultSchema, res);
|
|
104
104
|
}
|
|
105
105
|
/**
|
|
106
|
-
* Resumes a paused trigger.
|
|
106
|
+
* Resumes a paused trigger using its symbol ID for policy checks.
|
|
107
107
|
*/
|
|
108
108
|
async resume(input, options) {
|
|
109
109
|
const resolved = resolveAccountScopedInput(input, this.#resolver);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"triggers.js","names":["#client","Proto.TriggersService","#realtime","#resolver","#scales","#createTriggerInputSchema","#modifyTriggerInputSchema","#triggerSchema","#triggerEventSchema","Proto.TriggerSchema","Proto.TriggerEventSchema"],"sources":["../../../src/services/triggers/triggers.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { createReadyGate, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n createCreateTriggerInputSchema,\n createModifyTriggerInputSchema,\n ListTriggersInputSchema,\n CancelTriggerInputSchema,\n PauseTriggerInputSchema,\n ResumeTriggerInputSchema,\n GetTriggerInputSchema,\n ListTriggerEventsInputSchema,\n CreateTriggerResultSchema,\n CancelTriggerResultSchema,\n ModifyTriggerResultSchema,\n PauseTriggerResultSchema,\n ResumeTriggerResultSchema,\n createTriggerSchema,\n createTriggerEventSchema,\n type Trigger,\n type CreateTriggerInput,\n type ListTriggersInput,\n type CancelTriggerInput,\n type GetTriggerInput,\n type ModifyTriggerInput,\n type PauseTriggerInput,\n type ResumeTriggerInput,\n type ListTriggerEventsInput,\n type CreateTriggerResult,\n type CancelTriggerResult,\n type ModifyTriggerResult,\n type PauseTriggerResult,\n type ResumeTriggerResult,\n type ListTriggerEventsResult,\n type TriggerEvent,\n} from \"./triggers.schemas.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\n\nexport type {\n CreateTriggerResult,\n CancelTriggerResult,\n ModifyTriggerResult,\n PauseTriggerResult,\n ResumeTriggerResult,\n ListTriggerEventsResult,\n};\n\nexport interface ListTriggersResult {\n triggers: Trigger[];\n nextPageToken: string;\n}\n\nfunction hasKnownTriggerSymbol(scales: SdkScales, trigger: { symbolId: number }): boolean {\n try {\n scales.baseQty(trigger.symbolId);\n return true;\n } catch {\n return false;\n }\n}\n\ninterface SubscribeTriggersInput extends BaseSubscribeInput<Trigger> {\n accountId: string;\n}\n\ninterface SubscribeTriggerEventsInput extends BaseSubscribeInput<TriggerEvent> {\n accountId: string;\n}\n\n/**\n * Manages standalone order triggers and their realtime lifecycle/event streams.\n */\nexport class TriggersService {\n #client: Client<typeof Proto.TriggersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #createTriggerInputSchema: ReturnType<typeof createCreateTriggerInputSchema>;\n #modifyTriggerInputSchema: ReturnType<typeof createModifyTriggerInputSchema>;\n #triggerSchema: ReturnType<typeof createTriggerSchema>;\n #triggerEventSchema: ReturnType<typeof createTriggerEventSchema>;\n\n constructor(\n transport: Transport,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.TriggersService, transport);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#createTriggerInputSchema = createCreateTriggerInputSchema(scales);\n this.#modifyTriggerInputSchema = createModifyTriggerInputSchema(scales);\n this.#triggerSchema = createTriggerSchema(scales);\n this.#triggerEventSchema = createTriggerEventSchema(scales);\n }\n\n /**\n * Creates a standalone trigger, such as stop-loss, take-profit, trailing-stop, TWAP, or ladder, for the resolved account scope. The request includes trigger conditions, order fields, strategy-specific fields, and optional clientTriggerId.\n */\n async create(\n input: CreateTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#createTriggerInputSchema, resolved);\n const res = await this.#client.createTrigger(validatedInput, toConnectCallOptions(options));\n return parse(CreateTriggerResultSchema, res);\n }\n\n /**\n * Fetches one trigger by id in the resolved account scope and returns null when the backend response contains no trigger.\n */\n async get(input: GetTriggerInput, options?: PolyesterRequestOptions): Promise<Trigger | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(GetTriggerInputSchema, resolved);\n const res = await this.#client.getTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n\n if (!res.trigger) return null;\n return parse(this.#triggerSchema, res.trigger);\n }\n\n /**\n * Lists triggers for the resolved account scope with optional symbol, status, trigger type, parent order, limit, and page-token filters. Results are returned newest-first.\n */\n async list(\n input: ListTriggersInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggersResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggersInputSchema, resolved);\n const res = await this.#client.listTriggers(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return {\n triggers: parse(\n v.array(this.#triggerSchema),\n res.triggers.filter((trigger) => hasKnownTriggerSymbol(this.#scales, trigger)),\n ),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Cancels an active trigger by id in the resolved account scope and returns the trigger id, resulting status, and server timestamp.\n */\n async cancel(\n input: CancelTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(CancelTriggerInputSchema, resolved);\n const res = await this.#client.cancelTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelTriggerResultSchema, res);\n }\n\n /**\n * Applies a limited patch to an existing trigger, covering trigger price, limit price, trailing distance, activation price, and market slippage fields where supported.\n */\n async modify(\n input: ModifyTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(this.#modifyTriggerInputSchema, resolved);\n const res = await this.#client.modifyTrigger(validated, toConnectCallOptions(options));\n return parse(ModifyTriggerResultSchema, res);\n }\n\n /**\n * Pauses an active trigger without discarding its immutable strategy configuration.\n */\n async pause(\n input: PauseTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<PauseTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(PauseTriggerInputSchema, resolved);\n const res = await this.#client.pauseTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(PauseTriggerResultSchema, res);\n }\n\n /**\n * Resumes a paused trigger.\n */\n async resume(\n input: ResumeTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ResumeTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ResumeTriggerInputSchema, resolved);\n const res = await this.#client.resumeTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ResumeTriggerResultSchema, res);\n }\n\n /**\n * Returns newest-first historical lifecycle events for one trigger, optionally filtered by event type. Fired events enumerate child-order actions. The SDK defaults limit to 50.\n */\n async listEvents(\n input: ListTriggerEventsInput,\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggerEventsResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggerEventsInputSchema, resolved);\n\n const res = await this.#client.listTriggerEvents(\n removeUndefined({\n triggerId: validated.triggerId,\n subaccountId: validated.subaccountId,\n limit: validated.limit ?? 50,\n eventType: validated.eventType,\n pageToken: validated.pageToken ?? \"\",\n }),\n toConnectCallOptions(options),\n );\n\n return {\n events: parse(v.array(this.#triggerEventSchema), res.events),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private trigger state updates on private:spot:triggers:{accountId}:proto and emits parsed trigger records.\n */\n subscribe(input: SubscribeTriggersInput): () => void {\n const channel = `private:spot:triggers:${input.accountId}:proto`;\n const gate = createReadyGate(\n () => this.#scales.ready(),\n (error) => input.onError?.(publicationHandlerErrorContext(channel, error)),\n );\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.TriggerSchema,\n onPublication: (data) => {\n gate.run(() => {\n const trigger = parse(this.#triggerSchema, data);\n input.onEvent(trigger);\n });\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n\n /**\n * Subscribes to private trigger lifecycle events on private:spot:triggers:events:{accountId}:proto and emits parsed trigger event records.\n */\n subscribeEvents(input: SubscribeTriggerEventsInput): () => void {\n const channel = `private:spot:triggers:events:${input.accountId}:proto`;\n const gate = createReadyGate(\n () => this.#scales.ready(),\n (error) => input.onError?.(publicationHandlerErrorContext(channel, error)),\n );\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.TriggerEventSchema,\n onPublication: (data) => {\n gate.run(() => {\n const event = parse(this.#triggerEventSchema, data);\n input.onEvent(event);\n });\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AA+DA,SAAS,sBAAsB,QAAmB,SAAwC;CACtF,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M,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;AACJ"}
|
|
1
|
+
{"version":3,"file":"triggers.js","names":["#client","Proto.TriggersService","#realtime","#resolver","#scales","#createTriggerInputSchema","#modifyTriggerInputSchema","#triggerSchema","#triggerEventSchema","Proto.TriggerSchema","Proto.TriggerEventSchema"],"sources":["../../../src/services/triggers/triggers.ts"],"sourcesContent":["import * as Proto from \"../../gen/triggers/v1/triggers_pb.js\";\nimport { createClient, type Client, type Transport } from \"@connectrpc/connect\";\nimport { publicationHandlerErrorContext } from \"../../shared/subscription-errors.js\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { createReadyGate, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n createCreateTriggerInputSchema,\n createModifyTriggerInputSchema,\n ListTriggersInputSchema,\n CancelTriggerInputSchema,\n PauseTriggerInputSchema,\n ResumeTriggerInputSchema,\n GetTriggerInputSchema,\n ListTriggerEventsInputSchema,\n CreateTriggerResultSchema,\n CancelTriggerResultSchema,\n ModifyTriggerResultSchema,\n PauseTriggerResultSchema,\n ResumeTriggerResultSchema,\n createTriggerSchema,\n createTriggerEventSchema,\n type Trigger,\n type CreateTriggerInput,\n type ListTriggersInput,\n type CancelTriggerInput,\n type GetTriggerInput,\n type ModifyTriggerInput,\n type PauseTriggerInput,\n type ResumeTriggerInput,\n type ListTriggerEventsInput,\n type CreateTriggerResult,\n type CancelTriggerResult,\n type ModifyTriggerResult,\n type PauseTriggerResult,\n type ResumeTriggerResult,\n type ListTriggerEventsResult,\n type TriggerEvent,\n} from \"./triggers.schemas.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\n\nexport type {\n CreateTriggerResult,\n CancelTriggerResult,\n ModifyTriggerResult,\n PauseTriggerResult,\n ResumeTriggerResult,\n ListTriggerEventsResult,\n};\n\nexport interface ListTriggersResult {\n triggers: Trigger[];\n nextPageToken: string;\n}\n\nfunction hasKnownTriggerSymbol(scales: SdkScales, trigger: { symbolId: number }): boolean {\n try {\n scales.baseQty(trigger.symbolId);\n return true;\n } catch {\n return false;\n }\n}\n\ninterface SubscribeTriggersInput extends BaseSubscribeInput<Trigger> {\n accountId: string;\n}\n\ninterface SubscribeTriggerEventsInput extends BaseSubscribeInput<TriggerEvent> {\n accountId: string;\n}\n\n/**\n * Manages standalone order triggers and their realtime lifecycle/event streams.\n */\nexport class TriggersService {\n #client: Client<typeof Proto.TriggersService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n #createTriggerInputSchema: ReturnType<typeof createCreateTriggerInputSchema>;\n #modifyTriggerInputSchema: ReturnType<typeof createModifyTriggerInputSchema>;\n #triggerSchema: ReturnType<typeof createTriggerSchema>;\n #triggerEventSchema: ReturnType<typeof createTriggerEventSchema>;\n\n constructor(\n transport: Transport,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.TriggersService, transport);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n this.#createTriggerInputSchema = createCreateTriggerInputSchema(scales);\n this.#modifyTriggerInputSchema = createModifyTriggerInputSchema(scales);\n this.#triggerSchema = createTriggerSchema(scales);\n this.#triggerEventSchema = createTriggerEventSchema(scales);\n }\n\n /**\n * Creates a standalone trigger, such as stop-loss, take-profit, trailing-stop, TWAP, or ladder, for the resolved account scope. The request includes trigger conditions, order fields, strategy-specific fields, and optional clientTriggerId.\n */\n async create(\n input: CreateTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(this.#createTriggerInputSchema, resolved);\n const res = await this.#client.createTrigger(validatedInput, toConnectCallOptions(options));\n return parse(CreateTriggerResultSchema, res);\n }\n\n /**\n * Fetches one trigger by id in the resolved account scope and returns null when the backend response contains no trigger.\n */\n async get(input: GetTriggerInput, options?: PolyesterRequestOptions): Promise<Trigger | null> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(GetTriggerInputSchema, resolved);\n const res = await this.#client.getTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n\n if (!res.trigger) return null;\n return parse(this.#triggerSchema, res.trigger);\n }\n\n /**\n * Lists triggers for the resolved account scope with optional symbol, status, trigger type, parent order, limit, and page-token filters. Results are returned newest-first.\n */\n async list(\n input: ListTriggersInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggersResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggersInputSchema, resolved);\n const res = await this.#client.listTriggers(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return {\n triggers: parse(\n v.array(this.#triggerSchema),\n res.triggers.filter((trigger) => hasKnownTriggerSymbol(this.#scales, trigger)),\n ),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Cancels an active trigger by id in the resolved account scope and returns the trigger id, resulting status, and server timestamp.\n */\n async cancel(\n input: CancelTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<CancelTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(CancelTriggerInputSchema, resolved);\n const res = await this.#client.cancelTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(CancelTriggerResultSchema, res);\n }\n\n /**\n * Applies a limited patch to an existing trigger. The symbol ID routes policy checks for exposure-increasing changes.\n */\n async modify(\n input: ModifyTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ModifyTriggerResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(this.#modifyTriggerInputSchema, resolved);\n const res = await this.#client.modifyTrigger(validated, toConnectCallOptions(options));\n return parse(ModifyTriggerResultSchema, res);\n }\n\n /**\n * Pauses an active trigger without discarding its immutable strategy configuration.\n */\n async pause(\n input: PauseTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<PauseTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(PauseTriggerInputSchema, resolved);\n const res = await this.#client.pauseTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(PauseTriggerResultSchema, res);\n }\n\n /**\n * Resumes a paused trigger using its symbol ID for policy checks.\n */\n async resume(\n input: ResumeTriggerInput,\n options?: PolyesterMutationOptions,\n ): Promise<ResumeTriggerResult> {\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ResumeTriggerInputSchema, resolved);\n const res = await this.#client.resumeTrigger(\n removeUndefined(validated),\n toConnectCallOptions(options),\n );\n return parse(ResumeTriggerResultSchema, res);\n }\n\n /**\n * Returns newest-first historical lifecycle events for one trigger, optionally filtered by event type. Fired events enumerate child-order actions. The SDK defaults limit to 50.\n */\n async listEvents(\n input: ListTriggerEventsInput,\n options?: PolyesterRequestOptions,\n ): Promise<ListTriggerEventsResult> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validated = parse(ListTriggerEventsInputSchema, resolved);\n\n const res = await this.#client.listTriggerEvents(\n removeUndefined({\n triggerId: validated.triggerId,\n subaccountId: validated.subaccountId,\n limit: validated.limit ?? 50,\n eventType: validated.eventType,\n pageToken: validated.pageToken ?? \"\",\n }),\n toConnectCallOptions(options),\n );\n\n return {\n events: parse(v.array(this.#triggerEventSchema), res.events),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private trigger state updates on private:spot:triggers:{accountId}:proto and emits parsed trigger records.\n */\n subscribe(input: SubscribeTriggersInput): () => void {\n const channel = `private:spot:triggers:${input.accountId}:proto`;\n const gate = createReadyGate(\n () => this.#scales.ready(),\n (error) => input.onError?.(publicationHandlerErrorContext(channel, error)),\n );\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.TriggerSchema,\n onPublication: (data) => {\n gate.run(() => {\n const trigger = parse(this.#triggerSchema, data);\n input.onEvent(trigger);\n });\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n\n /**\n * Subscribes to private trigger lifecycle events on private:spot:triggers:events:{accountId}:proto and emits parsed trigger event records.\n */\n subscribeEvents(input: SubscribeTriggerEventsInput): () => void {\n const channel = `private:spot:triggers:events:${input.accountId}:proto`;\n const gate = createReadyGate(\n () => this.#scales.ready(),\n (error) => input.onError?.(publicationHandlerErrorContext(channel, error)),\n );\n return this.#realtime.connectProtoChannel({\n channel,\n schema: Proto.TriggerEventSchema,\n onPublication: (data) => {\n gate.run(() => {\n const event = parse(this.#triggerEventSchema, data);\n input.onEvent(event);\n });\n },\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;AA+DA,SAAS,sBAAsB,QAAmB,SAAwC;CACtF,IAAI;EACA,OAAO,QAAQ,QAAQ,QAAQ;EAC/B,OAAO;CACX,QAAQ;EACJ,OAAO;CACX;AACJ;;;;AAaA,IAAa,kBAAb,MAA6B;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YACI,WACA,UACA,UACA,QACF;EACE,KAAKA,UAAU,aAAaC,mBAAuB,SAAS;EAC5D,KAAKC,YAAY;EACjB,KAAKC,YAAY;EACjB,KAAKC,UAAU;EACf,KAAKC,4BAA4B,+BAA+B,MAAM;EACtE,KAAKC,4BAA4B,+BAA+B,MAAM;EACtE,KAAKC,iBAAiB,oBAAoB,MAAM;EAChD,KAAKC,sBAAsB,yBAAyB,MAAM;C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I;EACvB;CACJ;;;;CAKA,UAAU,OAA2C;EACjD,MAAM,UAAU,yBAAyB,MAAM,UAAU;EACzD,MAAM,OAAO,sBACH,KAAKJ,QAAQ,MAAM,IACxB,UAAU,MAAM,UAAU,+BAA+B,SAAS,KAAK,CAAC,CAC7E;EACA,OAAO,KAAKF,UAAU,oBAAoB;GACtC;GACA,QAAQO;GACR,gBAAgB,SAAS;IACrB,KAAK,UAAU;KACX,MAAM,UAAU,MAAM,KAAKF,gBAAgB,IAAI;KAC/C,MAAM,QAAQ,OAAO;IACzB,CAAC;GACL;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;;;;CAKA,gBAAgB,OAAgD;EAC5D,MAAM,UAAU,gCAAgC,MAAM,UAAU;EAChE,MAAM,OAAO,sBACH,KAAKH,QAAQ,MAAM,IACxB,UAAU,MAAM,UAAU,+BAA+B,SAAS,KAAK,CAAC,CAC7E;EACA,OAAO,KAAKF,UAAU,oBAAoB;GACtC;GACA,QAAQQ;GACR,gBAAgB,SAAS;IACrB,KAAK,UAAU;KACX,MAAM,QAAQ,MAAM,KAAKF,qBAAqB,IAAI;KAClD,MAAM,QAAQ,KAAK;IACvB,CAAC;GACL;GACA,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;AACJ"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { CancelTriggerInput, CreateTriggerInput, GetTriggerInput, ListTriggerEventsInput, ListTriggersInput, ModifyTriggerInput } from "./trigger-input.schemas.js";
|
|
2
|
-
import { CancelTriggerResult, CreateTriggerResult, LadderDetailsOutput, ListTriggerEventsResult, ModifyTriggerResult, StopDetailsOutput, TrailingDetailsOutput, Trigger, TriggerDetailsOutput, TriggerEvent, TwapDetailsOutput } from "./triggers-output.schemas.js";
|
|
1
|
+
import { CancelTriggerInput, CreateTriggerInput, GetTriggerInput, ListTriggerEventsInput, ListTriggersInput, ModifyTriggerInput, PauseTriggerInput, ResumeTriggerInput } from "./trigger-input.schemas.js";
|
|
2
|
+
import { CancelTriggerResult, CreateTriggerResult, LadderDetailsOutput, ListTriggerEventsResult, ModifyTriggerResult, PauseTriggerResult, ResumeTriggerResult, StopDetailsOutput, TrailingDetailsOutput, Trigger, TriggerDetailsOutput, TriggerEvent, TwapDetailsOutput } from "./triggers-output.schemas.js";
|
|
3
3
|
import "./triggers.schemas.js";
|
|
4
4
|
import { ListTriggersResult } from "./triggers.js";
|
|
5
|
-
export type { CancelTriggerInput, CancelTriggerResult, CreateTriggerInput, CreateTriggerResult, GetTriggerInput, LadderDetailsOutput, ListTriggerEventsInput, ListTriggerEventsResult, ListTriggersInput, ListTriggersResult, ModifyTriggerInput, ModifyTriggerResult, StopDetailsOutput, TrailingDetailsOutput, Trigger, TriggerDetailsOutput, TriggerEvent, TwapDetailsOutput };
|
|
5
|
+
export type { CancelTriggerInput, CancelTriggerResult, CreateTriggerInput, CreateTriggerResult, GetTriggerInput, LadderDetailsOutput, ListTriggerEventsInput, ListTriggerEventsResult, ListTriggersInput, ListTriggersResult, ModifyTriggerInput, ModifyTriggerResult, PauseTriggerInput, PauseTriggerResult, ResumeTriggerInput, ResumeTriggerResult, StopDetailsOutput, TrailingDetailsOutput, Trigger, TriggerDetailsOutput, TriggerEvent, TwapDetailsOutput };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;iBAkHgB,6BAA6B,IAAI,eAAe;;;;;;
|
|
1
|
+
{"version":3,"file":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;iBAkHgB,6BAA6B,IAAI,eAAe;;;;;;iBAyIhD,iBAAiB;;;;;;iBAyBjB,iCAAiC"}
|
|
@@ -75,6 +75,7 @@ function connectErrorToPolyesterError(ce) {
|
|
|
75
75
|
if (hasAuthErrorCode(ce, 35)) return new PolicyLockedError(withFallback("Policy is locked."), options);
|
|
76
76
|
if (hasAuthErrorCode(ce, 36)) return new PolicyScopeMismatchError(withFallback("Policy does not belong to the target account scope."), options);
|
|
77
77
|
if (hasAuthErrorCode(ce, 39)) return new MfaLastFactorRequiredError(withFallback("At least one active MFA factor must remain enrolled."), options);
|
|
78
|
+
if (hasAuthErrorCode(ce, 40)) return new InternalServerError(withFallback("Internal server error."), options);
|
|
78
79
|
const mfaVerificationReason = getMfaVerificationFailureReason(ce);
|
|
79
80
|
if (mfaVerificationReason) return new MfaVerificationError(withFallback("MFA verification failed."), mfaVerificationReason, options);
|
|
80
81
|
const mfaKind = detectMfaErrorKind(ce);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-error-mapping.js","names":["OrderErrorDetailSchema"],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { AuthErrorCode, AuthErrorDetailSchema } from \"../gen/auth/v1/auth_pb.js\";\nimport {\n ErrorCode as OrderErrorCode,\n ErrorDetailSchema as OrderErrorDetailSchema,\n} from \"../gen/orders/v1/orders_pb.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n InternalServerError,\n isAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n StepUpRequiredError,\n TimeoutError,\n TransientError,\n ValidationError,\n} from \"./errors.js\";\nimport { RateLimitDetailSchema, type RateLimitDetail } from \"./rate-limit.schemas.js\";\n\nfunction getAuthErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(AuthErrorDetailSchema);\n}\n\nfunction hasAuthErrorCode(err: unknown, code: AuthErrorCode): boolean {\n return getAuthErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction hasOrderErrorCode(err: unknown, code: OrderErrorCode): boolean {\n return getOrderErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction getOrderErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(OrderErrorDetailSchema);\n}\n\nfunction getRateLimitDetail(err: unknown): RateLimitDetail | undefined {\n for (const orderDetail of getOrderErrorDetails(err)) {\n if (!orderDetail.rateLimit) continue;\n const result = v.safeParse(RateLimitDetailSchema, orderDetail.rateLimit);\n if (result.success) return result.output;\n }\n return undefined;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_ELEVATION_REQUIRED)) {\n return \"session-elevation\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_STEP_UP_REQUIRED)) return \"step-up\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_NOT_ENROLLED)) return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n const value = ce.metadata.get(\"retry-after\");\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1000));\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const options: PolyesterErrorOptions = { cause: ce };\n const withFallback = (fallback: string) => message || fallback;\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_RESOURCE_NOT_FOUND)) {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_REVISION_CONFLICT)) {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_IN_USE)) {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_LOCKED)) {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_SCOPE_MISMATCH)) {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_MFA_LAST_FACTOR_REQUIRED)) {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(ce);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = detectMfaErrorKind(ce);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n if (hasOrderErrorCode(ce, OrderErrorCode.STALE_QUOTE)) {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = getRateLimitDetail(ce);\n if (rateLimit || hasOrderErrorCode(ce, OrderErrorCode.RATE_LIMIT_EXCEEDED)) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(err: unknown): MfaVerificationFailureReason | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_INVALID)) {\n return \"challenge-invalid\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_LOCKED)) {\n return \"challenge-locked\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_OTP_INVALID)) return \"otp-invalid\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_RECOVERY_INVALID)) {\n return \"recovery-code-invalid\";\n }\n if (\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_CREDENTIAL_INVALID) ||\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_VERIFY_FAILED)\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-cancelled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) return err;\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nasync function* mapStreamErrors<T>(source: AsyncIterable<T>): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw toPolyesterError(err);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n throw toPolyesterError(err);\n }\n };\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message) };\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n };\n}\n"],"mappings":";;;;;;;AAqCA,SAAS,oBAAoB,KAAc;CACvC,OAAO,aAAa,KAAK,GAAG,CAAC,CAAC,YAAY,qBAAqB;AACnE;AAEA,SAAS,iBAAiB,KAAc,MAA8B;CAClE,OAAO,oBAAoB,GAAG,CAAC,CAAC,MAAM,WAAW,OAAO,SAAS,IAAI;AACzE;AAEA,SAAS,kBAAkB,KAAc,MAA+B;CACpE,OAAO,qBAAqB,GAAG,CAAC,CAAC,MAAM,WAAW,OAAO,SAAS,IAAI;AAC1E;AAEA,SAAS,qBAAqB,KAAc;CACxC,OAAO,aAAa,KAAK,GAAG,CAAC,CAAC,YAAYA,iBAAsB;AACpE;AAEA,SAAS,mBAAmB,KAA2C;CACnE,KAAK,MAAM,eAAe,qBAAqB,GAAG,GAAG;EACjD,IAAI,CAAC,YAAY,WAAW;EAC5B,MAAM,SAAS,EAAE,UAAU,uBAAuB,YAAY,SAAS;EACvE,IAAI,OAAO,SAAS,OAAO,OAAO;CACtC;AAEJ;AAEA,SAAS,iBAAiB,WAA4D;CAClF,IAAI,WAAW,iBAAiB,KAAA,GAAW,OAAO,KAA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;CAC3C;CACA,OAAO;AACX;AAEA,gBAAgB,gBAAmB,QAA4C;CAC3E,IAAI;EACA,OAAO;CACX,SAAS,KAAK;EACV,MAAM,iBAAiB,GAAG;CAC9B;AACJ;;;;;;AAOA,SAAgB,gCAA6C;CACzD,QAAQ,SAAS,OAAO,QAAQ;EAC5B,IAAI;GACA,MAAM,MAAM,MAAM,KAAK,GAAG;GAC1B,IAAI,IAAI,QACJ,OAAO;IAAE,GAAG;IAAK,SAAS,gBAAgB,IAAI,OAAO;GAAE;GAE3D,OAAO;EACX,SAAS,KAAK;GACV,MAAM,iBAAiB,GAAG;EAC9B;CACJ;AACJ;;;;;AAMA,SAAgB,4BAA4B,WAAiC;CACzE,OAAO;EACH,MAAM,MAAM,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GACjE,IAAI;IACA,OAAO,MAAM,UAAU,MACnB,QACA,QACA,WACA,QACA,OACA,aACJ;GACJ,SAAS,OAAO;IACZ,MAAM,iBAAiB,KAAK;GAChC;EACJ;EACA,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,OAAO;IAAE;GACrE,SAAS,OAAO;IACZ,MAAM,iBAAiB,KAAK;GAChC;EACJ;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"connect-error-mapping.js","names":["OrderErrorDetailSchema"],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { AuthErrorCode, AuthErrorDetailSchema } from \"../gen/auth/v1/auth_pb.js\";\nimport {\n ErrorCode as OrderErrorCode,\n ErrorDetailSchema as OrderErrorDetailSchema,\n} from \"../gen/orders/v1/orders_pb.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n InternalServerError,\n isAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n PermissionError,\n PolicyInUseError,\n PolicyLockedError,\n PolicyScopeMismatchError,\n PolyesterError,\n type PolyesterErrorOptions,\n PreconditionFailedError,\n RateLimitError,\n ResourceNotFoundError,\n RevisionConflictError,\n ServiceUnavailableError,\n SessionElevationRequiredError,\n StaleQuoteError,\n StepUpRequiredError,\n TimeoutError,\n TransientError,\n ValidationError,\n} from \"./errors.js\";\nimport { RateLimitDetailSchema, type RateLimitDetail } from \"./rate-limit.schemas.js\";\n\nfunction getAuthErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(AuthErrorDetailSchema);\n}\n\nfunction hasAuthErrorCode(err: unknown, code: AuthErrorCode): boolean {\n return getAuthErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction hasOrderErrorCode(err: unknown, code: OrderErrorCode): boolean {\n return getOrderErrorDetails(err).some((detail) => detail.code === code);\n}\n\nfunction getOrderErrorDetails(err: unknown) {\n return ConnectError.from(err).findDetails(OrderErrorDetailSchema);\n}\n\nfunction getRateLimitDetail(err: unknown): RateLimitDetail | undefined {\n for (const orderDetail of getOrderErrorDetails(err)) {\n if (!orderDetail.rateLimit) continue;\n const result = v.safeParse(RateLimitDetailSchema, orderDetail.rateLimit);\n if (result.success) return result.output;\n }\n return undefined;\n}\n\nfunction safeRetryAfterMs(rateLimit: RateLimitDetail | undefined): number | undefined {\n if (rateLimit?.retryAfterMs === undefined) return undefined;\n const value = BigInt(rateLimit.retryAfterMs);\n return value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined;\n}\n\n/**\n * Returns the error message without the leading \"[code] \" prefix that\n * `ConnectError` prepends, e.g. \"[invalid_argument] Insufficient funds.\"\n * becomes \"Insufficient funds.\".\n */\nexport function getNormalizedConnectMessage(err: unknown): string {\n const ce = ConnectError.from(err);\n const raw = ce.message ?? \"\";\n return normalizeErrorMessage(raw);\n}\n\nexport type MfaErrorKind = \"session-elevation\" | \"enrollment\" | \"step-up\";\n\n/**\n * Classifies an error as one of the MFA flows the backend can demand.\n * Classification is based only on stable structured auth error details.\n */\nexport function detectMfaErrorKind(err: unknown): MfaErrorKind | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_ELEVATION_REQUIRED)) {\n return \"session-elevation\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_STEP_UP_REQUIRED)) return \"step-up\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_NOT_ENROLLED)) return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n const value = ce.metadata.get(\"retry-after\");\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1000));\n const date = Date.parse(value);\n if (!Number.isNaN(date)) return Math.max(0, date - Date.now());\n return undefined;\n}\n\nconst MFA_ERROR_CLASSES = {\n \"session-elevation\": SessionElevationRequiredError,\n enrollment: MfaEnrollmentRequiredError,\n \"step-up\": StepUpRequiredError,\n} as const;\n\n/**\n * Maps a `ConnectError` from the Polyester backend onto the typed\n * {@link PolyesterError} tree. The original error is preserved as `cause`.\n */\nexport function connectErrorToPolyesterError(ce: ConnectError): PolyesterError {\n const message = getNormalizedConnectMessage(ce);\n const options: PolyesterErrorOptions = { cause: ce };\n const withFallback = (fallback: string) => message || fallback;\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_RESOURCE_NOT_FOUND)) {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_REVISION_CONFLICT)) {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_IN_USE)) {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_LOCKED)) {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_POLICY_SCOPE_MISMATCH)) {\n return new PolicyScopeMismatchError(\n withFallback(\"Policy does not belong to the target account scope.\"),\n options,\n );\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_MFA_LAST_FACTOR_REQUIRED)) {\n return new MfaLastFactorRequiredError(\n withFallback(\"At least one active MFA factor must remain enrolled.\"),\n options,\n );\n }\n if (hasAuthErrorCode(ce, AuthErrorCode.AUTH_INTERNAL_ERROR)) {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(ce);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = detectMfaErrorKind(ce);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n if (hasOrderErrorCode(ce, OrderErrorCode.STALE_QUOTE)) {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = getRateLimitDetail(ce);\n if (rateLimit || hasOrderErrorCode(ce, OrderErrorCode.RATE_LIMIT_EXCEEDED)) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n switch (ce.code) {\n case Code.InvalidArgument:\n case Code.OutOfRange:\n return new ValidationError(withFallback(\"Invalid request.\"), options);\n case Code.NotFound:\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n case Code.AlreadyExists:\n return new AlreadyExistsError(withFallback(\"Resource already exists.\"), options);\n case Code.PermissionDenied:\n return new PermissionError(withFallback(\"Permission denied.\"), options);\n case Code.Unauthenticated:\n return new AuthenticationError(withFallback(\"Authentication required.\"), options);\n case Code.FailedPrecondition:\n return new PreconditionFailedError(withFallback(\"Precondition failed.\"), options);\n case Code.ResourceExhausted:\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n case Code.DeadlineExceeded:\n return new TimeoutError(withFallback(\"Request timed out.\"), options);\n case Code.Unavailable:\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n case Code.Aborted:\n return new TransientError(withFallback(\"Operation aborted by the backend.\"), options);\n default:\n // Gateways sometimes surface outages as Unknown with this stock phrase.\n if (/service temporarily unavailable/i.test(message)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\n }\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n}\n\nfunction getMfaVerificationFailureReason(err: unknown): MfaVerificationFailureReason | null {\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_INVALID)) {\n return \"challenge-invalid\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_CHALLENGE_LOCKED)) {\n return \"challenge-locked\";\n }\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_OTP_INVALID)) return \"otp-invalid\";\n if (hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_RECOVERY_INVALID)) {\n return \"recovery-code-invalid\";\n }\n if (\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_CREDENTIAL_INVALID) ||\n hasAuthErrorCode(err, AuthErrorCode.AUTH_MFA_PASSKEY_VERIFY_FAILED)\n ) {\n return \"passkey-invalid\";\n }\n\n return null;\n}\n\nfunction findPolyesterErrorInCauseChain(err: unknown): PolyesterError | null {\n let current: unknown = err;\n for (let depth = 0; depth < 5 && current instanceof Error; depth++) {\n current = current.cause;\n if (current instanceof PolyesterError) return current;\n }\n return null;\n}\n\n/**\n * Converts any RPC-layer failure into its typed SDK error. Abort errors and\n * caller-cancelled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) return err;\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nasync function* mapStreamErrors<T>(source: AsyncIterable<T>): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw toPolyesterError(err);\n }\n}\n\n/**\n * Interceptor that converts every RPC failure (unary and streaming) into the\n * typed {@link PolyesterError} hierarchy. Installed outermost by\n * `createTransports`, so callers of SDK services always see typed errors.\n */\nexport function createErrorMappingInterceptor(): Interceptor {\n return (next) => async (req) => {\n try {\n const res = await next(req);\n if (res.stream) {\n return { ...res, message: mapStreamErrors(res.message) };\n }\n return res;\n } catch (err) {\n throw toPolyesterError(err);\n }\n };\n}\n\n/**\n * Wraps a Connect transport so errors are translated after Connect's call\n * runner has applied its own error normalization.\n */\nexport function createErrorMappingTransport(transport: Transport): Transport {\n return {\n async unary(method, signal, timeoutMs, header, input, contextValues) {\n try {\n return await transport.unary(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n try {\n const response = await transport.stream(\n method,\n signal,\n timeoutMs,\n header,\n input,\n contextValues,\n );\n return { ...response, message: mapStreamErrors(response.message) };\n } catch (error) {\n throw toPolyesterError(error);\n }\n },\n };\n}\n"],"mappings":";;;;;;;AAqCA,SAAS,oBAAoB,KAAc;CACvC,OAAO,aAAa,KAAK,GAAG,CAAC,CAAC,YAAY,qBAAqB;AACnE;AAEA,SAAS,iBAAiB,KAAc,MAA8B;CAClE,OAAO,oBAAoB,GAAG,CAAC,CAAC,MAAM,WAA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OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,OAAO;IAAE;GACrE,SAAS,OAAO;IACZ,MAAM,iBAAiB,KAAK;GAChC;EACJ;CACJ;AACJ"}
|
package/dist/shared/schemas.js
CHANGED
|
@@ -17,7 +17,7 @@ const OptionalTimestampMsSchema = v.pipe(v.optional(TimestampSchema), v.transfor
|
|
|
17
17
|
const OptionalNumberDefaultNullSchema = v.optional(v.nullable(v.number()), null);
|
|
18
18
|
const OptionalNumberToBigIntOrZeroSchema = v.pipe(OptionalNumberDefaultNullSchema, v.transform((value) => toBigIntOrZero(value)));
|
|
19
19
|
const OptionalNumberToIntOrZeroSchema = v.pipe(OptionalNumberDefaultNullSchema, v.transform((value) => toIntOrZero(value)));
|
|
20
|
-
|
|
20
|
+
v.pipe(OptionalNumberDefaultNullSchema, v.transform((value) => toBpsOrZero(value)));
|
|
21
21
|
v.pipe(v.bigint(), v.transform((value) => tsNsToMs(value)));
|
|
22
22
|
const BigIntStringSchema = v.pipe(v.bigint(), v.transform((value) => value.toString()));
|
|
23
23
|
const OptionalBigIntStringSchema = v.pipe(v.optional(v.bigint()), v.transform((value) => value === void 0 ? void 0 : value.toString()));
|
|
@@ -60,6 +60,6 @@ function positiveBigintStringInputSchema(fieldName) {
|
|
|
60
60
|
}
|
|
61
61
|
const JsonObjectSchema = v.custom((input) => typeof input === "object" && input !== null && !Array.isArray(input));
|
|
62
62
|
//#endregion
|
|
63
|
-
export { BigIntStringSchema, JsonObjectSchema, OptionalBigIntStringSchema, OptionalNumberDefaultNullSchema, OptionalNumberToBigIntOrZeroSchema,
|
|
63
|
+
export { BigIntStringSchema, JsonObjectSchema, OptionalBigIntStringSchema, OptionalNumberDefaultNullSchema, OptionalNumberToBigIntOrZeroSchema, OptionalNumberToIntOrZeroSchema, OptionalPublicIdSchema, OptionalTimestampMsSchema, OptionalTimestampMsToUsInputSchema, OptionalTimestampSecondsInputSchema, PublicIdSchema, TimestampMsSchema, TimestampSchema, bigintStringInputSchema, idInputSchema, optionalIdInputSchema, optionalSubaccountIdInputSchema, optionalUint64DecimalFilterSchema, positiveBigintStringInputSchema };
|
|
64
64
|
|
|
65
65
|
//# sourceMappingURL=schemas.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schemas.js","names":[],"sources":["../../src/shared/schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { formatId, idToBigInt } from \"../utils/base58-id.js\";\nimport {\n parseOptionalUint64DecimalStrict,\n toBigIntOrZero,\n toBpsOrZero,\n toIntOrZero,\n} from \"../utils/numbers.js\";\nimport { tsNsToMs, tsObjToMs } from \"../utils/time.js\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\n\nconst UINT64_MAX = (1n << 64n) - 1n;\nconst MS_TO_US = 1_000n;\nconst MS_TO_NS = 1_000_000n;\nconst MAX_UINT64_TIMESTAMP_MS_US = Number(UINT64_MAX / MS_TO_US);\nconst MAX_UINT64_TIMESTAMP_MS = Number(UINT64_MAX / MS_TO_NS);\n\nexport const TimestampSchema = v.object({\n seconds: v.bigint(),\n nanos: v.optional(v.number(), 0),\n});\n\nexport const TimestampMsSchema = v.pipe(\n TimestampSchema,\n v.transform((value) => tsObjToMs(value)),\n);\n\nexport const OptionalTimestampMsSchema = v.pipe(\n v.optional(TimestampSchema),\n v.transform((value) => tsObjToMs(value)),\n);\n\nexport const OptionalNumberDefaultNullSchema = v.optional(v.nullable(v.number()), null);\n\nexport const OptionalNumberToBigIntOrZeroSchema = v.pipe(\n OptionalNumberDefaultNullSchema,\n v.transform((value) => toBigIntOrZero(value)),\n);\n\nexport const OptionalNumberToIntOrZeroSchema = v.pipe(\n OptionalNumberDefaultNullSchema,\n v.transform((value) => toIntOrZero(value)),\n);\n\nexport const OptionalNumberToBpsOrZeroSchema = v.pipe(\n OptionalNumberDefaultNullSchema,\n v.transform((value) => toBpsOrZero(value)),\n);\n\nexport const TimestampNsMsSchema = v.pipe(\n v.bigint(),\n v.transform((value) => tsNsToMs(value)),\n);\n\nexport const BigIntStringSchema = v.pipe(\n v.bigint(),\n v.transform((value) => value.toString()),\n);\n\nexport const OptionalBigIntStringSchema = v.pipe(\n v.optional(v.bigint()),\n v.transform((value) => (value === undefined ? undefined : value.toString())),\n);\n\nexport const OptionalTimestampMsToNsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(MAX_UINT64_TIMESTAMP_MS),\n v.transform((value) => BigInt(value) * MS_TO_NS),\n ),\n);\n\nexport const OptionalTimestampMsToUsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(MAX_UINT64_TIMESTAMP_MS_US),\n v.transform((value) => BigInt(value) * MS_TO_US),\n ),\n);\n\nexport const OptionalTimestampSecondsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n v.transform((value) => BigInt(value)),\n ),\n);\n\nexport const PublicIdSchema = v.pipe(\n v.bigint(),\n v.transform((value) => formatId(value)),\n);\n\nexport const OptionalPublicIdSchema = v.pipe(\n v.optional(v.bigint()),\n v.transform((value) => (value ? formatId(value) : undefined)),\n);\n\nconst TrimmedStringSchema = v.pipe(v.string(), v.trim());\n\nconst OptionalTrimmedStringSchema = v.optional(TrimmedStringSchema);\n\n/**\n * Creates a schema for required public id input.\n */\nexport function idInputSchema(fieldName: string) {\n return v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.transform((value) => idToBigInt(value, fieldName)),\n );\n}\n\n/**\n * Creates a schema for optional public id input.\n */\nexport function optionalIdInputSchema(fieldName: string) {\n return v.pipe(\n OptionalTrimmedStringSchema,\n v.transform((value) => (value ? idToBigInt(value, fieldName) : undefined)),\n );\n}\n\n/**\n * Creates a schema for optional subaccount id input.\n */\nexport function optionalSubaccountIdInputSchema() {\n return optionalIdInputSchema(\"subaccountId\");\n}\n\n/**\n * Creates a schema for optional uint64 decimal filter input.\n */\nexport function optionalUint64DecimalFilterSchema(fieldName: string) {\n return v.pipe(\n OptionalTrimmedStringSchema,\n v.transform((value) => parseOptionalUint64DecimalStrict(value, fieldName)),\n );\n}\n\n/**\n * Creates a schema for positive bigint-like input.\n */\nexport function positiveBigintLikeSchema(message: string) {\n return v.pipe(\n v.union([\n v.bigint(),\n v.pipe(\n TrimmedStringSchema,\n v.regex(/^\\d+$/),\n v.transform((value) => BigInt(value)),\n ),\n ]),\n v.check((value) => value > 0n, message),\n );\n}\n\nexport function bigintStringInputSchema(fieldName: string) {\n return v.pipe(\n TrimmedStringSchema,\n v.regex(/^\\d+$/, `${fieldName} must be a decimal integer`),\n v.transform((value) => BigInt(value)),\n );\n}\n\nexport function positiveBigintStringInputSchema(fieldName: string) {\n return v.pipe(\n bigintStringInputSchema(fieldName),\n v.check((value) => value > 0n, `${fieldName} must be greater than 0`),\n );\n}\n\nexport const JsonObjectSchema = v.custom<JsonObject>(\n (input): input is JsonObject =>\n typeof input === \"object\" && input !== null && !Array.isArray(input),\n);\n"],"mappings":";;;;;AAWA,MAAM,cAAc,MAAM,OAAO;AACjC,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,6BAA6B,OAAO,aAAa,QAAQ;AAC/D,MAAM,0BAA0B,OAAO,aAAa,QAAQ;AAE5D,MAAa,kBAAkB,EAAE,OAAO;CACpC,SAAS,EAAE,OAAO;CAClB,OAAO,EAAE,SAAS,EAAE,OAAO,GAAG,CAAC;AACnC,CAAC;AAED,MAAa,oBAAoB,EAAE,KAC/B,iBACA,EAAE,WAAW,UAAU,UAAU,KAAK,CAAC,CAC3C;AAEA,MAAa,4BAA4B,EAAE,KACvC,EAAE,SAAS,eAAe,GAC1B,EAAE,WAAW,UAAU,UAAU,KAAK,CAAC,CAC3C;AAEA,MAAa,kCAAkC,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,GAAG,IAAI;AAEtF,MAAa,qCAAqC,EAAE,KAChD,iCACA,EAAE,WAAW,UAAU,eAAe,KAAK,CAAC,CAChD;AAEA,MAAa,kCAAkC,EAAE,KAC7C,iCACA,EAAE,WAAW,UAAU,YAAY,KAAK,CAAC,CAC7C;
|
|
1
|
+
{"version":3,"file":"schemas.js","names":[],"sources":["../../src/shared/schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { formatId, idToBigInt } from \"../utils/base58-id.js\";\nimport {\n parseOptionalUint64DecimalStrict,\n toBigIntOrZero,\n toBpsOrZero,\n toIntOrZero,\n} from \"../utils/numbers.js\";\nimport { tsNsToMs, tsObjToMs } from \"../utils/time.js\";\nimport type { JsonObject } from \"@bufbuild/protobuf\";\n\nconst UINT64_MAX = (1n << 64n) - 1n;\nconst MS_TO_US = 1_000n;\nconst MS_TO_NS = 1_000_000n;\nconst MAX_UINT64_TIMESTAMP_MS_US = Number(UINT64_MAX / MS_TO_US);\nconst MAX_UINT64_TIMESTAMP_MS = Number(UINT64_MAX / MS_TO_NS);\n\nexport const TimestampSchema = v.object({\n seconds: v.bigint(),\n nanos: v.optional(v.number(), 0),\n});\n\nexport const TimestampMsSchema = v.pipe(\n TimestampSchema,\n v.transform((value) => tsObjToMs(value)),\n);\n\nexport const OptionalTimestampMsSchema = v.pipe(\n v.optional(TimestampSchema),\n v.transform((value) => tsObjToMs(value)),\n);\n\nexport const OptionalNumberDefaultNullSchema = v.optional(v.nullable(v.number()), null);\n\nexport const OptionalNumberToBigIntOrZeroSchema = v.pipe(\n OptionalNumberDefaultNullSchema,\n v.transform((value) => toBigIntOrZero(value)),\n);\n\nexport const OptionalNumberToIntOrZeroSchema = v.pipe(\n OptionalNumberDefaultNullSchema,\n v.transform((value) => toIntOrZero(value)),\n);\n\nexport const OptionalNumberToBpsOrZeroSchema = v.pipe(\n OptionalNumberDefaultNullSchema,\n v.transform((value) => toBpsOrZero(value)),\n);\n\nexport const TimestampNsMsSchema = v.pipe(\n v.bigint(),\n v.transform((value) => tsNsToMs(value)),\n);\n\nexport const BigIntStringSchema = v.pipe(\n v.bigint(),\n v.transform((value) => value.toString()),\n);\n\nexport const OptionalBigIntStringSchema = v.pipe(\n v.optional(v.bigint()),\n v.transform((value) => (value === undefined ? undefined : value.toString())),\n);\n\nexport const OptionalTimestampMsToNsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(MAX_UINT64_TIMESTAMP_MS),\n v.transform((value) => BigInt(value) * MS_TO_NS),\n ),\n);\n\nexport const OptionalTimestampMsToUsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(MAX_UINT64_TIMESTAMP_MS_US),\n v.transform((value) => BigInt(value) * MS_TO_US),\n ),\n);\n\nexport const OptionalTimestampSecondsInputSchema = v.optional(\n v.pipe(\n v.number(),\n v.integer(),\n v.minValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n v.transform((value) => BigInt(value)),\n ),\n);\n\nexport const PublicIdSchema = v.pipe(\n v.bigint(),\n v.transform((value) => formatId(value)),\n);\n\nexport const OptionalPublicIdSchema = v.pipe(\n v.optional(v.bigint()),\n v.transform((value) => (value ? formatId(value) : undefined)),\n);\n\nconst TrimmedStringSchema = v.pipe(v.string(), v.trim());\n\nconst OptionalTrimmedStringSchema = v.optional(TrimmedStringSchema);\n\n/**\n * Creates a schema for required public id input.\n */\nexport function idInputSchema(fieldName: string) {\n return v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.transform((value) => idToBigInt(value, fieldName)),\n );\n}\n\n/**\n * Creates a schema for optional public id input.\n */\nexport function optionalIdInputSchema(fieldName: string) {\n return v.pipe(\n OptionalTrimmedStringSchema,\n v.transform((value) => (value ? idToBigInt(value, fieldName) : undefined)),\n );\n}\n\n/**\n * Creates a schema for optional subaccount id input.\n */\nexport function optionalSubaccountIdInputSchema() {\n return optionalIdInputSchema(\"subaccountId\");\n}\n\n/**\n * Creates a schema for optional uint64 decimal filter input.\n */\nexport function optionalUint64DecimalFilterSchema(fieldName: string) {\n return v.pipe(\n OptionalTrimmedStringSchema,\n v.transform((value) => parseOptionalUint64DecimalStrict(value, fieldName)),\n );\n}\n\n/**\n * Creates a schema for positive bigint-like input.\n */\nexport function positiveBigintLikeSchema(message: string) {\n return v.pipe(\n v.union([\n v.bigint(),\n v.pipe(\n TrimmedStringSchema,\n v.regex(/^\\d+$/),\n v.transform((value) => BigInt(value)),\n ),\n ]),\n v.check((value) => value > 0n, message),\n );\n}\n\nexport function bigintStringInputSchema(fieldName: string) {\n return v.pipe(\n TrimmedStringSchema,\n v.regex(/^\\d+$/, `${fieldName} must be a decimal integer`),\n v.transform((value) => BigInt(value)),\n );\n}\n\nexport function positiveBigintStringInputSchema(fieldName: string) {\n return v.pipe(\n bigintStringInputSchema(fieldName),\n v.check((value) => value > 0n, `${fieldName} must be greater than 0`),\n );\n}\n\nexport const JsonObjectSchema = v.custom<JsonObject>(\n (input): input is JsonObject =>\n typeof input === \"object\" && input !== null && !Array.isArray(input),\n);\n"],"mappings":";;;;;AAWA,MAAM,cAAc,MAAM,OAAO;AACjC,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,6BAA6B,OAAO,aAAa,QAAQ;AAC/D,MAAM,0BAA0B,OAAO,aAAa,QAAQ;AAE5D,MAAa,kBAAkB,EAAE,OAAO;CACpC,SAAS,EAAE,OAAO;CAClB,OAAO,EAAE,SAAS,EAAE,OAAO,GAAG,CAAC;AACnC,CAAC;AAED,MAAa,oBAAoB,EAAE,KAC/B,iBACA,EAAE,WAAW,UAAU,UAAU,KAAK,CAAC,CAC3C;AAEA,MAAa,4BAA4B,EAAE,KACvC,EAAE,SAAS,eAAe,GAC1B,EAAE,WAAW,UAAU,UAAU,KAAK,CAAC,CAC3C;AAEA,MAAa,kCAAkC,EAAE,SAAS,EAAE,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AyB,EAAE,KACpC,EAAE,SAAS,EAAE,OAAO,CAAC,GACrB,EAAE,WAAW,UAAW,QAAQ,SAAS,KAAK,IAAI,KAAA,CAAU,CAChE;AAEA,MAAM,sBAAsB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,KAAK,CAAC;AAEvD,MAAM,8BAA8B,EAAE,SAAS,mBAAmB;;;;AAKlE,SAAgB,cAAc,WAAmB;CAC7C,OAAO,EAAE,KACL,EAAE,OAAO,GACT,EAAE,KAAK,GACP,EAAE,UAAU,CAAC,GACb,EAAE,WAAW,UAAU,WAAW,OAAO,SAAS,CAAC,CACvD;AACJ;;;;AAKA,SAAgB,sBAAsB,WAAmB;CACrD,OAAO,EAAE,KACL,6BACA,EAAE,WAAW,UAAW,QAAQ,WAAW,OAAO,SAAS,IAAI,KAAA,CAAU,CAC7E;AACJ;;;;AAKA,SAAgB,kCAAkC;CAC9C,OAAO,sBAAsB,cAAc;AAC/C;;;;AAKA,SAAgB,kCAAkC,WAAmB;CACjE,OAAO,EAAE,KACL,6BACA,EAAE,WAAW,UAAU,iCAAiC,OAAO,SAAS,CAAC,CAC7E;AACJ;AAmBA,SAAgB,wBAAwB,WAAmB;CACvD,OAAO,EAAE,KACL,qBACA,EAAE,MAAM,SAAS,GAAG,UAAU,2BAA2B,GACzD,EAAE,WAAW,UAAU,OAAO,KAAK,CAAC,CACxC;AACJ;AAEA,SAAgB,gCAAgC,WAAmB;CAC/D,OAAO,EAAE,KACL,wBAAwB,SAAS,GACjC,EAAE,OAAO,UAAU,QAAQ,IAAI,GAAG,UAAU,wBAAwB,CACxE;AACJ;AAEA,MAAa,mBAAmB,EAAE,QAC7B,UACG,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,CAC3E"}
|
|
@@ -50,6 +50,11 @@ async function sha256Hex(bytes) {
|
|
|
50
50
|
const hash = await crypto.subtle.digest("SHA-256", bytes.slice());
|
|
51
51
|
return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
52
52
|
}
|
|
53
|
+
let lastTimestamp = 0;
|
|
54
|
+
function nextTimestamp() {
|
|
55
|
+
lastTimestamp = Math.max(lastTimestamp + 1, Date.now());
|
|
56
|
+
return String(lastTimestamp);
|
|
57
|
+
}
|
|
53
58
|
function canonicalQueryString(params) {
|
|
54
59
|
const pairs = [];
|
|
55
60
|
for (const [k, v] of params.entries()) pairs.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
|
|
@@ -63,7 +68,7 @@ async function createApiKeyEd25519AuthHeaders(auth, request) {
|
|
|
63
68
|
const [keyId, secretKey] = await Promise.all([auth.getKeyId(), auth.getSecretKey()]);
|
|
64
69
|
if (!keyId || !secretKey) throw new ConfigurationError("Missing API key ID or secret key");
|
|
65
70
|
const urlObj = new URL(request.url);
|
|
66
|
-
const timestamp = request.timestamp ??
|
|
71
|
+
const timestamp = request.timestamp ?? nextTimestamp();
|
|
67
72
|
const bodyHash = await sha256Hex(request.body ?? /* @__PURE__ */ new Uint8Array(0));
|
|
68
73
|
const canonicalQuery = canonicalQueryString(urlObj.searchParams);
|
|
69
74
|
const canonical = `${timestamp}\n${request.method}\n${urlObj.pathname}\n${canonicalQuery}\n${bodyHash}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transports.js","names":[],"sources":["../../src/shared/transports.ts"],"sourcesContent":["import { createConnectTransport } from \"@connectrpc/connect-web\";\nimport type { Transport, Interceptor } from \"@connectrpc/connect\";\nimport { toBinary, toJsonString } from \"@bufbuild/protobuf\";\nimport { signAsync } from \"@noble/ed25519\";\nimport { createErrorMappingTransport } from \"./connect-error-mapping.js\";\nimport { ConfigurationError, isAbortError, NetworkError } from \"./errors.js\";\n\nexport { isAbortError };\n\nexport type ConnectWireFormat = \"binary\" | \"json\";\n\nexport const POLYESTER_MOCK_HEADER = \"x-polyester-mock\";\n\nexport interface TransportConfig {\n apiUrl: string;\n interceptors?: Interceptor[];\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n /**\n * Connect wire format. Defaults to binary for production performance.\n * Use `json` for the API Playground visualization.\n */\n wireFormat?: ConnectWireFormat;\n}\n\nexport interface Transports {\n authApi: Transport;\n publicApi: Transport;\n}\n\n/**\n * Generic JWT auth for HTTP/Connect endpoints that follow the Bearer token contract.\n */\nexport interface JwtAuthProvider {\n kind: \"jwt\";\n /** Typically wraps the configured browser auth token storage. */\n getToken: () => string | null | Promise<string | null>;\n}\n\n/**\n * Generic Ed25519 API key auth for HTTP/Connect endpoints that follow the\n * X-API-KEY-ID / X-API-TIMESTAMP / X-API-SIGNATURE contract.\n */\nexport interface ApiKeyEd25519AuthProvider {\n kind: \"api-key-ed25519\";\n getKeyId: () => string | null | Promise<string | null>;\n /** Ed25519 secret key bytes (not hex) for signing. */\n getSecretKey: () => Uint8Array | null | Promise<Uint8Array | null>;\n}\n\nexport interface ApiKeyEd25519SigningRequest {\n url: string | URL;\n method: string;\n body?: Uint8Array;\n timestamp?: string;\n}\n\n/**\n * Returns the fetch implementation used by SDK transports.\n */\nexport function makeFetch(): typeof fetch {\n const wrappedFetch = Object.assign(\n async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n // Normalize headers into a mutable Headers object\n const headers = new Headers(init?.headers);\n\n try {\n const res = await fetch(input, {\n ...init,\n headers,\n redirect: \"manual\",\n });\n\n return res;\n } catch (err) {\n if (isAbortError(err)) throw err;\n throw new NetworkError(\"Transport request failed\", { cause: err });\n }\n },\n fetch,\n );\n\n return wrappedFetch;\n}\n\n/**\n * Creates Connect transports for SDK service clients.\n */\nexport function createTransports(config: TransportConfig): Transports {\n const { apiUrl, interceptors = [], auth, wireFormat = \"binary\" } = config;\n const useBinaryFormat = wireFormat === \"binary\";\n const publicApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors,\n fetch: makeFetch(),\n }),\n );\n\n const authInterceptors = auth\n ? [createAuthInterceptor(auth, { wireFormat }), ...interceptors]\n : interceptors;\n const authApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors: authInterceptors,\n fetch: makeFetch(),\n }),\n );\n\n return { authApi, publicApi };\n}\n\n/**\n * Creates an interceptor that enables mock transport behavior.\n */\nexport function createMockInterceptor(getEnabled: () => boolean): Interceptor {\n return (next) => async (req) => {\n if (getEnabled()) req.header.set(POLYESTER_MOCK_HEADER, \"true\");\n return next(req);\n };\n}\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n if (typeof crypto === \"undefined\" || !crypto.subtle) {\n throw new ConfigurationError(\"SHA-256 not available in this environment\");\n }\n const hash = await crypto.subtle.digest(\"SHA-256\", bytes.slice());\n return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nfunction canonicalQueryString(params: URLSearchParams): string {\n const pairs: string[] = [];\n for (const [k, v] of params.entries()) {\n pairs.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);\n }\n pairs.sort();\n return pairs.join(\"&\");\n}\n\n/**\n * Creates API-key authentication headers for endpoints using the Polyester Ed25519 signing contract.\n */\nexport async function createApiKeyEd25519AuthHeaders(\n auth: ApiKeyEd25519AuthProvider,\n request: ApiKeyEd25519SigningRequest,\n): Promise<Record<string, string>> {\n const [keyId, secretKey] = await Promise.all([auth.getKeyId(), auth.getSecretKey()]);\n if (!keyId || !secretKey) throw new ConfigurationError(\"Missing API key ID or secret key\");\n\n const urlObj = new URL(request.url);\n const timestamp = request.timestamp ?? String(Date.now());\n const bodyHash = await sha256Hex(request.body ?? new Uint8Array(0));\n const canonicalQuery = canonicalQueryString(urlObj.searchParams);\n const canonical = `${timestamp}\\n${request.method}\\n${urlObj.pathname}\\n${canonicalQuery}\\n${bodyHash}`;\n const msgBytes = new TextEncoder().encode(canonical);\n const sig = await signAsync(msgBytes, secretKey);\n const signatureHex = Array.from(sig, (b: number) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n return {\n \"X-API-KEY-ID\": keyId,\n \"X-API-TIMESTAMP\": timestamp,\n \"X-API-SIGNATURE\": signatureHex,\n };\n}\n\n/**\n * Creates an interceptor that attaches SDK authentication headers.\n */\nexport function createAuthInterceptor(\n auth: JwtAuthProvider | ApiKeyEd25519AuthProvider,\n options?: { wireFormat?: ConnectWireFormat },\n): Interceptor {\n return (next) => async (req) => {\n const wireFormat = options?.wireFormat ?? \"binary\";\n if (auth.kind === \"jwt\") {\n const token = await auth.getToken();\n if (token) {\n req.header.set(\"Authorization\", `Bearer ${token}`);\n }\n } else if (auth.kind === \"api-key-ed25519\") {\n let bodyBytes: Uint8Array;\n if (!req.stream) {\n // unary request - serialize the message using the method's input schema\n const inputSchema = req.method.input;\n bodyBytes =\n wireFormat === \"json\"\n ? new TextEncoder().encode(toJsonString(inputSchema, req.message))\n : toBinary(inputSchema, req.message);\n } else {\n // stream request - empty body for signing (streams don't have a single body)\n bodyBytes = new Uint8Array(0);\n }\n\n const headers = await createApiKeyEd25519AuthHeaders(auth, {\n url: req.url,\n method: req.requestMethod,\n body: bodyBytes,\n });\n for (const [key, value] of Object.entries(headers)) {\n req.header.set(key, value);\n }\n }\n return next(req);\n };\n}\n"],"mappings":";;;;;;;;;AA2DA,SAAgB,YAA0B;CAsBtC,OArBqB,OAAO,OACxB,OAAO,OAAoC,SAAuC;EAE9E,MAAM,UAAU,IAAI,QAAQ,MAAM,OAAO;EAEzC,IAAI;GAOA,OAAO,MANW,MAAM,OAAO;IAC3B,GAAG;IACH;IACA,UAAU;GACd,CAAC;EAGL,SAAS,KAAK;GACV,IAAI,aAAa,GAAG,GAAG,MAAM;GAC7B,MAAM,IAAI,aAAa,4BAA4B,EAAE,OAAO,IAAI,CAAC;EACrE;CACJ,GACA,KAGc;AACtB;;;;AAKA,SAAgB,iBAAiB,QAAqC;CAClE,MAAM,EAAE,QAAQ,eAAe,CAAC,GAAG,MAAM,aAAa,aAAa;CACnE,MAAM,kBAAkB,eAAe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,OAAO,YAAY;CAC/D,MAAM,YAAY,GAAG,UAAU,IAAI,QAAQ,OAAO,IAAI,OAAO,SAAS,IAAI,eAAe,IAAI;CAC7F,MAAM,WAAW,IAAI,YAAY,CAAC,CAAC,OAAO,SAAS;CACnD,MAAM,MAAM,MAAM,UAAU,UAAU,SAAS;CAG/C,OAAO;EACH,gBAAgB;EAChB,mBAAmB;EACnB,mBALiB,MAAM,KAAK,MAAM,MAAc,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAKxD;CAClC;AACJ;;;;AAKA,SAAgB,sBACZ,MACA,SACW;CACX,QAAQ,SAAS,OAAO,QAAQ;EAC5B,MAAM,aAAa,SAAS,cAAc;EAC1C,IAAI,KAAK,SAAS,OAAO;GACrB,MAAM,QAAQ,MAAM,KAAK,SAAS;GAClC,IAAI,OACA,IAAI,OAAO,IAAI,iBAAiB,UAAU,OAAO;EAEzD,OAAO,IAAI,KAAK,SAAS,mBAAmB;GACxC,IAAI;GACJ,IAAI,CAAC,IAAI,QAAQ;IAEb,MAAM,cAAc,IAAI,OAAO;IAC/B,YACI,eAAe,SACT,IAAI,YAAY,CAAC,CAAC,OAAO,aAAa,aAAa,IAAI,OAAO,CAAC,IAC/D,SAAS,aAAa,IAAI,OAAO;GAC/C,OAEI,4BAAY,IAAI,WAAW,CAAC;GAGhC,MAAM,UAAU,MAAM,+BAA+B,MAAM;IACvD,KAAK,IAAI;IACT,QAAQ,IAAI;IACZ,MAAM;GACV,CAAC;GACD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC7C,IAAI,OAAO,IAAI,KAAK,KAAK;EAEjC;EACA,OAAO,KAAK,GAAG;CACnB;AACJ"}
|
|
1
|
+
{"version":3,"file":"transports.js","names":[],"sources":["../../src/shared/transports.ts"],"sourcesContent":["import { createConnectTransport } from \"@connectrpc/connect-web\";\nimport type { Transport, Interceptor } from \"@connectrpc/connect\";\nimport { toBinary, toJsonString } from \"@bufbuild/protobuf\";\nimport { signAsync } from \"@noble/ed25519\";\nimport { createErrorMappingTransport } from \"./connect-error-mapping.js\";\nimport { ConfigurationError, isAbortError, NetworkError } from \"./errors.js\";\n\nexport { isAbortError };\n\nexport type ConnectWireFormat = \"binary\" | \"json\";\n\nexport const POLYESTER_MOCK_HEADER = \"x-polyester-mock\";\n\nexport interface TransportConfig {\n apiUrl: string;\n interceptors?: Interceptor[];\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n /**\n * Connect wire format. Defaults to binary for production performance.\n * Use `json` for the API Playground visualization.\n */\n wireFormat?: ConnectWireFormat;\n}\n\nexport interface Transports {\n authApi: Transport;\n publicApi: Transport;\n}\n\n/**\n * Generic JWT auth for HTTP/Connect endpoints that follow the Bearer token contract.\n */\nexport interface JwtAuthProvider {\n kind: \"jwt\";\n /** Typically wraps the configured browser auth token storage. */\n getToken: () => string | null | Promise<string | null>;\n}\n\n/**\n * Generic Ed25519 API key auth for HTTP/Connect endpoints that follow the\n * X-API-KEY-ID / X-API-TIMESTAMP / X-API-SIGNATURE contract.\n */\nexport interface ApiKeyEd25519AuthProvider {\n kind: \"api-key-ed25519\";\n getKeyId: () => string | null | Promise<string | null>;\n /** Ed25519 secret key bytes (not hex) for signing. */\n getSecretKey: () => Uint8Array | null | Promise<Uint8Array | null>;\n}\n\nexport interface ApiKeyEd25519SigningRequest {\n url: string | URL;\n method: string;\n body?: Uint8Array;\n timestamp?: string;\n}\n\n/**\n * Returns the fetch implementation used by SDK transports.\n */\nexport function makeFetch(): typeof fetch {\n const wrappedFetch = Object.assign(\n async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n // Normalize headers into a mutable Headers object\n const headers = new Headers(init?.headers);\n\n try {\n const res = await fetch(input, {\n ...init,\n headers,\n redirect: \"manual\",\n });\n\n return res;\n } catch (err) {\n if (isAbortError(err)) throw err;\n throw new NetworkError(\"Transport request failed\", { cause: err });\n }\n },\n fetch,\n );\n\n return wrappedFetch;\n}\n\n/**\n * Creates Connect transports for SDK service clients.\n */\nexport function createTransports(config: TransportConfig): Transports {\n const { apiUrl, interceptors = [], auth, wireFormat = \"binary\" } = config;\n const useBinaryFormat = wireFormat === \"binary\";\n const publicApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors,\n fetch: makeFetch(),\n }),\n );\n\n const authInterceptors = auth\n ? [createAuthInterceptor(auth, { wireFormat }), ...interceptors]\n : interceptors;\n const authApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors: authInterceptors,\n fetch: makeFetch(),\n }),\n );\n\n return { authApi, publicApi };\n}\n\n/**\n * Creates an interceptor that enables mock transport behavior.\n */\nexport function createMockInterceptor(getEnabled: () => boolean): Interceptor {\n return (next) => async (req) => {\n if (getEnabled()) req.header.set(POLYESTER_MOCK_HEADER, \"true\");\n return next(req);\n };\n}\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n if (typeof crypto === \"undefined\" || !crypto.subtle) {\n throw new ConfigurationError(\"SHA-256 not available in this environment\");\n }\n const hash = await crypto.subtle.digest(\"SHA-256\", bytes.slice());\n return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nlet lastTimestamp = 0;\nfunction nextTimestamp(): string {\n lastTimestamp = Math.max(lastTimestamp + 1, Date.now());\n return String(lastTimestamp);\n}\n\nfunction canonicalQueryString(params: URLSearchParams): string {\n const pairs: string[] = [];\n for (const [k, v] of params.entries()) {\n pairs.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);\n }\n pairs.sort();\n return pairs.join(\"&\");\n}\n\n/**\n * Creates API-key authentication headers for endpoints using the Polyester Ed25519 signing contract.\n */\nexport async function createApiKeyEd25519AuthHeaders(\n auth: ApiKeyEd25519AuthProvider,\n request: ApiKeyEd25519SigningRequest,\n): Promise<Record<string, string>> {\n const [keyId, secretKey] = await Promise.all([auth.getKeyId(), auth.getSecretKey()]);\n if (!keyId || !secretKey) throw new ConfigurationError(\"Missing API key ID or secret key\");\n\n const urlObj = new URL(request.url);\n const timestamp = request.timestamp ?? nextTimestamp();\n const bodyHash = await sha256Hex(request.body ?? new Uint8Array(0));\n const canonicalQuery = canonicalQueryString(urlObj.searchParams);\n const canonical = `${timestamp}\\n${request.method}\\n${urlObj.pathname}\\n${canonicalQuery}\\n${bodyHash}`;\n const msgBytes = new TextEncoder().encode(canonical);\n const sig = await signAsync(msgBytes, secretKey);\n const signatureHex = Array.from(sig, (b: number) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n return {\n \"X-API-KEY-ID\": keyId,\n \"X-API-TIMESTAMP\": timestamp,\n \"X-API-SIGNATURE\": signatureHex,\n };\n}\n\n/**\n * Creates an interceptor that attaches SDK authentication headers.\n */\nexport function createAuthInterceptor(\n auth: JwtAuthProvider | ApiKeyEd25519AuthProvider,\n options?: { wireFormat?: ConnectWireFormat },\n): Interceptor {\n return (next) => async (req) => {\n const wireFormat = options?.wireFormat ?? \"binary\";\n if (auth.kind === \"jwt\") {\n const token = await auth.getToken();\n if (token) {\n req.header.set(\"Authorization\", `Bearer ${token}`);\n }\n } else if (auth.kind === \"api-key-ed25519\") {\n let bodyBytes: Uint8Array;\n if (!req.stream) {\n // unary request - serialize the message using the method's input schema\n const inputSchema = req.method.input;\n bodyBytes =\n wireFormat === \"json\"\n ? new TextEncoder().encode(toJsonString(inputSchema, req.message))\n : toBinary(inputSchema, req.message);\n } else {\n // stream request - empty body for signing (streams don't have a single body)\n bodyBytes = new Uint8Array(0);\n }\n\n const headers = await createApiKeyEd25519AuthHeaders(auth, {\n url: req.url,\n method: req.requestMethod,\n body: bodyBytes,\n });\n for (const [key, value] of Object.entries(headers)) {\n req.header.set(key, value);\n }\n }\n return next(req);\n };\n}\n"],"mappings":";;;;;;;;;AA2DA,SAAgB,YAA0B;CAsBtC,OArBqB,OAAO,OACxB,OAAO,OAAoC,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AI,YAAY,CAAC,CAAC,OAAO,aAAa,aAAa,IAAI,OAAO,CAAC,IAC/D,SAAS,aAAa,IAAI,OAAO;GAC/C,OAEI,4BAAY,IAAI,WAAW,CAAC;GAGhC,MAAM,UAAU,MAAM,+BAA+B,MAAM;IACvD,KAAK,IAAI;IACT,QAAQ,IAAI;IACZ,MAAM;GACV,CAAC;GACD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC7C,IAAI,OAAO,IAAI,KAAK,KAAK;EAEjC;EACA,OAAO,KAAK,GAAG;CACnB;AACJ"}
|
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
const PROTOBUF_INT64_MAX = 9223372036854775807n;
|
|
4
4
|
/** Largest value encodable by a protobuf `int32` field. */
|
|
5
5
|
const PROTOBUF_INT32_MAX = 2147483647n;
|
|
6
|
+
/** Largest value encodable by a protobuf `uint32` field. */
|
|
7
|
+
const PROTOBUF_UINT32_MAX = 4294967295;
|
|
6
8
|
//#endregion
|
|
7
|
-
export { PROTOBUF_INT32_MAX, PROTOBUF_INT64_MAX };
|
|
9
|
+
export { PROTOBUF_INT32_MAX, PROTOBUF_INT64_MAX, PROTOBUF_UINT32_MAX };
|
|
8
10
|
|
|
9
11
|
//# sourceMappingURL=wire-bounds.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wire-bounds.js","names":[],"sources":["../../src/shared/wire-bounds.ts"],"sourcesContent":["/** Largest value encodable by a protobuf `int64` field. */\nexport const PROTOBUF_INT64_MAX = 9_223_372_036_854_775_807n;\n\n/** Largest value encodable by a protobuf `int32` field. */\nexport const PROTOBUF_INT32_MAX = 2_147_483_647n;\n"],"mappings":";;AACA,MAAa,qBAAqB;;AAGlC,MAAa,qBAAqB"}
|
|
1
|
+
{"version":3,"file":"wire-bounds.js","names":[],"sources":["../../src/shared/wire-bounds.ts"],"sourcesContent":["/** Largest value encodable by a protobuf `int64` field. */\nexport const PROTOBUF_INT64_MAX = 9_223_372_036_854_775_807n;\n\n/** Largest value encodable by a protobuf `int32` field. */\nexport const PROTOBUF_INT32_MAX = 2_147_483_647n;\n\n/** Largest value encodable by a protobuf `uint32` field. */\nexport const PROTOBUF_UINT32_MAX = 4_294_967_295;\n"],"mappings":";;AACA,MAAa,qBAAqB;;AAGlC,MAAa,qBAAqB;;AAGlC,MAAa,sBAAsB"}
|
package/dist/utils/numbers.js
CHANGED
|
@@ -45,16 +45,7 @@ function toBpsOrZero(value) {
|
|
|
45
45
|
if (value == null || Number.isNaN(value)) return 0;
|
|
46
46
|
return Math.max(0, Math.trunc(value * 100));
|
|
47
47
|
}
|
|
48
|
-
/**
|
|
49
|
-
* Convert basis points to percentage.
|
|
50
|
-
* @param value - The value to convert.
|
|
51
|
-
* @returns The converted percentage.
|
|
52
|
-
*/
|
|
53
|
-
function bpsToPct(value) {
|
|
54
|
-
if (value == null || Number.isNaN(value)) return 0;
|
|
55
|
-
return value / 100;
|
|
56
|
-
}
|
|
57
48
|
//#endregion
|
|
58
|
-
export {
|
|
49
|
+
export { parseOptionalPositiveIntLike, parseOptionalUint64DecimalStrict, toBigIntOrZero, toBpsOrZero, toIntOrZero };
|
|
59
50
|
|
|
60
51
|
//# sourceMappingURL=numbers.js.map
|