manifest 6.0.0 → 7.0.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/dist/index.js CHANGED
@@ -1,443 +1,8 @@
1
- // src/runtime.ts
2
- import { randomUUID } from "crypto";
3
-
4
- // src/wire.ts
5
- var secretNames = /* @__PURE__ */ new Set([
6
- "api_key",
7
- "apikey",
8
- "api_token",
9
- "key",
10
- "token",
11
- "access_token",
12
- "refresh_token",
13
- "auth",
14
- "authorization",
15
- "signature",
16
- "sig",
17
- "secret",
18
- "client_secret",
19
- "password",
20
- "session",
21
- "session_id",
22
- "bearer",
23
- "jwt",
24
- "id_token",
25
- "auth_token",
26
- "pwd",
27
- "passwd",
28
- "private_key"
29
- ]);
30
- var roots = ["auth", "key", "token", "secret", "session", "password", "passwd", "cookie", "signature", "credential", "bearer", "jwt"];
31
- var normalize = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replaceAll("-", "_").toLowerCase().replace(/^x_/, "");
32
- var isSecret = (name) => secretNames.has(normalize(name));
33
- var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
34
- function safeUrl(raw) {
35
- const url = new URL(raw);
36
- url.username = "";
37
- url.password = "";
38
- url.hash = "";
39
- const pairs = [...url.searchParams].map(([key, value]) => [key, isSecret(key) ? "REDACTED" : value]);
40
- url.search = new URLSearchParams(pairs).toString();
41
- return url.toString();
42
- }
43
- function safeHeaders(headers) {
44
- return Object.fromEntries([...headers].map(([key, value]) => [
45
- key,
46
- isSecret(key) || roots.some((root) => normalize(key).includes(root)) ? "REDACTED" : value.slice(0, 1024)
47
- ]));
48
- }
49
- function travelingBody(body) {
50
- return isObject(body) ? Object.fromEntries(Object.entries(body).filter(([key]) => !isSecret(key))) : body;
51
- }
52
- function mergeBody(original, healed) {
53
- if (!isObject(original) || !isObject(healed)) return healed;
54
- return { ...Object.fromEntries(Object.entries(original).filter(([key]) => isSecret(key) && !Object.hasOwn(healed, key))), ...healed };
55
- }
56
- function boundedJson(value) {
57
- const stack = [[value, 0]];
58
- let count = 0;
59
- while (stack.length) {
60
- const [item, depth] = stack.pop();
61
- if (++count > 1e5 || depth > 64) return false;
62
- if (item !== null && typeof item === "object") {
63
- for (const child of Object.values(item)) stack.push([child, depth + 1]);
64
- }
65
- }
66
- return true;
67
- }
68
- function parseJson(bytes) {
69
- try {
70
- const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
71
- return boundedJson(value) ? value : null;
72
- } catch {
73
- return null;
74
- }
75
- }
76
- function errorBody(bytes) {
77
- const parsed = parseJson(bytes);
78
- const text = Buffer.from(bytes).toString("utf8");
79
- return parsed ?? new TextDecoder().decode(Buffer.from(text).subarray(0, 65536), { stream: true });
80
- }
81
- var TRANSPORT_ERROR = "Upstream retry failed before an HTTP response";
82
-
83
- // src/capture.ts
84
- var REQUEST_LIMIT = 262144;
85
- var RESPONSE_LIMIT = 65536;
86
- var CAPTURE_MS = 1e3;
87
- async function prefix(reader, limit, timeoutMs) {
88
- const chunks = [];
89
- let size = 0;
90
- let pending;
91
- let timer;
92
- const deadline = new Promise((resolve) => {
93
- timer = setTimeout(() => resolve(null), timeoutMs);
94
- });
95
- let complete = false;
96
- try {
97
- while (size <= limit) {
98
- pending = reader.read();
99
- const read = await Promise.race([pending, deadline]);
100
- if (read === null) break;
101
- pending = void 0;
102
- if (read.done) {
103
- complete = true;
104
- break;
105
- }
106
- chunks.push(read.value);
107
- size += read.value.byteLength;
108
- }
109
- } catch {
110
- } finally {
111
- clearTimeout(timer);
112
- }
113
- return { chunks, complete, pending, bytes: Buffer.concat(chunks, size).subarray(0, limit) };
114
- }
115
- async function captureRequest(request) {
116
- if (!request.body) return { body: null, complete: true };
117
- const clone = request.clone();
118
- const reader = clone.body.getReader();
119
- try {
120
- const result = await prefix(reader, REQUEST_LIMIT, CAPTURE_MS);
121
- return { body: result.complete ? parseJson(result.bytes) : null, complete: result.complete };
122
- } finally {
123
- void reader.cancel().catch(() => {
124
- });
125
- }
126
- }
127
- function metadata(response, original) {
128
- const clone = response.clone.bind(response);
129
- Object.defineProperties(response, {
130
- url: { value: original.url },
131
- redirected: { value: original.redirected },
132
- type: { value: original.type },
133
- clone: { value: () => metadata(clone(), original) }
134
- });
135
- return response;
136
- }
137
- async function captureResponse(original, limit = RESPONSE_LIMIT, timeoutMs = CAPTURE_MS) {
138
- if (!original.body) return { response: original, body: null, truncated: false, complete: true };
139
- const reader = original.body.getReader();
140
- const captured = await prefix(reader, limit, timeoutMs);
141
- let index = 0;
142
- let pending = captured.pending;
143
- const stream = new ReadableStream({
144
- async pull(controller) {
145
- try {
146
- if (index < captured.chunks.length) {
147
- controller.enqueue(captured.chunks[index++]);
148
- return;
149
- }
150
- const read = await (pending ?? reader.read());
151
- pending = void 0;
152
- if (read.done) {
153
- reader.releaseLock();
154
- controller.close();
155
- } else controller.enqueue(read.value);
156
- } catch (error) {
157
- controller.error(error);
158
- }
159
- },
160
- async cancel(reason) {
161
- await reader.cancel(reason);
162
- }
163
- }, { highWaterMark: 0 });
164
- const response = metadata(new Response(stream, {
165
- status: original.status,
166
- statusText: original.statusText,
167
- headers: original.headers
168
- }), original);
169
- return { response, body: errorBody(captured.bytes), truncated: !captured.complete || Buffer.byteLength(Buffer.from(captured.bytes).toString("utf8")) > limit, complete: captured.complete };
170
- }
171
-
172
- // src/api.ts
173
- var VERSION = "6.0.0";
174
- var warn = (message) => process.emitWarning(message, { code: "MNFST" });
175
- var HealApi = class {
176
- constructor(rawFetch, key, url, timeoutMs = 6e4, reportTimeoutMs = 5e3) {
177
- this.rawFetch = rawFetch;
178
- this.key = key;
179
- this.url = url;
180
- this.timeoutMs = timeoutMs;
181
- this.reportTimeoutMs = reportTimeoutMs;
182
- }
183
- rawFetch;
184
- key;
185
- url;
186
- timeoutMs;
187
- reportTimeoutMs;
188
- disabledUntil = 0;
189
- inFlight = 0;
190
- pending = /* @__PURE__ */ new Set();
191
- enabled() {
192
- return performance.now() >= this.disabledUntil;
193
- }
194
- headers() {
195
- return {
196
- authorization: `Bearer ${this.key}`,
197
- "content-type": "application/json",
198
- "user-agent": `mnfst-node/${VERSION}`,
199
- "x-mnfst-source": "node-sdk"
200
- };
201
- }
202
- async heal(capture, signal) {
203
- if (!this.enabled() || this.inFlight >= 8) return null;
204
- this.inFlight++;
205
- const controller = new AbortController();
206
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
207
- try {
208
- const response = await this.rawFetch(new URL("v1/heal", this.url), {
209
- method: "POST",
210
- headers: this.headers(),
211
- body: JSON.stringify(capture),
212
- signal: AbortSignal.any([signal, controller.signal]),
213
- redirect: "error"
214
- });
215
- if (response.status !== 200 && response.status !== 403) {
216
- void response.body?.cancel().catch(() => {
217
- });
218
- return null;
219
- }
220
- const captured = await captureResponse(response, 1048576, this.timeoutMs);
221
- void captured.response.body?.cancel().catch(() => {
222
- });
223
- if (!captured.complete || !isObject(captured.body) || !boundedJson(captured.body)) return null;
224
- if (response.status === 403 && captured.body.error === "project_disabled") {
225
- this.disabledUntil = performance.now() + 3e5;
226
- }
227
- if (response.status !== 200 || typeof captured.body.status !== "string") return null;
228
- return {
229
- status: captured.body.status,
230
- ...typeof captured.body.healAttemptId === "string" ? { healAttemptId: captured.body.healAttemptId } : {},
231
- ...Array.isArray(captured.body.operations) ? { operations: captured.body.operations } : {},
232
- ...isObject(captured.body.healedRequest) ? { healedRequest: captured.body.healedRequest } : {}
233
- };
234
- } catch {
235
- return null;
236
- } finally {
237
- clearTimeout(timer);
238
- this.inFlight--;
239
- }
240
- }
241
- report(id, outcome) {
242
- if (!id) return;
243
- if (this.pending.size >= 64) {
244
- warn("Outcome report capacity reached; report dropped");
245
- return;
246
- }
247
- const promise = this.send(id, outcome);
248
- this.pending.add(promise);
249
- void promise.then(() => this.pending.delete(promise));
250
- }
251
- async send(id, outcome) {
252
- const controller = new AbortController();
253
- const timer = setTimeout(() => controller.abort(), this.reportTimeoutMs);
254
- try {
255
- const response = await this.rawFetch(new URL(`v1/heal-attempts/${encodeURIComponent(id)}`, this.url), {
256
- method: "PATCH",
257
- headers: this.headers(),
258
- body: JSON.stringify(outcome),
259
- signal: controller.signal,
260
- redirect: "error"
261
- });
262
- void response.body?.cancel().catch(() => {
263
- });
264
- if (!response.ok) warn("Outcome report rejected; attempt remains unconfirmed");
265
- } catch {
266
- warn("Outcome report failed; attempt remains unconfirmed");
267
- } finally {
268
- clearTimeout(timer);
269
- }
270
- }
271
- async flush(timeoutMs = 5e3) {
272
- let timer;
273
- try {
274
- await Promise.race([
275
- Promise.allSettled([...this.pending]),
276
- new Promise((resolve) => {
277
- timer = setTimeout(resolve, Math.max(0, timeoutMs));
278
- })
279
- ]);
280
- } finally {
281
- clearTimeout(timer);
282
- }
283
- }
284
- };
285
-
286
- // src/runtime.ts
287
- var eligible = /* @__PURE__ */ new Set([400, 404, 422]);
288
- var Runtime = class {
289
- constructor(options, original, api) {
290
- this.options = options;
291
- this.original = original;
292
- this.api = api ?? new HealApi(original, options.key, options.url);
293
- }
294
- options;
295
- original;
296
- api;
297
- fetch = async (input, init) => {
298
- const request = new Request(input, init);
299
- const extras = { ...init };
300
- delete extras.body;
301
- delete extras.headers;
302
- const bodyPromise = captureRequest(request).catch(() => ({ body: null, complete: false }));
303
- const started = performance.now();
304
- const response = await this.original(request, extras);
305
- const responseTimeMs = performance.now() - started;
306
- if (!eligible.has(response.status) || response.redirected || !this.api.enabled()) return response;
307
- return this.repair(request, extras, response, await bodyPromise, responseTimeMs);
308
- };
309
- async repair(request, extras, original, body, responseTimeMs) {
310
- let response = original;
311
- let result = null;
312
- const started = performance.now();
313
- let replayStatusCode = null;
314
- let replayAttempted = false;
315
- try {
316
- const captured = await captureResponse(response);
317
- response = captured.response;
318
- const payload = {
319
- traceId: randomUUID(),
320
- request: { method: request.method, url: safeUrl(request.url), headers: safeHeaders(request.headers), body: travelingBody(body.body) },
321
- response: { statusCode: response.status, body: captured.body, truncated: captured.truncated },
322
- responseTimeMs: Math.round(responseTimeMs)
323
- };
324
- request.signal.throwIfAborted();
325
- result = await this.api.heal(payload, request.signal);
326
- request.signal.throwIfAborted();
327
- const retry = body.complete && captured.complete ? buildRetry(request, body.body, result) : null;
328
- if (!retry) {
329
- this.api.report(result?.healAttemptId, { failure: { kind: "not_attempted", message: "replay_not_attempted" } });
330
- return response;
331
- }
332
- replayAttempted = true;
333
- let retried;
334
- try {
335
- retried = await this.original(retry, extras);
336
- } catch {
337
- this.api.report(result?.healAttemptId, { failure: { kind: "transport_error", message: TRANSPORT_ERROR } });
338
- request.signal.throwIfAborted();
339
- return response;
340
- }
341
- replayStatusCode = retried.status;
342
- if (retried.status >= 400) {
343
- const capturedRetry = await captureResponse(retried);
344
- retried = capturedRetry.response;
345
- this.api.report(result?.healAttemptId, { response: { statusCode: retried.status, body: capturedRetry.body, truncated: capturedRetry.truncated } });
346
- } else {
347
- this.api.report(result?.healAttemptId, { response: { statusCode: retried.status } });
348
- }
349
- void response.body?.cancel().catch(() => {
350
- });
351
- return retried;
352
- } catch {
353
- request.signal.throwIfAborted();
354
- this.api.report(result?.healAttemptId, { failure: { kind: "not_attempted", message: "replay_not_attempted" } });
355
- return response;
356
- } finally {
357
- if (this.options.onHeal) {
358
- try {
359
- void Promise.resolve(this.options.onHeal({
360
- url: safeUrl(request.url),
361
- statusCode: original.status,
362
- healStatus: replayAttempted && replayStatusCode === null ? "replay_failed" : result?.status ?? "heal_unreachable",
363
- replayStatusCode,
364
- healMs: Math.round(performance.now() - started),
365
- operations: result?.operations
366
- })).catch(() => warn("onHeal callback failed"));
367
- } catch {
368
- warn("onHeal callback failed");
369
- }
370
- }
371
- }
372
- }
373
- };
374
- function buildRetry(request, originalBody, result) {
375
- if (!result || !["patched", "unverified"].includes(result.status) || !isObject(result.healedRequest)) return null;
376
- const healed = result.healedRequest;
377
- if (!["url", "headers", "body"].some((key) => Object.hasOwn(healed, key))) return null;
378
- try {
379
- const url = new URL(healed.url ?? request.url);
380
- if (url.origin !== new URL(request.url).origin || url.username || url.password) return null;
381
- const headers = new Headers(request.headers);
382
- headers.delete("content-length");
383
- if (healed.headers !== void 0 && !isObject(healed.headers)) return null;
384
- for (const [name, value] of Object.entries(healed.headers ?? {})) {
385
- if (value === null) headers.delete(name);
386
- else if (typeof value === "string") headers.set(name, value);
387
- else return null;
388
- }
389
- const body = Object.hasOwn(healed, "body") ? mergeBody(originalBody, healed.body) : originalBody;
390
- if (body === null && !["GET", "HEAD"].includes(request.method)) return null;
391
- return new Request(url, {
392
- method: request.method,
393
- headers,
394
- body: ["GET", "HEAD"].includes(request.method) ? void 0 : JSON.stringify(body),
395
- signal: request.signal,
396
- redirect: request.redirect,
397
- credentials: request.credentials,
398
- cache: request.cache,
399
- integrity: request.integrity,
400
- keepalive: request.keepalive,
401
- mode: request.mode,
402
- referrer: request.referrer,
403
- referrerPolicy: request.referrerPolicy
404
- });
405
- } catch {
406
- return null;
407
- }
408
- }
409
-
410
- // src/index.ts
411
- var STATE = /* @__PURE__ */ Symbol.for("mnfst.node.runtime.v1");
412
- var globals = globalThis;
413
- function manifest(options = {}) {
414
- const key = options.key || process.env.MNFST_KEY;
415
- if (!key) {
416
- warn("MNFST_KEY is not set; Manifest is disabled");
417
- return;
418
- }
419
- const url = new URL(options.url || process.env.MNFST_URL || "https://api.manifest.build");
420
- if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
421
- throw new TypeError("Manifest URL must be an HTTP(S) base URL without credentials, query or fragment");
422
- }
423
- if (!url.pathname.endsWith("/")) url.pathname += "/";
424
- const resolved = { ...options, key, url: url.toString() };
425
- const existing = globals[STATE];
426
- if (existing) {
427
- if (existing.options.key !== key || existing.options.url !== resolved.url || existing.options.onHeal !== options.onHeal) {
428
- warn("Manifest is already configured; changing configuration requires a process restart");
429
- }
430
- return;
431
- }
432
- const runtime = new Runtime(resolved, globalThis.fetch.bind(globalThis));
433
- globalThis.fetch = runtime.fetch;
434
- globals[STATE] = runtime;
435
- }
436
- async function flush(options = {}) {
437
- await globals[STATE]?.api.flush(options.timeoutMs ?? 5e3);
438
- }
1
+ import {
2
+ VERSION,
3
+ manifest
4
+ } from "./chunk-DP2C4E42.js";
439
5
  export {
440
6
  VERSION,
441
- flush,
442
7
  manifest
443
8
  };