@polyester/sdk 0.28.1 → 0.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- 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/social_verification_pb.d.ts +9 -0
- package/dist/gen/auth/v1/social_verification_pb.d.ts.map +1 -1
- package/dist/gen/auth/v1/social_verification_pb.js +6 -1
- package/dist/gen/auth/v1/social_verification_pb.js.map +1 -1
- package/dist/gen/claims/v1/claims_pb.d.ts +7 -1
- package/dist/gen/claims/v1/claims_pb.d.ts.map +1 -1
- package/dist/gen/claims/v1/claims_pb.js +7 -1
- package/dist/gen/claims/v1/claims_pb.js.map +1 -1
- package/dist/gen/orders/v1/orders_read_pb.d.ts +3 -1
- package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
- package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/services/address-book/address-book.schemas.d.ts +209 -85
- package/dist/services/address-book/address-book.schemas.d.ts.map +1 -1
- package/dist/services/address-book/address-book.schemas.js +22 -3
- package/dist/services/address-book/address-book.schemas.js.map +1 -1
- package/dist/services/address-book/address-book.types.d.ts +2 -2
- package/dist/services/address-book/index.d.ts +1 -1
- package/dist/services/api-keys/api-keys.schemas.d.ts +3 -3
- package/dist/services/api-keys/api-keys.schemas.d.ts.map +1 -1
- package/dist/services/api-keys/api-keys.schemas.js +2 -2
- package/dist/services/api-keys/api-keys.schemas.js.map +1 -1
- package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +42 -42
- package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
- package/dist/services/orders/orders-output.schemas.d.ts +6 -6
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.js +1 -1
- package/dist/services/policies/api-key-policies/api-key-policies.schemas.js.map +1 -1
- package/dist/services/social-verification/index.d.ts +2 -2
- package/dist/services/social-verification/social-verification.codecs.js +95 -1
- package/dist/services/social-verification/social-verification.codecs.js.map +1 -1
- package/dist/services/social-verification/social-verification.schemas.d.ts +10 -1
- package/dist/services/social-verification/social-verification.schemas.d.ts.map +1 -1
- package/dist/services/social-verification/social-verification.schemas.js +3 -1
- package/dist/services/social-verification/social-verification.schemas.js.map +1 -1
- package/dist/services/social-verification/social-verification.types.d.ts +2 -2
- package/dist/services/subaccounts/subaccounts.d.ts +2 -1
- package/dist/services/subaccounts/subaccounts.d.ts.map +1 -1
- package/dist/services/subaccounts/subaccounts.js +2 -1
- package/dist/services/subaccounts/subaccounts.js.map +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +2 -2
- package/dist/services/subaccounts/subaccounts.schemas.d.ts.map +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.js +3 -3
- package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
- package/dist/services/trades/trades.schemas.d.ts +15 -14
- package/dist/services/trades/trades.schemas.d.ts.map +1 -1
- package/dist/services/trades/trades.schemas.js +10 -3
- package/dist/services/trades/trades.schemas.js.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.d.ts +1 -1
- package/dist/services/triggers/triggers-output.schemas.d.ts +19 -19
- package/dist/shared/connect-error-mapping.d.ts.map +1 -1
- package/dist/shared/connect-error-mapping.js +6 -2
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/errors.d.ts +13 -2
- package/dist/shared/errors.d.ts.map +1 -1
- package/dist/shared/errors.js +14 -1
- package/dist/shared/errors.js.map +1 -1
- package/dist/shared/schemas.js +3 -1
- package/dist/shared/schemas.js.map +1 -1
- package/dist/shared/transports.d.ts +5 -0
- package/dist/shared/transports.d.ts.map +1 -1
- package/dist/shared/transports.js +14 -2
- package/dist/shared/transports.js.map +1 -1
- package/package.json +1 -1
|
@@ -87,7 +87,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
87
87
|
} & {
|
|
88
88
|
readonly orderId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
89
89
|
readonly lineageId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
90
|
-
readonly throughGeneration: v.OptionalSchema<v.
|
|
90
|
+
readonly throughGeneration: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
91
91
|
}, undefined>, v.StrictObjectSchema<{
|
|
92
92
|
readonly symbolId: v.SchemaWithPipe<readonly [v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.TransformAction<string, number>]>, undefined>, v.TransformAction<number | undefined, number | undefined>]>;
|
|
93
93
|
readonly afterMatchId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
@@ -103,7 +103,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
103
103
|
} & {
|
|
104
104
|
readonly orderId: v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.TransformAction<string, bigint>]>, v.CheckAction<bigint, `${string} must be greater than zero`>]>;
|
|
105
105
|
readonly lineageId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
106
|
-
readonly throughGeneration: v.OptionalSchema<v.
|
|
106
|
+
readonly throughGeneration: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
107
107
|
}, undefined>, v.StrictObjectSchema<{
|
|
108
108
|
readonly symbolId: v.SchemaWithPipe<readonly [v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.TransformAction<string, number>]>, undefined>, v.TransformAction<number | undefined, number | undefined>]>;
|
|
109
109
|
readonly afterMatchId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
@@ -135,7 +135,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
135
135
|
} & {
|
|
136
136
|
readonly orderId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
137
137
|
readonly lineageId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
138
|
-
readonly throughGeneration: v.OptionalSchema<v.
|
|
138
|
+
readonly throughGeneration: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
139
139
|
}, undefined>, v.StrictObjectSchema<{
|
|
140
140
|
readonly symbolId: v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.TransformAction<string, number>]>, v.CheckAction<number, "symbolId is required when afterMatchId is set">]>;
|
|
141
141
|
readonly afterMatchId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.TransformAction<string, bigint | undefined>]>;
|
|
@@ -151,7 +151,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
151
151
|
} & {
|
|
152
152
|
readonly orderId: v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.TransformAction<string, bigint>]>, v.CheckAction<bigint, `${string} must be greater than zero`>]>;
|
|
153
153
|
readonly lineageId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
154
|
-
readonly throughGeneration: v.OptionalSchema<v.
|
|
154
|
+
readonly throughGeneration: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
155
155
|
}, undefined>, v.StrictObjectSchema<{
|
|
156
156
|
readonly symbolId: v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.TransformAction<string, number>]>, v.CheckAction<number, "symbolId is required when afterMatchId is set">]>;
|
|
157
157
|
readonly afterMatchId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.TransformAction<string, bigint | undefined>]>;
|
|
@@ -168,7 +168,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
168
168
|
readonly orderId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
|
|
169
169
|
readonly lineageId: v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.TransformAction<string, bigint>]>, v.CheckAction<bigint, `${string} must be greater than zero`>]>;
|
|
170
170
|
readonly throughGeneration: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>, undefined>;
|
|
171
|
-
}, undefined>], undefined>], ({ input }: v.UnionIssue<v.NumberIssue | v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.UnionIssue<v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1>> | v.IntegerIssue<number> | v.MaxValueIssue<number, 4294967295> | v.CheckIssue<bigint> | v.BooleanIssue | v.NeverIssue | v.
|
|
171
|
+
}, undefined>], undefined>], ({ input }: v.UnionIssue<v.NumberIssue | v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.UnionIssue<v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1>> | v.IntegerIssue<number> | v.MaxValueIssue<number, 4294967295> | v.CheckIssue<bigint> | v.BooleanIssue | v.NeverIssue | v.MaxValueIssue<number, 1000> | v.MinValueIssue<number, 1> | v.UnionIssue<v.NumberIssue | v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.UnionIssue<v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1>> | v.IntegerIssue<number> | v.MaxValueIssue<number, 4294967295> | v.CheckIssue<bigint> | v.BooleanIssue | v.NeverIssue | v.MaxValueIssue<number, 1000> | v.MinValueIssue<number, 1>> | v.CheckIssue<number> | v.UnionIssue<v.NumberIssue | v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.UnionIssue<v.StringIssue | v.PicklistIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1>> | v.IntegerIssue<number> | v.MaxValueIssue<number, 4294967295> | v.CheckIssue<bigint> | v.BooleanIssue | v.NeverIssue | v.MaxValueIssue<number, 1000> | v.MinValueIssue<number, 1> | v.CheckIssue<number>>>) => "symbolId is required when afterMatchId is set" | "Provide at most one of orderId or lineageId" | "throughGeneration requires lineageId">, v.TransformAction<{
|
|
172
172
|
symbolId?: number | undefined;
|
|
173
173
|
afterMatchId?: undefined;
|
|
174
174
|
side?: Side.BUY | Side.SELL | undefined;
|
|
@@ -182,7 +182,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
182
182
|
} | undefined;
|
|
183
183
|
orderId?: undefined;
|
|
184
184
|
lineageId?: undefined;
|
|
185
|
-
throughGeneration?:
|
|
185
|
+
throughGeneration?: undefined;
|
|
186
186
|
} | {
|
|
187
187
|
symbolId?: number | undefined;
|
|
188
188
|
afterMatchId?: undefined;
|
|
@@ -197,7 +197,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
197
197
|
} | undefined;
|
|
198
198
|
orderId: bigint;
|
|
199
199
|
lineageId?: undefined;
|
|
200
|
-
throughGeneration?:
|
|
200
|
+
throughGeneration?: undefined;
|
|
201
201
|
} | {
|
|
202
202
|
symbolId?: number | undefined;
|
|
203
203
|
afterMatchId?: undefined;
|
|
@@ -227,7 +227,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
227
227
|
} | undefined;
|
|
228
228
|
orderId?: undefined;
|
|
229
229
|
lineageId?: undefined;
|
|
230
|
-
throughGeneration?:
|
|
230
|
+
throughGeneration?: undefined;
|
|
231
231
|
} | {
|
|
232
232
|
symbolId: number;
|
|
233
233
|
afterMatchId: bigint | undefined;
|
|
@@ -242,7 +242,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
242
242
|
} | undefined;
|
|
243
243
|
orderId: bigint;
|
|
244
244
|
lineageId?: undefined;
|
|
245
|
-
throughGeneration?:
|
|
245
|
+
throughGeneration?: undefined;
|
|
246
246
|
} | {
|
|
247
247
|
symbolId: number;
|
|
248
248
|
afterMatchId: bigint | undefined;
|
|
@@ -275,7 +275,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
275
275
|
limit?: number | undefined;
|
|
276
276
|
pageToken?: string | undefined;
|
|
277
277
|
includeTransfers?: boolean | undefined;
|
|
278
|
-
throughGeneration?:
|
|
278
|
+
throughGeneration?: undefined;
|
|
279
279
|
} | {
|
|
280
280
|
executionScope: {
|
|
281
281
|
readonly case: "orderId";
|
|
@@ -293,7 +293,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
293
293
|
limit?: number | undefined;
|
|
294
294
|
pageToken?: string | undefined;
|
|
295
295
|
includeTransfers?: boolean | undefined;
|
|
296
|
-
throughGeneration?:
|
|
296
|
+
throughGeneration?: undefined;
|
|
297
297
|
} | {
|
|
298
298
|
executionScope: {
|
|
299
299
|
readonly case: "orderId";
|
|
@@ -329,7 +329,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
329
329
|
limit?: number | undefined;
|
|
330
330
|
pageToken?: string | undefined;
|
|
331
331
|
includeTransfers?: boolean | undefined;
|
|
332
|
-
throughGeneration?:
|
|
332
|
+
throughGeneration?: undefined;
|
|
333
333
|
} | {
|
|
334
334
|
executionScope: {
|
|
335
335
|
readonly case: "orderId";
|
|
@@ -347,7 +347,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
347
347
|
limit?: number | undefined;
|
|
348
348
|
pageToken?: string | undefined;
|
|
349
349
|
includeTransfers?: boolean | undefined;
|
|
350
|
-
throughGeneration?:
|
|
350
|
+
throughGeneration?: undefined;
|
|
351
351
|
} | {
|
|
352
352
|
executionScope: {
|
|
353
353
|
readonly case: "orderId";
|
|
@@ -369,7 +369,8 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
|
|
|
369
369
|
}>]>;
|
|
370
370
|
/**
|
|
371
371
|
* Filters accepted by {@link TradesService.list}. Passing `afterMatchId` requires
|
|
372
|
-
* `symbolId`; the
|
|
372
|
+
* `symbolId`, and `throughGeneration` requires `lineageId`; the shapes form a discriminated
|
|
373
|
+
* union so both constraints are compile errors.
|
|
373
374
|
*/
|
|
374
375
|
type GetUserTradesInput = v.InferInput<typeof GetUserTradesInputSchema>;
|
|
375
376
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trades.schemas.d.ts","names":[],"sources":["../../../src/services/trades/trades.schemas.ts"],"mappings":";;;;;iBAoBgB,sBAAsB,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgD3C,QAAQ,EAAE,YAAY,kBAAkB;;
|
|
1
|
+
{"version":3,"file":"trades.schemas.d.ts","names":[],"sources":["../../../src/services/trades/trades.schemas.ts"],"mappings":";;;;;iBAoBgB,sBAAsB,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAgD3C,QAAQ,EAAE,YAAY,kBAAkB;;cAoFvC,0BAAwB,EAAA,yBAAA,EAAA,aAAA,EAAA,sBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA+BzB,qBAAqB,EAAE,kBAAkB"}
|
|
@@ -53,6 +53,7 @@ function createUserTradeSchema(scales) {
|
|
|
53
53
|
}
|
|
54
54
|
const AFTER_MATCH_REQUIRES_SYMBOL = "symbolId is required when afterMatchId is set";
|
|
55
55
|
const EXECUTION_SCOPE_CONFLICT = "Provide at most one of orderId or lineageId";
|
|
56
|
+
const THROUGH_GENERATION_REQUIRES_LINEAGE = "throughGeneration requires lineageId";
|
|
56
57
|
const SymbolIdStringSchema = v.pipe(v.string(), v.trim(), v.transform((value) => Number(value)));
|
|
57
58
|
const GetUserTradesCommonEntries = {
|
|
58
59
|
...AccountScopeInputEntries,
|
|
@@ -70,13 +71,13 @@ function userTradesScopeSchemas(entries) {
|
|
|
70
71
|
...entries,
|
|
71
72
|
orderId: v.optional(v.never()),
|
|
72
73
|
lineageId: v.optional(v.never()),
|
|
73
|
-
throughGeneration:
|
|
74
|
+
throughGeneration: v.optional(v.never())
|
|
74
75
|
}),
|
|
75
76
|
v.strictObject({
|
|
76
77
|
...entries,
|
|
77
78
|
orderId: positiveOrderIdInputSchema("orderId"),
|
|
78
79
|
lineageId: v.optional(v.never()),
|
|
79
|
-
throughGeneration:
|
|
80
|
+
throughGeneration: v.optional(v.never())
|
|
80
81
|
}),
|
|
81
82
|
v.strictObject({
|
|
82
83
|
...entries,
|
|
@@ -99,7 +100,13 @@ const ReplayUserTradesInputSchema = v.union(userTradesScopeSchemas({
|
|
|
99
100
|
afterMatchId: v.pipe(v.string(), v.trim(), v.minLength(1), v.transform((value) => parseOptionalUint64DecimalStrict(value, "afterMatchId")))
|
|
100
101
|
}));
|
|
101
102
|
/** Validates filters accepted by {@link TradesService.list}. */
|
|
102
|
-
const GetUserTradesInputSchema = v.pipe(v.union([BrowseUserTradesInputSchema, ReplayUserTradesInputSchema], ({ input }) =>
|
|
103
|
+
const GetUserTradesInputSchema = v.pipe(v.union([BrowseUserTradesInputSchema, ReplayUserTradesInputSchema], ({ input }) => {
|
|
104
|
+
const filters = typeof input === "object" && input !== null ? input : {};
|
|
105
|
+
const has = (key) => key in filters && filters[key] !== void 0;
|
|
106
|
+
if (has("orderId") && has("lineageId")) return EXECUTION_SCOPE_CONFLICT;
|
|
107
|
+
if (has("throughGeneration") && !has("lineageId")) return THROUGH_GENERATION_REQUIRES_LINEAGE;
|
|
108
|
+
return AFTER_MATCH_REQUIRES_SYMBOL;
|
|
109
|
+
}), v.transform(({ account, orderId, lineageId, ...input }) => {
|
|
103
110
|
const executionScope = orderId !== void 0 ? {
|
|
104
111
|
case: "orderId",
|
|
105
112
|
value: orderId
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trades.schemas.js","names":[],"sources":["../../../src/services/trades/trades.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { tsNsToISO, tsNsToMs } from \"../../utils/time.js\";\nimport { SideSchema } from \"../shared.js\";\nimport { FeeAssetCodec, OrderSideCodec } from \"../orders/orders.codecs.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport { optionalUint64DecimalFilterSchema, U128Schema } from \"../../shared/schemas.js\";\nimport { parseOptionalUint64DecimalStrict } from \"../../utils/numbers.js\";\nimport { PROTOBUF_UINT32_MAX } from \"../../shared/wire-bounds.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport { TradeSideCodec } from \"./trades.codecs.js\";\nimport { enumLabel } from \"../../shared/proto-enum-codec.js\";\nimport { E18_SCALE, scaledToDecimalOutput, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { fromU128 } from \"../../utils/u128.js\";\nimport { OrderLineageSchema } from \"../orders/order-lineage.schemas.js\";\nimport { positiveOrderIdInputSchema } from \"../orders/orders-identifiers.schemas.js\";\n\n/** Parses a generated user-trade fill into the SDK's JSON-safe public shape. */\nexport function createUserTradeSchema(scales: SdkScales) {\n return v.pipe(\n v.object({\n orderId: v.bigint(),\n symbolId: v.number(),\n side: v.number(),\n isMaker: v.boolean(),\n feeAsset: v.number(),\n qtyScaled: v.bigint(),\n priceTicks: v.bigint(),\n feeAmountE18: v.optional(U128Schema),\n referralShareAmountE18: v.optional(U128Schema),\n feeIsRebate: v.boolean(),\n tsNs: v.bigint(),\n matchId: v.bigint(),\n lineage: v.optional(OrderLineageSchema),\n }),\n v.transform((t) => {\n const feeAsset = enumLabel(FeeAssetCodec.protoToOutput, t.feeAsset);\n return {\n orderId: formatId(t.orderId),\n symbolId: t.symbolId,\n sideLabel: enumLabel(OrderSideCodec.protoToOutput, t.side),\n liquidityLabel: t.isMaker ? (\"maker\" as const) : (\"taker\" as const),\n feeAsset,\n qty: scaledToDecimalOutput(t.qtyScaled, scales.baseQty(t.symbolId)),\n price: scaledToDecimalOutput(t.priceTicks, scales.price()),\n fee: scaledToDecimalOutput(fromU128(t.feeAmountE18), E18_SCALE),\n ...(t.referralShareAmountE18 === undefined\n ? {}\n : {\n referralShare: scaledToDecimalOutput(\n fromU128(t.referralShareAmountE18),\n E18_SCALE,\n ),\n }),\n feeIsRebate: t.feeIsRebate,\n tsNs: t.tsNs.toString(),\n tsIso: tsNsToISO(t.tsNs),\n tsMs: tsNsToMs(t.tsNs),\n matchId: t.matchId.toString(),\n ...(t.lineage === undefined ? {} : { lineage: t.lineage }),\n };\n }),\n );\n}\n\n/** A JSON-safe authenticated trade fill returned by the SDK. */\nexport type Trade = v.InferOutput<ReturnType<typeof createUserTradeSchema>>;\n\nconst AFTER_MATCH_REQUIRES_SYMBOL = \"symbolId is required when afterMatchId is set\";\nconst EXECUTION_SCOPE_CONFLICT = \"Provide at most one of orderId or lineageId\";\n\nconst SymbolIdStringSchema = v.pipe(\n v.string(),\n v.trim(),\n v.transform((value) => Number(value)),\n);\n\nconst GetUserTradesCommonEntries = {\n ...AccountScopeInputEntries,\n side: v.pipe(\n v.optional(SideSchema),\n v.transform((v) => (v ? TradeSideCodec.inputToProto[v] : undefined)),\n ),\n startTsNs: optionalUint64DecimalFilterSchema(\"startTsNs\"),\n endTsNs: optionalUint64DecimalFilterSchema(\"endTsNs\"),\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000))),\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n includeTransfers: v.optional(v.boolean()),\n};\n\nconst ThroughGenerationSchema = v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(PROTOBUF_UINT32_MAX)),\n);\n\nfunction userTradesScopeSchemas<const TEntries extends v.ObjectEntries>(entries: TEntries) {\n return [\n v.strictObject({\n ...entries,\n orderId: v.optional(v.never()),\n lineageId: v.optional(v.never()),\n throughGeneration: ThroughGenerationSchema,\n }),\n v.strictObject({\n ...entries,\n orderId: positiveOrderIdInputSchema(\"orderId\"),\n lineageId: v.optional(v.never()),\n throughGeneration: ThroughGenerationSchema,\n }),\n v.strictObject({\n ...entries,\n orderId: v.optional(v.never()),\n lineageId: positiveOrderIdInputSchema(\"lineageId\"),\n throughGeneration: ThroughGenerationSchema,\n }),\n ] as const;\n}\n\n/** Browse mode: optional symbol filter, no replay cursor. */\nconst BrowseUserTradesInputSchema = v.union(\n userTradesScopeSchemas({\n ...GetUserTradesCommonEntries,\n symbolId: v.pipe(\n v.optional(SymbolIdStringSchema),\n v.transform((sid) =>\n sid !== undefined && Number.isFinite(sid) && sid > 0 ? sid : undefined,\n ),\n ),\n afterMatchId: v.optional(v.never()),\n }),\n);\n\n/** Replay mode: `afterMatchId` cursor, which the backend only accepts scoped to a symbol. */\nconst ReplayUserTradesInputSchema = v.union(\n userTradesScopeSchemas({\n ...GetUserTradesCommonEntries,\n symbolId: v.pipe(\n SymbolIdStringSchema,\n v.check((sid) => Number.isInteger(sid) && sid > 0, AFTER_MATCH_REQUIRES_SYMBOL),\n ),\n afterMatchId: v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.transform((value) => parseOptionalUint64DecimalStrict(value, \"afterMatchId\")),\n ),\n }),\n);\n\n/** Validates filters accepted by {@link TradesService.list}. */\nexport const GetUserTradesInputSchema = v.pipe(\n v.union([BrowseUserTradesInputSchema, ReplayUserTradesInputSchema], ({ input }) =>\n typeof input === \"object\" &&\n input !== null &&\n \"orderId\" in input &&\n input.orderId !== undefined &&\n \"lineageId\" in input &&\n input.lineageId !== undefined\n ? EXECUTION_SCOPE_CONFLICT\n : AFTER_MATCH_REQUIRES_SYMBOL,\n ),\n v.transform(({ account, orderId, lineageId, ...input }) => {\n const executionScope =\n orderId !== undefined\n ? ({ case: \"orderId\" as const, value: orderId } as const)\n : lineageId !== undefined\n ? ({ case: \"lineageId\" as const, value: lineageId } as const)\n : undefined;\n return {\n ...input,\n executionScope,\n subaccountId: accountScopeToSubaccountId(account),\n };\n }),\n);\n\n/**\n * Filters accepted by {@link TradesService.list}. Passing `afterMatchId` requires\n * `symbolId`; the two shapes form a discriminated union so the constraint is a compile error.\n */\nexport type GetUserTradesInput = v.InferInput<typeof GetUserTradesInputSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAgB,sBAAsB,QAAmB;CACrD,OAAO,EAAE,KACL,EAAE,OAAO;EACL,SAAS,EAAE,OAAO;EAClB,UAAU,EAAE,OAAO;EACnB,MAAM,EAAE,OAAO;EACf,SAAS,EAAE,QAAQ;EACnB,UAAU,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UAAU,EAAE,KACR,sBACA,EAAE,OAAO,QAAQ,OAAO,UAAU,GAAG,KAAK,MAAM,GAAG,2BAA2B,CAClF;CACA,cAAc,EAAE,KACZ,EAAE,OAAO,GACT,EAAE,KAAK,GACP,EAAE,UAAU,CAAC,GACb,EAAE,WAAW,UAAU,iCAAiC,OAAO,cAAc,CAAC,CAClF;AACJ,CAAC,CACL;;AAGA,MAAa,2BAA2B,EAAE,KACtC,EAAE,MAAM,CAAC,6BAA6B,2BAA2B,IAAI,EAAE,YACnE,OAAO,UAAU,YACjB,UAAU,QACV,aAAa,SACb,MAAM,YAAY,KAAA,KAClB,eAAe,SACf,MAAM,cAAc,KAAA,IACd,2BACA,2BACV,GACA,EAAE,WAAW,EAAE,SAAS,SAAS,WAAW,GAAG,YAAY;CACvD,MAAM,iBACF,YAAY,KAAA,IACL;EAAE,MAAM;EAAoB,OAAO;CAAQ,IAC5C,cAAc,KAAA,IACX;EAAE,MAAM;EAAsB,OAAO;CAAU,IAChD,KAAA;CACZ,OAAO;EACH,GAAG;EACH;EACA,cAAc,2BAA2B,OAAO;CACpD;AACJ,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"trades.schemas.js","names":[],"sources":["../../../src/services/trades/trades.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { tsNsToISO, tsNsToMs } from \"../../utils/time.js\";\nimport { SideSchema } from \"../shared.js\";\nimport { FeeAssetCodec, OrderSideCodec } from \"../orders/orders.codecs.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport { optionalUint64DecimalFilterSchema, U128Schema } from \"../../shared/schemas.js\";\nimport { parseOptionalUint64DecimalStrict } from \"../../utils/numbers.js\";\nimport { PROTOBUF_UINT32_MAX } from \"../../shared/wire-bounds.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport { TradeSideCodec } from \"./trades.codecs.js\";\nimport { enumLabel } from \"../../shared/proto-enum-codec.js\";\nimport { E18_SCALE, scaledToDecimalOutput, type SdkScales } from \"../../shared/decimal-surface.js\";\nimport { fromU128 } from \"../../utils/u128.js\";\nimport { OrderLineageSchema } from \"../orders/order-lineage.schemas.js\";\nimport { positiveOrderIdInputSchema } from \"../orders/orders-identifiers.schemas.js\";\n\n/** Parses a generated user-trade fill into the SDK's JSON-safe public shape. */\nexport function createUserTradeSchema(scales: SdkScales) {\n return v.pipe(\n v.object({\n orderId: v.bigint(),\n symbolId: v.number(),\n side: v.number(),\n isMaker: v.boolean(),\n feeAsset: v.number(),\n qtyScaled: v.bigint(),\n priceTicks: v.bigint(),\n feeAmountE18: v.optional(U128Schema),\n referralShareAmountE18: v.optional(U128Schema),\n feeIsRebate: v.boolean(),\n tsNs: v.bigint(),\n matchId: v.bigint(),\n lineage: v.optional(OrderLineageSchema),\n }),\n v.transform((t) => {\n const feeAsset = enumLabel(FeeAssetCodec.protoToOutput, t.feeAsset);\n return {\n orderId: formatId(t.orderId),\n symbolId: t.symbolId,\n sideLabel: enumLabel(OrderSideCodec.protoToOutput, t.side),\n liquidityLabel: t.isMaker ? (\"maker\" as const) : (\"taker\" as const),\n feeAsset,\n qty: scaledToDecimalOutput(t.qtyScaled, scales.baseQty(t.symbolId)),\n price: scaledToDecimalOutput(t.priceTicks, scales.price()),\n fee: scaledToDecimalOutput(fromU128(t.feeAmountE18), E18_SCALE),\n ...(t.referralShareAmountE18 === undefined\n ? {}\n : {\n referralShare: scaledToDecimalOutput(\n fromU128(t.referralShareAmountE18),\n E18_SCALE,\n ),\n }),\n feeIsRebate: t.feeIsRebate,\n tsNs: t.tsNs.toString(),\n tsIso: tsNsToISO(t.tsNs),\n tsMs: tsNsToMs(t.tsNs),\n matchId: t.matchId.toString(),\n ...(t.lineage === undefined ? {} : { lineage: t.lineage }),\n };\n }),\n );\n}\n\n/** A JSON-safe authenticated trade fill returned by the SDK. */\nexport type Trade = v.InferOutput<ReturnType<typeof createUserTradeSchema>>;\n\nconst AFTER_MATCH_REQUIRES_SYMBOL = \"symbolId is required when afterMatchId is set\";\nconst EXECUTION_SCOPE_CONFLICT = \"Provide at most one of orderId or lineageId\";\nconst THROUGH_GENERATION_REQUIRES_LINEAGE = \"throughGeneration requires lineageId\";\n\nconst SymbolIdStringSchema = v.pipe(\n v.string(),\n v.trim(),\n v.transform((value) => Number(value)),\n);\n\nconst GetUserTradesCommonEntries = {\n ...AccountScopeInputEntries,\n side: v.pipe(\n v.optional(SideSchema),\n v.transform((v) => (v ? TradeSideCodec.inputToProto[v] : undefined)),\n ),\n startTsNs: optionalUint64DecimalFilterSchema(\"startTsNs\"),\n endTsNs: optionalUint64DecimalFilterSchema(\"endTsNs\"),\n limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(1000))),\n pageToken: v.optional(v.pipe(v.string(), v.trim())),\n includeTransfers: v.optional(v.boolean()),\n};\n\nconst ThroughGenerationSchema = v.optional(\n v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(PROTOBUF_UINT32_MAX)),\n);\n\nfunction userTradesScopeSchemas<const TEntries extends v.ObjectEntries>(entries: TEntries) {\n return [\n v.strictObject({\n ...entries,\n orderId: v.optional(v.never()),\n lineageId: v.optional(v.never()),\n throughGeneration: v.optional(v.never()),\n }),\n v.strictObject({\n ...entries,\n orderId: positiveOrderIdInputSchema(\"orderId\"),\n lineageId: v.optional(v.never()),\n throughGeneration: v.optional(v.never()),\n }),\n v.strictObject({\n ...entries,\n orderId: v.optional(v.never()),\n lineageId: positiveOrderIdInputSchema(\"lineageId\"),\n throughGeneration: ThroughGenerationSchema,\n }),\n ] as const;\n}\n\n/** Browse mode: optional symbol filter, no replay cursor. */\nconst BrowseUserTradesInputSchema = v.union(\n userTradesScopeSchemas({\n ...GetUserTradesCommonEntries,\n symbolId: v.pipe(\n v.optional(SymbolIdStringSchema),\n v.transform((sid) =>\n sid !== undefined && Number.isFinite(sid) && sid > 0 ? sid : undefined,\n ),\n ),\n afterMatchId: v.optional(v.never()),\n }),\n);\n\n/** Replay mode: `afterMatchId` cursor, which the backend only accepts scoped to a symbol. */\nconst ReplayUserTradesInputSchema = v.union(\n userTradesScopeSchemas({\n ...GetUserTradesCommonEntries,\n symbolId: v.pipe(\n SymbolIdStringSchema,\n v.check((sid) => Number.isInteger(sid) && sid > 0, AFTER_MATCH_REQUIRES_SYMBOL),\n ),\n afterMatchId: v.pipe(\n v.string(),\n v.trim(),\n v.minLength(1),\n v.transform((value) => parseOptionalUint64DecimalStrict(value, \"afterMatchId\")),\n ),\n }),\n);\n\n/** Validates filters accepted by {@link TradesService.list}. */\nexport const GetUserTradesInputSchema = v.pipe(\n v.union([BrowseUserTradesInputSchema, ReplayUserTradesInputSchema], ({ input }) => {\n const filters = typeof input === \"object\" && input !== null ? input : {};\n const has = (key: string) =>\n key in filters && (filters as Record<string, unknown>)[key] !== undefined;\n if (has(\"orderId\") && has(\"lineageId\")) return EXECUTION_SCOPE_CONFLICT;\n if (has(\"throughGeneration\") && !has(\"lineageId\")) {\n return THROUGH_GENERATION_REQUIRES_LINEAGE;\n }\n return AFTER_MATCH_REQUIRES_SYMBOL;\n }),\n v.transform(({ account, orderId, lineageId, ...input }) => {\n const executionScope =\n orderId !== undefined\n ? ({ case: \"orderId\" as const, value: orderId } as const)\n : lineageId !== undefined\n ? ({ case: \"lineageId\" as const, value: lineageId } as const)\n : undefined;\n return {\n ...input,\n executionScope,\n subaccountId: accountScopeToSubaccountId(account),\n };\n }),\n);\n\n/**\n * Filters accepted by {@link TradesService.list}. Passing `afterMatchId` requires\n * `symbolId`, and `throughGeneration` requires `lineageId`; the shapes form a discriminated\n * union so both constraints are compile errors.\n */\nexport type GetUserTradesInput = v.InferInput<typeof GetUserTradesInputSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;AAoBA,SAAgB,sBAAsB,QAAmB;CACrD,OAAO,EAAE,KACL,EAAE,OAAO;EACL,SAAS,EAAE,OAAO;EAClB,UAAU,EAAE,OAAO;EACnB,MAAM,EAAE,OAAO;EACf,SAAS,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c,EAAE,SAAS,EAAE,MAAM,CAAC;AACtC,CAAC,CACL;;AAGA,MAAM,8BAA8B,EAAE,MAClC,uBAAuB;CACnB,GAAG;CACH,UAAU,EAAE,KACR,sBACA,EAAE,OAAO,QAAQ,OAAO,UAAU,GAAG,KAAK,MAAM,GAAG,2BAA2B,CAClF;CACA,cAAc,EAAE,KACZ,EAAE,OAAO,GACT,EAAE,KAAK,GACP,EAAE,UAAU,CAAC,GACb,EAAE,WAAW,UAAU,iCAAiC,OAAO,cAAc,CAAC,CAClF;AACJ,CAAC,CACL;;AAGA,MAAa,2BAA2B,EAAE,KACtC,EAAE,MAAM,CAAC,6BAA6B,2BAA2B,IAAI,EAAE,YAAY;CAC/E,MAAM,UAAU,OAAO,UAAU,YAAY,UAAU,OAAO,QAAQ,CAAC;CACvE,MAAM,OAAO,QACT,OAAO,WAAY,QAAoC,SAAS,KAAA;CACpE,IAAI,IAAI,SAAS,KAAK,IAAI,WAAW,GAAG,OAAO;CAC/C,IAAI,IAAI,mBAAmB,KAAK,CAAC,IAAI,WAAW,GAC5C,OAAO;CAEX,OAAO;AACX,CAAC,GACD,EAAE,WAAW,EAAE,SAAS,SAAS,WAAW,GAAG,YAAY;CACvD,MAAM,iBACF,YAAY,KAAA,IACL;EAAE,MAAM;EAAoB,OAAO;CAAQ,IAC5C,cAAc,KAAA,IACX;EAAE,MAAM;EAAsB,OAAO;CAAU,IAChD,KAAA;CACZ,OAAO;EACH,GAAG;EACH;EACA,cAAc,2BAA2B,OAAO;CACpD;AACJ,CAAC,CACL"}
|
|
@@ -845,7 +845,7 @@ type CreateTriggerInput = v.InferInput<ReturnType<typeof createCreateTriggerInpu
|
|
|
845
845
|
declare const ListTriggersInputSchema: v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
|
|
846
846
|
readonly parentOrderId: v.SchemaWithPipe<readonly [v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction]>, undefined>, v.TransformAction<string | undefined, bigint | undefined>]>;
|
|
847
847
|
readonly symbolId: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>, undefined>;
|
|
848
|
-
readonly status: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ArraySchema<v.PicklistSchema<readonly ["created", "armed", "running", "completed", "cancelled", "failed", "paused"], undefined>, undefined>, undefined>, v.TransformAction<("
|
|
848
|
+
readonly status: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ArraySchema<v.PicklistSchema<readonly ["created", "armed", "running", "completed", "cancelled", "failed", "paused"], undefined>, undefined>, undefined>, v.TransformAction<("completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused")[] | undefined, (TriggerStatus.STATUS_CREATED | TriggerStatus.STATUS_ARMED | TriggerStatus.STATUS_RUNNING | TriggerStatus.STATUS_COMPLETED | TriggerStatus.STATUS_CANCELED | TriggerStatus.STATUS_FAILED | TriggerStatus.STATUS_PAUSED)[]>]>;
|
|
849
849
|
readonly triggerType: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["stop_loss", "take_profit", "trailing_stop", "twap", "ladder"], undefined>, undefined>, v.TransformAction<"stop_loss" | "take_profit" | "trailing_stop" | "twap" | "ladder" | undefined, TriggerType>]>;
|
|
850
850
|
readonly limit: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 1000, undefined>]>, 50>;
|
|
851
851
|
readonly pageToken: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction]>, "">;
|
|
@@ -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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "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" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
88
88
|
}>]>;
|
|
89
89
|
type ResumeTriggerResult = v.InferOutput<typeof ResumeTriggerResultSchema>;
|
|
90
90
|
type StopDetailsOutput = {
|
|
@@ -555,12 +555,12 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
555
555
|
};
|
|
556
556
|
}, {
|
|
557
557
|
runtimeDetails: TriggerDetailsOutput;
|
|
558
|
-
cancelReason: "unspecified" | "
|
|
558
|
+
cancelReason: "unspecified" | "internal_error" | "oco" | "user_request" | "parent_canceled_no_fill" | "missing_reason_code";
|
|
559
559
|
failureReason: undefined;
|
|
560
560
|
triggerId: string;
|
|
561
561
|
subaccountId: string;
|
|
562
562
|
symbolId: number;
|
|
563
|
-
status: "unspecified" | "
|
|
563
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
564
564
|
parentOrderId: string | undefined;
|
|
565
565
|
qty: string;
|
|
566
566
|
feeAsset: "unspecified" | "quote" | "base";
|
|
@@ -712,11 +712,11 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
712
712
|
} | {
|
|
713
713
|
runtimeDetails: TriggerDetailsOutput;
|
|
714
714
|
cancelReason: undefined;
|
|
715
|
-
failureReason: "unspecified" | "
|
|
715
|
+
failureReason: "unspecified" | "internal_error" | "missing_reason_code" | "unknown_symbol" | "pair_disabled" | "min_notional" | "tick_size" | "insufficient_funds" | "risk_limit" | "duplicate_client_id" | "market_halted" | "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";
|
|
716
716
|
triggerId: string;
|
|
717
717
|
subaccountId: string;
|
|
718
718
|
symbolId: number;
|
|
719
|
-
status: "unspecified" | "
|
|
719
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
720
720
|
parentOrderId: string | undefined;
|
|
721
721
|
qty: string;
|
|
722
722
|
feeAsset: "unspecified" | "quote" | "base";
|
|
@@ -872,7 +872,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
872
872
|
triggerId: string;
|
|
873
873
|
subaccountId: string;
|
|
874
874
|
symbolId: number;
|
|
875
|
-
status: "unspecified" | "
|
|
875
|
+
status: "unspecified" | "completed" | "failed" | "cancelled" | "created" | "armed" | "running" | "paused";
|
|
876
876
|
parentOrderId: string | undefined;
|
|
877
877
|
qty: string;
|
|
878
878
|
feeAsset: "unspecified" | "quote" | "base";
|
|
@@ -1065,7 +1065,7 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1065
1065
|
value?: undefined;
|
|
1066
1066
|
};
|
|
1067
1067
|
}, {
|
|
1068
|
-
cancelReason: "unspecified" | "
|
|
1068
|
+
cancelReason: "unspecified" | "internal_error" | "oco" | "user_request" | "parent_canceled_no_fill" | "missing_reason_code";
|
|
1069
1069
|
failureReason: undefined;
|
|
1070
1070
|
triggerId: string;
|
|
1071
1071
|
subaccountId: string;
|
|
@@ -1078,7 +1078,7 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1078
1078
|
firePrice: string | undefined;
|
|
1079
1079
|
} | {
|
|
1080
1080
|
cancelReason: undefined;
|
|
1081
|
-
failureReason: "unspecified" | "
|
|
1081
|
+
failureReason: "unspecified" | "internal_error" | "missing_reason_code" | "unknown_symbol" | "pair_disabled" | "min_notional" | "tick_size" | "insufficient_funds" | "risk_limit" | "duplicate_client_id" | "market_halted" | "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";
|
|
1082
1082
|
triggerId: string;
|
|
1083
1083
|
subaccountId: string;
|
|
1084
1084
|
symbolId: 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":";;;;;;;iBAyIgB,6BAA6B,IAAI,eAAe;;;;;;iBAuLhD,iBAAiB;;;;;;iBA0CjB,iCAAiC"}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import { AlreadyExistsError, AuthenticationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaVerificationError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PreconditionFailedError, RateLimitError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage } from "./errors.js";
|
|
1
|
+
import { AlreadyExistsError, AuthenticationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaVerificationError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PreconditionFailedError, RateLimitError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage } from "./errors.js";
|
|
2
2
|
import { parseConnectErrorDetail } from "./error-detail.js";
|
|
3
3
|
import { Code, ConnectError } from "@connectrpc/connect";
|
|
4
4
|
//#region src/shared/connect-error-mapping.ts
|
|
5
|
+
/** Backend code for API-key signatures whose timestamp is outside the skew window. */
|
|
6
|
+
const TIMESTAMP_SKEW_CODE = "TIMESTAMP_SKEW";
|
|
5
7
|
function hasTransientServiceError(detail) {
|
|
6
8
|
if (detail?.service === "withdraw") return [
|
|
7
9
|
"SERVICE_UNAVAILABLE",
|
|
@@ -76,6 +78,7 @@ function connectErrorToPolyesterError(ce) {
|
|
|
76
78
|
detail
|
|
77
79
|
};
|
|
78
80
|
const withFallback = (fallback) => message || fallback;
|
|
81
|
+
if (ce.rawMessage === "TIMESTAMP_SKEW") return new TimestampSkewError("API key timestamp is outside the allowed skew window.", options);
|
|
79
82
|
const httpStatus = /^HTTP (\d{3})$/u.exec(ce.rawMessage)?.[1];
|
|
80
83
|
if (!detail && httpStatus && httpStatus !== "404") return errorFromHttpStatus(Number(httpStatus), message, {
|
|
81
84
|
...options,
|
|
@@ -84,6 +87,7 @@ function connectErrorToPolyesterError(ce) {
|
|
|
84
87
|
if (detail?.service === "auth" && detail.code === "AUTH_RESOURCE_NOT_FOUND") return new ResourceNotFoundError(withFallback("Resource not found."), options);
|
|
85
88
|
if (detail?.service === "auth" && detail.code === "AUTH_REVISION_CONFLICT") return new RevisionConflictError(withFallback("Resource changed since it was last read."), options);
|
|
86
89
|
if (detail?.service === "auth" && detail.code === "AUTH_SUBACCOUNT_CHALLENGE_INVALID") return new SubaccountChallengeInvalidError(withFallback("Subaccount challenge is expired, replaced, or invalid."), options);
|
|
90
|
+
if (detail?.service === "auth" && detail.code === "AUTH_SOCIAL_ACCOUNT_ALREADY_LINKED") return new AlreadyExistsError(withFallback("Social account is already linked to another Polyester account."), options);
|
|
87
91
|
if (detail?.service === "auth" && detail.code === "AUTH_POLICY_IN_USE") return new PolicyInUseError(withFallback("Policy is still in use."), options);
|
|
88
92
|
if (detail?.service === "auth" && detail.code === "AUTH_POLICY_LOCKED") return new PolicyLockedError(withFallback("Policy is locked."), options);
|
|
89
93
|
if (detail?.service === "auth" && detail.code === "AUTH_POLICY_SCOPE_MISMATCH") return new PolicyScopeMismatchError(withFallback("Policy does not belong to the target account scope."), options);
|
|
@@ -217,6 +221,6 @@ function createErrorMappingTransport(transport) {
|
|
|
217
221
|
};
|
|
218
222
|
}
|
|
219
223
|
//#endregion
|
|
220
|
-
export { connectErrorToPolyesterError, createErrorMappingInterceptor, createErrorMappingTransport, getNormalizedConnectMessage, toPolyesterError };
|
|
224
|
+
export { TIMESTAMP_SKEW_CODE, connectErrorToPolyesterError, createErrorMappingInterceptor, createErrorMappingTransport, getNormalizedConnectMessage, toPolyesterError };
|
|
221
225
|
|
|
222
226
|
//# 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 { parseConnectErrorDetail, type PolyesterErrorDetail } from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\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 SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TransientError,\n ValidationError,\n} from \"./errors.js\";\nimport type { RateLimitDetail } from \"./rate-limit.schemas.js\";\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 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/**\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 options: PolyesterErrorOptions = { cause: ce, detail };\n const withFallback = (fallback: string) => message || fallback;\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 const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\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_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 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-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\nfunction callerAbortError(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\nfunction toTransportError(err: unknown, signal?: AbortSignal): unknown {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\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 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 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 callerAbortError(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 toTransportError(error, signal);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw callerAbortError(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 toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;AAmCA,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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B,SAAS,SAAS,MAAM;IAAE;GAC7E,SAAS,OAAO;IACZ,MAAM,iBAAiB,OAAO,MAAM;GACxC;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 { parseConnectErrorDetail, type PolyesterErrorDetail } from \"./error-detail.js\";\nimport {\n AlreadyExistsError,\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n NotImplementedError,\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 SubaccountChallengeInvalidError,\n StepUpRequiredError,\n TimeoutError,\n TimestampSkewError,\n TransientError,\n ValidationError,\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\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 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/**\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 options: PolyesterErrorOptions = { cause: ce, detail };\n const withFallback = (fallback: string) => message || fallback;\n\n if (ce.rawMessage === TIMESTAMP_SKEW_CODE) {\n return new TimestampSkewError(\n \"API key timestamp is outside the allowed skew window.\",\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 const httpStatus = /^HTTP (\\d{3})$/u.exec(ce.rawMessage)?.[1];\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 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-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\nfunction callerAbortError(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\nfunction toTransportError(err: unknown, signal?: AbortSignal): unknown {\n if (signal?.aborted && err instanceof ConnectError && err.code === Code.Canceled) {\n return callerAbortError(signal);\n }\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 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 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 callerAbortError(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 toTransportError(error, signal);\n }\n },\n async stream(method, signal, timeoutMs, header, input, contextValues) {\n if (signal?.aborted) throw callerAbortError(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 toTransportError(error, signal);\n }\n },\n };\n}\n"],"mappings":";;;;;AAqCA,MAAa,sBAAs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AAM,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GACjE,IAAI,QAAQ,SAAS,MAAM,iBAAiB,MAAM;GAClD,IAAI;IACA,OAAO,MAAM,UAAU,MACnB,QACA,QACA,WACA,QACA,OACA,aACJ;GACJ,SAAS,OAAO;IACZ,MAAM,iBAAiB,OAAO,MAAM;GACxC;EACJ;EACA,MAAM,OAAO,QAAQ,QAAQ,WAAW,QAAQ,OAAO,eAAe;GAClE,IAAI,QAAQ,SAAS,MAAM,iBAAiB,MAAM;GAClD,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,iBAAiB,OAAO,MAAM;GACxC;EACJ;CACJ;AACJ"}
|
package/dist/shared/errors.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { RateLimitDetail } from "./rate-limit.schemas.js";
|
|
|
14
14
|
* │ ├── NetworkError NETWORK_ERROR true
|
|
15
15
|
* │ ├── TimeoutError TIMEOUT true
|
|
16
16
|
* │ ├── RateLimitError RATE_LIMITED true
|
|
17
|
+
* │ ├── TimestampSkewError TIMESTAMP_SKEW true
|
|
17
18
|
* │ └── ServiceUnavailableError SERVICE_UNAVAILABLE true
|
|
18
19
|
* ├── RequestError REQUEST_FAILED false
|
|
19
20
|
* │ ├── ValidationError VALIDATION_FAILED false
|
|
@@ -57,7 +58,7 @@ import { RateLimitDetail } from "./rate-limit.schemas.js";
|
|
|
57
58
|
* ```
|
|
58
59
|
*/
|
|
59
60
|
/** Stable machine-readable codes carried by built-in SDK errors. */
|
|
60
|
-
type PolyesterErrorCode = "TRANSIENT_FAILURE" | "NETWORK_ERROR" | "TIMEOUT" | "RATE_LIMITED" | "SERVICE_UNAVAILABLE" | "REQUEST_FAILED" | "VALIDATION_FAILED" | "STALE_QUOTE" | "RESOURCE_NOT_FOUND" | "NOT_IMPLEMENTED" | "ALREADY_EXISTS" | "PERMISSION_DENIED" | "UNAUTHENTICATED" | "PRECONDITION_FAILED" | "REVISION_CONFLICT" | "POLICY_IN_USE" | "POLICY_LOCKED" | "POLICY_SCOPE_MISMATCH" | "INVALID_CONFIGURATION" | "MFA_REQUIRED" | "MFA_ENROLLMENT_REQUIRED" | "STEP_UP_REQUIRED" | "SESSION_ELEVATION_REQUIRED" | "MFA_LAST_FACTOR_REQUIRED" | "MFA_VERIFICATION_FAILED" | "INTERNAL_SERVER_ERROR" | "CATALOG_LOOKUP_MISS" | "CATALOG_NOT_READY" | "CATALOG_CONVERSION_INVALID" | "CATALOG_VALIDATION_FAILED";
|
|
61
|
+
type PolyesterErrorCode = "TRANSIENT_FAILURE" | "NETWORK_ERROR" | "TIMEOUT" | "RATE_LIMITED" | "TIMESTAMP_SKEW" | "SERVICE_UNAVAILABLE" | "REQUEST_FAILED" | "VALIDATION_FAILED" | "STALE_QUOTE" | "RESOURCE_NOT_FOUND" | "NOT_IMPLEMENTED" | "ALREADY_EXISTS" | "PERMISSION_DENIED" | "UNAUTHENTICATED" | "PRECONDITION_FAILED" | "REVISION_CONFLICT" | "POLICY_IN_USE" | "POLICY_LOCKED" | "POLICY_SCOPE_MISMATCH" | "INVALID_CONFIGURATION" | "MFA_REQUIRED" | "MFA_ENROLLMENT_REQUIRED" | "STEP_UP_REQUIRED" | "SESSION_ELEVATION_REQUIRED" | "MFA_LAST_FACTOR_REQUIRED" | "MFA_VERIFICATION_FAILED" | "INTERNAL_SERVER_ERROR" | "CATALOG_LOOKUP_MISS" | "CATALOG_NOT_READY" | "CATALOG_CONVERSION_INVALID" | "CATALOG_VALIDATION_FAILED";
|
|
61
62
|
interface PolyesterErrorOptions {
|
|
62
63
|
/** Underlying error, typically the original `ConnectError` for RPC failures. */
|
|
63
64
|
cause?: unknown;
|
|
@@ -116,6 +117,16 @@ declare class RateLimitError extends TransientError {
|
|
|
116
117
|
readonly rateLimit?: RateLimitDetail;
|
|
117
118
|
constructor(message: string, options?: RateLimitErrorOptions);
|
|
118
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* The API-key signature timestamp fell outside the backend's skew window, e.g.
|
|
122
|
+
* because the request waited too long in the runtime's fetch queue during a
|
|
123
|
+
* large concurrent burst, or the local clock drifted. Retrying the call signs
|
|
124
|
+
* it again with a fresh timestamp; bound concurrency if it recurs.
|
|
125
|
+
*/
|
|
126
|
+
declare class TimestampSkewError extends TransientError {
|
|
127
|
+
readonly code: string;
|
|
128
|
+
constructor(message: string, options?: PolyesterErrorOptions);
|
|
129
|
+
}
|
|
119
130
|
/** The backend is temporarily unavailable (e.g. overloaded or restarting). */
|
|
120
131
|
declare class ServiceUnavailableError extends TransientError {
|
|
121
132
|
readonly code: string;
|
|
@@ -264,5 +275,5 @@ declare function isAbortError(err: unknown): boolean;
|
|
|
264
275
|
/** Maps a plain HTTP status code onto the SDK error tree. */
|
|
265
276
|
declare function errorFromHttpStatus(status: number, message: string, options?: RateLimitErrorOptions): PolyesterError;
|
|
266
277
|
//#endregion
|
|
267
|
-
export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, MfaVerificationFailureReason, NetworkError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PolyesterErrorCode, type PolyesterErrorDetail, PolyesterErrorOptions, PreconditionFailedError, RateLimitError, RateLimitErrorOptions, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage };
|
|
278
|
+
export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, MfaVerificationFailureReason, NetworkError, NotImplementedError, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterError, PolyesterErrorCode, type PolyesterErrorDetail, PolyesterErrorOptions, PreconditionFailedError, RateLimitError, RateLimitErrorOptions, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, SubaccountChallengeInvalidError, TimeoutError, TimestampSkewError, TransientError, ValidationError, errorFromHttpStatus, isAbortError, normalizeErrorMessage };
|
|
268
279
|
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/shared/errors.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"errors.d.ts","names":[],"sources":["../../src/shared/errors.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KA8DY;UAiCK;;EAEb;;EAEA,SAAS;;iBAKG,sBAAsB;;;;;;;;uBAWhB,uBAAuB;;oBAEvB;;oBAEA;WACT,QAAQ;EAEL,YAAA,iBAAiB,UAAU;;;;;;;;cAe9B,uBAAuB;WACvB;WACA;EAEG,YAAA,iBAAiB,UAAU;;;cAO9B,qBAAqB;WACZ;EAEN,YAAA,iBAAiB,UAAU;;;cAO9B,qBAAqB;WACZ;EAEN,YAAA,iBAAiB,UAAU;;UAM1B,8BAA8B;;EAE3C;;EAEA,YAAY;;;cAIH,uBAAuB;WACd;;WAET;;WAEA,YAAY;EAET,YAAA,iBAAiB,UAAU;;;;;;;;cAc9B,2BAA2B;WAClB;EAEN,YAAA,iBAAiB,UAAU;;;cAO9B,gCAAgC;WACvB;EAEN,YAAA,iBAAiB,UAAU;;;;;;cAU9B,qBAAqB;WACrB;WACA;EAEG,YAAA,iBAAiB,UAAU;;;cAO9B,wBAAwB;WACf;EAEN,YAAA,iBAAiB,UAAU;;;cAO9B,wBAAwB;WACf;EAEN,YAAA,iBAAiB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