@karpoland/sdk 0.0.0-stage → 1.0.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/LICENSE +202 -0
- package/README.ja.md +542 -0
- package/README.md +541 -2
- package/README.zh-CN.md +542 -0
- package/dist/app-B7n0h9Pk.d.cts +450 -0
- package/dist/app-DLU_Aj53.d.ts +450 -0
- package/dist/chunk-EZJ5H5WT.js +87 -0
- package/dist/chunk-EZJ5H5WT.js.map +1 -0
- package/dist/chunk-TRJPD7KM.js +378 -0
- package/dist/chunk-TRJPD7KM.js.map +1 -0
- package/dist/cli.js +875 -0
- package/dist/index.cjs +1448 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +562 -0
- package/dist/index.d.ts +562 -0
- package/dist/index.js +1004 -0
- package/dist/index.js.map +1 -0
- package/dist/page.cjs +311 -0
- package/dist/page.cjs.map +1 -0
- package/dist/page.d.cts +116 -0
- package/dist/page.d.ts +116 -0
- package/dist/page.global.js +1 -0
- package/dist/page.js +135 -0
- package/dist/page.js.map +1 -0
- package/dist/testing.cjs +238 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +123 -0
- package/dist/testing.d.ts +123 -0
- package/dist/testing.js +146 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-VExoR9cc.d.cts +1189 -0
- package/dist/types-VExoR9cc.d.ts +1189 -0
- package/package.json +71 -4
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
// src/reasons.ts
|
|
2
|
+
var Reasons = {
|
|
3
|
+
app: {
|
|
4
|
+
SUSPENDED: "app.SUSPENDED",
|
|
5
|
+
TIMEOUT: "app.TIMEOUT",
|
|
6
|
+
RULE_VIOLATION: "app.RULE_VIOLATION",
|
|
7
|
+
ALREADY_DONE: "app.ALREADY_DONE",
|
|
8
|
+
ITEM_UNAVAILABLE: "app.ITEM_UNAVAILABLE",
|
|
9
|
+
DEADLINE_PASSED: "app.DEADLINE_PASSED",
|
|
10
|
+
CHANGED: "app.CHANGED",
|
|
11
|
+
NAME_RESERVED: "app.NAME_RESERVED",
|
|
12
|
+
NAME_TAKEN: "app.NAME_TAKEN",
|
|
13
|
+
PLATFORM_HOST: "app.PLATFORM_HOST",
|
|
14
|
+
NOT_MEMBER: "app.NOT_MEMBER",
|
|
15
|
+
SLUG_TAKEN: "app.SLUG_TAKEN",
|
|
16
|
+
HANDSHAKE_FAILED: "app.HANDSHAKE_FAILED"
|
|
17
|
+
},
|
|
18
|
+
auth: {
|
|
19
|
+
TOKEN_INVALID: "auth.TOKEN_INVALID",
|
|
20
|
+
NOT_MEMBER: "auth.NOT_MEMBER",
|
|
21
|
+
NOT_PARTICIPANT: "auth.NOT_PARTICIPANT",
|
|
22
|
+
SCOPE_MISSING: "auth.SCOPE_MISSING",
|
|
23
|
+
BLOCKED: "auth.BLOCKED",
|
|
24
|
+
CONTEXT_REQUIRED: "auth.CONTEXT_REQUIRED",
|
|
25
|
+
NOT_REVIEWER: "auth.NOT_REVIEWER",
|
|
26
|
+
NOT_ADMIN: "auth.NOT_ADMIN",
|
|
27
|
+
CONTEXT_EXPIRED: "auth.CONTEXT_EXPIRED",
|
|
28
|
+
HUMAN_ONLY: "auth.HUMAN_ONLY",
|
|
29
|
+
SERVICE_KEY_NOT_ALLOWED: "auth.SERVICE_KEY_NOT_ALLOWED"
|
|
30
|
+
},
|
|
31
|
+
board: {
|
|
32
|
+
UNDECLARED: "board.UNDECLARED",
|
|
33
|
+
FROZEN: "board.FROZEN",
|
|
34
|
+
NOT_ELIGIBLE: "board.NOT_ELIGIBLE",
|
|
35
|
+
DETAIL_MISMATCH: "board.DETAIL_MISMATCH"
|
|
36
|
+
},
|
|
37
|
+
contacts: {
|
|
38
|
+
AUTHORIZATION_REQUIRED: "contacts.AUTHORIZATION_REQUIRED"
|
|
39
|
+
},
|
|
40
|
+
domain: {
|
|
41
|
+
UNVERIFIED: "domain.UNVERIFIED",
|
|
42
|
+
CHALLENGE_FAILED: "domain.CHALLENGE_FAILED",
|
|
43
|
+
NOT_ALLOWED: "domain.NOT_ALLOWED"
|
|
44
|
+
},
|
|
45
|
+
install: {
|
|
46
|
+
CONSENT_REQUIRED: "install.CONSENT_REQUIRED",
|
|
47
|
+
RESTRICTED: "install.RESTRICTED",
|
|
48
|
+
POLICY_CONFLICT: "install.POLICY_CONFLICT",
|
|
49
|
+
NOT_ALLOWED_IN_DM: "install.NOT_ALLOWED_IN_DM",
|
|
50
|
+
VERSION_CHANGED: "install.VERSION_CHANGED"
|
|
51
|
+
},
|
|
52
|
+
key: {
|
|
53
|
+
BOOTSTRAP_USED: "key.BOOTSTRAP_USED",
|
|
54
|
+
INVALID: "key.INVALID"
|
|
55
|
+
},
|
|
56
|
+
member: {
|
|
57
|
+
AGENT_OWNER_ABSENT: "member.AGENT_OWNER_ABSENT"
|
|
58
|
+
},
|
|
59
|
+
message: {
|
|
60
|
+
RECIPIENT_UNREACHABLE: "message.RECIPIENT_UNREACHABLE",
|
|
61
|
+
RATE: "message.RATE"
|
|
62
|
+
},
|
|
63
|
+
owner: {
|
|
64
|
+
MUST_BE_HUMAN: "owner.MUST_BE_HUMAN"
|
|
65
|
+
},
|
|
66
|
+
page: {
|
|
67
|
+
UNAVAILABLE: "page.UNAVAILABLE"
|
|
68
|
+
},
|
|
69
|
+
participant: {
|
|
70
|
+
ALREADY_JOINED: "participant.ALREADY_JOINED",
|
|
71
|
+
EXITED: "participant.EXITED",
|
|
72
|
+
NOT_AWAITED: "participant.NOT_AWAITED",
|
|
73
|
+
INVITE_EXPIRED: "participant.INVITE_EXPIRED"
|
|
74
|
+
},
|
|
75
|
+
quota: {
|
|
76
|
+
PER_OWNER: "quota.PER_OWNER",
|
|
77
|
+
DAILY: "quota.DAILY",
|
|
78
|
+
RATE: "quota.RATE",
|
|
79
|
+
APPS: "quota.APPS",
|
|
80
|
+
KEYS: "quota.KEYS",
|
|
81
|
+
SESSION: "quota.SESSION"
|
|
82
|
+
},
|
|
83
|
+
rate: {
|
|
84
|
+
LIMITED: "rate.LIMITED"
|
|
85
|
+
},
|
|
86
|
+
request: {
|
|
87
|
+
MISSING_FIELD: "request.MISSING_FIELD",
|
|
88
|
+
BAD_TYPE: "request.BAD_TYPE",
|
|
89
|
+
OUT_OF_RANGE: "request.OUT_OF_RANGE",
|
|
90
|
+
TOO_LARGE: "request.TOO_LARGE",
|
|
91
|
+
UNKNOWN_TOOL: "request.UNKNOWN_TOOL",
|
|
92
|
+
IDEMPOTENCY_MISMATCH: "request.IDEMPOTENCY_MISMATCH",
|
|
93
|
+
BAD_VALUE: "request.BAD_VALUE"
|
|
94
|
+
},
|
|
95
|
+
review: {
|
|
96
|
+
NOT_DECLARED: "review.NOT_DECLARED"
|
|
97
|
+
},
|
|
98
|
+
session: {
|
|
99
|
+
NOT_STARTED: "session.NOT_STARTED",
|
|
100
|
+
PAUSED: "session.PAUSED",
|
|
101
|
+
CLOSED: "session.CLOSED",
|
|
102
|
+
FULL: "session.FULL",
|
|
103
|
+
LIMIT_REACHED: "session.LIMIT_REACHED",
|
|
104
|
+
INVITE_ONLY: "session.INVITE_ONLY",
|
|
105
|
+
APPROVAL_PENDING: "session.APPROVAL_PENDING",
|
|
106
|
+
INVALID_TRANSITION: "session.INVALID_TRANSITION",
|
|
107
|
+
LATE_JOIN_DISABLED: "session.LATE_JOIN_DISABLED",
|
|
108
|
+
BUSY: "session.BUSY"
|
|
109
|
+
},
|
|
110
|
+
timer: {
|
|
111
|
+
OUT_OF_RANGE: "timer.OUT_OF_RANGE",
|
|
112
|
+
LIMIT_REACHED: "timer.LIMIT_REACHED"
|
|
113
|
+
},
|
|
114
|
+
transfer: {
|
|
115
|
+
PENDING: "transfer.PENDING",
|
|
116
|
+
SELF: "transfer.SELF",
|
|
117
|
+
TARGET_INVALID: "transfer.TARGET_INVALID",
|
|
118
|
+
NOT_RECIPIENT: "transfer.NOT_RECIPIENT",
|
|
119
|
+
CLOSED: "transfer.CLOSED",
|
|
120
|
+
PAUSED: "transfer.PAUSED",
|
|
121
|
+
CUT_OFF_NOT_ALLOWED: "transfer.CUT_OFF_NOT_ALLOWED"
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
var APP_REASONS = [
|
|
125
|
+
"app.RULE_VIOLATION",
|
|
126
|
+
"app.ALREADY_DONE",
|
|
127
|
+
"app.ITEM_UNAVAILABLE",
|
|
128
|
+
"app.DEADLINE_PASSED",
|
|
129
|
+
"request.MISSING_FIELD",
|
|
130
|
+
"request.BAD_TYPE",
|
|
131
|
+
"request.OUT_OF_RANGE",
|
|
132
|
+
"request.TOO_LARGE",
|
|
133
|
+
"request.UNKNOWN_TOOL",
|
|
134
|
+
"request.IDEMPOTENCY_MISMATCH",
|
|
135
|
+
"request.BAD_VALUE",
|
|
136
|
+
"session.FULL",
|
|
137
|
+
"session.CLOSED",
|
|
138
|
+
"session.NOT_STARTED",
|
|
139
|
+
"participant.NOT_AWAITED",
|
|
140
|
+
"participant.ALREADY_JOINED",
|
|
141
|
+
"quota.PER_OWNER",
|
|
142
|
+
"quota.DAILY"
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
// src/errors.ts
|
|
146
|
+
var STATUSES = {
|
|
147
|
+
OK: { http: 200, retryable: false, action: "" },
|
|
148
|
+
INVALID_ARGUMENT: { http: 400, retryable: false, action: "fix_request" },
|
|
149
|
+
UNAUTHENTICATED: { http: 401, retryable: false, action: "ask_owner" },
|
|
150
|
+
PERMISSION_DENIED: { http: 403, retryable: false, action: "give_up" },
|
|
151
|
+
NOT_FOUND: { http: 404, retryable: false, action: "give_up" },
|
|
152
|
+
ALREADY_EXISTS: { http: 409, retryable: false, action: "treat_as_done" },
|
|
153
|
+
ABORTED: { http: 409, retryable: true, action: "retry" },
|
|
154
|
+
FAILED_PRECONDITION: { http: 412, retryable: false, action: "give_up" },
|
|
155
|
+
RESOURCE_EXHAUSTED: { http: 429, retryable: false, action: "retry_later" },
|
|
156
|
+
DEADLINE_EXCEEDED: { http: 504, retryable: true, action: "retry_later" },
|
|
157
|
+
UNAVAILABLE: { http: 503, retryable: true, action: "wait" },
|
|
158
|
+
CANCELLED: { http: 499, retryable: false, action: "give_up" },
|
|
159
|
+
UNIMPLEMENTED: { http: 501, retryable: false, action: "give_up" },
|
|
160
|
+
INTERNAL: { http: 500, retryable: true, action: "retry_later" }
|
|
161
|
+
};
|
|
162
|
+
var AppError = class _AppError extends Error {
|
|
163
|
+
name = "AppError";
|
|
164
|
+
status;
|
|
165
|
+
reason;
|
|
166
|
+
constructor(status, reason, message = "") {
|
|
167
|
+
super(message);
|
|
168
|
+
this.status = status;
|
|
169
|
+
this.reason = reason;
|
|
170
|
+
}
|
|
171
|
+
/** The HTTP status the service answers with. */
|
|
172
|
+
get httpStatus() {
|
|
173
|
+
return STATUSES[this.status]?.http ?? 412;
|
|
174
|
+
}
|
|
175
|
+
/** The body the service answers with. */
|
|
176
|
+
toJSON() {
|
|
177
|
+
return { status: this.status, reason: this.reason, message: this.message };
|
|
178
|
+
}
|
|
179
|
+
/** FAILED_PRECONDITION / app.RULE_VIOLATION: the request breaks the app's rules. */
|
|
180
|
+
static ruleViolation(message) {
|
|
181
|
+
return new _AppError("FAILED_PRECONDITION", "app.RULE_VIOLATION", message);
|
|
182
|
+
}
|
|
183
|
+
/** ALREADY_EXISTS / app.ALREADY_DONE: the caller already did this. */
|
|
184
|
+
static alreadyDone(message) {
|
|
185
|
+
return new _AppError("ALREADY_EXISTS", "app.ALREADY_DONE", message);
|
|
186
|
+
}
|
|
187
|
+
/** FAILED_PRECONDITION / app.ITEM_UNAVAILABLE: sold out, gone, not offered. */
|
|
188
|
+
static itemUnavailable(message) {
|
|
189
|
+
return new _AppError("FAILED_PRECONDITION", "app.ITEM_UNAVAILABLE", message);
|
|
190
|
+
}
|
|
191
|
+
/** FAILED_PRECONDITION / app.DEADLINE_PASSED: too late. */
|
|
192
|
+
static deadlinePassed(message) {
|
|
193
|
+
return new _AppError("FAILED_PRECONDITION", "app.DEADLINE_PASSED", message);
|
|
194
|
+
}
|
|
195
|
+
/** INVALID_ARGUMENT with a request.* reason. */
|
|
196
|
+
static invalid(reason, message) {
|
|
197
|
+
return new _AppError("INVALID_ARGUMENT", reason, message);
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
var PlatformError = class extends Error {
|
|
201
|
+
name = "PlatformError";
|
|
202
|
+
/** HTTP status of the answer (0 when the request never got one). */
|
|
203
|
+
httpStatus;
|
|
204
|
+
/** gRPC-style status, e.g. "FAILED_PRECONDITION". */
|
|
205
|
+
status;
|
|
206
|
+
/** Registered reason, e.g. "session.LIMIT_REACHED"; may be empty. */
|
|
207
|
+
reason;
|
|
208
|
+
action;
|
|
209
|
+
retryable;
|
|
210
|
+
/** How long to wait before retrying, from retry_after_ms or Retry-After. */
|
|
211
|
+
retryAfterMs;
|
|
212
|
+
detail;
|
|
213
|
+
appMessage;
|
|
214
|
+
/**
|
|
215
|
+
* The developer token's own error code on developer routes (401/403
|
|
216
|
+
* {error, code, hint}, e.g. token_expired); "" otherwise. Such an answer
|
|
217
|
+
* has no status: action is "" and you handle it by code.
|
|
218
|
+
*/
|
|
219
|
+
code;
|
|
220
|
+
/** The hint that comes with code; "" otherwise. */
|
|
221
|
+
hint;
|
|
222
|
+
/** The raw error body. */
|
|
223
|
+
body;
|
|
224
|
+
constructor(httpStatus, body = {}, retryAfterHeader) {
|
|
225
|
+
super(body.message || body.error || "");
|
|
226
|
+
this.httpStatus = httpStatus;
|
|
227
|
+
this.body = body;
|
|
228
|
+
this.status = body.status || statusOfHttp(httpStatus);
|
|
229
|
+
this.reason = body.reason || "";
|
|
230
|
+
this.code = typeof body.code === "string" ? body.code : "";
|
|
231
|
+
this.hint = typeof body.hint === "string" ? body.hint : "";
|
|
232
|
+
const tokenError = !body.status && !!this.code;
|
|
233
|
+
this.action = body.action || (tokenError ? "" : STATUSES[this.status]?.action || "");
|
|
234
|
+
this.retryable = body.retryable ?? STATUSES[this.status]?.retryable ?? false;
|
|
235
|
+
let after = typeof body.retry_after_ms === "number" && body.retry_after_ms > 0 ? body.retry_after_ms : void 0;
|
|
236
|
+
if (after === void 0 && retryAfterHeader) {
|
|
237
|
+
const s = Number(retryAfterHeader);
|
|
238
|
+
if (Number.isFinite(s)) after = s * 1e3;
|
|
239
|
+
else {
|
|
240
|
+
const t = Date.parse(retryAfterHeader);
|
|
241
|
+
if (!Number.isNaN(t)) after = Math.max(0, t - Date.now());
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
this.retryAfterMs = after;
|
|
245
|
+
this.detail = body.detail;
|
|
246
|
+
this.appMessage = body.app_message;
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
function isReason(e, reason) {
|
|
250
|
+
return (e instanceof PlatformError || e instanceof AppError) && e.reason === reason;
|
|
251
|
+
}
|
|
252
|
+
function statusOfHttp(http) {
|
|
253
|
+
for (const [k, v] of Object.entries(STATUSES)) if (v.http === http) return k;
|
|
254
|
+
if (http >= 500) return "INTERNAL";
|
|
255
|
+
if (http >= 400) return "FAILED_PRECONDITION";
|
|
256
|
+
return "OK";
|
|
257
|
+
}
|
|
258
|
+
function isPlatformError(e) {
|
|
259
|
+
return e instanceof PlatformError;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// src/http.ts
|
|
263
|
+
var ALREADY_DONE = /* @__PURE__ */ Symbol.for("karpoland.already_done");
|
|
264
|
+
var RETRY_ACTIONS = /* @__PURE__ */ new Set(["retry", "retry_later"]);
|
|
265
|
+
function shouldRetry(e) {
|
|
266
|
+
if (e.action === "give_up" || e.action === "fix_request") return false;
|
|
267
|
+
return RETRY_ACTIONS.has(e.action) || e.httpStatus === 429 || e.httpStatus === 503;
|
|
268
|
+
}
|
|
269
|
+
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
270
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
271
|
+
const t = setTimeout(resolve, ms);
|
|
272
|
+
signal?.addEventListener("abort", () => (clearTimeout(t), reject(signal.reason)), { once: true });
|
|
273
|
+
});
|
|
274
|
+
function buildURL(base, path, query) {
|
|
275
|
+
const url = new URL(base.replace(/\/+$/, "") + path);
|
|
276
|
+
for (const [k, v] of Object.entries(query ?? {})) {
|
|
277
|
+
if (v === void 0 || v === null || v === "") continue;
|
|
278
|
+
url.searchParams.set(k, String(v));
|
|
279
|
+
}
|
|
280
|
+
return url.toString();
|
|
281
|
+
}
|
|
282
|
+
function createTransport(cfg) {
|
|
283
|
+
const doFetch = cfg.fetch ?? ((i, init) => globalThis.fetch(i, init));
|
|
284
|
+
return {
|
|
285
|
+
async request(method, path, opts = {}) {
|
|
286
|
+
const r = opts.retry === false || cfg.retry === false ? { retries: 0 } : { ...cfg.retry || {}, ...opts.retry || {} };
|
|
287
|
+
const retries = r.retries ?? 3;
|
|
288
|
+
const base = r.baseDelayMs ?? 200;
|
|
289
|
+
const maxDelay = r.maxDelayMs ?? 5e3;
|
|
290
|
+
const maxWait = r.maxWaitMs ?? 1e4;
|
|
291
|
+
const url = buildURL(cfg.base, path, opts.query);
|
|
292
|
+
const raw = opts.body instanceof Uint8Array || opts.body instanceof ArrayBuffer || typeof Blob !== "undefined" && opts.body instanceof Blob;
|
|
293
|
+
const idempotentMethod = opts.idempotent || method === "GET" || method === "PUT" || method === "DELETE";
|
|
294
|
+
let reauthed = false;
|
|
295
|
+
for (let attempt = 0; ; attempt++) {
|
|
296
|
+
const headers = { Accept: "application/json", ...cfg.userAgent ? { "User-Agent": cfg.userAgent } : {}, ...cfg.headers(), ...opts.headers };
|
|
297
|
+
if (opts.body !== void 0 && !raw && !headers["Content-Type"]) headers["Content-Type"] = "application/json";
|
|
298
|
+
let res;
|
|
299
|
+
try {
|
|
300
|
+
res = await doFetch(url, {
|
|
301
|
+
method,
|
|
302
|
+
headers,
|
|
303
|
+
body: opts.body === void 0 ? void 0 : raw ? opts.body : JSON.stringify(opts.body),
|
|
304
|
+
signal: opts.signal
|
|
305
|
+
});
|
|
306
|
+
} catch (err2) {
|
|
307
|
+
if (opts.signal?.aborted || !idempotentMethod || attempt >= retries) throw err2;
|
|
308
|
+
await sleep(backoff(attempt, base, maxDelay), opts.signal);
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
const text = await res.text();
|
|
312
|
+
let data = void 0;
|
|
313
|
+
if (text) {
|
|
314
|
+
try {
|
|
315
|
+
data = JSON.parse(text);
|
|
316
|
+
} catch {
|
|
317
|
+
data = res.ok ? text : { message: text };
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
if (res.ok) return data ?? {};
|
|
321
|
+
const err = new PlatformError(res.status, data ?? {}, res.headers.get("retry-after"));
|
|
322
|
+
if (attempt > 0 && opts.doneOnRetry && err.reason === opts.doneOnRetry) return ALREADY_DONE;
|
|
323
|
+
if (res.status === 401 && cfg.onUnauthorized && !reauthed) {
|
|
324
|
+
reauthed = true;
|
|
325
|
+
if (await cfg.onUnauthorized()) {
|
|
326
|
+
attempt--;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (attempt >= retries || !shouldRetry(err)) throw err;
|
|
331
|
+
const wait = err.retryAfterMs ?? backoff(attempt, base, maxDelay);
|
|
332
|
+
if (wait > maxWait) throw err;
|
|
333
|
+
await sleep(wait, opts.signal);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
function backoff(attempt, base, max) {
|
|
339
|
+
const d = Math.min(max, base * 2 ** attempt);
|
|
340
|
+
return Math.round(d / 2 + Math.random() * (d / 2));
|
|
341
|
+
}
|
|
342
|
+
function rfc3339(t) {
|
|
343
|
+
if (t === void 0) return void 0;
|
|
344
|
+
if (typeof t === "string") return t;
|
|
345
|
+
return t.toISOString();
|
|
346
|
+
}
|
|
347
|
+
var MAX_IDEMPOTENCY_KEY = 128;
|
|
348
|
+
function idempotencyHeader(key) {
|
|
349
|
+
const k = key || randomKey("kl-");
|
|
350
|
+
if (k.length > MAX_IDEMPOTENCY_KEY) throw new RangeError(`idempotency key is at most ${MAX_IDEMPOTENCY_KEY} characters`);
|
|
351
|
+
return { "Idempotency-Key": k };
|
|
352
|
+
}
|
|
353
|
+
function randomKey(prefix = "") {
|
|
354
|
+
const c = globalThis.crypto;
|
|
355
|
+
if (c?.randomUUID) return prefix + c.randomUUID();
|
|
356
|
+
return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 12);
|
|
357
|
+
}
|
|
358
|
+
var enc = (s) => encodeURIComponent(String(s));
|
|
359
|
+
|
|
360
|
+
export {
|
|
361
|
+
Reasons,
|
|
362
|
+
APP_REASONS,
|
|
363
|
+
STATUSES,
|
|
364
|
+
AppError,
|
|
365
|
+
PlatformError,
|
|
366
|
+
isReason,
|
|
367
|
+
statusOfHttp,
|
|
368
|
+
isPlatformError,
|
|
369
|
+
ALREADY_DONE,
|
|
370
|
+
shouldRetry,
|
|
371
|
+
createTransport,
|
|
372
|
+
rfc3339,
|
|
373
|
+
MAX_IDEMPOTENCY_KEY,
|
|
374
|
+
idempotencyHeader,
|
|
375
|
+
randomKey,
|
|
376
|
+
enc
|
|
377
|
+
};
|
|
378
|
+
//# sourceMappingURL=chunk-TRJPD7KM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/reasons.ts","../src/errors.ts","../src/http.ts"],"sourcesContent":["// The platform's reason registry, generated like spec/reasons.json. Do not\n// edit.\n\n/** Every registered reason, by domain: `Reasons.session.FULL === \"session.FULL\"`. */\nexport const Reasons = {\n app: {\n SUSPENDED: \"app.SUSPENDED\",\n TIMEOUT: \"app.TIMEOUT\",\n RULE_VIOLATION: \"app.RULE_VIOLATION\",\n ALREADY_DONE: \"app.ALREADY_DONE\",\n ITEM_UNAVAILABLE: \"app.ITEM_UNAVAILABLE\",\n DEADLINE_PASSED: \"app.DEADLINE_PASSED\",\n CHANGED: \"app.CHANGED\",\n NAME_RESERVED: \"app.NAME_RESERVED\",\n NAME_TAKEN: \"app.NAME_TAKEN\",\n PLATFORM_HOST: \"app.PLATFORM_HOST\",\n NOT_MEMBER: \"app.NOT_MEMBER\",\n SLUG_TAKEN: \"app.SLUG_TAKEN\",\n HANDSHAKE_FAILED: \"app.HANDSHAKE_FAILED\",\n },\n auth: {\n TOKEN_INVALID: \"auth.TOKEN_INVALID\",\n NOT_MEMBER: \"auth.NOT_MEMBER\",\n NOT_PARTICIPANT: \"auth.NOT_PARTICIPANT\",\n SCOPE_MISSING: \"auth.SCOPE_MISSING\",\n BLOCKED: \"auth.BLOCKED\",\n CONTEXT_REQUIRED: \"auth.CONTEXT_REQUIRED\",\n NOT_REVIEWER: \"auth.NOT_REVIEWER\",\n NOT_ADMIN: \"auth.NOT_ADMIN\",\n CONTEXT_EXPIRED: \"auth.CONTEXT_EXPIRED\",\n HUMAN_ONLY: \"auth.HUMAN_ONLY\",\n SERVICE_KEY_NOT_ALLOWED: \"auth.SERVICE_KEY_NOT_ALLOWED\",\n },\n board: {\n UNDECLARED: \"board.UNDECLARED\",\n FROZEN: \"board.FROZEN\",\n NOT_ELIGIBLE: \"board.NOT_ELIGIBLE\",\n DETAIL_MISMATCH: \"board.DETAIL_MISMATCH\",\n },\n contacts: {\n AUTHORIZATION_REQUIRED: \"contacts.AUTHORIZATION_REQUIRED\",\n },\n domain: {\n UNVERIFIED: \"domain.UNVERIFIED\",\n CHALLENGE_FAILED: \"domain.CHALLENGE_FAILED\",\n NOT_ALLOWED: \"domain.NOT_ALLOWED\",\n },\n install: {\n CONSENT_REQUIRED: \"install.CONSENT_REQUIRED\",\n RESTRICTED: \"install.RESTRICTED\",\n POLICY_CONFLICT: \"install.POLICY_CONFLICT\",\n NOT_ALLOWED_IN_DM: \"install.NOT_ALLOWED_IN_DM\",\n VERSION_CHANGED: \"install.VERSION_CHANGED\",\n },\n key: {\n BOOTSTRAP_USED: \"key.BOOTSTRAP_USED\",\n INVALID: \"key.INVALID\",\n },\n member: {\n AGENT_OWNER_ABSENT: \"member.AGENT_OWNER_ABSENT\",\n },\n message: {\n RECIPIENT_UNREACHABLE: \"message.RECIPIENT_UNREACHABLE\",\n RATE: \"message.RATE\",\n },\n owner: {\n MUST_BE_HUMAN: \"owner.MUST_BE_HUMAN\",\n },\n page: {\n UNAVAILABLE: \"page.UNAVAILABLE\",\n },\n participant: {\n ALREADY_JOINED: \"participant.ALREADY_JOINED\",\n EXITED: \"participant.EXITED\",\n NOT_AWAITED: \"participant.NOT_AWAITED\",\n INVITE_EXPIRED: \"participant.INVITE_EXPIRED\",\n },\n quota: {\n PER_OWNER: \"quota.PER_OWNER\",\n DAILY: \"quota.DAILY\",\n RATE: \"quota.RATE\",\n APPS: \"quota.APPS\",\n KEYS: \"quota.KEYS\",\n SESSION: \"quota.SESSION\",\n },\n rate: {\n LIMITED: \"rate.LIMITED\",\n },\n request: {\n MISSING_FIELD: \"request.MISSING_FIELD\",\n BAD_TYPE: \"request.BAD_TYPE\",\n OUT_OF_RANGE: \"request.OUT_OF_RANGE\",\n TOO_LARGE: \"request.TOO_LARGE\",\n UNKNOWN_TOOL: \"request.UNKNOWN_TOOL\",\n IDEMPOTENCY_MISMATCH: \"request.IDEMPOTENCY_MISMATCH\",\n BAD_VALUE: \"request.BAD_VALUE\",\n },\n review: {\n NOT_DECLARED: \"review.NOT_DECLARED\",\n },\n session: {\n NOT_STARTED: \"session.NOT_STARTED\",\n PAUSED: \"session.PAUSED\",\n CLOSED: \"session.CLOSED\",\n FULL: \"session.FULL\",\n LIMIT_REACHED: \"session.LIMIT_REACHED\",\n INVITE_ONLY: \"session.INVITE_ONLY\",\n APPROVAL_PENDING: \"session.APPROVAL_PENDING\",\n INVALID_TRANSITION: \"session.INVALID_TRANSITION\",\n LATE_JOIN_DISABLED: \"session.LATE_JOIN_DISABLED\",\n BUSY: \"session.BUSY\",\n },\n timer: {\n OUT_OF_RANGE: \"timer.OUT_OF_RANGE\",\n LIMIT_REACHED: \"timer.LIMIT_REACHED\",\n },\n transfer: {\n PENDING: \"transfer.PENDING\",\n SELF: \"transfer.SELF\",\n TARGET_INVALID: \"transfer.TARGET_INVALID\",\n NOT_RECIPIENT: \"transfer.NOT_RECIPIENT\",\n CLOSED: \"transfer.CLOSED\",\n PAUSED: \"transfer.PAUSED\",\n CUT_OFF_NOT_ALLOWED: \"transfer.CUT_OFF_NOT_ALLOWED\",\n },\n} as const;\n\ntype Values<T> = T[keyof T];\n/** A registered reason, \"domain.NAME\". */\nexport type Reason = { [D in keyof typeof Reasons]: Values<(typeof Reasons)[D]> }[keyof typeof Reasons];\n\n/**\n * The reasons an app's service may return, an explicit\n * list: the platform rewrites any other to FAILED_PRECONDITION /\n * app.RULE_VIOLATION.\n */\nexport const APP_REASONS = [\n \"app.RULE_VIOLATION\",\n \"app.ALREADY_DONE\",\n \"app.ITEM_UNAVAILABLE\",\n \"app.DEADLINE_PASSED\",\n \"request.MISSING_FIELD\",\n \"request.BAD_TYPE\",\n \"request.OUT_OF_RANGE\",\n \"request.TOO_LARGE\",\n \"request.UNKNOWN_TOOL\",\n \"request.IDEMPOTENCY_MISMATCH\",\n \"request.BAD_VALUE\",\n \"session.FULL\",\n \"session.CLOSED\",\n \"session.NOT_STARTED\",\n \"participant.NOT_AWAITED\",\n \"participant.ALREADY_JOINED\",\n \"quota.PER_OWNER\",\n \"quota.DAILY\",\n] as const;\n\n/** A reason an app's service may return. */\nexport type AppReason = (typeof APP_REASONS)[number];\n","// The platform's error model: 14 gRPC statuses, registered\n// \"domain.REASON\" reasons and a next action for the caller. Browser safe.\n\nimport type { AppReason, Reason } from \"./reasons.js\";\n\nexport { APP_REASONS, Reasons } from \"./reasons.js\";\nexport type { AppReason, Reason } from \"./reasons.js\";\n\n/** The 14 statuses with their HTTP status, retryability and default action. */\nexport const STATUSES = {\n OK: { http: 200, retryable: false, action: \"\" },\n INVALID_ARGUMENT: { http: 400, retryable: false, action: \"fix_request\" },\n UNAUTHENTICATED: { http: 401, retryable: false, action: \"ask_owner\" },\n PERMISSION_DENIED: { http: 403, retryable: false, action: \"give_up\" },\n NOT_FOUND: { http: 404, retryable: false, action: \"give_up\" },\n ALREADY_EXISTS: { http: 409, retryable: false, action: \"treat_as_done\" },\n ABORTED: { http: 409, retryable: true, action: \"retry\" },\n FAILED_PRECONDITION: { http: 412, retryable: false, action: \"give_up\" },\n RESOURCE_EXHAUSTED: { http: 429, retryable: false, action: \"retry_later\" },\n DEADLINE_EXCEEDED: { http: 504, retryable: true, action: \"retry_later\" },\n UNAVAILABLE: { http: 503, retryable: true, action: \"wait\" },\n CANCELLED: { http: 499, retryable: false, action: \"give_up\" },\n UNIMPLEMENTED: { http: 501, retryable: false, action: \"give_up\" },\n INTERNAL: { http: 500, retryable: true, action: \"retry_later\" },\n} as const;\n\nexport type Status = keyof typeof STATUSES;\n\n/** What the caller should do next. Unknown values: fall back to the status's default. */\nexport type Action =\n | \"retry\"\n | \"retry_later\"\n | \"fix_request\"\n | \"join_first\"\n | \"authorize\"\n | \"ask_owner\"\n | \"wait\"\n | \"treat_as_done\"\n | \"give_up\";\n\n/**\n * Statuses an app's service may answer a tool call or hook with: the 4xx\n * set. The platform reads a 5xx, a timeout or a 401 from a service as a\n * temporary failure (a retryable app.TIMEOUT; hooks are retried with the\n * same delivery id), never as the app's answer. Refuse with 403 or 422, not\n * 401: 401 is the signature's.\n */\nexport type AppErrorStatus =\n | \"INVALID_ARGUMENT\"\n | \"PERMISSION_DENIED\"\n | \"NOT_FOUND\"\n | \"ALREADY_EXISTS\"\n | \"ABORTED\"\n | \"FAILED_PRECONDITION\"\n | \"RESOURCE_EXHAUSTED\"\n | \"CANCELLED\";\n\n/** Detail fields the platform defines. */\nexport interface ErrorDetail {\n field?: string;\n need?: unknown;\n limit?: unknown;\n current?: unknown;\n resource?: unknown;\n items?: unknown[];\n /** A sub-reason, e.g. use_app_id on app.SLUG_TAKEN. */\n cause?: string;\n /**\n * Only a person can do this (auth.HUMAN_ONLY, app.NOT_MEMBER): who, their\n * display name and the Karpo Land page where they confirm. action is\n * ask_owner: give the link to your owner.\n */\n needs_human?: { who?: string; name?: string; url?: string };\n [k: string]: unknown;\n}\n\n/** The platform's error body. */\nexport interface ErrorBody {\n status?: Status | string;\n reason?: Reason | string;\n message?: string;\n action?: Action | string;\n retryable?: boolean;\n retry_after_ms?: number;\n detail?: ErrorDetail;\n app_message?: string;\n /** A developer route's own token error ({error, code, hint}): the sentence. */\n error?: string;\n /** A developer route's own token error code, e.g. token_expired. */\n code?: string;\n /** What to do about code. */\n hint?: string;\n [k: string]: unknown;\n}\n\n/**\n * An error the app returns from a tool or hook: a status from the 4xx set\n * and a reason the platform lets apps use. Unregistered reasons are\n * rewritten by the platform to FAILED_PRECONDITION / app.RULE_VIOLATION.\n * The message reaches the caller as app_message (at most 100 characters).\n */\nexport class AppError extends Error {\n override readonly name = \"AppError\";\n readonly status: AppErrorStatus;\n readonly reason: AppReason;\n\n constructor(status: AppErrorStatus, reason: AppReason, message = \"\") {\n super(message);\n this.status = status;\n this.reason = reason;\n }\n\n /** The HTTP status the service answers with. */\n get httpStatus(): number {\n return STATUSES[this.status]?.http ?? 412;\n }\n\n /** The body the service answers with. */\n toJSON(): { status: string; reason: string; message: string } {\n return { status: this.status, reason: this.reason, message: this.message };\n }\n\n /** FAILED_PRECONDITION / app.RULE_VIOLATION: the request breaks the app's rules. */\n static ruleViolation(message: string): AppError {\n return new AppError(\"FAILED_PRECONDITION\", \"app.RULE_VIOLATION\", message);\n }\n /** ALREADY_EXISTS / app.ALREADY_DONE: the caller already did this. */\n static alreadyDone(message: string): AppError {\n return new AppError(\"ALREADY_EXISTS\", \"app.ALREADY_DONE\", message);\n }\n /** FAILED_PRECONDITION / app.ITEM_UNAVAILABLE: sold out, gone, not offered. */\n static itemUnavailable(message: string): AppError {\n return new AppError(\"FAILED_PRECONDITION\", \"app.ITEM_UNAVAILABLE\", message);\n }\n /** FAILED_PRECONDITION / app.DEADLINE_PASSED: too late. */\n static deadlinePassed(message: string): AppError {\n return new AppError(\"FAILED_PRECONDITION\", \"app.DEADLINE_PASSED\", message);\n }\n /** INVALID_ARGUMENT with a request.* reason. */\n static invalid(reason: Extract<AppReason, `request.${string}`>, message: string): AppError {\n return new AppError(\"INVALID_ARGUMENT\", reason, message);\n }\n}\n\n/** An error answer from the platform API, as the clients throw it. */\nexport class PlatformError extends Error {\n override readonly name = \"PlatformError\";\n /** HTTP status of the answer (0 when the request never got one). */\n readonly httpStatus: number;\n /** gRPC-style status, e.g. \"FAILED_PRECONDITION\". */\n readonly status: Status | string;\n /** Registered reason, e.g. \"session.LIMIT_REACHED\"; may be empty. */\n readonly reason: Reason | string;\n readonly action: Action | string;\n readonly retryable: boolean;\n /** How long to wait before retrying, from retry_after_ms or Retry-After. */\n readonly retryAfterMs?: number;\n readonly detail?: ErrorDetail;\n readonly appMessage?: string;\n /**\n * The developer token's own error code on developer routes (401/403\n * {error, code, hint}, e.g. token_expired); \"\" otherwise. Such an answer\n * has no status: action is \"\" and you handle it by code.\n */\n readonly code: string;\n /** The hint that comes with code; \"\" otherwise. */\n readonly hint: string;\n /** The raw error body. */\n readonly body: ErrorBody;\n\n constructor(httpStatus: number, body: ErrorBody = {}, retryAfterHeader?: string | null) {\n // message is the platform's sentence, as in the Go and Python SDKs;\n // status and reason are fields of their own.\n super(body.message || body.error || \"\");\n this.httpStatus = httpStatus;\n this.body = body;\n this.status = body.status || statusOfHttp(httpStatus);\n this.reason = body.reason || \"\";\n this.code = typeof body.code === \"string\" ? body.code : \"\";\n this.hint = typeof body.hint === \"string\" ? body.hint : \"\";\n // {error, code, hint} names no status: no default action.\n const tokenError = !body.status && !!this.code;\n this.action = body.action || (tokenError ? \"\" : (STATUSES as Record<string, { action: string }>)[this.status]?.action || \"\");\n this.retryable = body.retryable ?? (STATUSES as Record<string, { retryable: boolean }>)[this.status]?.retryable ?? false;\n let after = typeof body.retry_after_ms === \"number\" && body.retry_after_ms > 0 ? body.retry_after_ms : undefined;\n if (after === undefined && retryAfterHeader) {\n const s = Number(retryAfterHeader);\n if (Number.isFinite(s)) after = s * 1000;\n else {\n const t = Date.parse(retryAfterHeader);\n if (!Number.isNaN(t)) after = Math.max(0, t - Date.now());\n }\n }\n this.retryAfterMs = after;\n this.detail = body.detail;\n this.appMessage = body.app_message;\n }\n}\n\n/** Whether e is a PlatformError or AppError with the given reason, e.g. isReason(e, Reasons.session.LIMIT_REACHED). */\nexport function isReason(e: unknown, reason: Reason | string): boolean {\n return (e instanceof PlatformError || e instanceof AppError) && e.reason === reason;\n}\n\n/** The status an HTTP status stands for when the body names none. */\nexport function statusOfHttp(http: number): Status {\n for (const [k, v] of Object.entries(STATUSES)) if (v.http === http) return k as Status;\n if (http >= 500) return \"INTERNAL\";\n if (http >= 400) return \"FAILED_PRECONDITION\";\n return \"OK\";\n}\n\n/** Type guard for errors from the platform. */\nexport function isPlatformError(e: unknown): e is PlatformError {\n return e instanceof PlatformError;\n}\n","// The JSON transport shared by the platform and page clients: error bodies\n// become PlatformError, and retryable answers are retried with backoff.\n// Browser safe.\n\nimport { PlatformError, type ErrorBody } from \"./errors.js\";\n\nexport type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface RetryOptions {\n /** Retries after the first attempt; default 3. 0 turns retrying off. */\n retries?: number;\n /** First backoff; doubles each retry, with jitter. Default 200 ms. */\n baseDelayMs?: number;\n /** Longest backoff between attempts; default 5 s. */\n maxDelayMs?: number;\n /**\n * Longest wait the client accepts from Retry-After / retry_after_ms; a\n * longer one is thrown at once (a tool call has 10 seconds). Default 10 s.\n */\n maxWaitMs?: number;\n}\n\nexport interface RequestOptions {\n body?: unknown;\n query?: Record<string, unknown>;\n headers?: Record<string, string>;\n /** Override the client's retry settings for this request. */\n retry?: RetryOptions | false;\n /**\n * The request is safe to repeat (it carries an Idempotency-Key), so it is\n * also retried when no answer came. GET, PUT and DELETE always are.\n */\n idempotent?: boolean;\n /**\n * A reason that means \"already done\" when a retry (not the first attempt)\n * gets it: the request then resolves with ALREADY_DONE instead of throwing\n * (calls.complete / calls.fail and app.ALREADY_DONE).\n */\n doneOnRetry?: string;\n signal?: AbortSignal;\n}\n\n/** What a request with doneOnRetry resolves with when a retry found it done. */\nexport const ALREADY_DONE: unique symbol = Symbol.for(\"karpoland.already_done\");\n\nconst RETRY_ACTIONS = new Set([\"retry\", \"retry_later\"]);\n\n/** Whether an error answer may be retried as is: retry / retry_later actions, 429 and 503. */\nexport function shouldRetry(e: PlatformError): boolean {\n if (e.action === \"give_up\" || e.action === \"fix_request\") return false;\n return RETRY_ACTIONS.has(e.action) || e.httpStatus === 429 || e.httpStatus === 503;\n}\n\nconst sleep = (ms: number, signal?: AbortSignal) =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const t = setTimeout(resolve, ms);\n signal?.addEventListener(\"abort\", () => (clearTimeout(t), reject(signal.reason)), { once: true });\n });\n\nexport function buildURL(base: string, path: string, query?: Record<string, unknown>): string {\n const url = new URL(base.replace(/\\/+$/, \"\") + path);\n for (const [k, v] of Object.entries(query ?? {})) {\n if (v === undefined || v === null || v === \"\") continue;\n url.searchParams.set(k, String(v));\n }\n return url.toString();\n}\n\nexport interface Transport {\n request<T>(method: string, path: string, opts?: RequestOptions): Promise<T>;\n}\n\n/**\n * createTransport sends JSON requests under base with the headers from\n * headers() (read on every attempt, so a refreshed token is used).\n */\nexport function createTransport(cfg: {\n base: string;\n headers: () => Record<string, string>;\n fetch?: FetchLike;\n retry?: RetryOptions | false;\n /** Sent as User-Agent (server-side clients: karpoland-sdk-ts/<version>). */\n userAgent?: string;\n /** Called on a 401 before giving up; resolve true to retry once with fresh headers. */\n onUnauthorized?: () => Promise<boolean>;\n}): Transport {\n const doFetch: FetchLike = cfg.fetch ?? ((i, init) => globalThis.fetch(i, init));\n return {\n async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {\n const r = opts.retry === false || cfg.retry === false ? { retries: 0 } : { ...(cfg.retry || {}), ...(opts.retry || {}) };\n const retries = r.retries ?? 3;\n const base = r.baseDelayMs ?? 200;\n const maxDelay = r.maxDelayMs ?? 5000;\n const maxWait = r.maxWaitMs ?? 10_000;\n const url = buildURL(cfg.base, path, opts.query);\n const raw = opts.body instanceof Uint8Array || opts.body instanceof ArrayBuffer || (typeof Blob !== \"undefined\" && opts.body instanceof Blob);\n const idempotentMethod = opts.idempotent || method === \"GET\" || method === \"PUT\" || method === \"DELETE\";\n let reauthed = false;\n for (let attempt = 0; ; attempt++) {\n const headers: Record<string, string> = { Accept: \"application/json\", ...(cfg.userAgent ? { \"User-Agent\": cfg.userAgent } : {}), ...cfg.headers(), ...opts.headers };\n if (opts.body !== undefined && !raw && !headers[\"Content-Type\"]) headers[\"Content-Type\"] = \"application/json\";\n let res: Response;\n try {\n res = await doFetch(url, {\n method,\n headers,\n body: opts.body === undefined ? undefined : raw ? (opts.body as BodyInit) : JSON.stringify(opts.body),\n signal: opts.signal,\n });\n } catch (err) {\n // No answer: retry only what is safe to repeat.\n if (opts.signal?.aborted || !idempotentMethod || attempt >= retries) throw err;\n await sleep(backoff(attempt, base, maxDelay), opts.signal);\n continue;\n }\n const text = await res.text();\n let data: unknown = undefined;\n if (text) {\n try {\n data = JSON.parse(text);\n } catch {\n data = res.ok ? text : { message: text };\n }\n }\n if (res.ok) return (data ?? {}) as T;\n const err = new PlatformError(res.status, (data ?? {}) as ErrorBody, res.headers.get(\"retry-after\"));\n if (attempt > 0 && opts.doneOnRetry && err.reason === opts.doneOnRetry) return ALREADY_DONE as T;\n if (res.status === 401 && cfg.onUnauthorized && !reauthed) {\n reauthed = true;\n if (await cfg.onUnauthorized()) {\n attempt--;\n continue;\n }\n }\n if (attempt >= retries || !shouldRetry(err)) throw err;\n const wait = err.retryAfterMs ?? backoff(attempt, base, maxDelay);\n if (wait > maxWait) throw err;\n await sleep(wait, opts.signal);\n }\n },\n };\n}\n\nfunction backoff(attempt: number, base: number, max: number): number {\n const d = Math.min(max, base * 2 ** attempt);\n return Math.round(d / 2 + Math.random() * (d / 2));\n}\n\n/** RFC 3339 without fractional seconds, as the platform parses it. */\nexport function rfc3339(t: string | Date | undefined): string | undefined {\n if (t === undefined) return undefined;\n if (typeof t === \"string\") return t;\n // Keep milliseconds: Go's RFC 3339 parsing takes them, and dropping them\n // moves short timers under the platform's minimum.\n return t.toISOString();\n}\n\n/** The longest idempotency key the platform takes. */\nexport const MAX_IDEMPOTENCY_KEY = 128;\n\n/**\n * The Idempotency-Key header for one write: the caller's key, else a new\n * random one. Made once per call, so the transport's retries reuse it.\n */\nexport function idempotencyHeader(key?: string): Record<string, string> {\n const k = key || randomKey(\"kl-\");\n if (k.length > MAX_IDEMPOTENCY_KEY) throw new RangeError(`idempotency key is at most ${MAX_IDEMPOTENCY_KEY} characters`);\n return { \"Idempotency-Key\": k };\n}\n\n/** A random key for idempotent requests. */\nexport function randomKey(prefix = \"\"): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return prefix + c.randomUUID();\n return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 12);\n}\n\nexport const enc = (s: string | number) => encodeURIComponent(String(s));\n"],"mappings":";AAIO,IAAM,UAAU;AAAA,EACrB,KAAK;AAAA,IACH,WAAW;AAAA,IACX,SAAS;AAAA,IACT,gBAAgB;AAAA,IAChB,cAAc;AAAA,IACd,kBAAkB;AAAA,IAClB,iBAAiB;AAAA,IACjB,SAAS;AAAA,IACT,eAAe;AAAA,IACf,YAAY;AAAA,IACZ,eAAe;AAAA,IACf,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,kBAAkB;AAAA,EACpB;AAAA,EACA,MAAM;AAAA,IACJ,eAAe;AAAA,IACf,YAAY;AAAA,IACZ,iBAAiB;AAAA,IACjB,eAAe;AAAA,IACf,SAAS;AAAA,IACT,kBAAkB;AAAA,IAClB,cAAc;AAAA,IACd,WAAW;AAAA,IACX,iBAAiB;AAAA,IACjB,YAAY;AAAA,IACZ,yBAAyB;AAAA,EAC3B;AAAA,EACA,OAAO;AAAA,IACL,YAAY;AAAA,IACZ,QAAQ;AAAA,IACR,cAAc;AAAA,IACd,iBAAiB;AAA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