@compose-market/sdk 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +43 -0
- package/LICENSE +21 -0
- package/README.md +186 -0
- package/dist/errors.d.ts +145 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +152 -0
- package/dist/errors.js.map +1 -0
- package/dist/http.d.ts +98 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +350 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +104 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +137 -0
- package/dist/index.js.map +1 -0
- package/dist/resources/inference.d.ts +161 -0
- package/dist/resources/inference.d.ts.map +1 -0
- package/dist/resources/inference.js +710 -0
- package/dist/resources/inference.js.map +1 -0
- package/dist/resources/keys.d.ts +50 -0
- package/dist/resources/keys.d.ts.map +1 -0
- package/dist/resources/keys.js +154 -0
- package/dist/resources/keys.js.map +1 -0
- package/dist/resources/models.d.ts +26 -0
- package/dist/resources/models.d.ts.map +1 -0
- package/dist/resources/models.js +52 -0
- package/dist/resources/models.js.map +1 -0
- package/dist/resources/webhooks.d.ts +27 -0
- package/dist/resources/webhooks.d.ts.map +1 -0
- package/dist/resources/webhooks.js +78 -0
- package/dist/resources/webhooks.js.map +1 -0
- package/dist/resources/x402.d.ts +37 -0
- package/dist/resources/x402.d.ts.map +1 -0
- package/dist/resources/x402.js +72 -0
- package/dist/resources/x402.js.map +1 -0
- package/dist/streaming/receipt.d.ts +25 -0
- package/dist/streaming/receipt.d.ts.map +1 -0
- package/dist/streaming/receipt.js +92 -0
- package/dist/streaming/receipt.js.map +1 -0
- package/dist/streaming/sse.d.ts +29 -0
- package/dist/streaming/sse.d.ts.map +1 -0
- package/dist/streaming/sse.js +125 -0
- package/dist/streaming/sse.js.map +1 -0
- package/dist/types/index.d.ts +497 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/index.js +10 -0
- package/dist/types/index.js.map +1 -0
- package/package.json +30 -89
- package/index.d.ts +0 -244
- package/index.js +0 -397
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAgBH,MAAM,MAAM,SAAS,GAAG,CACpB,KAAK,EAAE,WAAW,GAAG,GAAG,EACxB,IAAI,CAAC,EAAE,WAAW,KACjB,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEvB,MAAM,WAAW,WAAW;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,cAAc,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,SAAS,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,KAAK,EAAE,WAAW,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE;QACL,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;QAC9D,IAAI,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;QAC7D,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,IAAI,CAAC;KACjE,CAAC;CACL;AAED,MAAM,WAAW,cAAc;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,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;QAAC,QAAQ,EAAE,QAAQ,CAAA;KAAE,CAAC,CAAC;IACzD,gCAAgC;IAChC,KAAK,CAAC,OAAO,GAAG,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,OAAO,KAAK,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC;IACxH,kCAAkC;IAClC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CACxD;AAuDD,wBAAgB,YAAY,CAAC,KAAK,EAAE,cAAc,GAAG;IACjD,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,GAAG,WAAW,GAAG,KAAK,CAAC;CAC3C,GAAG,OAAO,CAyDV;AA6DD,qBAAa,UAAU;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAoB;gBAEhC,OAAO,EAAE,iBAAiB;IAItC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,UAAU,CAAC,CAAC,CAAC;YA4BnC,OAAO;IAkGrB,OAAO,CAAC,cAAc;IAOtB,OAAO,CAAC,UAAU;YAOJ,iBAAiB;YAgBjB,YAAY;CAa7B"}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP client core for the Compose Market SDK.
|
|
3
|
+
*
|
|
4
|
+
* Responsibilities:
|
|
5
|
+
* - Build canonical headers (Authorization / x-session-user-address / x-chain-id /
|
|
6
|
+
* PAYMENT-SIGNATURE / x-x402-max-amount-wei / x-idempotency-key / User-Agent).
|
|
7
|
+
* - Apply retries with exponential backoff + jitter (default 2 retries, honor
|
|
8
|
+
* Retry-After).
|
|
9
|
+
* - Attach an AbortSignal for caller-driven cancellation and an internal
|
|
10
|
+
* timeout.
|
|
11
|
+
* - Parse error envelopes + PaymentRequired into typed error classes.
|
|
12
|
+
* - Return an `APIPromise<T>` that exposes `.asResponse()` and `.withResponse()`
|
|
13
|
+
* so callers can read headers (receipts, request-id, tx hash) without parsing.
|
|
14
|
+
*
|
|
15
|
+
* Zero runtime dependencies. Uses the platform `fetch`.
|
|
16
|
+
*/
|
|
17
|
+
import { BadRequestError, buildApiError, ComposeConnectionError, ComposeTimeoutError, RateLimitError, } from "./errors.js";
|
|
18
|
+
const RETRYABLE_STATUSES = new Set([408, 409, 425, 429, 500, 502, 503, 504]);
|
|
19
|
+
function delay(ms, signal) {
|
|
20
|
+
return new Promise((resolve, reject) => {
|
|
21
|
+
const timer = setTimeout(() => {
|
|
22
|
+
signal?.removeEventListener("abort", onAbort);
|
|
23
|
+
resolve();
|
|
24
|
+
}, ms);
|
|
25
|
+
const onAbort = () => {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
reject(new ComposeTimeoutError({ message: "request aborted" }));
|
|
28
|
+
};
|
|
29
|
+
if (signal) {
|
|
30
|
+
if (signal.aborted) {
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
reject(new ComposeTimeoutError({ message: "request aborted" }));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
function combineSignals(a, b) {
|
|
40
|
+
if (!a)
|
|
41
|
+
return b ?? new AbortController().signal;
|
|
42
|
+
if (!b)
|
|
43
|
+
return a;
|
|
44
|
+
const controller = new AbortController();
|
|
45
|
+
const forward = () => controller.abort();
|
|
46
|
+
if (a.aborted || b.aborted)
|
|
47
|
+
controller.abort();
|
|
48
|
+
a.addEventListener("abort", forward, { once: true });
|
|
49
|
+
b.addEventListener("abort", forward, { once: true });
|
|
50
|
+
return controller.signal;
|
|
51
|
+
}
|
|
52
|
+
function buildQueryString(query) {
|
|
53
|
+
if (!query)
|
|
54
|
+
return "";
|
|
55
|
+
const params = new URLSearchParams();
|
|
56
|
+
for (const [key, value] of Object.entries(query)) {
|
|
57
|
+
if (value === undefined || value === null)
|
|
58
|
+
continue;
|
|
59
|
+
params.append(key, String(value));
|
|
60
|
+
}
|
|
61
|
+
const encoded = params.toString();
|
|
62
|
+
return encoded.length > 0 ? `?${encoded}` : "";
|
|
63
|
+
}
|
|
64
|
+
function normalizeWalletAddress(value) {
|
|
65
|
+
const trimmed = value.trim().toLowerCase();
|
|
66
|
+
if (!/^0x[a-f0-9]{40}$/.test(trimmed)) {
|
|
67
|
+
throw new BadRequestError({ message: "wallet address must be a valid 0x-prefixed EVM address" });
|
|
68
|
+
}
|
|
69
|
+
return trimmed;
|
|
70
|
+
}
|
|
71
|
+
export function buildHeaders(input) {
|
|
72
|
+
const headers = new Headers();
|
|
73
|
+
for (const [key, value] of Object.entries(input.defaultHeaders)) {
|
|
74
|
+
headers.set(key, value);
|
|
75
|
+
}
|
|
76
|
+
if (input.bodyType === "json") {
|
|
77
|
+
headers.set("Content-Type", "application/json");
|
|
78
|
+
}
|
|
79
|
+
// For "form-data" we let the runtime set the multipart boundary; we do not
|
|
80
|
+
// set Content-Type manually. For "raw" the caller sets it.
|
|
81
|
+
if (input.authJwt) {
|
|
82
|
+
headers.set("Authorization", `Bearer ${input.authJwt}`);
|
|
83
|
+
}
|
|
84
|
+
else if (input.composeKey) {
|
|
85
|
+
headers.set("Authorization", `Bearer ${input.composeKey}`);
|
|
86
|
+
}
|
|
87
|
+
if (input.walletAddress) {
|
|
88
|
+
headers.set("x-session-user-address", normalizeWalletAddress(input.walletAddress));
|
|
89
|
+
}
|
|
90
|
+
if (typeof input.chainId === "number" && Number.isInteger(input.chainId) && input.chainId > 0) {
|
|
91
|
+
headers.set("x-chain-id", String(input.chainId));
|
|
92
|
+
}
|
|
93
|
+
if (input.paymentSignature) {
|
|
94
|
+
headers.set("PAYMENT-SIGNATURE", input.paymentSignature);
|
|
95
|
+
}
|
|
96
|
+
if (input.x402MaxAmountWei) {
|
|
97
|
+
headers.set("x-x402-max-amount-wei", input.x402MaxAmountWei);
|
|
98
|
+
}
|
|
99
|
+
if (input.idempotencyKey) {
|
|
100
|
+
headers.set("x-idempotency-key", input.idempotencyKey);
|
|
101
|
+
}
|
|
102
|
+
if (input.composeRunId) {
|
|
103
|
+
headers.set("x-compose-run-id", input.composeRunId);
|
|
104
|
+
}
|
|
105
|
+
if (input.requestId) {
|
|
106
|
+
headers.set("x-request-id", input.requestId);
|
|
107
|
+
}
|
|
108
|
+
headers.set("User-Agent", input.userAgent);
|
|
109
|
+
if (input.extra) {
|
|
110
|
+
for (const [key, value] of Object.entries(input.extra)) {
|
|
111
|
+
if (typeof value === "string" && value.length > 0) {
|
|
112
|
+
headers.set(key, value);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return headers;
|
|
117
|
+
}
|
|
118
|
+
function parseErrorBody(body) {
|
|
119
|
+
if (body && typeof body === "object") {
|
|
120
|
+
const envelope = body;
|
|
121
|
+
if (envelope.error && typeof envelope.error === "object") {
|
|
122
|
+
return {
|
|
123
|
+
code: envelope.error.code || "internal_error",
|
|
124
|
+
message: typeof envelope.error.message === "string" ? envelope.error.message : "Request failed",
|
|
125
|
+
details: envelope.error.details,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
// Raw PaymentRequired body served directly as the 402 body (the x402
|
|
129
|
+
// core facilitator spec shape). Infer `payment_required` as the code.
|
|
130
|
+
const pr = body;
|
|
131
|
+
if (pr.x402Version === 2 && Array.isArray(pr.accepts)) {
|
|
132
|
+
const rawError = typeof pr.error === "string" ? pr.error : "Payment required";
|
|
133
|
+
return { code: "payment_required", message: rawError };
|
|
134
|
+
}
|
|
135
|
+
// Legacy shapes
|
|
136
|
+
const legacy = body;
|
|
137
|
+
if (typeof legacy.error === "string") {
|
|
138
|
+
return { code: (typeof legacy.code === "string" ? legacy.code : "internal_error"), message: legacy.error };
|
|
139
|
+
}
|
|
140
|
+
if (typeof legacy.message === "string") {
|
|
141
|
+
return { code: "internal_error", message: legacy.message };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return { code: "internal_error", message: "Request failed" };
|
|
145
|
+
}
|
|
146
|
+
function extractPaymentRequired(body, header) {
|
|
147
|
+
if (typeof header === "string" && header.length > 0) {
|
|
148
|
+
try {
|
|
149
|
+
const normalized = header.replace(/-/g, "+").replace(/_/g, "/");
|
|
150
|
+
const padding = normalized.length % 4 === 0 ? "" : "=".repeat(4 - (normalized.length % 4));
|
|
151
|
+
const decoded = typeof globalThis.atob === "function"
|
|
152
|
+
? globalThis.atob(normalized + padding)
|
|
153
|
+
: Buffer.from(normalized + padding, "base64").toString("utf-8");
|
|
154
|
+
const bytes = new Uint8Array(decoded.length);
|
|
155
|
+
for (let i = 0; i < decoded.length; i += 1)
|
|
156
|
+
bytes[i] = decoded.charCodeAt(i);
|
|
157
|
+
const text = new TextDecoder("utf-8").decode(bytes);
|
|
158
|
+
const parsed = JSON.parse(text);
|
|
159
|
+
if (parsed && parsed.x402Version === 2 && Array.isArray(parsed.accepts)) {
|
|
160
|
+
return parsed;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// fall through
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (body && typeof body === "object") {
|
|
168
|
+
const record = body;
|
|
169
|
+
if (record.x402Version === 2 && Array.isArray(record.accepts) && record.resource) {
|
|
170
|
+
return record;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
export class HttpClient {
|
|
176
|
+
options;
|
|
177
|
+
constructor(options) {
|
|
178
|
+
this.options = options;
|
|
179
|
+
}
|
|
180
|
+
request(config) {
|
|
181
|
+
// The promise is built lazily: `execute()` only runs when the caller
|
|
182
|
+
// awaits (or calls `.asResponse()` / `.withResponse()`). Awaiting the
|
|
183
|
+
// wrapper directly consumes the body; calling `.asResponse()` leaves
|
|
184
|
+
// the body intact so the caller can stream it.
|
|
185
|
+
let cachedJson = null;
|
|
186
|
+
let cachedStream = null;
|
|
187
|
+
const runJson = () => {
|
|
188
|
+
if (!cachedJson)
|
|
189
|
+
cachedJson = this.execute(config);
|
|
190
|
+
return cachedJson;
|
|
191
|
+
};
|
|
192
|
+
const runStream = () => {
|
|
193
|
+
if (!cachedStream)
|
|
194
|
+
cachedStream = this.execute({ ...config, expectStream: true });
|
|
195
|
+
return cachedStream;
|
|
196
|
+
};
|
|
197
|
+
const wrapper = {
|
|
198
|
+
then: (onFulfilled, onRejected) => runJson().then(({ data }) => data).then(onFulfilled, onRejected),
|
|
199
|
+
catch: (onRejected) => runJson().then(({ data }) => data).catch(onRejected),
|
|
200
|
+
finally: (onFinally) => runJson().then(({ data }) => data).finally(onFinally),
|
|
201
|
+
asResponse: async () => (await runStream()).response,
|
|
202
|
+
withResponse: async () => runJson(),
|
|
203
|
+
};
|
|
204
|
+
return wrapper;
|
|
205
|
+
}
|
|
206
|
+
async execute(config) {
|
|
207
|
+
const query = buildQueryString(config.query);
|
|
208
|
+
const url = `${this.options.baseUrl}${config.path}${query}`;
|
|
209
|
+
const bodyType = config.bodyType
|
|
210
|
+
?? (config.rawBody !== undefined ? "raw" : "json");
|
|
211
|
+
const retry = { ...this.options.retry, ...(config.retry ?? {}) };
|
|
212
|
+
const timeoutMs = config.timeoutMs ?? this.options.timeoutMs;
|
|
213
|
+
const headers = buildHeaders({
|
|
214
|
+
...(config.headers ?? {}),
|
|
215
|
+
defaultHeaders: this.options.defaultHeaders,
|
|
216
|
+
userAgent: this.options.userAgent,
|
|
217
|
+
bodyType,
|
|
218
|
+
});
|
|
219
|
+
const body = this.encodeBody(config, bodyType);
|
|
220
|
+
let attempt = 0;
|
|
221
|
+
let lastError = null;
|
|
222
|
+
while (true) {
|
|
223
|
+
attempt += 1;
|
|
224
|
+
const attemptController = new AbortController();
|
|
225
|
+
const timeoutHandle = setTimeout(() => attemptController.abort(), timeoutMs);
|
|
226
|
+
const signal = combineSignals(config.signal, attemptController.signal);
|
|
227
|
+
let response;
|
|
228
|
+
try {
|
|
229
|
+
response = await this.options.fetch(url, {
|
|
230
|
+
method: config.method,
|
|
231
|
+
headers,
|
|
232
|
+
body,
|
|
233
|
+
signal,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
catch (fetchError) {
|
|
237
|
+
clearTimeout(timeoutHandle);
|
|
238
|
+
const isAbort = signal.aborted || (fetchError instanceof Error && (fetchError.name === "AbortError" || fetchError.message.includes("aborted")));
|
|
239
|
+
if (isAbort && config.signal?.aborted) {
|
|
240
|
+
throw new ComposeTimeoutError({ message: "request aborted" });
|
|
241
|
+
}
|
|
242
|
+
if (isAbort) {
|
|
243
|
+
lastError = new ComposeTimeoutError({
|
|
244
|
+
message: `request timed out after ${timeoutMs}ms`,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
lastError = new ComposeConnectionError({
|
|
249
|
+
message: fetchError instanceof Error ? fetchError.message : String(fetchError),
|
|
250
|
+
cause: fetchError,
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
if (config.doNotRetry || attempt > retry.maxRetries)
|
|
254
|
+
throw lastError;
|
|
255
|
+
await delay(this.computeBackoff(attempt, retry), config.signal);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
clearTimeout(timeoutHandle);
|
|
259
|
+
if (response.ok) {
|
|
260
|
+
const data = config.expectStream ? undefined : await this.parseResponseBody(response);
|
|
261
|
+
return { data, response };
|
|
262
|
+
}
|
|
263
|
+
const errorBody = await this.safeReadJson(response);
|
|
264
|
+
const parsed = parseErrorBody(errorBody);
|
|
265
|
+
const requestId = response.headers.get("x-request-id") ?? response.headers.get("X-Request-Id") ?? undefined;
|
|
266
|
+
const retryAfterHeader = response.headers.get("retry-after");
|
|
267
|
+
const retryAfter = retryAfterHeader ? Math.max(0, parseInt(retryAfterHeader, 10)) : undefined;
|
|
268
|
+
const paymentRequired = response.status === 402
|
|
269
|
+
? extractPaymentRequired(errorBody, response.headers.get("payment-required") ?? response.headers.get("PAYMENT-REQUIRED"))
|
|
270
|
+
: null;
|
|
271
|
+
const apiError = buildApiError({
|
|
272
|
+
status: response.status,
|
|
273
|
+
code: parsed.code,
|
|
274
|
+
message: parsed.message,
|
|
275
|
+
details: parsed.details,
|
|
276
|
+
requestId: requestId ?? undefined,
|
|
277
|
+
headers: headersToRecord(response.headers),
|
|
278
|
+
body: errorBody,
|
|
279
|
+
paymentRequired,
|
|
280
|
+
paymentRequiredHeader: response.headers.get("payment-required") ?? response.headers.get("PAYMENT-REQUIRED"),
|
|
281
|
+
retryAfter,
|
|
282
|
+
});
|
|
283
|
+
const isRetryable = RETRYABLE_STATUSES.has(response.status) && !config.doNotRetry;
|
|
284
|
+
if (isRetryable && attempt <= retry.maxRetries) {
|
|
285
|
+
const wait = apiError instanceof RateLimitError && apiError.retryAfter
|
|
286
|
+
? apiError.retryAfter * 1000
|
|
287
|
+
: this.computeBackoff(attempt, retry);
|
|
288
|
+
await delay(wait, config.signal);
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
throw apiError;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
computeBackoff(attempt, retry) {
|
|
295
|
+
const base = Math.min(retry.initialDelayMs * (2 ** (attempt - 1)), retry.maxDelayMs);
|
|
296
|
+
if (!retry.jitter)
|
|
297
|
+
return base;
|
|
298
|
+
// Full jitter — uniformly between 0 and base.
|
|
299
|
+
return Math.random() * base;
|
|
300
|
+
}
|
|
301
|
+
encodeBody(config, bodyType) {
|
|
302
|
+
if (config.method === "GET" || config.method === "HEAD")
|
|
303
|
+
return undefined;
|
|
304
|
+
if (config.rawBody !== undefined)
|
|
305
|
+
return config.rawBody;
|
|
306
|
+
if (bodyType === "json" && config.body !== undefined)
|
|
307
|
+
return JSON.stringify(config.body);
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
async parseResponseBody(response) {
|
|
311
|
+
const contentType = response.headers.get("content-type") || "";
|
|
312
|
+
if (contentType.includes("application/json")) {
|
|
313
|
+
const text = await response.text();
|
|
314
|
+
if (!text)
|
|
315
|
+
return undefined;
|
|
316
|
+
return JSON.parse(text);
|
|
317
|
+
}
|
|
318
|
+
if (contentType.startsWith("text/")) {
|
|
319
|
+
return (await response.text());
|
|
320
|
+
}
|
|
321
|
+
// Binary responses (audio/speech, etc.) return the raw Response via
|
|
322
|
+
// asResponse(); the generic T is set to undefined for callers who do
|
|
323
|
+
// not ask for the Response directly.
|
|
324
|
+
return undefined;
|
|
325
|
+
}
|
|
326
|
+
async safeReadJson(response) {
|
|
327
|
+
try {
|
|
328
|
+
const text = await response.text();
|
|
329
|
+
if (!text)
|
|
330
|
+
return null;
|
|
331
|
+
try {
|
|
332
|
+
return JSON.parse(text);
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
return text;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
function headersToRecord(headers) {
|
|
344
|
+
const record = {};
|
|
345
|
+
headers.forEach((value, key) => {
|
|
346
|
+
record[key] = value;
|
|
347
|
+
});
|
|
348
|
+
return record;
|
|
349
|
+
}
|
|
350
|
+
//# sourceMappingURL=http.js.map
|
package/dist/http.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EACH,eAAe,EACf,aAAa,EACb,sBAAsB,EAEtB,mBAAmB,EACnB,cAAc,GACjB,MAAM,aAAa,CAAC;AA+ErB,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,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W,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;YAClC,OAAO,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAiB,CAAC;QACnD,CAAC;QACD,oEAAoE;QACpE,qEAAqE;QACrE,qCAAqC;QACrC,OAAO,SAAyB,CAAC;IACrC,CAAC;IAEO,KAAK,CAAC,YAAY,CAAC,QAAkB;QACzC,IAAI,CAAC;YACD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;YACnC,IAAI,CAAC,IAAI;gBAAE,OAAO,IAAI,CAAC;YACvB,IAAI,CAAC;gBACD,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC5B,CAAC;YAAC,MAAM,CAAC;gBACL,OAAO,IAAI,CAAC;YAChB,CAAC;QACL,CAAC;QAAC,MAAM,CAAC;YACL,OAAO,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;CACJ;AAED,SAAS,eAAe,CAAC,OAAgB;IACrC,MAAM,MAAM,GAA2B,EAAE,CAAC;IAC1C,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QAC3B,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACxB,CAAC,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AAClB,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@compose-market/sdk` — Official SDK for Compose Market.
|
|
3
|
+
*
|
|
4
|
+
* Exposes the canonical header contract (`Authorization: Bearer compose-<jwt>`,
|
|
5
|
+
* `x-session-user-address`, `x-chain-id`) that powers Compose's first-party
|
|
6
|
+
* apps (web/, mesh/) and lets any third-party integrator embed:
|
|
7
|
+
*
|
|
8
|
+
* - Compose Key lifecycle (create / list / get / revoke, session metadata)
|
|
9
|
+
* - 45k+ model catalog (list / listAll / search / get / getParams)
|
|
10
|
+
* - OpenAI-shaped inference (chat.completions, responses, embeddings, images,
|
|
11
|
+
* audio.speech, audio.transcriptions, videos) with full SSE streaming and
|
|
12
|
+
* typed tool-call deltas + reasoning deltas.
|
|
13
|
+
* - x402 facilitator access (supported / chains / verify / settle) and typed
|
|
14
|
+
* decoders for PAYMENT-REQUIRED, PAYMENT-RESPONSE, X-Compose-Receipt.
|
|
15
|
+
* - Webhook signature verification (HMAC-SHA256, Stripe-style header).
|
|
16
|
+
*
|
|
17
|
+
* Design:
|
|
18
|
+
* - Zero runtime dependencies. Uses platform `fetch`, WebCrypto, TextDecoder,
|
|
19
|
+
* ReadableStream. Works in Node 20+, Bun, Deno, Cloudflare Workers, browsers.
|
|
20
|
+
* - Identity is whatever the integrator already has. The SDK does NOT call a
|
|
21
|
+
* wallet, does NOT request signatures, does NOT run KYC. The end-user's
|
|
22
|
+
* wallet address — produced by whatever auth stack the integrator already
|
|
23
|
+
* uses — is trusted in the same exact way our first-party apps trust it —
|
|
24
|
+
* via the `x-session-user-address` header. The Compose Key JWT returned by
|
|
25
|
+
* `keys.create(...)` is the real cryptographic identity from that point on.
|
|
26
|
+
* - Every billable call returns a `ComposeCompletion<T>` carrying the parsed
|
|
27
|
+
* body, the settlement receipt (if any), the request id, and the raw
|
|
28
|
+
* Response so integrators can read non-standard headers without parsing.
|
|
29
|
+
*/
|
|
30
|
+
import { type FetchLike, type HttpClientOptions, type RetryPolicy } from "./http.js";
|
|
31
|
+
import { KeysResource } from "./resources/keys.js";
|
|
32
|
+
import { ModelsResource } from "./resources/models.js";
|
|
33
|
+
import { InferenceResource } from "./resources/inference.js";
|
|
34
|
+
import { X402Resource } from "./resources/x402.js";
|
|
35
|
+
import { WebhooksResource } from "./resources/webhooks.js";
|
|
36
|
+
export * from "./types/index.js";
|
|
37
|
+
export * from "./errors.js";
|
|
38
|
+
export type { APIPromise, HeaderBagInput, HttpClientOptions, RequestOptions, RetryPolicy, } from "./http.js";
|
|
39
|
+
export type { ComposeCallOptions, ComposeCompletion, ChatCompletionFinalResult, ResponsesStreamFinalResult, ComposeStreamIterator, } from "./resources/inference.js";
|
|
40
|
+
export type { ComposeWebhookEvent, VerifyWebhookInput, } from "./resources/webhooks.js";
|
|
41
|
+
export { decodeReceiptHeader, extractReceiptFromResponse, parseReceiptEvent } from "./streaming/receipt.js";
|
|
42
|
+
export { parseSSEStream } from "./streaming/sse.js";
|
|
43
|
+
export declare const SDK_VERSION = "1.0.0";
|
|
44
|
+
export interface ComposeSDKOptions {
|
|
45
|
+
/** API base URL. Defaults to `https://api.compose.market`. */
|
|
46
|
+
baseUrl?: string;
|
|
47
|
+
/** Custom fetch implementation. Defaults to the global `fetch`. */
|
|
48
|
+
fetch?: FetchLike;
|
|
49
|
+
/**
|
|
50
|
+
* End-user wallet address. Whatever identity stack you already use produced
|
|
51
|
+
* this address — pass it through. The SDK relays it exactly as our
|
|
52
|
+
* first-party apps do, and does not care how you obtained it.
|
|
53
|
+
*/
|
|
54
|
+
userAddress?: string;
|
|
55
|
+
/**
|
|
56
|
+
* Chain id. Must be one of the facilitator-configured chains. Call
|
|
57
|
+
* `sdk.x402.facilitator.chains()` to enumerate supported chains + USDC
|
|
58
|
+
* contracts at runtime.
|
|
59
|
+
*/
|
|
60
|
+
chainId?: number;
|
|
61
|
+
/**
|
|
62
|
+
* A previously-issued Compose Key JWT. The SDK stores this in-memory and
|
|
63
|
+
* attaches it as `Authorization: Bearer compose-<jwt>` on every call.
|
|
64
|
+
*/
|
|
65
|
+
composeKey?: string;
|
|
66
|
+
/** Default timeout for each HTTP call, in milliseconds. Default 60_000. */
|
|
67
|
+
timeoutMs?: number;
|
|
68
|
+
/** Retry policy applied to transient errors (5xx, 429, network). */
|
|
69
|
+
retry?: Partial<RetryPolicy>;
|
|
70
|
+
/** Headers merged into every request. */
|
|
71
|
+
defaultHeaders?: Record<string, string>;
|
|
72
|
+
/**
|
|
73
|
+
* `User-Agent` suffix so Compose analytics can distinguish integrators.
|
|
74
|
+
* The base string is `@compose-market/sdk/<version>`.
|
|
75
|
+
*/
|
|
76
|
+
userAgent?: string;
|
|
77
|
+
/** Optional debug/logging hooks. */
|
|
78
|
+
logger?: HttpClientOptions["logger"];
|
|
79
|
+
}
|
|
80
|
+
export declare class ComposeSDK {
|
|
81
|
+
readonly keys: KeysResource;
|
|
82
|
+
readonly models: ModelsResource;
|
|
83
|
+
readonly inference: InferenceResource;
|
|
84
|
+
readonly x402: X402Resource;
|
|
85
|
+
readonly webhooks: WebhooksResource;
|
|
86
|
+
readonly wallets: {
|
|
87
|
+
attach: (input: {
|
|
88
|
+
address: string;
|
|
89
|
+
chainId: number;
|
|
90
|
+
}) => void;
|
|
91
|
+
current: () => {
|
|
92
|
+
address: string | null;
|
|
93
|
+
chainId: number | null;
|
|
94
|
+
};
|
|
95
|
+
clear: () => void;
|
|
96
|
+
};
|
|
97
|
+
private readonly http;
|
|
98
|
+
private walletAddress;
|
|
99
|
+
private chainId;
|
|
100
|
+
private composeKey;
|
|
101
|
+
constructor(options?: ComposeSDKOptions);
|
|
102
|
+
}
|
|
103
|
+
export default ComposeSDK;
|
|
104
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAAc,KAAK,SAAS,EAAE,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AACjG,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAG3D,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CA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AI,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,gBAAgB,CAAC;IAEpC,QAAQ,CAAC,OAAO,EAAE;QACd,MAAM,EAAE,CAAC,KAAK,EAAE;YAAE,OAAO,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAE,KAAK,IAAI,CAAC;QAC9D,OAAO,EAAE,MAAM;YAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;YAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;SAAE,CAAC;QAClE,KAAK,EAAE,MAAM,IAAI,CAAC;KACrB,CAAC;IAEF,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAa;IAClC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,UAAU,CAAgB;gBAEtB,OAAO,GAAE,iBAAsB;CA+D9C;AAED,eAAe,UAAU,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@compose-market/sdk` — Official SDK for Compose Market.
|
|
3
|
+
*
|
|
4
|
+
* Exposes the canonical header contract (`Authorization: Bearer compose-<jwt>`,
|
|
5
|
+
* `x-session-user-address`, `x-chain-id`) that powers Compose's first-party
|
|
6
|
+
* apps (web/, mesh/) and lets any third-party integrator embed:
|
|
7
|
+
*
|
|
8
|
+
* - Compose Key lifecycle (create / list / get / revoke, session metadata)
|
|
9
|
+
* - 45k+ model catalog (list / listAll / search / get / getParams)
|
|
10
|
+
* - OpenAI-shaped inference (chat.completions, responses, embeddings, images,
|
|
11
|
+
* audio.speech, audio.transcriptions, videos) with full SSE streaming and
|
|
12
|
+
* typed tool-call deltas + reasoning deltas.
|
|
13
|
+
* - x402 facilitator access (supported / chains / verify / settle) and typed
|
|
14
|
+
* decoders for PAYMENT-REQUIRED, PAYMENT-RESPONSE, X-Compose-Receipt.
|
|
15
|
+
* - Webhook signature verification (HMAC-SHA256, Stripe-style header).
|
|
16
|
+
*
|
|
17
|
+
* Design:
|
|
18
|
+
* - Zero runtime dependencies. Uses platform `fetch`, WebCrypto, TextDecoder,
|
|
19
|
+
* ReadableStream. Works in Node 20+, Bun, Deno, Cloudflare Workers, browsers.
|
|
20
|
+
* - Identity is whatever the integrator already has. The SDK does NOT call a
|
|
21
|
+
* wallet, does NOT request signatures, does NOT run KYC. The end-user's
|
|
22
|
+
* wallet address — produced by whatever auth stack the integrator already
|
|
23
|
+
* uses — is trusted in the same exact way our first-party apps trust it —
|
|
24
|
+
* via the `x-session-user-address` header. The Compose Key JWT returned by
|
|
25
|
+
* `keys.create(...)` is the real cryptographic identity from that point on.
|
|
26
|
+
* - Every billable call returns a `ComposeCompletion<T>` carrying the parsed
|
|
27
|
+
* body, the settlement receipt (if any), the request id, and the raw
|
|
28
|
+
* Response so integrators can read non-standard headers without parsing.
|
|
29
|
+
*/
|
|
30
|
+
import { HttpClient } from "./http.js";
|
|
31
|
+
import { KeysResource } from "./resources/keys.js";
|
|
32
|
+
import { ModelsResource } from "./resources/models.js";
|
|
33
|
+
import { InferenceResource } from "./resources/inference.js";
|
|
34
|
+
import { X402Resource } from "./resources/x402.js";
|
|
35
|
+
import { WebhooksResource } from "./resources/webhooks.js";
|
|
36
|
+
import { BadRequestError } from "./errors.js";
|
|
37
|
+
export * from "./types/index.js";
|
|
38
|
+
export * from "./errors.js";
|
|
39
|
+
export { decodeReceiptHeader, extractReceiptFromResponse, parseReceiptEvent } from "./streaming/receipt.js";
|
|
40
|
+
export { parseSSEStream } from "./streaming/sse.js";
|
|
41
|
+
export const SDK_VERSION = "1.0.0";
|
|
42
|
+
const DEFAULT_RETRY = {
|
|
43
|
+
maxRetries: 2,
|
|
44
|
+
initialDelayMs: 500,
|
|
45
|
+
maxDelayMs: 8_000,
|
|
46
|
+
jitter: true,
|
|
47
|
+
};
|
|
48
|
+
function normalizeBaseUrl(value) {
|
|
49
|
+
return (value || "https://api.compose.market").replace(/\/+$/, "");
|
|
50
|
+
}
|
|
51
|
+
function normalizeWalletAddress(value) {
|
|
52
|
+
const trimmed = value.trim().toLowerCase();
|
|
53
|
+
if (!/^0x[a-f0-9]{40}$/.test(trimmed)) {
|
|
54
|
+
throw new BadRequestError({ message: "userAddress must be a valid 0x-prefixed EVM address" });
|
|
55
|
+
}
|
|
56
|
+
return trimmed;
|
|
57
|
+
}
|
|
58
|
+
function normalizeChainId(value) {
|
|
59
|
+
if (value === undefined || value === null)
|
|
60
|
+
return null;
|
|
61
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
62
|
+
throw new BadRequestError({ message: "chainId must be a positive integer" });
|
|
63
|
+
}
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
export class ComposeSDK {
|
|
67
|
+
keys;
|
|
68
|
+
models;
|
|
69
|
+
inference;
|
|
70
|
+
x402;
|
|
71
|
+
webhooks;
|
|
72
|
+
wallets;
|
|
73
|
+
http;
|
|
74
|
+
walletAddress;
|
|
75
|
+
chainId;
|
|
76
|
+
composeKey;
|
|
77
|
+
constructor(options = {}) {
|
|
78
|
+
this.walletAddress = options.userAddress ? normalizeWalletAddress(options.userAddress) : null;
|
|
79
|
+
this.chainId = normalizeChainId(options.chainId);
|
|
80
|
+
this.composeKey = options.composeKey ?? null;
|
|
81
|
+
const userAgent = options.userAgent
|
|
82
|
+
? `@compose-market/sdk/${SDK_VERSION} ${options.userAgent}`
|
|
83
|
+
: `@compose-market/sdk/${SDK_VERSION}`;
|
|
84
|
+
this.http = new HttpClient({
|
|
85
|
+
baseUrl: normalizeBaseUrl(options.baseUrl),
|
|
86
|
+
fetch: options.fetch ?? globalThis.fetch.bind(globalThis),
|
|
87
|
+
timeoutMs: options.timeoutMs ?? 60_000,
|
|
88
|
+
defaultHeaders: { ...(options.defaultHeaders ?? {}) },
|
|
89
|
+
retry: { ...DEFAULT_RETRY, ...(options.retry ?? {}) },
|
|
90
|
+
userAgent,
|
|
91
|
+
logger: options.logger,
|
|
92
|
+
});
|
|
93
|
+
this.wallets = {
|
|
94
|
+
attach: (input) => {
|
|
95
|
+
this.walletAddress = normalizeWalletAddress(input.address);
|
|
96
|
+
this.chainId = normalizeChainId(input.chainId);
|
|
97
|
+
},
|
|
98
|
+
current: () => ({ address: this.walletAddress, chainId: this.chainId }),
|
|
99
|
+
clear: () => {
|
|
100
|
+
this.walletAddress = null;
|
|
101
|
+
this.chainId = null;
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
const getWallet = () => {
|
|
105
|
+
if (!this.walletAddress) {
|
|
106
|
+
throw new BadRequestError({
|
|
107
|
+
message: "Wallet context is required. Call sdk.wallets.attach({ address, chainId }) first, or pass userAddress + chainId to the constructor.",
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
if (this.chainId === null) {
|
|
111
|
+
throw new BadRequestError({
|
|
112
|
+
message: "chainId is required. Call sdk.wallets.attach(...) or pass chainId to the constructor.",
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
return { address: this.walletAddress, chainId: this.chainId };
|
|
116
|
+
};
|
|
117
|
+
const getWalletMaybe = () => ({
|
|
118
|
+
address: this.walletAddress,
|
|
119
|
+
chainId: this.chainId,
|
|
120
|
+
});
|
|
121
|
+
this.keys = new KeysResource(this.http, {
|
|
122
|
+
getWallet,
|
|
123
|
+
setToken: (token) => { this.composeKey = token; },
|
|
124
|
+
getToken: () => this.composeKey,
|
|
125
|
+
clearToken: () => { this.composeKey = null; },
|
|
126
|
+
});
|
|
127
|
+
this.models = new ModelsResource(this.http);
|
|
128
|
+
this.inference = new InferenceResource(this.http, {
|
|
129
|
+
getWalletMaybe,
|
|
130
|
+
getTokenMaybe: () => this.composeKey,
|
|
131
|
+
});
|
|
132
|
+
this.x402 = new X402Resource(this.http);
|
|
133
|
+
this.webhooks = new WebhooksResource();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
export default ComposeSDK;
|
|
137
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,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