engine7 7.1.143 → 7.1.145

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.
@@ -0,0 +1,636 @@
1
+ // src/travel/oss-bundle-stream.ts
2
+ import { readFileSync as readFileSync3, existsSync as existsSync3 } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { isAbsolute } from "node:path";
5
+
6
+ // src/travel/chunk-store.ts
7
+ import { createHash, randomUUID } from "node:crypto";
8
+ import {
9
+ closeSync,
10
+ existsSync,
11
+ fstatSync,
12
+ fsyncSync,
13
+ lstatSync,
14
+ mkdirSync,
15
+ openSync,
16
+ readFileSync,
17
+ readSync,
18
+ renameSync,
19
+ unlinkSync,
20
+ writeFileSync,
21
+ writeSync,
22
+ constants
23
+ } from "node:fs";
24
+ import { gunzipSync, gzip } from "node:zlib";
25
+ import { promisify } from "node:util";
26
+ import { dirname, join } from "node:path";
27
+ var CHUNK_BYTES = 4 * 1024 * 1024;
28
+ var DATABASE_CHUNK_BYTES = 64 * 1024;
29
+ var chunkBytesFor = (path) => /\.(db|sqlite)(-wal|-shm)?$/.test(path) ? DATABASE_CHUNK_BYTES : CHUNK_BYTES;
30
+ var SHA = /^[a-f0-9]{64}$/;
31
+ var sha256 = (body) => createHash("sha256").update(body).digest("hex");
32
+ var compress = promisify(gzip);
33
+ function validateChunkRef(ref) {
34
+ if (!ref || !SHA.test(ref.sha256) || !Number.isSafeInteger(ref.bytes) || ref.bytes < 1 || ref.bytes > CHUNK_BYTES)
35
+ throw new Error("TRAVEL_INVALID_CHUNK");
36
+ }
37
+ function validateFileManifest(file) {
38
+ if (!file || !SHA.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || !Array.isArray(file.chunks))
39
+ throw new Error("TRAVEL_INVALID_FILE");
40
+ let total = 0;
41
+ for (const ref of file.chunks) {
42
+ validateChunkRef(ref);
43
+ total += ref.bytes;
44
+ }
45
+ if (total !== file.bytes) throw new Error("TRAVEL_INVALID_FILE");
46
+ }
47
+ var ChunkStore = class {
48
+ dir;
49
+ verified = /* @__PURE__ */ new Map();
50
+ constructor(dir) {
51
+ this.dir = dir;
52
+ mkdirSync(dir, { recursive: true, mode: 448 });
53
+ }
54
+ chunkPath(sha) {
55
+ return join(this.dir, sha + ".gz");
56
+ }
57
+ fingerprint(path) {
58
+ const s = lstatSync(path, { bigint: true });
59
+ if (!s.isFile()) throw Error("TRAVEL_CHUNK_CORRUPT");
60
+ return [s.dev, s.ino, s.size, s.mtimeNs, s.ctimeNs].join(":");
61
+ }
62
+ /** 幂等:同 sha 已存在直接返回;写盘走 tmp+rename,读者永远看不到半个块。 */
63
+ async put(body) {
64
+ if (!(body instanceof Buffer) || body.length < 1 || body.length > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
65
+ const stable = Buffer.from(body), ref = { sha256: sha256(stable), bytes: stable.length };
66
+ const path = this.chunkPath(ref.sha256);
67
+ if (!await this.has(ref.sha256)) {
68
+ const temp = path + "." + randomUUID() + ".tmp";
69
+ try {
70
+ writeFileSync(temp, await compress(stable), { flag: "wx", mode: 384 });
71
+ renameSync(temp, path);
72
+ this.verified.set(ref.sha256, this.fingerprint(path));
73
+ } finally {
74
+ try {
75
+ if (existsSync(temp)) unlinkSync(temp);
76
+ } catch {
77
+ }
78
+ }
79
+ }
80
+ return ref;
81
+ }
82
+ async has(sha) {
83
+ if (!SHA.test(sha)) throw new Error("TRAVEL_INVALID_CHUNK");
84
+ const known = this.verified.get(sha);
85
+ if (known) try {
86
+ if (this.fingerprint(this.chunkPath(sha)) === known) return true;
87
+ } catch {
88
+ }
89
+ this.verified.delete(sha);
90
+ if (!existsSync(this.chunkPath(sha))) return false;
91
+ try {
92
+ await this.read(sha);
93
+ return true;
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+ async read(sha, bytes = -1) {
99
+ if (!SHA.test(sha) || !Number.isSafeInteger(bytes) || bytes < -1 || bytes > CHUNK_BYTES) throw new Error("TRAVEL_INVALID_CHUNK");
100
+ let plain;
101
+ let before;
102
+ try {
103
+ before = this.fingerprint(this.chunkPath(sha));
104
+ plain = gunzipSync(readFileSync(this.chunkPath(sha)), { maxOutputLength: CHUNK_BYTES });
105
+ } catch {
106
+ throw new Error("TRAVEL_CHUNK_CORRUPT");
107
+ }
108
+ if (sha256(plain) !== sha || bytes >= 0 && plain.length !== bytes) throw new Error("TRAVEL_CHUNK_CORRUPT");
109
+ try {
110
+ if (this.fingerprint(this.chunkPath(sha)) === before) this.verified.set(sha, before);
111
+ else this.verified.delete(sha);
112
+ } catch {
113
+ this.verified.delete(sha);
114
+ }
115
+ return plain;
116
+ }
117
+ /** 读磁盘上的原始 gzip 体(OSS 直传用:线上/磁盘同为 gz,省一次解压重压)。 */
118
+ readGzipRaw(sha) {
119
+ if (!SHA.test(sha)) throw new Error("TRAVEL_INVALID_CHUNK");
120
+ return readFileSync(this.chunkPath(sha));
121
+ }
122
+ /** 捕获 = 边读边入仓。1122 晚(VACUUM 拆除后 raw 直捕实弹):活引擎的库/wal/
123
+ * jsonl 读到一半被写是常态,一律拒绝会把整个准备打死(晓雯 19:31 实弹
124
+ * TRAVEL_SOURCE_CHANGED)。策略=重读两轮仍变=活写入者,接受最后一次自洽读
125
+ * (sha 与实际读到的字节严格对应;预复制只入仓、不落位,正式迁移随后
126
+ * 使用停机后的稳定 DB/WAL 捕获组)。静止路径(引擎已停)守卫天然不触发。 */
127
+ async captureFile(source, onProgress) {
128
+ let lastError = null;
129
+ for (let attempt = 0; attempt < 3; attempt++) {
130
+ try {
131
+ return await this.captureFileOnce(source, attempt === 2, onProgress);
132
+ } catch (error) {
133
+ if (!(error instanceof Error) || error.message !== "TRAVEL_SOURCE_CHANGED") throw error;
134
+ lastError = error;
135
+ }
136
+ }
137
+ throw lastError;
138
+ }
139
+ async captureFileOnce(source, acceptLiveWrite, onProgress) {
140
+ const fd = openSync(source, constants.O_RDONLY);
141
+ try {
142
+ const before = fstatSync(fd, { bigint: true });
143
+ if (!before.isFile()) throw new Error("TRAVEL_NOT_REGULAR_FILE");
144
+ const digest = createHash("sha256");
145
+ const buffer = Buffer.alloc(Math.min(chunkBytesFor(source), Number(before.size) || 1));
146
+ const chunks = [];
147
+ let bytes = 0;
148
+ for (; ; ) {
149
+ const count = readSync(fd, buffer, 0, buffer.length, null);
150
+ if (!count) break;
151
+ const piece = Buffer.from(buffer.subarray(0, count));
152
+ digest.update(piece);
153
+ bytes += count;
154
+ chunks.push(await this.put(piece));
155
+ onProgress?.(bytes);
156
+ }
157
+ const after = fstatSync(fd, { bigint: true });
158
+ const pathInfo = lstatSync(source, { bigint: true });
159
+ const changed = ["dev", "ino", "size", "mtimeNs", "ctimeNs"].some((key) => after[key] !== before[key] || pathInfo[key] !== before[key]) || BigInt(bytes) !== before.size;
160
+ if (changed && !acceptLiveWrite) throw new Error("TRAVEL_SOURCE_CHANGED");
161
+ if (changed) console.warn(`[travel] ${source} \u6355\u83B7\u671F\u95F4\u6301\u7EED\u88AB\u5199\uFF08\u6D3B\u5F15\u64CE\uFF09\u2014\u2014\u63A5\u53D7\u77AC\u65F6\u5FEB\u7167\uFF0C\u9759\u6B62\u540C\u6B65\u5C06\u8986\u76D6`);
162
+ return { sha256: digest.digest("hex"), bytes, chunks };
163
+ } finally {
164
+ closeSync(fd);
165
+ }
166
+ }
167
+ async restoreFile(file, destination, mode = 384) {
168
+ validateFileManifest(file);
169
+ if (existsSync(destination)) throw new Error("TRAVEL_DESTINATION_EXISTS");
170
+ mkdirSync(dirname(destination), { recursive: true, mode: 448 });
171
+ const temp = destination + "." + randomUUID() + ".incoming";
172
+ const digest = createHash("sha256");
173
+ const fd = openSync(temp, "wx", mode);
174
+ try {
175
+ for (const ref of file.chunks) {
176
+ const body = await this.read(ref.sha256, ref.bytes);
177
+ digest.update(body);
178
+ let offset = 0;
179
+ while (offset < body.length) offset += writeSync(fd, body, offset, body.length - offset);
180
+ }
181
+ if (digest.digest("hex") !== file.sha256) throw new Error("TRAVEL_FILE_CORRUPT");
182
+ fsyncSync(fd);
183
+ renameSync(temp, destination);
184
+ } finally {
185
+ closeSync(fd);
186
+ try {
187
+ if (existsSync(temp)) unlinkSync(temp);
188
+ } catch {
189
+ }
190
+ }
191
+ }
192
+ /** 盘上文件是否与 manifest 一致(apply 的跳过判断)。 */
193
+ static fileMatches(destination, manifest) {
194
+ try {
195
+ const info = lstatSync(destination);
196
+ if (!info.isFile() || info.size !== manifest.bytes) return false;
197
+ const digest = createHash("sha256");
198
+ const fd = openSync(destination, constants.O_RDONLY);
199
+ try {
200
+ const buffer = Buffer.alloc(Math.min(CHUNK_BYTES, manifest.bytes || 1));
201
+ for (; ; ) {
202
+ const count = readSync(fd, buffer, 0, buffer.length, null);
203
+ if (!count) break;
204
+ digest.update(buffer.subarray(0, count));
205
+ }
206
+ } finally {
207
+ closeSync(fd);
208
+ }
209
+ return digest.digest("hex") === manifest.sha256;
210
+ } catch {
211
+ return false;
212
+ }
213
+ }
214
+ };
215
+ function openChunkStore(dir) {
216
+ return new ChunkStore(dir);
217
+ }
218
+
219
+ // src/travel/oss-transport.ts
220
+ import { createHmac, createHash as createHash2 } from "node:crypto";
221
+
222
+ // src/travel/oss-broker.ts
223
+ var cache = /* @__PURE__ */ new WeakMap();
224
+ var signingQueues = /* @__PURE__ */ new WeakMap();
225
+ var cacheKey = (o) => JSON.stringify([o.method, o.key, o.contentMD5 ?? "", o.contentType ?? ""]);
226
+ function validateAuthorization(config, value, operations) {
227
+ if (!value || !Number.isSafeInteger(value.expiresAt) || value.expiresAt > Date.now() / 1e3 + 960 || !Array.isArray(value.objects) || value.objects.length !== operations.length) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
228
+ if (!/^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/.test(value.bucket) || !/^oss-[a-z0-9-]+(?:-internal)?\.aliyuncs\.com$/.test(value.endpoint) && !/^http:\/\/127\.0\.0\.1:\d+$/.test(value.endpoint)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
229
+ if (config.bucket && config.bucket !== value.bucket || config.endpoint && config.endpoint !== value.endpoint) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
230
+ let tokenId = config.broker.tokenId;
231
+ for (let i = 0; i < operations.length; i++) {
232
+ const expected = operations[i], actual = value.objects[i], url = new URL(actual.url);
233
+ const local = value.endpoint.startsWith("http://127.0.0.1:");
234
+ const host = local ? new URL(value.endpoint).host : `${value.bucket}.${value.endpoint}`;
235
+ const root = (local ? "/" + value.bucket : "") + "/chunks/7yi/";
236
+ const [owner, transferId, ...key] = url.pathname.slice(root.length).split("/");
237
+ if (!url.pathname.startsWith(root) || !owner || !/^[1-9][0-9]{0,18}$/.test(owner) || transferId !== config.broker.transferId || key.join("/") !== expected.key || tokenId && owner !== tokenId) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
238
+ tokenId = owner;
239
+ if (actual.method !== expected.method || actual.key !== expected.key || url.host !== host || url.protocol !== (local ? "http:" : "https:") || url.username || url.password || url.hash || !actual.headers || Object.keys(actual.headers).some((k) => !["Content-MD5", "Content-Type"].includes(k))) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
240
+ if (expected.method === "PUT" && (actual.headers["Content-MD5"] !== expected.contentMD5 || actual.headers["Content-Type"] !== expected.contentType)) throw Error("TRAVEL_OSS_INVALID_AUTHORIZATION");
241
+ }
242
+ config.broker.tokenId = tokenId;
243
+ }
244
+ async function authorizeHttp(config, operations) {
245
+ const broker = config.broker;
246
+ let result;
247
+ try {
248
+ const response = await fetch(broker.url, { method: "POST", redirect: "error", headers: { Authorization: "Bearer " + broker.apiKey, "Content-Type": "application/json" }, body: JSON.stringify({ transferId: broker.transferId, internal: config.endpoint.includes("-internal."), objects: operations }), signal: AbortSignal.timeout(2e4) });
249
+ if (!response.ok) {
250
+ await response.body?.cancel();
251
+ throw Error(`TRAVEL_OSS_AUTHORIZATION_HTTP_${response.status}`);
252
+ }
253
+ result = await response.json();
254
+ validateAuthorization(config, result, operations);
255
+ } catch (error) {
256
+ if (error instanceof Error && /^TRAVEL_OSS_AUTHORIZATION_HTTP_[0-9]{3}$/.test(error.message)) throw error;
257
+ throw Error("TRAVEL_OSS_AUTHORIZATION_FAILED");
258
+ }
259
+ return result;
260
+ }
261
+ async function authorize(config, operations, background = false) {
262
+ const broker = config.broker;
263
+ let queue = signingQueues.get(broker);
264
+ if (!queue) {
265
+ queue = { tail: Promise.resolve(), last: 0 };
266
+ signingQueues.set(broker, queue);
267
+ }
268
+ const current = queue;
269
+ const result = current.tail.catch(() => {
270
+ }).then(async () => {
271
+ const wait = 1e3 - (Date.now() - current.last);
272
+ if (wait > 0) await new Promise((resolve2) => {
273
+ const timer = setTimeout(resolve2, wait);
274
+ if (background) timer.unref();
275
+ });
276
+ try {
277
+ return await authorizeHttp(config, operations);
278
+ } finally {
279
+ current.last = Date.now();
280
+ }
281
+ });
282
+ current.tail = result;
283
+ return result;
284
+ }
285
+ async function prepareOssRequests(config, operations, background = false) {
286
+ if (!config.broker) return;
287
+ let entries = cache.get(config);
288
+ if (!entries) {
289
+ entries = /* @__PURE__ */ new Map();
290
+ cache.set(config, entries);
291
+ }
292
+ const missing = operations.filter((o) => (entries.get(cacheKey(o))?.expiresAt ?? 0) <= Date.now() / 1e3 + 30);
293
+ for (let i = 0; i < missing.length; i += 128) {
294
+ const batch = missing.slice(i, i + 128), result = await authorize(config, batch, background);
295
+ for (const [index, object] of result.objects.entries()) entries.set(cacheKey(batch[index]), { object, expiresAt: result.expiresAt });
296
+ }
297
+ }
298
+ async function withOssBatches(config, items, operation, transfer, background = false) {
299
+ for (let i = 0; i < items.length; i += 128) {
300
+ const batch = items.slice(i, i + 128), operations = batch.map(operation);
301
+ try {
302
+ await prepareOssRequests(config, operations, background);
303
+ await transfer(batch);
304
+ } finally {
305
+ for (const op of operations) cache.get(config)?.delete(cacheKey(op));
306
+ }
307
+ }
308
+ }
309
+ async function signedOssRequest(config, operation, refresh = false) {
310
+ if (refresh) cache.get(config)?.delete(cacheKey(operation));
311
+ for (let attempt = 0; attempt < 2; attempt++) {
312
+ await prepareOssRequests(config, [operation]);
313
+ const entry = cache.get(config)?.get(cacheKey(operation));
314
+ if (entry && entry.expiresAt > Date.now() / 1e3 + 30) return entry.object;
315
+ }
316
+ throw Error("TRAVEL_OSS_AUTHORIZATION_EXPIRED");
317
+ }
318
+
319
+ // src/travel/oss-transport.ts
320
+ function ossFailureCode(error) {
321
+ const message = error instanceof Error ? error.message : "";
322
+ const code = /^TRAVEL_[A-Z_0-9]+/.exec(message)?.[0];
323
+ if (code) {
324
+ const status = code === "TRAVEL_OSS_ERROR" ? /→ ([0-9]{3})/.exec(message)?.[1] : void 0;
325
+ return status ? `${code}_HTTP_${status}` : code;
326
+ }
327
+ const system = error?.code;
328
+ if (system === "Z_DATA_ERROR" || system === "Z_BUF_ERROR") return "TRAVEL_BUNDLE_CORRUPT";
329
+ if (["ENOSPC", "EACCES", "EROFS", "ETIMEDOUT"].includes(system ?? "")) return "TRAVEL_OSS_RECEIVE_" + system;
330
+ return "TRAVEL_OSS_BUNDLE_RECEIVE_FAILED";
331
+ }
332
+ function internalEndpointOf(endpoint) {
333
+ if (endpoint.includes("-internal.")) return endpoint;
334
+ const at = endpoint.indexOf(".aliyuncs.com");
335
+ if (at < 0) return endpoint;
336
+ return endpoint.slice(0, at) + "-internal" + endpoint.slice(at);
337
+ }
338
+ function signedHeaders(config, method, resourcePath, headers) {
339
+ const date = (/* @__PURE__ */ new Date()).toUTCString();
340
+ const all = { ...headers, Date: date };
341
+ const ossHeaders = Object.keys(all).filter((key) => key.toLowerCase().startsWith("x-oss-")).sort((a, b) => a < b ? -1 : a > b ? 1 : 0).map((key) => `${key.toLowerCase()}:${all[key]}
342
+ `).join("");
343
+ const pick = (name) => {
344
+ const key = Object.keys(all).find((k) => k.toLowerCase() === name);
345
+ return key ? String(all[key]) : "";
346
+ };
347
+ const stringToSign = `${method}
348
+ ${pick("content-md5")}
349
+ ${pick("content-type")}
350
+ ${date}
351
+ ${ossHeaders}/${config.bucket}${resourcePath}`;
352
+ if (!config.accessKeyId || !config.accessKeySecret) throw Error("TRAVEL_OSS_NOT_CONFIGURED");
353
+ const signature = createHmac("sha1", config.accessKeySecret).update(stringToSign).digest("base64");
354
+ return { ...all, Authorization: `OSS ${config.accessKeyId}:${signature}` };
355
+ }
356
+ async function ossFetch(config, method, resourcePath, body, headers = {}, okCodes = [200]) {
357
+ if (config.broker) {
358
+ const operation = { method, key: resourcePath.slice(1), ...method === "PUT" ? { contentMD5: md5Base64(body ?? Buffer.alloc(0)), contentType: "application/octet-stream" } : {} };
359
+ for (let attempt = 0; attempt < 2; attempt++) {
360
+ const signed2 = await signedOssRequest(config, operation, attempt > 0);
361
+ let response2;
362
+ try {
363
+ response2 = await fetch(signed2.url, { method, headers: signed2.headers, body, redirect: "error", signal: AbortSignal.timeout(Math.max(12e4, Math.round((body?.length ?? 0) / 1048576) * 12e3)) });
364
+ } catch {
365
+ throw Error("TRAVEL_OSS_TRANSFER_FAILED");
366
+ }
367
+ if (response2.status === 403 && attempt === 0) {
368
+ await response2.body?.cancel();
369
+ continue;
370
+ }
371
+ if (!okCodes.includes(response2.status)) {
372
+ await response2.body?.cancel();
373
+ throw Error(`TRAVEL_OSS_ERROR (${method} \u2192 ${response2.status})`);
374
+ }
375
+ return response2;
376
+ }
377
+ throw Error("TRAVEL_OSS_TRANSFER_FAILED");
378
+ }
379
+ const signed = signedHeaders(config, method, resourcePath, headers);
380
+ const scheme = config.endpoint.startsWith("http://") ? "http://" : "https://";
381
+ const host = config.endpoint.replace(/^https?:\/\//, "");
382
+ const pathStyle = /^[\d.]+$/.test(host) || host.startsWith("localhost") || host.startsWith("127.");
383
+ const url = pathStyle ? `${scheme}${host}/${config.bucket}${resourcePath}` : `${scheme}${config.bucket}.${host}${resourcePath}`;
384
+ const response = await fetch(url, {
385
+ method,
386
+ headers: signed,
387
+ body,
388
+ // 1123 妹妹 review:固定 120s 对慢上行的大块太贴边(10MB@1Mbps≈80s)——
389
+ // 按 body 长度放宽(≥120s,每 1MB 加 12s 余量)。
390
+ signal: AbortSignal.timeout(Math.max(12e4, Math.round((body?.length ?? 0) / 1024 / 1024) * 12e3))
391
+ });
392
+ if (!okCodes.includes(response.status)) {
393
+ const detail = await response.text().catch(() => "");
394
+ throw new Error(`TRAVEL_OSS_ERROR\uFF08${method} ${resourcePath} \u2192 ${response.status}\uFF09\uFF1A${detail.slice(0, 300)}`);
395
+ }
396
+ return response;
397
+ }
398
+ function md5Base64(body) {
399
+ return createHash2("md5").update(body).digest("base64");
400
+ }
401
+ function objectPath(key) {
402
+ if (!/^[A-Za-z0-9/_.-]+$/.test(key) || key.startsWith("/") || key.includes("..")) throw Error("TRAVEL_OSS_INVALID_OBJECT_KEY");
403
+ return "/" + key;
404
+ }
405
+ async function ossGetObject(config, key, maxBytes = 64 * 1048576) {
406
+ const response = await ossFetch(config, "GET", objectPath(key));
407
+ if (Number(response.headers.get("content-length")) > maxBytes) {
408
+ await response.body?.cancel();
409
+ throw Error("TRAVEL_OSS_OBJECT_TOO_LARGE");
410
+ }
411
+ const reader = response.body?.getReader();
412
+ if (!reader) return Buffer.alloc(0);
413
+ let bytes = 0;
414
+ const parts = [];
415
+ try {
416
+ for (; ; ) {
417
+ const next = await reader.read();
418
+ if (next.done) break;
419
+ bytes += next.value.length;
420
+ if (bytes > maxBytes) {
421
+ await reader.cancel();
422
+ throw Error("TRAVEL_OSS_OBJECT_TOO_LARGE");
423
+ }
424
+ parts.push(Buffer.from(next.value));
425
+ }
426
+ return Buffer.concat(parts);
427
+ } finally {
428
+ reader.releaseLock();
429
+ }
430
+ }
431
+
432
+ // src/travel/oss-bundle.ts
433
+ import { createHash as createHash3 } from "node:crypto";
434
+ import { gzip as gzip2, gunzip } from "node:zlib";
435
+ import { promisify as promisify2 } from "node:util";
436
+ var BUNDLE_GZIP_MAX = 8 * 1048576;
437
+ var BUNDLE_RAW_MAX = 32 * 1048576;
438
+ var BUNDLE_HEADER_MAX = 256 * 1024;
439
+ var BUNDLE_REFS_MAX = 2048;
440
+ var MAGIC = Buffer.from([69, 55, 80, 75, 0, 0, 0, 1]);
441
+ var zip = promisify2(gzip2);
442
+ var unzip = promisify2(gunzip);
443
+ function validateBundleRef(value) {
444
+ if (!value || !/^[a-f0-9]{64}$/.test(value.sha256) || !Number.isSafeInteger(value.plainBytes) || value.plainBytes < 12 || value.plainBytes > BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12 || !Array.isArray(value.refs) || !value.refs.length || value.refs.length > BUNDLE_REFS_MAX) throw Error("TRAVEL_INVALID_BUNDLE");
445
+ const seen = /* @__PURE__ */ new Set();
446
+ let bytes = 0;
447
+ for (const ref of value.refs) {
448
+ validateChunkRef(ref);
449
+ if (seen.has(ref.sha256)) throw Error("TRAVEL_INVALID_BUNDLE");
450
+ seen.add(ref.sha256);
451
+ bytes += ref.bytes;
452
+ }
453
+ if (bytes > BUNDLE_RAW_MAX) throw Error("TRAVEL_INVALID_BUNDLE");
454
+ }
455
+ async function unpackBundle(body, expected) {
456
+ if (body.length > BUNDLE_GZIP_MAX || !/^[a-f0-9]{64}$/.test(expected.sha256) || !Number.isSafeInteger(expected.plainBytes) || expected.plainBytes > BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12) throw Error("TRAVEL_INVALID_BUNDLE");
457
+ const plain = await unzip(body, { maxOutputLength: BUNDLE_RAW_MAX + BUNDLE_HEADER_MAX + 12 });
458
+ if (plain.length !== expected.plainBytes || createHash3("sha256").update(plain).digest("hex") !== expected.sha256 || !plain.subarray(0, 8).equals(MAGIC)) throw Error("TRAVEL_BUNDLE_CORRUPT");
459
+ const size = plain.readUInt32BE(8);
460
+ if (!size || size > BUNDLE_HEADER_MAX || 12 + size > plain.length) throw Error("TRAVEL_BUNDLE_CORRUPT");
461
+ const header = JSON.parse(plain.subarray(12, 12 + size).toString());
462
+ if (header.version !== 1) throw Error("TRAVEL_INVALID_BUNDLE");
463
+ if (expected.refsDigest && createHash3("sha256").update(JSON.stringify(header.refs)).digest("hex") !== expected.refsDigest) throw Error("TRAVEL_BUNDLE_CORRUPT");
464
+ const bundle = { ...expected, refs: header.refs };
465
+ validateBundleRef(bundle);
466
+ const parts = [];
467
+ let offset = 12 + size;
468
+ for (const ref of bundle.refs) {
469
+ const part = plain.subarray(offset, offset + ref.bytes);
470
+ if (part.length !== ref.bytes || createHash3("sha256").update(part).digest("hex") !== ref.sha256) throw Error("TRAVEL_CHUNK_CORRUPT");
471
+ parts.push({ ref, body: part });
472
+ offset += ref.bytes;
473
+ }
474
+ if (offset !== plain.length) throw Error("TRAVEL_BUNDLE_CORRUPT");
475
+ return parts;
476
+ }
477
+
478
+ // src/travel/apply-transaction.ts
479
+ import { closeSync as closeSync2, existsSync as existsSync2, fsyncSync as fsyncSync2, lstatSync as lstatSync2, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync2, readSync as readSync2, renameSync as renameSync2, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
480
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
481
+ var safeRel = (rel) => !!rel && !/[\\:\x00-\x1f]/.test(rel) && rel.split("/").every((p) => p && p !== "." && p !== "..");
482
+ function assertPath(root, rel) {
483
+ if (!safeRel(rel)) throw Error("TRAVEL_UNSAFE_PATH");
484
+ let path = root;
485
+ for (const part of rel.split("/")) {
486
+ path = join2(path, part);
487
+ try {
488
+ if (lstatSync2(path).isSymbolicLink()) throw Error("TRAVEL_UNSAFE_PATH");
489
+ } catch (e) {
490
+ if (e.code !== "ENOENT") throw e;
491
+ }
492
+ }
493
+ return path;
494
+ }
495
+
496
+ // src/travel/oss-bundle-stream.ts
497
+ var bootstrap = `import{createInterface}from'node:readline';const rl=createInterface({input:process.stdin,crlfDelay:Infinity}),it=rl[Symbol.asyncIterator]();try{const first=await it.next(),x=JSON.parse(first.value),m=await import('data:text/javascript;base64,'+Buffer.from(x.module).toString('base64'));await m.runOssBundleStream(x.root,x.config,it,p=>process.stdout.write(JSON.stringify(p)+'\\n'))}catch(e){console.error(e.message);process.exitCode=1}`;
498
+ var quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
499
+ function makeBundleReceiver(root, config) {
500
+ if (!isAbsolute(root)) throw Error("TRAVEL_UNSAFE_PATH");
501
+ const store = openChunkStore(assertPath(root, ".travel/chunks"));
502
+ let active = 0;
503
+ const waiters = [];
504
+ const acquire = async () => {
505
+ if (active < 4) {
506
+ active++;
507
+ return;
508
+ }
509
+ await new Promise((r) => waiters.push(r));
510
+ }, release = () => {
511
+ const next = waiters.shift();
512
+ if (next) next();
513
+ else active--;
514
+ };
515
+ return async (bundles) => {
516
+ const result = { bundles: 0, chunks: 0, bytes: 0, failed: [] };
517
+ await withOssBatches(config, bundles, (b) => ({ method: "GET", key: "chunks/" + b.sha256 + ".gz" }), async (batch) => {
518
+ await Promise.all(batch.map(async (bundle) => {
519
+ await acquire();
520
+ try {
521
+ const chunks = await unpackBundle(await ossGetObject(config, "chunks/" + bundle.sha256 + ".gz", BUNDLE_GZIP_MAX), bundle);
522
+ for (const chunk of chunks) await store.put(chunk.body);
523
+ result.bundles++;
524
+ result.chunks += chunks.length;
525
+ result.bytes += chunks.reduce((n, c) => n + c.ref.bytes, 0);
526
+ } catch (error) {
527
+ result.failed.push({ sha256: bundle.sha256, code: ossFailureCode(error) });
528
+ } finally {
529
+ release();
530
+ }
531
+ }));
532
+ });
533
+ return result;
534
+ };
535
+ }
536
+ async function runOssBundleStream(root, initial, lines, send) {
537
+ const receive = makeBundleReceiver(root, { ...initial, endpoint: internalEndpointOf(initial.endpoint) }), jobs = /* @__PURE__ */ new Set();
538
+ send({ ready: true });
539
+ for await (const line of lines) {
540
+ const input = JSON.parse(line);
541
+ if (!Number.isSafeInteger(input.id) || input.id < 1 || !Array.isArray(input.bundles) || input.bundles.length < 1 || input.bundles.length > 8) throw Error("TRAVEL_OSS_BUNDLE_PROTOCOL");
542
+ const job = receive(input.bundles).then((result) => send({ id: input.id, result }), (error) => send({ id: input.id, error: ossFailureCode(error) }));
543
+ jobs.add(job);
544
+ void job.finally(() => jobs.delete(job));
545
+ if (jobs.size >= 2) await Promise.race(jobs);
546
+ }
547
+ await Promise.all(jobs);
548
+ }
549
+ function openBundleStream(options) {
550
+ let source = options.source;
551
+ if (!source) {
552
+ for (const url of [new URL("./travel-oss-bundle-stream.mjs", import.meta.url), new URL("../../dist/travel-oss-bundle-stream.mjs", import.meta.url)]) if (existsSync3(fileURLToPath(url))) {
553
+ source = readFileSync3(url, "utf8");
554
+ break;
555
+ }
556
+ }
557
+ if (!source) throw Error("TRAVEL_OSS_HELPER_MISSING");
558
+ const child = options.spawn("node --input-type=module -e " + quote(bootstrap)), pending = /* @__PURE__ */ new Map();
559
+ let sequence = 0, text = "", settled = false, closed = false, resolveReady, rejectReady;
560
+ const ready = new Promise((resolve2, reject) => {
561
+ resolveReady = resolve2;
562
+ rejectReady = reject;
563
+ });
564
+ const fail = () => {
565
+ closed = true;
566
+ const error = Error("TRAVEL_OSS_BUNDLE_CONNECTION_CLOSED");
567
+ if (!settled) {
568
+ settled = true;
569
+ rejectReady(error);
570
+ }
571
+ for (const p of pending.values()) p.reject(error);
572
+ pending.clear();
573
+ };
574
+ child.on("error", fail);
575
+ child.on("close", fail);
576
+ child.stdin.on("error", fail);
577
+ child.stderr.on("data", (b) => options.log("[bundle-receiver] " + b.toString().trim()));
578
+ child.stdout.on("data", (b) => {
579
+ text += b.toString();
580
+ for (; ; ) {
581
+ const i = text.indexOf("\n");
582
+ if (i < 0) break;
583
+ const line = text.slice(0, i);
584
+ text = text.slice(i + 1);
585
+ try {
586
+ const value = JSON.parse(line);
587
+ if (value.ready) {
588
+ settled = true;
589
+ resolveReady();
590
+ continue;
591
+ }
592
+ const p = pending.get(value.id);
593
+ if (p) {
594
+ pending.delete(value.id);
595
+ value.error ? p.reject(Error(value.error)) : p.resolve(value.result);
596
+ }
597
+ } catch {
598
+ fail();
599
+ }
600
+ }
601
+ });
602
+ child.stdin.write(JSON.stringify({ module: source, root: options.root, config: options.config }) + "\n");
603
+ const deadline = setTimeout(() => {
604
+ child.kill();
605
+ fail();
606
+ }, 30 * 6e4);
607
+ child.once("close", () => clearTimeout(deadline));
608
+ return { ready, receive: async (bundles) => {
609
+ await ready;
610
+ if (closed) throw Error("TRAVEL_OSS_BUNDLE_CONNECTION_CLOSED");
611
+ const id = ++sequence;
612
+ return new Promise((resolve2, reject) => {
613
+ pending.set(id, { resolve: resolve2, reject });
614
+ child.stdin.write(JSON.stringify({ id, bundles }) + "\n", (error) => {
615
+ if (error) {
616
+ pending.delete(id);
617
+ reject(error);
618
+ }
619
+ });
620
+ });
621
+ }, close: async () => {
622
+ if (!closed) {
623
+ child.stdin.end();
624
+ await Promise.race([new Promise((r) => child.once("close", () => r())), new Promise((r) => setTimeout(() => {
625
+ child.kill();
626
+ r();
627
+ }, 5e3))]);
628
+ }
629
+ clearTimeout(deadline);
630
+ } };
631
+ }
632
+ export {
633
+ makeBundleReceiver,
634
+ openBundleStream,
635
+ runOssBundleStream
636
+ };