@polyester/sdk 0.24.0 → 0.24.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 +10 -0
- package/dist/account-signer/types.d.ts +1 -1
- package/dist/account-signer/types.js.map +1 -1
- package/dist/core-client.d.ts.map +1 -1
- package/dist/core-client.js +18 -45
- package/dist/core-client.js.map +1 -1
- package/dist/realtime/client.js +45 -26
- package/dist/realtime/client.js.map +1 -1
- package/dist/services/auth/account-signer-auth.js +1 -1
- package/dist/services/auth/account-signer-auth.js.map +1 -1
- package/dist/services/candles/candles.schemas.d.ts +10 -10
- package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
- package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
- package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
- package/dist/services/orders/orders-output.schemas.d.ts +6 -6
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +5 -5
- package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
- package/dist/services/triggers/triggers-output.schemas.d.ts +18 -18
- package/dist/shared/transports.d.ts +5 -1
- package/dist/shared/transports.d.ts.map +1 -1
- package/dist/shared/transports.js.map +1 -1
- package/package.json +1 -1
|
@@ -31,62 +31,62 @@ declare const CreateTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSche
|
|
|
31
31
|
type CreateTriggerResult = v.InferOutput<typeof CreateTriggerResultSchema>;
|
|
32
32
|
declare const CancelTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
33
33
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
34
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
34
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
35
35
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
36
36
|
}, undefined>, v.TransformAction<{
|
|
37
37
|
triggerId: string;
|
|
38
|
-
status: "unspecified" | "
|
|
38
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
39
39
|
tsNs: bigint;
|
|
40
40
|
}, {
|
|
41
41
|
ts: number;
|
|
42
42
|
tsNs: string;
|
|
43
43
|
triggerId: string;
|
|
44
|
-
status: "unspecified" | "
|
|
44
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
45
45
|
}>]>;
|
|
46
46
|
type CancelTriggerResult = v.InferOutput<typeof CancelTriggerResultSchema>;
|
|
47
47
|
declare const ModifyTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
48
48
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
49
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
49
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
50
50
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
51
51
|
}, undefined>, v.TransformAction<{
|
|
52
52
|
triggerId: string;
|
|
53
|
-
status: "unspecified" | "
|
|
53
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
54
54
|
tsNs: bigint;
|
|
55
55
|
}, {
|
|
56
56
|
ts: number;
|
|
57
57
|
tsNs: string;
|
|
58
58
|
triggerId: string;
|
|
59
|
-
status: "unspecified" | "
|
|
59
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
60
60
|
}>]>;
|
|
61
61
|
type ModifyTriggerResult = v.InferOutput<typeof ModifyTriggerResultSchema>;
|
|
62
62
|
declare const PauseTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
63
63
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
64
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
64
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
65
65
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
66
66
|
}, undefined>, v.TransformAction<{
|
|
67
67
|
triggerId: string;
|
|
68
|
-
status: "unspecified" | "
|
|
68
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
69
69
|
tsNs: bigint;
|
|
70
70
|
}, {
|
|
71
71
|
ts: number;
|
|
72
72
|
tsNs: string;
|
|
73
73
|
triggerId: string;
|
|
74
|
-
status: "unspecified" | "
|
|
74
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
75
75
|
}>]>;
|
|
76
76
|
type PauseTriggerResult = v.InferOutput<typeof PauseTriggerResultSchema>;
|
|
77
77
|
declare const ResumeTriggerResultSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
78
78
|
readonly triggerId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
|
|
79
|
-
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "
|
|
79
|
+
readonly status: v.SchemaWithPipe<readonly [v.EnumSchema<typeof TriggerStatus, undefined>, v.TransformAction<TriggerStatus, "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused">]>;
|
|
80
80
|
readonly tsNs: v.BigintSchema<undefined>;
|
|
81
81
|
}, undefined>, v.TransformAction<{
|
|
82
82
|
triggerId: string;
|
|
83
|
-
status: "unspecified" | "
|
|
83
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
84
84
|
tsNs: bigint;
|
|
85
85
|
}, {
|
|
86
86
|
ts: number;
|
|
87
87
|
tsNs: string;
|
|
88
88
|
triggerId: string;
|
|
89
|
-
status: "unspecified" | "
|
|
89
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
90
90
|
}>]>;
|
|
91
91
|
type ResumeTriggerResult = v.InferOutput<typeof ResumeTriggerResultSchema>;
|
|
92
92
|
type StopDetailsOutput = {
|
|
@@ -558,7 +558,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
558
558
|
triggerId: string;
|
|
559
559
|
subaccountId: string;
|
|
560
560
|
symbolId: number;
|
|
561
|
-
status: "unspecified" | "
|
|
561
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
562
562
|
parentOrderId: string | undefined;
|
|
563
563
|
qty: string;
|
|
564
564
|
feeAsset: "unspecified" | "quote" | "base";
|
|
@@ -714,7 +714,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
714
714
|
triggerId: string;
|
|
715
715
|
subaccountId: string;
|
|
716
716
|
symbolId: number;
|
|
717
|
-
status: "unspecified" | "
|
|
717
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
718
718
|
parentOrderId: string | undefined;
|
|
719
719
|
qty: string;
|
|
720
720
|
feeAsset: "unspecified" | "quote" | "base";
|
|
@@ -870,7 +870,7 @@ declare function createTriggerSchema(scales: SdkScales): v.SchemaWithPipe<readon
|
|
|
870
870
|
triggerId: string;
|
|
871
871
|
subaccountId: string;
|
|
872
872
|
symbolId: number;
|
|
873
|
-
status: "unspecified" | "
|
|
873
|
+
status: "unspecified" | "failed" | "cancelled" | "completed" | "created" | "armed" | "running" | "paused";
|
|
874
874
|
parentOrderId: string | undefined;
|
|
875
875
|
qty: string;
|
|
876
876
|
feeAsset: "unspecified" | "quote" | "base";
|
|
@@ -1069,7 +1069,7 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1069
1069
|
subaccountId: string;
|
|
1070
1070
|
symbolId: number;
|
|
1071
1071
|
triggerType: "unspecified" | "stop_loss" | "take_profit" | "trailing_stop" | "twap" | "ladder";
|
|
1072
|
-
eventType: "unspecified" | "
|
|
1072
|
+
eventType: "unspecified" | "failed" | "updated" | "canceled" | "fired";
|
|
1073
1073
|
ts: number;
|
|
1074
1074
|
childSeq: number;
|
|
1075
1075
|
childOrderId: string | undefined;
|
|
@@ -1081,7 +1081,7 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1081
1081
|
subaccountId: string;
|
|
1082
1082
|
symbolId: number;
|
|
1083
1083
|
triggerType: "unspecified" | "stop_loss" | "take_profit" | "trailing_stop" | "twap" | "ladder";
|
|
1084
|
-
eventType: "unspecified" | "
|
|
1084
|
+
eventType: "unspecified" | "failed" | "updated" | "canceled" | "fired";
|
|
1085
1085
|
ts: number;
|
|
1086
1086
|
childSeq: number;
|
|
1087
1087
|
childOrderId: string | undefined;
|
|
@@ -1093,7 +1093,7 @@ declare function createTriggerEventSchema(scales: SdkScales): v.SchemaWithPipe<r
|
|
|
1093
1093
|
subaccountId: string;
|
|
1094
1094
|
symbolId: number;
|
|
1095
1095
|
triggerType: "unspecified" | "stop_loss" | "take_profit" | "trailing_stop" | "twap" | "ladder";
|
|
1096
|
-
eventType: "unspecified" | "
|
|
1096
|
+
eventType: "unspecified" | "failed" | "updated" | "canceled" | "fired";
|
|
1097
1097
|
ts: number;
|
|
1098
1098
|
childSeq: number;
|
|
1099
1099
|
childOrderId: string | undefined;
|
|
@@ -16,7 +16,11 @@ type AuthAndPublicApiTransports = Pick<Transports, "authApi" | "publicApi">;
|
|
|
16
16
|
*/
|
|
17
17
|
interface JwtAuthProvider {
|
|
18
18
|
kind: "jwt";
|
|
19
|
-
/**
|
|
19
|
+
/**
|
|
20
|
+
* Typically wraps the configured browser auth token storage. The SDK reads
|
|
21
|
+
* the current value for every request and for every realtime auth check, so
|
|
22
|
+
* keep this cheap and return the freshest credential rather than caching.
|
|
23
|
+
*/
|
|
20
24
|
getToken: () => string | null | Promise<string | null>;
|
|
21
25
|
}
|
|
22
26
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transports.d.ts","names":[],"sources":["../../src/shared/transports.ts"],"mappings":";;;UA8BiB;EACb,SAAS;EACT,WAAW;;;KAIH,oBAAoB,KAAK;;KAGzB,sBAAsB,KAAK;;KAG3B,6BAA6B,KAAK;;;;UAK7B;EACb
|
|
1
|
+
{"version":3,"file":"transports.d.ts","names":[],"sources":["../../src/shared/transports.ts"],"mappings":";;;UA8BiB;EACb,SAAS;EACT,WAAW;;;KAIH,oBAAoB,KAAK;;KAGzB,sBAAsB,KAAK;;KAG3B,6BAA6B,KAAK;;;;UAK7B;EACb;;;;;;EAMA,gCAAgC;;;;;;UAOnB;EACb;EACA,gCAAgC;;EAEhC,oBAAoB,oBAAoB,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transports.js","names":[],"sources":["../../src/shared/transports.ts"],"sourcesContent":["import { createConnectTransport } from \"@connectrpc/connect-web\";\nimport type { Transport, Interceptor } from \"@connectrpc/connect\";\nimport { toBinary, toJsonString } from \"@bufbuild/protobuf\";\nimport { signAsync } from \"@noble/ed25519\";\nimport { createErrorMappingTransport } from \"./connect-error-mapping.js\";\nimport {\n AuthenticationError,\n ConfigurationError,\n isAbortError,\n NetworkError,\n PolyesterError,\n} from \"./errors.js\";\n\nexport { isAbortError };\n\nexport type ConnectWireFormat = \"binary\" | \"json\";\n\nexport const POLYESTER_MOCK_HEADER = \"x-polyester-mock\";\n\nexport interface TransportConfig {\n apiUrl: string;\n interceptors?: Interceptor[];\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n /**\n * Connect wire format. Defaults to binary for production performance.\n * Use `json` for the API Playground visualization.\n */\n wireFormat?: ConnectWireFormat;\n}\n\nexport interface Transports {\n authApi: Transport;\n publicApi: Transport;\n}\n\n/** Connect transports available to services that call authenticated APIs. */\nexport type AuthApiTransports = Pick<Transports, \"authApi\">;\n\n/** Connect transports available to services that call public APIs. */\nexport type PublicApiTransports = Pick<Transports, \"publicApi\">;\n\n/** Connect transports available to services that call both public and authenticated APIs. */\nexport type AuthAndPublicApiTransports = Pick<Transports, \"authApi\" | \"publicApi\">;\n\n/**\n * Generic JWT auth for HTTP/Connect endpoints that follow the Bearer token contract.\n */\nexport interface JwtAuthProvider {\n kind: \"jwt\";\n /** Typically wraps the configured browser auth token storage. */\n getToken: () => string | null | Promise<string | null>;\n}\n\n/**\n * Generic Ed25519 API key auth for HTTP/Connect endpoints that follow the\n * X-API-KEY-ID / X-API-TIMESTAMP / X-API-SIGNATURE contract.\n */\nexport interface ApiKeyEd25519AuthProvider {\n kind: \"api-key-ed25519\";\n getKeyId: () => string | null | Promise<string | null>;\n /** Ed25519 secret key bytes (not hex) for signing. */\n getSecretKey: () => Uint8Array | null | Promise<Uint8Array | null>;\n}\n\nexport interface ApiKeyEd25519SigningRequest {\n url: string | URL;\n method: string;\n body?: Uint8Array;\n timestamp?: string;\n}\n\n/**\n * Returns the fetch implementation used by SDK transports.\n */\nexport function makeFetch(): typeof fetch {\n const wrappedFetch = Object.assign(\n async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n // Normalize headers into a mutable Headers object\n const headers = new Headers(init?.headers);\n\n try {\n const res = await fetch(input, {\n ...init,\n headers,\n redirect: \"manual\",\n });\n\n return res;\n } catch (err) {\n if (isAbortError(err)) throw err;\n throw new NetworkError(\"Transport request failed\", { cause: err });\n }\n },\n fetch,\n );\n\n return wrappedFetch;\n}\n\n/**\n * Creates Connect transports for SDK service clients.\n */\nexport function createTransports(config: TransportConfig): Transports {\n const { apiUrl, interceptors = [], auth, wireFormat = \"binary\" } = config;\n const useBinaryFormat = wireFormat === \"binary\";\n const publicApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors,\n fetch: makeFetch(),\n }),\n );\n\n const authInterceptors = auth\n ? auth.kind === \"jwt\"\n ? [createAuthInterceptor(auth, { wireFormat }), ...interceptors]\n : [...interceptors, createAuthInterceptor(auth, { wireFormat })]\n : interceptors;\n const authApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors: authInterceptors,\n fetch: makeFetch(),\n }),\n );\n\n return { authApi, publicApi };\n}\n\n/**\n * Creates an interceptor that enables mock transport behavior.\n */\nexport function createMockInterceptor(getEnabled: () => boolean): Interceptor {\n return (next) => async (req) => {\n if (getEnabled()) req.header.set(POLYESTER_MOCK_HEADER, \"true\");\n return next(req);\n };\n}\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n if (typeof crypto === \"undefined\" || !crypto.subtle) {\n throw new ConfigurationError(\"SHA-256 not available in this environment\");\n }\n const hash = await crypto.subtle.digest(\"SHA-256\", bytes.slice());\n return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nlet lastTimestamp = 0;\nfunction nextTimestamp(): string {\n lastTimestamp = Math.max(lastTimestamp + 1, Date.now());\n return String(lastTimestamp);\n}\n\nfunction canonicalQueryString(params: URLSearchParams): string {\n const pairs: string[] = [];\n for (const [k, v] of params.entries()) {\n pairs.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);\n }\n pairs.sort();\n return pairs.join(\"&\");\n}\n\n/**\n * Creates API-key authentication headers for endpoints using the Polyester Ed25519 signing contract.\n */\nexport async function createApiKeyEd25519AuthHeaders(\n auth: ApiKeyEd25519AuthProvider,\n request: ApiKeyEd25519SigningRequest,\n): Promise<Record<string, string>> {\n let keyId: string | null;\n let secretKey: Uint8Array | null;\n try {\n [keyId, secretKey] = await Promise.all([auth.getKeyId(), auth.getSecretKey()]);\n } catch (cause) {\n if (cause instanceof PolyesterError) throw cause;\n throw new ConfigurationError(\"API key credential provider failed\", { cause });\n }\n if (!keyId || !secretKey) throw new ConfigurationError(\"Missing API key ID or secret key\");\n if (!(secretKey instanceof Uint8Array) || secretKey.byteLength !== 32) {\n throw new ConfigurationError(\"API key secret key must contain exactly 32 bytes\");\n }\n\n const urlObj = new URL(request.url);\n const timestamp = request.timestamp ?? nextTimestamp();\n const bodyHash = await sha256Hex(request.body ?? new Uint8Array(0));\n const canonicalQuery = canonicalQueryString(urlObj.searchParams);\n const canonical = `${timestamp}\\n${request.method}\\n${urlObj.pathname}\\n${canonicalQuery}\\n${bodyHash}`;\n const msgBytes = new TextEncoder().encode(canonical);\n const sig = await signAsync(msgBytes, secretKey);\n const signatureHex = Array.from(sig, (b: number) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n return {\n \"X-API-KEY-ID\": keyId,\n \"X-API-TIMESTAMP\": timestamp,\n \"X-API-SIGNATURE\": signatureHex,\n };\n}\n\n/**\n * Resolves a JWT credential and translates provider failures or invalid values\n * into stable SDK errors.\n */\nexport async function resolveJwtToken(auth: JwtAuthProvider): Promise<string | null> {\n let token: string | null;\n try {\n token = await auth.getToken();\n } catch (cause) {\n if (cause instanceof PolyesterError) throw cause;\n throw new AuthenticationError(\"JWT token provider failed\", { cause });\n }\n if (token !== null && typeof token !== \"string\") {\n throw new ConfigurationError(\"JWT token provider must return a string or null\");\n }\n return token;\n}\n\n/**\n * Creates an interceptor that attaches SDK authentication headers.\n */\nexport function createAuthInterceptor(\n auth: JwtAuthProvider | ApiKeyEd25519AuthProvider,\n options?: { wireFormat?: ConnectWireFormat },\n): Interceptor {\n return (next) => async (req) => {\n const wireFormat = options?.wireFormat ?? \"binary\";\n if (auth.kind === \"jwt\") {\n const token = await resolveJwtToken(auth);\n if (token) {\n req.header.set(\"Authorization\", `Bearer ${token}`);\n }\n } else if (auth.kind === \"api-key-ed25519\") {\n if (req.stream) {\n throw new ConfigurationError(\n \"API key authentication does not support streaming Connect RPCs\",\n );\n }\n // Unary request: serialize the message using the method's input schema.\n const inputSchema = req.method.input;\n const bodyBytes =\n wireFormat === \"json\"\n ? new TextEncoder().encode(toJsonString(inputSchema, req.message))\n : toBinary(inputSchema, req.message);\n\n const headers = await createApiKeyEd25519AuthHeaders(auth, {\n url: req.url,\n method: req.requestMethod,\n body: bodyBytes,\n });\n for (const [key, value] of Object.entries(headers)) {\n req.header.set(key, value);\n }\n }\n return next(req);\n };\n}\n"],"mappings":";;;;;;;;;AA0EA,SAAgB,YAA0B;CAsBtC,OArBqB,OAAO,OACxB,OAAO,OAAoC,SAAuC;EAE9E,MAAM,UAAU,IAAI,QAAQ,MAAM,OAAO;EAEzC,IAAI;GAOA,OAAO,MANW,MAAM,OAAO;IAC3B,GAAG;IACH;IACA,UAAU;GACd,CAAC;EAGL,SAAS,KAAK;GACV,IAAI,aAAa,GAAG,GAAG,MAAM;GAC7B,MAAM,IAAI,aAAa,4BAA4B,EAAE,OAAO,IAAI,CAAC;EACrE;CACJ,GACA,KAGc;AACtB;;;;AAKA,SAAgB,iBAAiB,QAAqC;CAClE,MAAM,EAAE,QAAQ,eAAe,CAAC,GAAG,MAAM,aAAa,aAAa;CACnE,MAAM,kBAAkB,eAAe;CACvC,MAAM,YAAY,4BACd,uBAAuB;EACnB,SAAS;EACT;EACA;EACA,OAAO,UAAU;CACrB,CAAC,CACL;CAEA,MAAM,mBAAmB,OACnB,KAAK,SAAS,QACV,CAAC,sBAAsB,MAAM,EAAE,WAAW,CAAC,GAAG,GAAG,Y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AAc,IAAI,OAAO;GAC/B,MAAM,YACF,eAAe,SACT,IAAI,YAAY,CAAC,CAAC,OAAO,aAAa,aAAa,IAAI,OAAO,CAAC,IAC/D,SAAS,aAAa,IAAI,OAAO;GAE3C,MAAM,UAAU,MAAM,+BAA+B,MAAM;IACvD,KAAK,IAAI;IACT,QAAQ,IAAI;IACZ,MAAM;GACV,CAAC;GACD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC7C,IAAI,OAAO,IAAI,KAAK,KAAK;EAEjC;EACA,OAAO,KAAK,GAAG;CACnB;AACJ"}
|
|
1
|
+
{"version":3,"file":"transports.js","names":[],"sources":["../../src/shared/transports.ts"],"sourcesContent":["import { createConnectTransport } from \"@connectrpc/connect-web\";\nimport type { Transport, Interceptor } from \"@connectrpc/connect\";\nimport { toBinary, toJsonString } from \"@bufbuild/protobuf\";\nimport { signAsync } from \"@noble/ed25519\";\nimport { createErrorMappingTransport } from \"./connect-error-mapping.js\";\nimport {\n AuthenticationError,\n ConfigurationError,\n isAbortError,\n NetworkError,\n PolyesterError,\n} from \"./errors.js\";\n\nexport { isAbortError };\n\nexport type ConnectWireFormat = \"binary\" | \"json\";\n\nexport const POLYESTER_MOCK_HEADER = \"x-polyester-mock\";\n\nexport interface TransportConfig {\n apiUrl: string;\n interceptors?: Interceptor[];\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n /**\n * Connect wire format. Defaults to binary for production performance.\n * Use `json` for the API Playground visualization.\n */\n wireFormat?: ConnectWireFormat;\n}\n\nexport interface Transports {\n authApi: Transport;\n publicApi: Transport;\n}\n\n/** Connect transports available to services that call authenticated APIs. */\nexport type AuthApiTransports = Pick<Transports, \"authApi\">;\n\n/** Connect transports available to services that call public APIs. */\nexport type PublicApiTransports = Pick<Transports, \"publicApi\">;\n\n/** Connect transports available to services that call both public and authenticated APIs. */\nexport type AuthAndPublicApiTransports = Pick<Transports, \"authApi\" | \"publicApi\">;\n\n/**\n * Generic JWT auth for HTTP/Connect endpoints that follow the Bearer token contract.\n */\nexport interface JwtAuthProvider {\n kind: \"jwt\";\n /**\n * Typically wraps the configured browser auth token storage. The SDK reads\n * the current value for every request and for every realtime auth check, so\n * keep this cheap and return the freshest credential rather than caching.\n */\n getToken: () => string | null | Promise<string | null>;\n}\n\n/**\n * Generic Ed25519 API key auth for HTTP/Connect endpoints that follow the\n * X-API-KEY-ID / X-API-TIMESTAMP / X-API-SIGNATURE contract.\n */\nexport interface ApiKeyEd25519AuthProvider {\n kind: \"api-key-ed25519\";\n getKeyId: () => string | null | Promise<string | null>;\n /** Ed25519 secret key bytes (not hex) for signing. */\n getSecretKey: () => Uint8Array | null | Promise<Uint8Array | null>;\n}\n\nexport interface ApiKeyEd25519SigningRequest {\n url: string | URL;\n method: string;\n body?: Uint8Array;\n timestamp?: string;\n}\n\n/**\n * Returns the fetch implementation used by SDK transports.\n */\nexport function makeFetch(): typeof fetch {\n const wrappedFetch = Object.assign(\n async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n // Normalize headers into a mutable Headers object\n const headers = new Headers(init?.headers);\n\n try {\n const res = await fetch(input, {\n ...init,\n headers,\n redirect: \"manual\",\n });\n\n return res;\n } catch (err) {\n if (isAbortError(err)) throw err;\n throw new NetworkError(\"Transport request failed\", { cause: err });\n }\n },\n fetch,\n );\n\n return wrappedFetch;\n}\n\n/**\n * Creates Connect transports for SDK service clients.\n */\nexport function createTransports(config: TransportConfig): Transports {\n const { apiUrl, interceptors = [], auth, wireFormat = \"binary\" } = config;\n const useBinaryFormat = wireFormat === \"binary\";\n const publicApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors,\n fetch: makeFetch(),\n }),\n );\n\n const authInterceptors = auth\n ? auth.kind === \"jwt\"\n ? [createAuthInterceptor(auth, { wireFormat }), ...interceptors]\n : [...interceptors, createAuthInterceptor(auth, { wireFormat })]\n : interceptors;\n const authApi = createErrorMappingTransport(\n createConnectTransport({\n baseUrl: apiUrl,\n useBinaryFormat,\n interceptors: authInterceptors,\n fetch: makeFetch(),\n }),\n );\n\n return { authApi, publicApi };\n}\n\n/**\n * Creates an interceptor that enables mock transport behavior.\n */\nexport function createMockInterceptor(getEnabled: () => boolean): Interceptor {\n return (next) => async (req) => {\n if (getEnabled()) req.header.set(POLYESTER_MOCK_HEADER, \"true\");\n return next(req);\n };\n}\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n if (typeof crypto === \"undefined\" || !crypto.subtle) {\n throw new ConfigurationError(\"SHA-256 not available in this environment\");\n }\n const hash = await crypto.subtle.digest(\"SHA-256\", bytes.slice());\n return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nlet lastTimestamp = 0;\nfunction nextTimestamp(): string {\n lastTimestamp = Math.max(lastTimestamp + 1, Date.now());\n return String(lastTimestamp);\n}\n\nfunction canonicalQueryString(params: URLSearchParams): string {\n const pairs: string[] = [];\n for (const [k, v] of params.entries()) {\n pairs.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);\n }\n pairs.sort();\n return pairs.join(\"&\");\n}\n\n/**\n * Creates API-key authentication headers for endpoints using the Polyester Ed25519 signing contract.\n */\nexport async function createApiKeyEd25519AuthHeaders(\n auth: ApiKeyEd25519AuthProvider,\n request: ApiKeyEd25519SigningRequest,\n): Promise<Record<string, string>> {\n let keyId: string | null;\n let secretKey: Uint8Array | null;\n try {\n [keyId, secretKey] = await Promise.all([auth.getKeyId(), auth.getSecretKey()]);\n } catch (cause) {\n if (cause instanceof PolyesterError) throw cause;\n throw new ConfigurationError(\"API key credential provider failed\", { cause });\n }\n if (!keyId || !secretKey) throw new ConfigurationError(\"Missing API key ID or secret key\");\n if (!(secretKey instanceof Uint8Array) || secretKey.byteLength !== 32) {\n throw new ConfigurationError(\"API key secret key must contain exactly 32 bytes\");\n }\n\n const urlObj = new URL(request.url);\n const timestamp = request.timestamp ?? nextTimestamp();\n const bodyHash = await sha256Hex(request.body ?? new Uint8Array(0));\n const canonicalQuery = canonicalQueryString(urlObj.searchParams);\n const canonical = `${timestamp}\\n${request.method}\\n${urlObj.pathname}\\n${canonicalQuery}\\n${bodyHash}`;\n const msgBytes = new TextEncoder().encode(canonical);\n const sig = await signAsync(msgBytes, secretKey);\n const signatureHex = Array.from(sig, (b: number) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n return {\n \"X-API-KEY-ID\": keyId,\n \"X-API-TIMESTAMP\": timestamp,\n \"X-API-SIGNATURE\": signatureHex,\n };\n}\n\n/**\n * Resolves a JWT credential and translates provider failures or invalid values\n * into stable SDK errors.\n */\nexport async function resolveJwtToken(auth: JwtAuthProvider): Promise<string | null> {\n let token: string | null;\n try {\n token = await auth.getToken();\n } catch (cause) {\n if (cause instanceof PolyesterError) throw cause;\n throw new AuthenticationError(\"JWT token provider failed\", { cause });\n }\n if (token !== null && typeof token !== \"string\") {\n throw new ConfigurationError(\"JWT token provider must return a string or null\");\n }\n return token;\n}\n\n/**\n * Creates an interceptor that attaches SDK authentication headers.\n */\nexport function createAuthInterceptor(\n auth: JwtAuthProvider | ApiKeyEd25519AuthProvider,\n options?: { wireFormat?: ConnectWireFormat },\n): Interceptor {\n return (next) => async (req) => {\n const wireFormat = options?.wireFormat ?? \"binary\";\n if (auth.kind === \"jwt\") {\n const token = await resolveJwtToken(auth);\n if (token) {\n req.header.set(\"Authorization\", `Bearer ${token}`);\n }\n } else if (auth.kind === \"api-key-ed25519\") {\n if (req.stream) {\n throw new ConfigurationError(\n \"API key authentication does not support streaming Connect RPCs\",\n );\n }\n // Unary request: serialize the message using the method's input schema.\n const inputSchema = req.method.input;\n const bodyBytes =\n wireFormat === \"json\"\n ? new TextEncoder().encode(toJsonString(inputSchema, req.message))\n : toBinary(inputSchema, req.message);\n\n const headers = await createApiKeyEd25519AuthHeaders(auth, {\n url: req.url,\n method: req.requestMethod,\n body: bodyBytes,\n });\n for (const [key, value] of Object.entries(headers)) {\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