@polyester/sdk 0.34.1-devnet-20261106033258 → 0.35.0-devnet-20261107174905
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 +11 -1
- package/README.md +12 -0
- package/dist/index.d.ts +2 -2
- package/dist/realtime/client.d.ts.map +1 -1
- package/dist/realtime/client.js +178 -29
- package/dist/realtime/client.js.map +1 -1
- package/dist/realtime/index.d.ts +2 -2
- package/dist/realtime/types.d.ts +21 -2
- package/dist/realtime/types.d.ts.map +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts +2 -2
- package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +19 -19
- package/dist/services/candles/candles.schemas.d.ts +10 -10
- package/dist/services/checkpoints/checkpoints.schemas.d.ts +2 -2
- package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +42 -42
- package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
- package/dist/services/orderbook/orderbook.d.ts +1 -1
- package/dist/services/orderbook/orderbook.js +1 -1
- package/dist/services/orderbook/orderbook.js.map +1 -1
- package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
- package/dist/services/orders/orders-batch.schemas.d.ts +19 -19
- package/dist/services/orders/orders-output.schemas.d.ts +15 -15
- package/dist/services/rewards/rewards.schemas.d.ts +3 -3
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +15 -15
- package/dist/services/trades/trades.schemas.d.ts +2 -2
- package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
- package/dist/services/triggers/triggers-output.schemas.d.ts +37 -37
- package/dist/shared/connect-error-mapping.d.ts.map +1 -1
- package/dist/shared/connect-error-mapping.js +5 -2
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/subscription-errors.d.ts +2 -0
- package/dist/shared/subscription-errors.d.ts.map +1 -1
- package/dist/shared/subscription-errors.js.map +1 -1
- package/package.json +1 -1
|
@@ -29,62 +29,62 @@ declare const CreateTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSche
|
|
|
29
29
|
type CreateTriggerResult = v.InferOutput<typeof CreateTriggerResultSchema>;
|
|
30
30
|
declare const CancelTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
31
31
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
32
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
32
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
33
33
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
34
34
|
}, undefined>, v.TransformAction<{
|
|
35
35
|
triggerId: string;
|
|
36
|
-
status: "unspecified" | "
|
|
36
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
37
37
|
tsNs: bigint;
|
|
38
38
|
}, {
|
|
39
39
|
ts: number;
|
|
40
40
|
tsNs: string;
|
|
41
41
|
triggerId: string;
|
|
42
|
-
status: "unspecified" | "
|
|
42
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
43
43
|
}>]>;
|
|
44
44
|
type CancelTriggerResult = v.InferOutput<typeof CancelTriggerResultSchema>;
|
|
45
45
|
declare const ModifyTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
46
46
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
47
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
47
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
48
48
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
49
49
|
}, undefined>, v.TransformAction<{
|
|
50
50
|
triggerId: string;
|
|
51
|
-
status: "unspecified" | "
|
|
51
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
52
52
|
tsNs: bigint;
|
|
53
53
|
}, {
|
|
54
54
|
ts: number;
|
|
55
55
|
tsNs: string;
|
|
56
56
|
triggerId: string;
|
|
57
|
-
status: "unspecified" | "
|
|
57
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
58
58
|
}>]>;
|
|
59
59
|
type ModifyTriggerResult = v.InferOutput<typeof ModifyTriggerResultSchema>;
|
|
60
60
|
declare const PauseTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
61
61
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
62
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
62
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
63
63
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
64
64
|
}, undefined>, v.TransformAction<{
|
|
65
65
|
triggerId: string;
|
|
66
|
-
status: "unspecified" | "
|
|
66
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
67
67
|
tsNs: bigint;
|
|
68
68
|
}, {
|
|
69
69
|
ts: number;
|
|
70
70
|
tsNs: string;
|
|
71
71
|
triggerId: string;
|
|
72
|
-
status: "unspecified" | "
|
|
72
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
73
73
|
}>]>;
|
|
74
74
|
type PauseTriggerResult = v.InferOutput<typeof PauseTriggerResultSchema>;
|
|
75
75
|
declare const ResumeTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
76
76
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
77
|
-
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "
|
|
77
|
+
readonly status: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
78
78
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
79
79
|
}, undefined>, v.TransformAction<{
|
|
80
80
|
triggerId: string;
|
|
81
|
-
status: "unspecified" | "
|
|
81
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
82
82
|
tsNs: bigint;
|
|
83
83
|
}, {
|
|
84
84
|
ts: number;
|
|
85
85
|
tsNs: string;
|
|
86
86
|
triggerId: string;
|
|
87
|
-
status: "unspecified" | "
|
|
87
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
88
88
|
}>]>;
|
|
89
89
|
type ResumeTriggerResult = v.InferOutput<typeof ResumeTriggerResultSchema>;
|
|
90
90
|
type StopDetailsOutput = {
|
|
@@ -608,19 +608,19 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
608
608
|
}, {
|
|
609
609
|
runtimeDetails: TriggerDetailsOutput;
|
|
610
610
|
version: number;
|
|
611
|
-
cancelReason: "unspecified" | "
|
|
611
|
+
cancelReason: "unspecified" | "oco" | "user_request" | "account_repair" | "market_halted" | "internal_error" | "parent_canceled_no_fill" | "self_trade_prevention" | "pair_drain_trigger" | "pair_drain_twap" | "pair_drain_ladder" | "pair_drain_attached_leg" | "missing_reason_code";
|
|
612
612
|
failureReason: undefined;
|
|
613
613
|
triggerId: string;
|
|
614
614
|
subaccountId: string;
|
|
615
615
|
symbolId: number;
|
|
616
|
-
status: "unspecified" | "
|
|
616
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
617
617
|
parentOrderId: string | undefined;
|
|
618
618
|
qty: string;
|
|
619
619
|
feeAsset: "unspecified" | "quote" | "base";
|
|
620
620
|
selfTradePreventionMode: "unspecified" | "expire_taker" | "expire_maker" | "expire_both";
|
|
621
621
|
configuration: {
|
|
622
622
|
type: "stop_loss" | "take_profit";
|
|
623
|
-
side: "
|
|
623
|
+
side: "buy" | "sell" | "unspecified";
|
|
624
624
|
triggerPrice: string;
|
|
625
625
|
execution: {
|
|
626
626
|
readonly type: "market_ioc";
|
|
@@ -672,7 +672,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
672
672
|
readonly postOnly?: undefined;
|
|
673
673
|
} | {
|
|
674
674
|
type: "trailing_stop";
|
|
675
|
-
side: "
|
|
675
|
+
side: "buy" | "sell" | "unspecified";
|
|
676
676
|
trailingDistance: {
|
|
677
677
|
kind: "distance";
|
|
678
678
|
distance: string;
|
|
@@ -711,7 +711,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
711
711
|
readonly postOnly?: undefined;
|
|
712
712
|
} | {
|
|
713
713
|
type: "twap";
|
|
714
|
-
side: "
|
|
714
|
+
side: "buy" | "sell" | "unspecified";
|
|
715
715
|
durationMs: number;
|
|
716
716
|
sliceIntervalMs: number;
|
|
717
717
|
execution: {
|
|
@@ -750,7 +750,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
750
750
|
readonly postOnly?: undefined;
|
|
751
751
|
} | {
|
|
752
752
|
type: "ladder";
|
|
753
|
-
side: "
|
|
753
|
+
side: "buy" | "sell" | "unspecified";
|
|
754
754
|
priceMin: string;
|
|
755
755
|
priceMax: string;
|
|
756
756
|
levels: number;
|
|
@@ -788,18 +788,18 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
788
788
|
runtimeDetails: TriggerDetailsOutput;
|
|
789
789
|
version: number;
|
|
790
790
|
cancelReason: undefined;
|
|
791
|
-
failureReason: "unspecified" | "
|
|
791
|
+
failureReason: "unspecified" | "market_halted" | "internal_error" | "missing_reason_code" | "unknown_symbol" | "pair_disabled" | "min_notional" | "tick_size" | "insufficient_funds" | "risk_limit" | "duplicate_client_id" | "engine_busy" | "account_unknown" | "order_unknown" | "post_only_cross" | "reduce_only_blocked" | "price_band_violation" | "market_cap_violation" | "empty_book" | "fok_insufficient_liquidity" | "fee_asset_not_allowed" | "market_price_unavailable" | "stale_quote" | "min_quantity" | "step_size" | "invalid_sizing" | "max_quote_debit_too_small" | "fee_ceiling_exceeded" | "trigger_price_invalid" | "trigger_price_source_unsupported" | "trailing_distance_invalid" | "modification_requires_replace" | "order_already_terminal" | "conflict_idempotency_key_reuse" | "rate_limited" | "policy_spot_trade_deny" | "policy_market_deny" | "policy_max_notional" | "policy_max_open_orders" | "policy_trading_halted" | "max_slippage_invalid" | "invalid_time_in_force" | "duplicate_order_id" | "max_quantity" | "max_notional" | "pair_post_only" | "max_open_orders_total" | "stp_mode_not_allowed" | "pair_backlogged" | "mode_not_supported" | "market_quote_stale" | "market_quote_unhealthy" | "qty_invalid" | "limit_price_invalid" | "twap_interval_invalid" | "ladder_range_too_narrow" | "ladder_levels_invalid" | "attached_legs_exceeded" | "price_levels_exhausted" | "settlement_backlogged" | "client_order_ids_exhausted" | "invalid_order_id" | "order_id_conflict" | "invalid_side" | "invalid_order_type" | "invalid_stp_mode" | "invalid_order_flags" | "price_level_quantity_limit" | "child_qty_raise_not_allowed" | "triggers_exhausted" | "order_sequence_exhausted" | "fee_schedule_unavailable" | "policy_unavailable" | "account_routing_invalid" | "client_trigger_id_invalid" | "trigger_direction_invalid" | "fee_asset_invalid" | "fee_ceiling_invalid" | "unsupported_field_set" | "trigger_fire_limit_reached" | "condition_flags_invalid" | "condition_parameter_set" | "slippage_ticks_invalid" | "slippage_bps_invalid" | "slippage_bounds_conflict" | "limit_child_slippage_set" | "new_account_capacity_reached" | "order_type_not_allowed_in_auction" | "post_only_not_allowed_in_auction" | "twap_capacity_reached" | "order_limits_unavailable" | "child_order_inconsistent" | "index_price_unavailable" | "trigger_would_trigger_immediately" | "max_open_orders_per_pair" | "account_repairing" | "self_trade_prevented";
|
|
792
792
|
triggerId: string;
|
|
793
793
|
subaccountId: string;
|
|
794
794
|
symbolId: number;
|
|
795
|
-
status: "unspecified" | "
|
|
795
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
796
796
|
parentOrderId: string | undefined;
|
|
797
797
|
qty: string;
|
|
798
798
|
feeAsset: "unspecified" | "quote" | "base";
|
|
799
799
|
selfTradePreventionMode: "unspecified" | "expire_taker" | "expire_maker" | "expire_both";
|
|
800
800
|
configuration: {
|
|
801
801
|
type: "stop_loss" | "take_profit";
|
|
802
|
-
side: "
|
|
802
|
+
side: "buy" | "sell" | "unspecified";
|
|
803
803
|
triggerPrice: string;
|
|
804
804
|
execution: {
|
|
805
805
|
readonly type: "market_ioc";
|
|
@@ -851,7 +851,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
851
851
|
readonly postOnly?: undefined;
|
|
852
852
|
} | {
|
|
853
853
|
type: "trailing_stop";
|
|
854
|
-
side: "
|
|
854
|
+
side: "buy" | "sell" | "unspecified";
|
|
855
855
|
trailingDistance: {
|
|
856
856
|
kind: "distance";
|
|
857
857
|
distance: string;
|
|
@@ -890,7 +890,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
890
890
|
readonly postOnly?: undefined;
|
|
891
891
|
} | {
|
|
892
892
|
type: "twap";
|
|
893
|
-
side: "
|
|
893
|
+
side: "buy" | "sell" | "unspecified";
|
|
894
894
|
durationMs: number;
|
|
895
895
|
sliceIntervalMs: number;
|
|
896
896
|
execution: {
|
|
@@ -929,7 +929,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
929
929
|
readonly postOnly?: undefined;
|
|
930
930
|
} | {
|
|
931
931
|
type: "ladder";
|
|
932
|
-
side: "
|
|
932
|
+
side: "buy" | "sell" | "unspecified";
|
|
933
933
|
priceMin: string;
|
|
934
934
|
priceMax: string;
|
|
935
935
|
levels: number;
|
|
@@ -971,14 +971,14 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
971
971
|
triggerId: string;
|
|
972
972
|
subaccountId: string;
|
|
973
973
|
symbolId: number;
|
|
974
|
-
status: "unspecified" | "
|
|
974
|
+
status: "unspecified" | "failed" | "canceled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
975
975
|
parentOrderId: string | undefined;
|
|
976
976
|
qty: string;
|
|
977
977
|
feeAsset: "unspecified" | "quote" | "base";
|
|
978
978
|
selfTradePreventionMode: "unspecified" | "expire_taker" | "expire_maker" | "expire_both";
|
|
979
979
|
configuration: {
|
|
980
980
|
type: "stop_loss" | "take_profit";
|
|
981
|
-
side: "
|
|
981
|
+
side: "buy" | "sell" | "unspecified";
|
|
982
982
|
triggerPrice: string;
|
|
983
983
|
execution: {
|
|
984
984
|
readonly type: "market_ioc";
|
|
@@ -1030,7 +1030,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
1030
1030
|
readonly postOnly?: undefined;
|
|
1031
1031
|
} | {
|
|
1032
1032
|
type: "trailing_stop";
|
|
1033
|
-
side: "
|
|
1033
|
+
side: "buy" | "sell" | "unspecified";
|
|
1034
1034
|
trailingDistance: {
|
|
1035
1035
|
kind: "distance";
|
|
1036
1036
|
distance: string;
|
|
@@ -1069,7 +1069,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
1069
1069
|
readonly postOnly?: undefined;
|
|
1070
1070
|
} | {
|
|
1071
1071
|
type: "twap";
|
|
1072
|
-
side: "
|
|
1072
|
+
side: "buy" | "sell" | "unspecified";
|
|
1073
1073
|
durationMs: number;
|
|
1074
1074
|
sliceIntervalMs: number;
|
|
1075
1075
|
execution: {
|
|
@@ -1108,7 +1108,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
1108
1108
|
readonly postOnly?: undefined;
|
|
1109
1109
|
} | {
|
|
1110
1110
|
type: "ladder";
|
|
1111
|
-
side: "
|
|
1111
|
+
side: "buy" | "sell" | "unspecified";
|
|
1112
1112
|
priceMin: string;
|
|
1113
1113
|
priceMax: string;
|
|
1114
1114
|
levels: number;
|
|
@@ -1189,14 +1189,14 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1189
1189
|
fireRefusalReason?: number | undefined;
|
|
1190
1190
|
}, {
|
|
1191
1191
|
/** Why a `fire_refused` attempt was refused; the trigger stayed live. */
|
|
1192
|
-
fireRefusalReason: "unspecified" | "
|
|
1193
|
-
cancelReason: "unspecified" | "
|
|
1192
|
+
fireRefusalReason: "unspecified" | "market_halted" | "internal_error" | "missing_reason_code" | "unknown_symbol" | "pair_disabled" | "min_notional" | "tick_size" | "insufficient_funds" | "risk_limit" | "duplicate_client_id" | "engine_busy" | "account_unknown" | "order_unknown" | "post_only_cross" | "reduce_only_blocked" | "price_band_violation" | "market_cap_violation" | "empty_book" | "fok_insufficient_liquidity" | "fee_asset_not_allowed" | "market_price_unavailable" | "stale_quote" | "min_quantity" | "step_size" | "invalid_sizing" | "max_quote_debit_too_small" | "fee_ceiling_exceeded" | "trigger_price_invalid" | "trigger_price_source_unsupported" | "trailing_distance_invalid" | "modification_requires_replace" | "order_already_terminal" | "conflict_idempotency_key_reuse" | "rate_limited" | "policy_spot_trade_deny" | "policy_market_deny" | "policy_max_notional" | "policy_max_open_orders" | "policy_trading_halted" | "max_slippage_invalid" | "invalid_time_in_force" | "duplicate_order_id" | "max_quantity" | "max_notional" | "pair_post_only" | "max_open_orders_total" | "stp_mode_not_allowed" | "pair_backlogged" | "mode_not_supported" | "market_quote_stale" | "market_quote_unhealthy" | "qty_invalid" | "limit_price_invalid" | "twap_interval_invalid" | "ladder_range_too_narrow" | "ladder_levels_invalid" | "attached_legs_exceeded" | "price_levels_exhausted" | "settlement_backlogged" | "client_order_ids_exhausted" | "invalid_order_id" | "order_id_conflict" | "invalid_side" | "invalid_order_type" | "invalid_stp_mode" | "invalid_order_flags" | "price_level_quantity_limit" | "child_qty_raise_not_allowed" | "triggers_exhausted" | "order_sequence_exhausted" | "fee_schedule_unavailable" | "policy_unavailable" | "account_routing_invalid" | "client_trigger_id_invalid" | "trigger_direction_invalid" | "fee_asset_invalid" | "fee_ceiling_invalid" | "unsupported_field_set" | "trigger_fire_limit_reached" | "condition_flags_invalid" | "condition_parameter_set" | "slippage_ticks_invalid" | "slippage_bps_invalid" | "slippage_bounds_conflict" | "limit_child_slippage_set" | "new_account_capacity_reached" | "order_type_not_allowed_in_auction" | "post_only_not_allowed_in_auction" | "twap_capacity_reached" | "order_limits_unavailable" | "child_order_inconsistent" | "index_price_unavailable" | "trigger_would_trigger_immediately" | "max_open_orders_per_pair" | "account_repairing" | "self_trade_prevented" | undefined;
|
|
1193
|
+
cancelReason: "unspecified" | "oco" | "user_request" | "account_repair" | "market_halted" | "internal_error" | "parent_canceled_no_fill" | "self_trade_prevention" | "pair_drain_trigger" | "pair_drain_twap" | "pair_drain_ladder" | "pair_drain_attached_leg" | "missing_reason_code";
|
|
1194
1194
|
failureReason: undefined;
|
|
1195
1195
|
triggerId: string;
|
|
1196
1196
|
subaccountId: string;
|
|
1197
1197
|
symbolId: number;
|
|
1198
1198
|
triggerType: "unspecified" | "twap" | "ladder" | "stop_loss" | "take_profit" | "trailing_stop";
|
|
1199
|
-
eventType: "unspecified" | "failed" | "canceled" | "
|
|
1199
|
+
eventType: "unspecified" | "failed" | "canceled" | "armed" | "updated" | "fired" | "activated" | "fire_refused";
|
|
1200
1200
|
ts: number;
|
|
1201
1201
|
tsNs: string;
|
|
1202
1202
|
childSeq: number;
|
|
@@ -1204,14 +1204,14 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1204
1204
|
firePrice: string | undefined;
|
|
1205
1205
|
} | {
|
|
1206
1206
|
/** Why a `fire_refused` attempt was refused; the trigger stayed live. */
|
|
1207
|
-
fireRefusalReason: "unspecified" | "
|
|
1207
|
+
fireRefusalReason: "unspecified" | "market_halted" | "internal_error" | "missing_reason_code" | "unknown_symbol" | "pair_disabled" | "min_notional" | "tick_size" | "insufficient_funds" | "risk_limit" | "duplicate_client_id" | "engine_busy" | "account_unknown" | "order_unknown" | "post_only_cross" | "reduce_only_blocked" | "price_band_violation" | "market_cap_violation" | "empty_book" | "fok_insufficient_liquidity" | "fee_asset_not_allowed" | "market_price_unavailable" | "stale_quote" | "min_quantity" | "step_size" | "invalid_sizing" | "max_quote_debit_too_small" | "fee_ceiling_exceeded" | "trigger_price_invalid" | "trigger_price_source_unsupported" | "trailing_distance_invalid" | "modification_requires_replace" | "order_already_terminal" | "conflict_idempotency_key_reuse" | "rate_limited" | "policy_spot_trade_deny" | "policy_market_deny" | "policy_max_notional" | "policy_max_open_orders" | "policy_trading_halted" | "max_slippage_invalid" | "invalid_time_in_force" | "duplicate_order_id" | "max_quantity" | "max_notional" | "pair_post_only" | "max_open_orders_total" | "stp_mode_not_allowed" | "pair_backlogged" | "mode_not_supported" | "market_quote_stale" | "market_quote_unhealthy" | "qty_invalid" | "limit_price_invalid" | "twap_interval_invalid" | "ladder_range_too_narrow" | "ladder_levels_invalid" | "attached_legs_exceeded" | "price_levels_exhausted" | "settlement_backlogged" | "client_order_ids_exhausted" | "invalid_order_id" | "order_id_conflict" | "invalid_side" | "invalid_order_type" | "invalid_stp_mode" | "invalid_order_flags" | "price_level_quantity_limit" | "child_qty_raise_not_allowed" | "triggers_exhausted" | "order_sequence_exhausted" | "fee_schedule_unavailable" | "policy_unavailable" | "account_routing_invalid" | "client_trigger_id_invalid" | "trigger_direction_invalid" | "fee_asset_invalid" | "fee_ceiling_invalid" | "unsupported_field_set" | "trigger_fire_limit_reached" | "condition_flags_invalid" | "condition_parameter_set" | "slippage_ticks_invalid" | "slippage_bps_invalid" | "slippage_bounds_conflict" | "limit_child_slippage_set" | "new_account_capacity_reached" | "order_type_not_allowed_in_auction" | "post_only_not_allowed_in_auction" | "twap_capacity_reached" | "order_limits_unavailable" | "child_order_inconsistent" | "index_price_unavailable" | "trigger_would_trigger_immediately" | "max_open_orders_per_pair" | "account_repairing" | "self_trade_prevented" | undefined;
|
|
1208
1208
|
cancelReason: undefined;
|
|
1209
|
-
failureReason: "unspecified" | "
|
|
1209
|
+
failureReason: "unspecified" | "market_halted" | "internal_error" | "missing_reason_code" | "unknown_symbol" | "pair_disabled" | "min_notional" | "tick_size" | "insufficient_funds" | "risk_limit" | "duplicate_client_id" | "engine_busy" | "account_unknown" | "order_unknown" | "post_only_cross" | "reduce_only_blocked" | "price_band_violation" | "market_cap_violation" | "empty_book" | "fok_insufficient_liquidity" | "fee_asset_not_allowed" | "market_price_unavailable" | "stale_quote" | "min_quantity" | "step_size" | "invalid_sizing" | "max_quote_debit_too_small" | "fee_ceiling_exceeded" | "trigger_price_invalid" | "trigger_price_source_unsupported" | "trailing_distance_invalid" | "modification_requires_replace" | "order_already_terminal" | "conflict_idempotency_key_reuse" | "rate_limited" | "policy_spot_trade_deny" | "policy_market_deny" | "policy_max_notional" | "policy_max_open_orders" | "policy_trading_halted" | "max_slippage_invalid" | "invalid_time_in_force" | "duplicate_order_id" | "max_quantity" | "max_notional" | "pair_post_only" | "max_open_orders_total" | "stp_mode_not_allowed" | "pair_backlogged" | "mode_not_supported" | "market_quote_stale" | "market_quote_unhealthy" | "qty_invalid" | "limit_price_invalid" | "twap_interval_invalid" | "ladder_range_too_narrow" | "ladder_levels_invalid" | "attached_legs_exceeded" | "price_levels_exhausted" | "settlement_backlogged" | "client_order_ids_exhausted" | "invalid_order_id" | "order_id_conflict" | "invalid_side" | "invalid_order_type" | "invalid_stp_mode" | "invalid_order_flags" | "price_level_quantity_limit" | "child_qty_raise_not_allowed" | "triggers_exhausted" | "order_sequence_exhausted" | "fee_schedule_unavailable" | "policy_unavailable" | "account_routing_invalid" | "client_trigger_id_invalid" | "trigger_direction_invalid" | "fee_asset_invalid" | "fee_ceiling_invalid" | "unsupported_field_set" | "trigger_fire_limit_reached" | "condition_flags_invalid" | "condition_parameter_set" | "slippage_ticks_invalid" | "slippage_bps_invalid" | "slippage_bounds_conflict" | "limit_child_slippage_set" | "new_account_capacity_reached" | "order_type_not_allowed_in_auction" | "post_only_not_allowed_in_auction" | "twap_capacity_reached" | "order_limits_unavailable" | "child_order_inconsistent" | "index_price_unavailable" | "trigger_would_trigger_immediately" | "max_open_orders_per_pair" | "account_repairing" | "self_trade_prevented";
|
|
1210
1210
|
triggerId: string;
|
|
1211
1211
|
subaccountId: string;
|
|
1212
1212
|
symbolId: number;
|
|
1213
1213
|
triggerType: "unspecified" | "twap" | "ladder" | "stop_loss" | "take_profit" | "trailing_stop";
|
|
1214
|
-
eventType: "unspecified" | "failed" | "canceled" | "
|
|
1214
|
+
eventType: "unspecified" | "failed" | "canceled" | "armed" | "updated" | "fired" | "activated" | "fire_refused";
|
|
1215
1215
|
ts: number;
|
|
1216
1216
|
tsNs: string;
|
|
1217
1217
|
childSeq: number;
|
|
@@ -1219,14 +1219,14 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1219
1219
|
firePrice: string | undefined;
|
|
1220
1220
|
} | {
|
|
1221
1221
|
/** Why a `fire_refused` attempt was refused; the trigger stayed live. */
|
|
1222
|
-
fireRefusalReason: "unspecified" | "
|
|
1222
|
+
fireRefusalReason: "unspecified" | "market_halted" | "internal_error" | "missing_reason_code" | "unknown_symbol" | "pair_disabled" | "min_notional" | "tick_size" | "insufficient_funds" | "risk_limit" | "duplicate_client_id" | "engine_busy" | "account_unknown" | "order_unknown" | "post_only_cross" | "reduce_only_blocked" | "price_band_violation" | "market_cap_violation" | "empty_book" | "fok_insufficient_liquidity" | "fee_asset_not_allowed" | "market_price_unavailable" | "stale_quote" | "min_quantity" | "step_size" | "invalid_sizing" | "max_quote_debit_too_small" | "fee_ceiling_exceeded" | "trigger_price_invalid" | "trigger_price_source_unsupported" | "trailing_distance_invalid" | "modification_requires_replace" | "order_already_terminal" | "conflict_idempotency_key_reuse" | "rate_limited" | "policy_spot_trade_deny" | "policy_market_deny" | "policy_max_notional" | "policy_max_open_orders" | "policy_trading_halted" | "max_slippage_invalid" | "invalid_time_in_force" | "duplicate_order_id" | "max_quantity" | "max_notional" | "pair_post_only" | "max_open_orders_total" | "stp_mode_not_allowed" | "pair_backlogged" | "mode_not_supported" | "market_quote_stale" | "market_quote_unhealthy" | "qty_invalid" | "limit_price_invalid" | "twap_interval_invalid" | "ladder_range_too_narrow" | "ladder_levels_invalid" | "attached_legs_exceeded" | "price_levels_exhausted" | "settlement_backlogged" | "client_order_ids_exhausted" | "invalid_order_id" | "order_id_conflict" | "invalid_side" | "invalid_order_type" | "invalid_stp_mode" | "invalid_order_flags" | "price_level_quantity_limit" | "child_qty_raise_not_allowed" | "triggers_exhausted" | "order_sequence_exhausted" | "fee_schedule_unavailable" | "policy_unavailable" | "account_routing_invalid" | "client_trigger_id_invalid" | "trigger_direction_invalid" | "fee_asset_invalid" | "fee_ceiling_invalid" | "unsupported_field_set" | "trigger_fire_limit_reached" | "condition_flags_invalid" | "condition_parameter_set" | "slippage_ticks_invalid" | "slippage_bps_invalid" | "slippage_bounds_conflict" | "limit_child_slippage_set" | "new_account_capacity_reached" | "order_type_not_allowed_in_auction" | "post_only_not_allowed_in_auction" | "twap_capacity_reached" | "order_limits_unavailable" | "child_order_inconsistent" | "index_price_unavailable" | "trigger_would_trigger_immediately" | "max_open_orders_per_pair" | "account_repairing" | "self_trade_prevented" | undefined;
|
|
1223
1223
|
cancelReason: undefined;
|
|
1224
1224
|
failureReason: undefined;
|
|
1225
1225
|
triggerId: string;
|
|
1226
1226
|
subaccountId: string;
|
|
1227
1227
|
symbolId: number;
|
|
1228
1228
|
triggerType: "unspecified" | "twap" | "ladder" | "stop_loss" | "take_profit" | "trailing_stop";
|
|
1229
|
-
eventType: "unspecified" | "failed" | "canceled" | "
|
|
1229
|
+
eventType: "unspecified" | "failed" | "canceled" | "armed" | "updated" | "fired" | "activated" | "fire_refused";
|
|
1230
1230
|
ts: number;
|
|
1231
1231
|
tsNs: string;
|
|
1232
1232
|
childSeq: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"connect-error-mapping.d.ts","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"mappings":";;;;;;;iBAgMgB,6BAA6B,IAAI,eAAe;;;;;;;;;iBAiNhD,iBAAiB;;;;;;iBAyDjB,iCAAiC"}
|
|
@@ -53,7 +53,10 @@ function mfaErrorKind(detail) {
|
|
|
53
53
|
return null;
|
|
54
54
|
}
|
|
55
55
|
function parseRetryAfterMs(ce) {
|
|
56
|
-
|
|
56
|
+
return parseRetryAfterHeader(ce.metadata.get("retry-after"));
|
|
57
|
+
}
|
|
58
|
+
/** Parses an HTTP `Retry-After` value (delay seconds or HTTP date) into milliseconds. */
|
|
59
|
+
function parseRetryAfterHeader(value) {
|
|
57
60
|
if (!value) return void 0;
|
|
58
61
|
if (/^\d+$/u.test(value)) {
|
|
59
62
|
const seconds = BigInt(value);
|
|
@@ -262,6 +265,6 @@ function createErrorMappingTransport(transport) {
|
|
|
262
265
|
};
|
|
263
266
|
}
|
|
264
267
|
//#endregion
|
|
265
|
-
export { TIMESTAMP_SKEW_CODE, connectErrorToPolyesterError, createErrorMappingInterceptor, createErrorMappingTransport, getNormalizedConnectMessage, toPolyesterError };
|
|
268
|
+
export { TIMESTAMP_SKEW_CODE, connectErrorToPolyesterError, createErrorMappingInterceptor, createErrorMappingTransport, getNormalizedConnectMessage, parseRetryAfterHeader, toPolyesterError };
|
|
266
269
|
|
|
267
270
|
//# sourceMappingURL=connect-error-mapping.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect-error-mapping.js","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport {\n loadErrorDetailDecoders,\n parseConnectErrorDetail,\n type PolyesterErrorDetail,\n} from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\n isAbortError,\n isTimeoutAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n OutcomeUnknownError,\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 SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TimestampSkewError,\n TransientError,\n ValidationError,\n WithdrawDeadlineExpiredError,\n} from \"./errors.js\";\nimport type { RateLimitDetail } from \"./rate-limit.schemas.js\";\n\n/** Backend code for API-key signatures whose timestamp is outside the skew window. */\nexport const TIMESTAMP_SKEW_CODE = \"TIMESTAMP_SKEW\";\n\n// The withdraw service has no structured code for this; match its message.\nconst WITHDRAW_DEADLINE_EXPIRED_MESSAGE = \"deadline_ts_sec has expired\";\n\nfunction hasTransientServiceError(detail: PolyesterErrorDetail | undefined): boolean {\n if (detail?.service === \"withdraw\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SOURCE_SMART_ACCOUNT_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"CHAIN_METADATA_UNAVAILABLE\",\n \"FEE_UNAVAILABLE\",\n \"SUPPLY_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"DESTINATION_VALIDATION_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"internal_transfer\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SMART_ACCOUNT_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"claims\") {\n return [\"SERVICE_UNAVAILABLE\", \"CLAIM_TEMPORARILY_UNAVAILABLE\"].includes(detail.code);\n }\n // The account request changed nothing; the same request can be retried.\n if (detail?.service === \"auth\") {\n return detail.code === \"AUTH_TEMPORARILY_UNAVAILABLE\";\n }\n return false;\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\nconst HTTP_WEEKDAY = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst HTTP_WEEKDAY_LONG = \"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\";\nconst HTTP_MONTH = \"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\";\nconst HTTP_DATE_RE = new RegExp(\n `^(?:${HTTP_WEEKDAY}, \\\\d{2} ${HTTP_MONTH} \\\\d{4} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY_LONG}, \\\\d{2}-${HTTP_MONTH}-\\\\d{2} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY} ${HTTP_MONTH} {1,2}\\\\d{1,2} \\\\d{2}:\\\\d{2}:\\\\d{2} \\\\d{4})$`,\n \"u\",\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 const mapped = toPolyesterError(err);\n return mfaErrorKind(mapped instanceof PolyesterError ? mapped.detail : undefined);\n}\n\nfunction mfaErrorKind(detail: PolyesterErrorDetail | undefined): MfaErrorKind | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_ELEVATION_REQUIRED\") {\n return \"session-elevation\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_STEP_UP_REQUIRED\") return \"step-up\";\n if (detail?.service === \"auth\" && detail.code === \"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 if (/^\\d+$/u.test(value)) {\n const seconds = BigInt(value);\n const maxSafeSeconds = BigInt(Math.floor(Number.MAX_SAFE_INTEGER / 1000));\n return seconds <= maxSafeSeconds ? Number(seconds) * 1000 : undefined;\n }\n if (!HTTP_DATE_RE.test(value)) return undefined;\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// Client-side failures (timeouts, fetch errors, aborts) carry no response metadata.\nfunction hasResponseMetadata(ce: ConnectError): boolean {\n return !ce.metadata.keys().next().done;\n}\n\n// HTTP status Connect servers send for each error code\n// (https://connectrpc.com/docs/protocol#error-codes). Connect's own\n// codeToHttpStatus is internal and outside its semver.\nconst CONNECT_CODE_HTTP_STATUS: Record<Code, number> = {\n [Code.Canceled]: 499,\n [Code.Unknown]: 500,\n [Code.InvalidArgument]: 400,\n [Code.DeadlineExceeded]: 504,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.PermissionDenied]: 403,\n [Code.ResourceExhausted]: 429,\n [Code.FailedPrecondition]: 400,\n [Code.Aborted]: 409,\n [Code.OutOfRange]: 400,\n [Code.Unimplemented]: 501,\n [Code.Internal]: 500,\n [Code.Unavailable]: 503,\n [Code.DataLoss]: 500,\n [Code.Unauthenticated]: 401,\n};\n\nfunction responseStatusFromCode(ce: ConnectError): number | undefined {\n return hasResponseMetadata(ce) ? CONNECT_CODE_HTTP_STATUS[ce.code] : undefined;\n}\n\n// Runtimes word AbortSignal.timeout() reasons differently (\"signal timed out\",\n// \"The operation timed out.\", \"The operation was aborted due to timeout\"), and\n// ConnectError.from keeps only the message. Only matched on client-side cancels,\n// so a server-sent `canceled` mentioning a timeout passes through.\nconst TIMEOUT_ABORT_MESSAGE_RE = /timed out|due to timeout/iu;\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 detail = parseConnectErrorDetail(ce);\n const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\n const options: PolyesterErrorOptions = {\n cause: ce,\n detail,\n status: httpStatus ? Number(httpStatus) : responseStatusFromCode(ce),\n };\n const withFallback = (fallback: string) => message || fallback;\n\n if (\n ce.rawMessage === TIMESTAMP_SKEW_CODE ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_TIMESTAMP_SKEW\")\n ) {\n return new TimestampSkewError(\n \"API key timestamp is outside the allowed skew window.\",\n options,\n );\n }\n\n if (ce.code === Code.InvalidArgument && ce.rawMessage === WITHDRAW_DEADLINE_EXPIRED_MESSAGE) {\n return new WithdrawDeadlineExpiredError(\n \"Withdraw signature deadline has passed. Prepare the withdraw again.\",\n options,\n );\n }\n\n // Connect reports non-Connect HTTP error bodies as \"HTTP <status>\" with a lossy\n // code (e.g. 501 → Unknown), so map the real status. Bare 404 keeps Connect's\n // Unimplemented: it means the route is missing, not the resource.\n if (!detail && httpStatus && httpStatus !== \"404\") {\n return errorFromHttpStatus(Number(httpStatus), message, {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RESOURCE_NOT_FOUND\") {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SUBACCOUNT_CHALLENGE_INVALID\") {\n return new SubaccountChallengeInvalidError(\n withFallback(\"Subaccount challenge is expired, replaced, or invalid.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Social account is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_IN_USE\") {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_LOCKED\") {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"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 (detail?.service === \"auth\" && detail.code === \"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 (detail?.service === \"auth\" && detail.code === \"AUTH_INTERNAL_ERROR\") {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(detail);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = mfaErrorKind(detail);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n // Checked before rate limits and the transport code: these arrive as\n // DeadlineExceeded, which would otherwise map to a retryable TimeoutError.\n if (detail?.service === \"orders\" && detail.code.endsWith(\"_OUTCOME_UNKNOWN\")) {\n return new OutcomeUnknownError(\n withFallback(\"Outcome unknown; read the current state before retrying.\"),\n options,\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"STALE_QUOTE\") {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = detail?.service === \"orders\" ? detail.rateLimit : undefined;\n if (\n rateLimit ||\n ((detail?.service === \"orders\" ||\n detail?.service === \"withdraw\" ||\n detail?.service === \"internal_transfer\" ||\n detail?.service === \"claims\") &&\n detail.code === \"RATE_LIMIT_EXCEEDED\")\n ) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n if (hasTransientServiceError(detail)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\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.Unimplemented:\n return new NotImplementedError(withFallback(\"Operation not implemented.\"), 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(\n detail: PolyesterErrorDetail | undefined,\n): MfaVerificationFailureReason | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_INVALID\") {\n return \"challenge-invalid\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_LOCKED\") {\n return \"challenge-locked\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_OTP_INVALID\") return \"otp-invalid\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_RECOVERY_INVALID\") {\n return \"recovery-code-invalid\";\n }\n if (\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_CREDENTIAL_INVALID\") ||\n (detail?.service === \"auth\" && detail.code === \"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-canceled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n * `AbortSignal.timeout()` expiries become {@link TimeoutError}, whether the\n * timeout signal was passed by the caller or added by an interceptor. Prefer the\n * `timeoutMs` request option, which Connect reports as `DeadlineExceeded`.\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isTimeoutAbortError(err)) return new TimeoutError(\"Request timed out.\", { cause: err });\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) {\n return !hasResponseMetadata(err) && TIMEOUT_ABORT_MESSAGE_RE.test(err.rawMessage)\n ? new TimeoutError(\"Request timed out.\", { cause: err })\n : err;\n }\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nfunction callerAbortError(signal: AbortSignal): DOMException | TimeoutError {\n const reason: unknown = signal.reason;\n if (isTimeoutAbortError(reason))\n return new TimeoutError(\"Request timed out.\", { cause: reason });\n return preAbortedError(signal);\n}\n\n// A signal that fired before the call started is a cancellation even when it was\n// a timeout: a retryable TimeoutError would let retry loops spin on a dead signal.\nfunction preAbortedError(signal: AbortSignal): DOMException {\n const reason: unknown = signal.reason;\n return reason instanceof DOMException && reason.name === \"AbortError\"\n ? reason\n : new DOMException(\"Request canceled.\", \"AbortError\");\n}\n\nasync function toTransportError(err: unknown, signal?: AbortSignal): Promise<unknown> {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\n await loadErrorDetailDecoders(err);\n return toPolyesterError(err);\n}\n\nasync function* mapStreamErrors<T>(\n source: AsyncIterable<T>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw await toTransportError(err, signal);\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 await loadErrorDetailDecoders(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 if (signal?.aborted) throw preAbortedError(signal);\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 await toTransportError(error, signal);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\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, signal) };\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;;AA4CA,MAAa,sBAAsB;AAGnC,MAAM,oCAAoC;AAE1C,SAAS,yBAAyB,QAAmD;CACjF,IAAI,QAAQ,YAAY,YACpB,OAAO;EACH;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ,YAAY,qBACpB,OAAO;EACH;EACA;EACA;EACA;EACA;CACJ,CAAC,CAAC,SAAS,OAAO,IAAI;CAE1B,IAAI,QAAQ,YAAY,UACpB,OAAO,CAAC,uBAA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AM;GAC9C;EACJ;EACA,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI,QAAQ,SAAS,MAAM,gBAAgB,MAAM;GACjD,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,SAAS,MAAM;IAAE;GAC7E,SAAS,OAAO;IACZ,MAAM,MAAM,iBAAiB,OAAO,MAAM;GAC9C;EACJ;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"connect-error-mapping.js","names":[],"sources":["../../src/shared/connect-error-mapping.ts"],"sourcesContent":["import { Code, ConnectError, type Interceptor, type Transport } from \"@connectrpc/connect\";\nimport {\n loadErrorDetailDecoders,\n parseConnectErrorDetail,\n type PolyesterErrorDetail,\n} from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\n isAbortError,\n isTimeoutAbortError,\n MfaEnrollmentRequiredError,\n MfaLastFactorRequiredError,\n MfaVerificationError,\n type MfaVerificationFailureReason,\n normalizeErrorMessage,\n OutcomeUnknownError,\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 SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TimestampSkewError,\n TransientError,\n ValidationError,\n WithdrawDeadlineExpiredError,\n} from \"./errors.js\";\nimport type { RateLimitDetail } from \"./rate-limit.schemas.js\";\n\n/** Backend code for API-key signatures whose timestamp is outside the skew window. */\nexport const TIMESTAMP_SKEW_CODE = \"TIMESTAMP_SKEW\";\n\n// The withdraw service has no structured code for this; match its message.\nconst WITHDRAW_DEADLINE_EXPIRED_MESSAGE = \"deadline_ts_sec has expired\";\n\nfunction hasTransientServiceError(detail: PolyesterErrorDetail | undefined): boolean {\n if (detail?.service === \"withdraw\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SOURCE_SMART_ACCOUNT_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"CHAIN_METADATA_UNAVAILABLE\",\n \"FEE_UNAVAILABLE\",\n \"SUPPLY_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"DESTINATION_VALIDATION_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"internal_transfer\") {\n return [\n \"SERVICE_UNAVAILABLE\",\n \"SMART_ACCOUNT_UNAVAILABLE\",\n \"STEP_UP_UNAVAILABLE\",\n \"CAPITAL_VIEW_UNAVAILABLE\",\n \"ACCOUNT_SHARD_UNAVAILABLE\",\n ].includes(detail.code);\n }\n if (detail?.service === \"claims\") {\n return [\"SERVICE_UNAVAILABLE\", \"CLAIM_TEMPORARILY_UNAVAILABLE\"].includes(detail.code);\n }\n // The account request changed nothing; the same request can be retried.\n if (detail?.service === \"auth\") {\n return detail.code === \"AUTH_TEMPORARILY_UNAVAILABLE\";\n }\n return false;\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\nconst HTTP_WEEKDAY = \"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\";\nconst HTTP_WEEKDAY_LONG = \"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\";\nconst HTTP_MONTH = \"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\";\nconst HTTP_DATE_RE = new RegExp(\n `^(?:${HTTP_WEEKDAY}, \\\\d{2} ${HTTP_MONTH} \\\\d{4} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY_LONG}, \\\\d{2}-${HTTP_MONTH}-\\\\d{2} \\\\d{2}:\\\\d{2}:\\\\d{2} GMT|${HTTP_WEEKDAY} ${HTTP_MONTH} {1,2}\\\\d{1,2} \\\\d{2}:\\\\d{2}:\\\\d{2} \\\\d{4})$`,\n \"u\",\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 const mapped = toPolyesterError(err);\n return mfaErrorKind(mapped instanceof PolyesterError ? mapped.detail : undefined);\n}\n\nfunction mfaErrorKind(detail: PolyesterErrorDetail | undefined): MfaErrorKind | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_ELEVATION_REQUIRED\") {\n return \"session-elevation\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_STEP_UP_REQUIRED\") return \"step-up\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_NOT_ENROLLED\") return \"enrollment\";\n return null;\n}\n\nfunction parseRetryAfterMs(ce: ConnectError): number | undefined {\n return parseRetryAfterHeader(ce.metadata.get(\"retry-after\"));\n}\n\n/** Parses an HTTP `Retry-After` value (delay seconds or HTTP date) into milliseconds. */\nexport function parseRetryAfterHeader(value: string | null): number | undefined {\n if (!value) return undefined;\n if (/^\\d+$/u.test(value)) {\n const seconds = BigInt(value);\n const maxSafeSeconds = BigInt(Math.floor(Number.MAX_SAFE_INTEGER / 1000));\n return seconds <= maxSafeSeconds ? Number(seconds) * 1000 : undefined;\n }\n if (!HTTP_DATE_RE.test(value)) return undefined;\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// Client-side failures (timeouts, fetch errors, aborts) carry no response metadata.\nfunction hasResponseMetadata(ce: ConnectError): boolean {\n return !ce.metadata.keys().next().done;\n}\n\n// HTTP status Connect servers send for each error code\n// (https://connectrpc.com/docs/protocol#error-codes). Connect's own\n// codeToHttpStatus is internal and outside its semver.\nconst CONNECT_CODE_HTTP_STATUS: Record<Code, number> = {\n [Code.Canceled]: 499,\n [Code.Unknown]: 500,\n [Code.InvalidArgument]: 400,\n [Code.DeadlineExceeded]: 504,\n [Code.NotFound]: 404,\n [Code.AlreadyExists]: 409,\n [Code.PermissionDenied]: 403,\n [Code.ResourceExhausted]: 429,\n [Code.FailedPrecondition]: 400,\n [Code.Aborted]: 409,\n [Code.OutOfRange]: 400,\n [Code.Unimplemented]: 501,\n [Code.Internal]: 500,\n [Code.Unavailable]: 503,\n [Code.DataLoss]: 500,\n [Code.Unauthenticated]: 401,\n};\n\nfunction responseStatusFromCode(ce: ConnectError): number | undefined {\n return hasResponseMetadata(ce) ? CONNECT_CODE_HTTP_STATUS[ce.code] : undefined;\n}\n\n// Runtimes word AbortSignal.timeout() reasons differently (\"signal timed out\",\n// \"The operation timed out.\", \"The operation was aborted due to timeout\"), and\n// ConnectError.from keeps only the message. Only matched on client-side cancels,\n// so a server-sent `canceled` mentioning a timeout passes through.\nconst TIMEOUT_ABORT_MESSAGE_RE = /timed out|due to timeout/iu;\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 detail = parseConnectErrorDetail(ce);\n const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\n const options: PolyesterErrorOptions = {\n cause: ce,\n detail,\n status: httpStatus ? Number(httpStatus) : responseStatusFromCode(ce),\n };\n const withFallback = (fallback: string) => message || fallback;\n\n if (\n ce.rawMessage === TIMESTAMP_SKEW_CODE ||\n (detail?.service === \"auth\" && detail.code === \"AUTH_TIMESTAMP_SKEW\")\n ) {\n return new TimestampSkewError(\n \"API key timestamp is outside the allowed skew window.\",\n options,\n );\n }\n\n if (ce.code === Code.InvalidArgument && ce.rawMessage === WITHDRAW_DEADLINE_EXPIRED_MESSAGE) {\n return new WithdrawDeadlineExpiredError(\n \"Withdraw signature deadline has passed. Prepare the withdraw again.\",\n options,\n );\n }\n\n // Connect reports non-Connect HTTP error bodies as \"HTTP <status>\" with a lossy\n // code (e.g. 501 → Unknown), so map the real status. Bare 404 keeps Connect's\n // Unimplemented: it means the route is missing, not the resource.\n if (!detail && httpStatus && httpStatus !== \"404\") {\n return errorFromHttpStatus(Number(httpStatus), message, {\n ...options,\n retryAfterMs: parseRetryAfterMs(ce),\n });\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_RESOURCE_NOT_FOUND\") {\n return new ResourceNotFoundError(withFallback(\"Resource not found.\"), options);\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_REVISION_CONFLICT\") {\n return new RevisionConflictError(\n withFallback(\"Resource changed since it was last read.\"),\n options,\n );\n }\n\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SUBACCOUNT_CHALLENGE_INVALID\") {\n return new SubaccountChallengeInvalidError(\n withFallback(\"Subaccount challenge is expired, replaced, or invalid.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED\") {\n return new AlreadyExistsError(\n withFallback(\"Social account is already linked to another Polyester account.\"),\n options,\n );\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_IN_USE\") {\n return new PolicyInUseError(withFallback(\"Policy is still in use.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_POLICY_LOCKED\") {\n return new PolicyLockedError(withFallback(\"Policy is locked.\"), options);\n }\n if (detail?.service === \"auth\" && detail.code === \"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 (detail?.service === \"auth\" && detail.code === \"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 (detail?.service === \"auth\" && detail.code === \"AUTH_INTERNAL_ERROR\") {\n return new InternalServerError(withFallback(\"Internal server error.\"), options);\n }\n\n const mfaVerificationReason = getMfaVerificationFailureReason(detail);\n if (mfaVerificationReason) {\n return new MfaVerificationError(\n withFallback(\"MFA verification failed.\"),\n mfaVerificationReason,\n options,\n );\n }\n\n const mfaKind = mfaErrorKind(detail);\n if (mfaKind) {\n return new MFA_ERROR_CLASSES[mfaKind](\n withFallback(\"Multi-factor authentication required.\"),\n options,\n );\n }\n\n // Checked before rate limits and the transport code: these arrive as\n // DeadlineExceeded, which would otherwise map to a retryable TimeoutError.\n if (detail?.service === \"orders\" && detail.code.endsWith(\"_OUTCOME_UNKNOWN\")) {\n return new OutcomeUnknownError(\n withFallback(\"Outcome unknown; read the current state before retrying.\"),\n options,\n );\n }\n\n if (detail?.service === \"orders\" && detail.code === \"STALE_QUOTE\") {\n return new StaleQuoteError(withFallback(\"The submitted market quote is stale.\"), options);\n }\n\n const rateLimit = detail?.service === \"orders\" ? detail.rateLimit : undefined;\n if (\n rateLimit ||\n ((detail?.service === \"orders\" ||\n detail?.service === \"withdraw\" ||\n detail?.service === \"internal_transfer\" ||\n detail?.service === \"claims\") &&\n detail.code === \"RATE_LIMIT_EXCEEDED\")\n ) {\n return new RateLimitError(withFallback(\"Rate limit exceeded.\"), {\n ...options,\n rateLimit,\n retryAfterMs: safeRetryAfterMs(rateLimit) ?? parseRetryAfterMs(ce),\n });\n }\n\n if (hasTransientServiceError(detail)) {\n return new ServiceUnavailableError(withFallback(\"Service unavailable.\"), options);\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.Unimplemented:\n return new NotImplementedError(withFallback(\"Operation not implemented.\"), 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(\n detail: PolyesterErrorDetail | undefined,\n): MfaVerificationFailureReason | null {\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_INVALID\") {\n return \"challenge-invalid\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_CHALLENGE_LOCKED\") {\n return \"challenge-locked\";\n }\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_OTP_INVALID\") return \"otp-invalid\";\n if (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_RECOVERY_INVALID\") {\n return \"recovery-code-invalid\";\n }\n if (\n (detail?.service === \"auth\" && detail.code === \"AUTH_MFA_PASSKEY_CREDENTIAL_INVALID\") ||\n (detail?.service === \"auth\" && detail.code === \"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-canceled requests pass through unchanged, as do errors that are\n * already typed (e.g. a `NetworkError` from the SDK fetch wrapper).\n * `AbortSignal.timeout()` expiries become {@link TimeoutError}, whether the\n * timeout signal was passed by the caller or added by an interceptor. Prefer the\n * `timeoutMs` request option, which Connect reports as `DeadlineExceeded`.\n */\nexport function toPolyesterError(err: unknown): unknown {\n if (err instanceof PolyesterError) return err;\n if (isTimeoutAbortError(err)) return new TimeoutError(\"Request timed out.\", { cause: err });\n if (isAbortError(err)) return err;\n if (err instanceof ConnectError) {\n if (err.code === Code.Canceled) {\n return !hasResponseMetadata(err) && TIMEOUT_ABORT_MESSAGE_RE.test(err.rawMessage)\n ? new TimeoutError(\"Request timed out.\", { cause: err })\n : err;\n }\n const wrapped = findPolyesterErrorInCauseChain(err);\n if (wrapped) return wrapped;\n return connectErrorToPolyesterError(err);\n }\n return err;\n}\n\nfunction callerAbortError(signal: AbortSignal): DOMException | TimeoutError {\n const reason: unknown = signal.reason;\n if (isTimeoutAbortError(reason))\n return new TimeoutError(\"Request timed out.\", { cause: reason });\n return preAbortedError(signal);\n}\n\n// A signal that fired before the call started is a cancellation even when it was\n// a timeout: a retryable TimeoutError would let retry loops spin on a dead signal.\nfunction preAbortedError(signal: AbortSignal): DOMException {\n const reason: unknown = signal.reason;\n return reason instanceof DOMException && reason.name === \"AbortError\"\n ? reason\n : new DOMException(\"Request canceled.\", \"AbortError\");\n}\n\nasync function toTransportError(err: unknown, signal?: AbortSignal): Promise<unknown> {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\n await loadErrorDetailDecoders(err);\n return toPolyesterError(err);\n}\n\nasync function* mapStreamErrors<T>(\n source: AsyncIterable<T>,\n signal?: AbortSignal,\n): AsyncIterable<T> {\n try {\n yield* source;\n } catch (err) {\n throw await toTransportError(err, signal);\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 await loadErrorDetailDecoders(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 if (signal?.aborted) throw preAbortedError(signal);\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 await toTransportError(error, signal);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw preAbortedError(signal);\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, signal) };\n } catch (error) {\n throw await toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;;AA4CA,MAAa,sBAAsB;AAGnC,MAAM,oCAAoC;AAE1C,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wBAAwB,GAAG;GACjC,MAAM,iBAAiB,GAAG;EAC9B;CACJ;AACJ;;;;;AAMA,SAAgB,4BAA4B,WAAiC;CACzE,OAAO;EACH,MAAM,MAAM,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GACjE,IAAI,QAAQ,SAAS,MAAM,gBAAgB,MAAM;GACjD,IAAI;IACA,OAAO,MAAM,UAAU,MACnB,QACA,QACA,WACA,QACA,OACA,aACJ;GACJ,SAAS,OAAO;IACZ,MAAM,MAAM,iBAAiB,OAAO,MAAM;GAC9C;EACJ;EACA,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI,QAAQ,SAAS,MAAM,gBAAgB,MAAM;GACjD,IAAI;IACA,MAAM,WAAW,MAAM,UAAU,OAC7B,QACA,QACA,WACA,QACA,OACA,aACJ;IACA,OAAO;KAAE,GAAG;KAAU,SAAS,gBAAgB,SAAS,SAAS,MAAM;IAAE;GAC7E,SAAS,OAAO;IACZ,MAAM,MAAM,iBAAiB,OAAO,MAAM;GAC9C;EACJ;CACJ;AACJ"}
|
|
@@ -6,6 +6,8 @@ type SdkSubscriptionErrorContext = {
|
|
|
6
6
|
/**
|
|
7
7
|
* Always an `Error`. Server and websocket failures arrive as {@link RealtimeError};
|
|
8
8
|
* skip reporting when `retryable` is true, the realtime client is already retrying.
|
|
9
|
+
* A `"transport"` error is retryable too, but the channel gets no data until the socket
|
|
10
|
+
* recovers, so show it rather than ignore it.
|
|
9
11
|
*/
|
|
10
12
|
error: Error;
|
|
11
13
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscription-errors.d.ts","names":[],"sources":["../../src/shared/subscription-errors.ts"],"mappings":";;KAGY;EACR;EACA
|
|
1
|
+
{"version":3,"file":"subscription-errors.d.ts","names":[],"sources":["../../src/shared/subscription-errors.ts"],"mappings":";;KAGY;EACR;EACA;;;;;;;EAOA,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscription-errors.js","names":[],"sources":["../../src/shared/subscription-errors.ts"],"sourcesContent":["import type { SubscriptionErrorContext as CentrifugeSubscriptionErrorContext } from \"centrifuge/build/protobuf\";\nimport { RealtimeError } from \"./errors.js\";\n\nexport type SdkSubscriptionErrorContext = {\n channel: string;\n type: string;\n /**\n * Always an `Error`. Server and websocket failures arrive as {@link RealtimeError};\n * skip reporting when `retryable` is true, the realtime client is already retrying.\n */\n error: Error;\n};\n\nfunction toRealtimeError(error: unknown, retryable: boolean): Error {\n if (error instanceof Error) return error;\n if (typeof error === \"string\") return new RealtimeError(error, { retryable });\n if (typeof error === \"object\" && error !== null) {\n const { code, message } = error as { code?: unknown; message?: unknown };\n return new RealtimeError(\n typeof message === \"string\" && message\n ? message\n : \"Unknown realtime subscription error\",\n { realtimeCode: typeof code === \"number\" ? code : 0, retryable },\n );\n }\n return new RealtimeError(\"Unknown realtime subscription error\", { retryable });\n}\n\nexport function createSdkSubscriptionErrorContext(\n channel: string,\n type: string,\n error: unknown,\n): SdkSubscriptionErrorContext {\n return { channel, type, error: toRealtimeError(error, false) };\n}\n\nexport function publicationHandlerErrorContext(\n channel: string,\n error: unknown,\n): SdkSubscriptionErrorContext {\n return createSdkSubscriptionErrorContext(channel, \"publication_handler\", error);\n}\n\n/**\n * Delivers every event of one batch publication in order. A failing event is\n * reported on its own, so it does not drop the rest of the batch.\n */\nexport function deliverBatch<T>(\n channel: string,\n events: readonly T[],\n deliver: (event: T) => void,\n onError: ((error: SdkSubscriptionErrorContext) => void) | undefined,\n): void {\n for (const event of events) {\n try {\n deliver(event);\n } catch (error) {\n onError?.(publicationHandlerErrorContext(channel, error));\n }\n }\n}\n\n/**\n * Centrifuge emits plain `{ code, message, temporary }` objects despite its types, and\n * only emits subscription `error` events for failures it retries itself; fatal ones\n * arrive as `unsubscribed`.\n */\nexport function fromCentrifugeSubscriptionError(\n ctx: CentrifugeSubscriptionErrorContext,\n): SdkSubscriptionErrorContext {\n return { channel: ctx.channel, type: ctx.type, error: toRealtimeError(ctx.error, true) };\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"subscription-errors.js","names":[],"sources":["../../src/shared/subscription-errors.ts"],"sourcesContent":["import type { SubscriptionErrorContext as CentrifugeSubscriptionErrorContext } from \"centrifuge/build/protobuf\";\nimport { RealtimeError } from \"./errors.js\";\n\nexport type SdkSubscriptionErrorContext = {\n channel: string;\n type: string;\n /**\n * Always an `Error`. Server and websocket failures arrive as {@link RealtimeError};\n * skip reporting when `retryable` is true, the realtime client is already retrying.\n * A `\"transport\"` error is retryable too, but the channel gets no data until the socket\n * recovers, so show it rather than ignore it.\n */\n error: Error;\n};\n\nfunction toRealtimeError(error: unknown, retryable: boolean): Error {\n if (error instanceof Error) return error;\n if (typeof error === \"string\") return new RealtimeError(error, { retryable });\n if (typeof error === \"object\" && error !== null) {\n const { code, message } = error as { code?: unknown; message?: unknown };\n return new RealtimeError(\n typeof message === \"string\" && message\n ? message\n : \"Unknown realtime subscription error\",\n { realtimeCode: typeof code === \"number\" ? code : 0, retryable },\n );\n }\n return new RealtimeError(\"Unknown realtime subscription error\", { retryable });\n}\n\nexport function createSdkSubscriptionErrorContext(\n channel: string,\n type: string,\n error: unknown,\n): SdkSubscriptionErrorContext {\n return { channel, type, error: toRealtimeError(error, false) };\n}\n\nexport function publicationHandlerErrorContext(\n channel: string,\n error: unknown,\n): SdkSubscriptionErrorContext {\n return createSdkSubscriptionErrorContext(channel, \"publication_handler\", error);\n}\n\n/**\n * Delivers every event of one batch publication in order. A failing event is\n * reported on its own, so it does not drop the rest of the batch.\n */\nexport function deliverBatch<T>(\n channel: string,\n events: readonly T[],\n deliver: (event: T) => void,\n onError: ((error: SdkSubscriptionErrorContext) => void) | undefined,\n): void {\n for (const event of events) {\n try {\n deliver(event);\n } catch (error) {\n onError?.(publicationHandlerErrorContext(channel, error));\n }\n }\n}\n\n/**\n * Centrifuge emits plain `{ code, message, temporary }` objects despite its types, and\n * only emits subscription `error` events for failures it retries itself; fatal ones\n * arrive as `unsubscribed`.\n */\nexport function fromCentrifugeSubscriptionError(\n ctx: CentrifugeSubscriptionErrorContext,\n): SdkSubscriptionErrorContext {\n return { channel: ctx.channel, type: ctx.type, error: toRealtimeError(ctx.error, true) };\n}\n"],"mappings":";;AAeA,SAAS,gBAAgB,OAAgB,WAA2B;CAChE,IAAI,iBAAiB,OAAO,OAAO;CACnC,IAAI,OAAO,UAAU,UAAU,OAAO,IAAI,cAAc,OAAO,EAAE,UAAU,CAAC;CAC5E,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM;EAC7C,MAAM,EAAE,MAAM,YAAY;EAC1B,OAAO,IAAI,cACP,OAAO,YAAY,YAAY,UACzB,UACA,uCACN;GAAE,cAAc,OAAO,SAAS,WAAW,OAAO;GAAG;EAAU,CACnE;CACJ;CACA,OAAO,IAAI,cAAc,uCAAuC,EAAE,UAAU,CAAC;AACjF;AAEA,SAAgB,kCACZ,SACA,MACA,OAC2B;CAC3B,OAAO;EAAE;EAAS;EAAM,OAAO,gBAAgB,OAAO,KAAK;CAAE;AACjE;AAEA,SAAgB,+BACZ,SACA,OAC2B;CAC3B,OAAO,kCAAkC,SAAS,uBAAuB,KAAK;AAClF;;;;;AAMA,SAAgB,aACZ,SACA,QACA,SACA,SACI;CACJ,KAAK,MAAM,SAAS,QAChB,IAAI;EACA,QAAQ,KAAK;CACjB,SAAS,OAAO;EACZ,UAAU,+BAA+B,SAAS,KAAK,CAAC;CAC5D;AAER;;;;;;AAOA,SAAgB,gCACZ,KAC2B;CAC3B,OAAO;EAAE,SAAS,IAAI;EAAS,MAAM,IAAI;EAAM,OAAO,gBAAgB,IAAI,OAAO,IAAI;CAAE;AAC3F"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@polyester/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.35.0-devnet-20261107174905",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "TypeScript SDK providing access to APIs on Polyester Exchange.",
|
|
6
6
|
"homepage": "https://github.com/Fabric-Labs/polyester-sdk-typescript#readme",
|