Diffinery

homeflare/celldpublic

celld/crates/celld/js/node_buffer.js
798 lines · 31.9 KBRaw History
1// node:buffer for Cells.
2//
3// Compiled lazily: as a LAZY_GLOBALS entry (first read of `Buffer`) and as
4// the LAZY_MODULES source for `node:buffer`, so an isolate that never
5// touches Buffer pays nothing at boot. The script is self-guarded on
6// `__buffer` because both seams can run it; `globalThis.Buffer` itself is
7// defined by the lazy-global machinery, never assigned here.
8//
9// Node's Buffer is part of Cloudflare's nodejs_compat contract and is
10// used at module scope by undici/pi-agent. Keep it Uint8Array-backed so
11// Web APIs accept it naturally. Encoding, validation, and error-code
12// semantics follow Node's lib/buffer.js, with the argument dances
13// adapted from Deno's ext/node/polyfills/internal/buffer.mjs (MIT).
14if (!globalThis.__buffer) (() => {
15 const __kMaxLength = 2147483647;
16 const __kStringMaxLength = 536870888;
17 const __bufErr = (E, code, msg) => {
18 const e = new E(msg); e.code = code; return e;
19 };
20 // Node formats large received values with numeric separators.
21 const __numSep = (s) => {
22 let out = "", n = 0;
23 for (let i = s.length - 1; i >= 0; i--, n++) {
24 if (n && n % 3 === 0 && s[i] !== "-") out = "_" + out;
25 out = s[i] + out;
26 }
27 return out;
28 };
29 const __bufRange = (name, range, value) => {
30 let received = String(value);
31 if (typeof value === "bigint") received = __numSep(received) + "n";
32 else if (Number.isInteger(value) && Math.abs(value) > 2 ** 32)
33 received = __numSep(received);
34 return __bufErr(RangeError, "ERR_OUT_OF_RANGE",
35 `The value of "${name}" is out of range. It must be ${range}. ` +
36 `Received ${received}`);
37 };
38 const __bufType = (name, expected, value) => __bufErr(TypeError,
39 "ERR_INVALID_ARG_TYPE",
40 `The "${name}" argument must be ${expected}. Received ` +
41 (value === null ? "null"
42 : value === undefined ? "undefined"
43 : typeof value === "object"
44 ? `an instance of ${value.constructor?.name ?? "Object"}`
45 : `type ${typeof value}`));
46 const __checkNum = (name, value, min, max) => {
47 if (typeof value !== "number")
48 throw __bufType(name, "of type number", value);
49 if (Number.isNaN(value) || value < min || value > max)
50 throw __bufRange(name, `>= ${min} and <= ${max}`, value);
51 return value;
52 };
53 const __badEnc = (enc) => __bufErr(TypeError,
54 "ERR_UNKNOWN_ENCODING", `Unknown encoding: ${enc}`);
55 const __normEnc = (enc) => {
56 switch (String(enc).toLowerCase()) {
57 case "utf8": case "utf-8": return "utf8";
58 case "utf16le": case "utf-16le": case "ucs2": case "ucs-2":
59 return "utf16le";
60 case "latin1": case "binary": return "latin1";
61 case "ascii": return "ascii";
62 case "base64": return "base64";
63 case "base64url": return "base64url";
64 case "hex": return "hex";
65 default: return undefined;
66 }
67 };
68 const __b64lut = (() => {
69 const lut = new Int8Array(128).fill(-1);
70 const abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
71 "abcdefghijklmnopqrstuvwxyz0123456789+/";
72 for (let i = 0; i < 64; i++) lut[abc.charCodeAt(i)] = i;
73 lut[45] = 62; lut[95] = 63; // '-' '_'
74 return lut;
75 })();
76 // Nibble value per code unit, -1 for anything else. Node's own table is
77 // 256 wide and indexed with `& 0xff`, so it decodes 'Ł' (U+0141) as 'A';
78 // a 128-entry table with the guard below rejects every non-ASCII code
79 // unit instead, which is what the regex it replaces did.
80 const __hexlut = (() => {
81 const lut = new Int8Array(128).fill(-1);
82 const lower = "0123456789abcdef", upper = "0123456789ABCDEF";
83 for (let i = 0; i < 16; i++) {
84 lut[lower.charCodeAt(i)] = i; lut[upper.charCodeAt(i)] = i;
85 }
86 return lut;
87 })();
88 // string -> bytes. Hex stops at the first invalid pair; base64 is
89 // forgiving (skips invalid characters, '=' terminates), like Node.
90 const __encodeStr = (string, enc) => {
91 switch (enc) {
92 case "utf8": return new TextEncoder().encode(string);
93 case "latin1": case "ascii":
94 return Uint8Array.from(string, (c) => c.charCodeAt(0) & 255);
95 case "utf16le": {
96 const out = new Uint8Array(string.length * 2);
97 for (let i = 0; i < string.length; i++) {
98 const c = string.charCodeAt(i);
99 out[i * 2] = c & 255; out[i * 2 + 1] = c >>> 8;
100 }
101 return out;
102 }
103 case "hex": {
104 const n = string.length >>> 1;
105 const out = new Uint8Array(n);
106 let i = 0;
107 for (; i < n; i++) {
108 const hi = string.charCodeAt(i * 2);
109 const lo = string.charCodeAt(i * 2 + 1);
110 const a = hi < 128 ? __hexlut[hi] : -1;
111 const b = lo < 128 ? __hexlut[lo] : -1;
112 if (a < 0 || b < 0) break;
113 out[i] = (a << 4) | b;
114 }
115 return i === n ? out : out.subarray(0, i);
116 }
117 default: { // base64 / base64url
118 // Four source characters carry at most three bytes, and a skipped
119 // character or an interior '=' only shrinks that, so this is an
120 // upper bound and the subarray below trims any slack. Sizing the
121 // output up front replaces one push and one copy per byte.
122 // Discounting the trailing padding matters: without it a padded
123 // input, which is most base64, always overshoots and always pays
124 // for the trim. `byteLength` computes the same bound.
125 const pad = string.charCodeAt(string.length - 1) === 61
126 ? (string.charCodeAt(string.length - 2) === 61 ? 2 : 1) : 0;
127 const out = new Uint8Array(((string.length - pad) * 3) >>> 2);
128 let n = 0, acc = 0, bits = 0;
129 for (let i = 0; i < string.length; i++) {
130 const c = string.charCodeAt(i);
131 if (c === 61) break; // '='
132 const v = c < 128 ? __b64lut[c] : -1;
133 if (v < 0) continue;
134 acc = (acc << 6) | v; bits += 6;
135 if (bits >= 8) { bits -= 8; out[n++] = (acc >>> bits) & 255; }
136 }
137 return n === out.length ? out : out.subarray(0, n);
138 }
139 }
140 };
141 const __decodeStr = (bytes, enc) => {
142 switch (enc) {
143 case "utf8": return new TextDecoder().decode(bytes);
144 case "latin1": {
145 let s = "";
146 for (let i = 0; i < bytes.length; i += 0x2000)
147 s += String.fromCharCode(...bytes.subarray(i, i + 0x2000));
148 return s;
149 }
150 case "ascii": {
151 let s = "";
152 for (let i = 0; i < bytes.length; i++)
153 s += String.fromCharCode(bytes[i] & 0x7f);
154 return s;
155 }
156 case "utf16le": {
157 let s = "";
158 for (let i = 0; i + 1 < bytes.length; i += 2)
159 s += String.fromCharCode(bytes[i] | (bytes[i + 1] << 8));
160 return s;
161 }
162 case "hex": {
163 let s = "";
164 for (let i = 0; i < bytes.length; i++)
165 s += bytes[i].toString(16).padStart(2, "0");
166 return s;
167 }
168 default: { // base64 / base64url
169 let raw = "";
170 for (let i = 0; i < bytes.length; i += 0x2000)
171 raw += String.fromCharCode(...bytes.subarray(i, i + 0x2000));
172 const s = btoa(raw);
173 return enc === "base64url"
174 ? s.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
175 : s;
176 }
177 }
178 };
179 const __assertSize = (size) => {
180 if (typeof size !== "number")
181 throw __bufType("size", "of type number", size);
182 if (!(size >= 0 && size <= __kMaxLength))
183 throw __bufRange("size", `>= 0 && <= ${__kMaxLength}`, size);
184 return Math.floor(size);
185 };
186 const __u8 = (v) =>
187 v instanceof Uint8Array
188 ? v
189 : ArrayBuffer.isView(v) && !(v instanceof DataView)
190 ? new Uint8Array(v.buffer, v.byteOffset, v.byteLength)
191 : undefined;
192 const __rawCompare = (a, b) => {
193 const n = Math.min(a.length, b.length);
194 for (let i = 0; i < n; i++)
195 if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1;
196 return a.length === b.length ? 0 : a.length < b.length ? -1 : 1;
197 };
198 class NodeBuffer extends Uint8Array {
199 static poolSize = 8192;
200 static from(value, encodingOrOffset, length) {
201 if (typeof value === "string") {
202 const enc = __normEnc(encodingOrOffset ?? "utf8");
203 if (!enc) throw __badEnc(encodingOrOffset);
204 return new NodeBuffer(__encodeStr(value, enc));
205 }
206 if (value instanceof ArrayBuffer ||
207 (typeof SharedArrayBuffer !== "undefined" &&
208 value instanceof SharedArrayBuffer)) {
209 // A view over the given buffer, not a copy, like Node. A
210 // non-numeric byteOffset defaults to 0.
211 let offset = Number(encodingOrOffset || 0);
212 if (Number.isNaN(offset)) offset = 0;
213 if (!(offset >= 0 && offset <= value.byteLength))
214 throw __bufErr(RangeError, "ERR_BUFFER_OUT_OF_BOUNDS",
215 '"offset" is outside of buffer bounds');
216 let len = length === undefined
217 ? value.byteLength - offset : Number(length);
218 if (Number.isNaN(len)) len = 0;
219 if (!(len >= 0 && offset + len <= value.byteLength))
220 throw __bufErr(RangeError, "ERR_BUFFER_OUT_OF_BOUNDS",
221 '"length" is outside of buffer bounds');
222 return new NodeBuffer(value, offset, len);
223 }
224 if (ArrayBuffer.isView(value)) {
225 if (value instanceof Uint8Array) {
226 const copy = new NodeBuffer(value.byteLength);
227 copy.set(value);
228 return copy;
229 }
230 return new NodeBuffer(value); // element-wise copy, like Node
231 }
232 if (value === null || typeof value !== "object")
233 throw __bufType("first",
234 "of type string or an instance of Buffer, ArrayBuffer, or " +
235 "Array or an Array-like Object", value);
236 if (value.type === "Buffer" && Array.isArray(value.data))
237 return new NodeBuffer(value.data);
238 const vo = value.valueOf?.();
239 if (vo != null && vo !== value &&
240 (typeof vo === "string" || typeof vo === "object"))
241 return NodeBuffer.from(vo, encodingOrOffset, length);
242 if ("length" in value || Symbol.iterator in value ||
243 value.buffer instanceof ArrayBuffer ||
244 (typeof SharedArrayBuffer !== "undefined" &&
245 value.buffer instanceof SharedArrayBuffer))
246 return new NodeBuffer(value); // array-like / iterable
247 const prim = value[Symbol.toPrimitive]?.("string");
248 if (typeof prim === "string")
249 return NodeBuffer.from(prim, encodingOrOffset, length);
250 throw __bufType("first",
251 "of type string or an instance of Buffer, ArrayBuffer, or " +
252 "Array or an Array-like Object", value);
253 }
254 static alloc(size, fill, encoding) {
255 const b = new NodeBuffer(__assertSize(size));
256 return fill === undefined || fill === 0
257 ? b : b.fill(fill, 0, b.length, encoding);
258 }
259 static allocUnsafe(size) {
260 return new NodeBuffer(__assertSize(size));
261 }
262 static allocUnsafeSlow(size) {
263 return new NodeBuffer(__assertSize(size));
264 }
265 static isBuffer(value) { return value instanceof NodeBuffer; }
266 static isEncoding(enc) {
267 return typeof enc === "string" && __normEnc(enc) !== undefined;
268 }
269 static byteLength(value, encoding) {
270 if (typeof value !== "string") {
271 if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer ||
272 (typeof SharedArrayBuffer !== "undefined" &&
273 value instanceof SharedArrayBuffer))
274 return value.byteLength;
275 throw __bufType("string",
276 "of type string or an instance of Buffer or ArrayBuffer",
277 value);
278 }
279 switch (__normEnc(encoding ?? "utf8") ?? "utf8") {
280 case "latin1": case "ascii": return value.length;
281 case "utf16le": return value.length * 2;
282 case "hex": return value.length >>> 1;
283 case "base64": case "base64url": {
284 const pad = value.endsWith("==") ? 2
285 : value.endsWith("=") ? 1 : 0;
286 return Math.floor(((value.length - pad) * 3) / 4);
287 }
288 default: return new TextEncoder().encode(value).length;
289 }
290 }
291 static compare(a, b) {
292 const ab = __u8(a), bb = __u8(b);
293 if (!ab) throw __bufType("buf1",
294 "an instance of Buffer or Uint8Array", a);
295 if (!bb) throw __bufType("buf2",
296 "an instance of Buffer or Uint8Array", b);
297 return __rawCompare(ab, bb);
298 }
299 static concat(list, totalLength) {
300 if (!Array.isArray(list))
301 throw __bufType("list",
302 "an instance of Array", list);
303 if (list.length === 0) return new NodeBuffer(0);
304 const items = [];
305 for (let i = 0; i < list.length; i++) {
306 const item = __u8(list[i]);
307 if (!item)
308 throw __bufType(`list[${i}]`,
309 "an instance of Buffer or Uint8Array", list[i]);
310 items.push(item);
311 }
312 const total = totalLength === undefined
313 ? items.reduce((sum, b) => sum + b.length, 0)
314 : __assertSize(totalLength);
315 const out = new NodeBuffer(total);
316 let off = 0;
317 for (const item of items) {
318 // Re-read the live length: a getter above may have shrunk a
319 // resizable ArrayBuffer out from under the view.
320 const n = Math.min(item.length, total - off);
321 out.set(item.subarray(0, n), off);
322 off += n;
323 if (off >= total) break;
324 }
325 return out;
326 }
327 // try/catch, not instanceof: the prototype itself must read as
328 // undefined, and it *is* instanceof Uint8Array.
329 get offset() {
330 try { return this.byteOffset; } catch { return undefined; }
331 }
332 get parent() {
333 try { return this.buffer; } catch { return undefined; }
334 }
335 toString(encoding, start, end) {
336 const enc = encoding === undefined ? "utf8" : __normEnc(encoding);
337 if (!enc) throw __badEnc(encoding);
338 const len = this.length;
339 let s = start === undefined ? 0 : Math.trunc(Number(start)) || 0;
340 let e = end === undefined ? len : Math.trunc(Number(end)) || 0;
341 s = Math.min(Math.max(s, 0), len);
342 e = Math.min(Math.max(e, s), len);
343 if (e <= s) return "";
344 return __decodeStr(this.subarray(s, e), enc);
345 }
346 equals(other) {
347 const ob = __u8(other);
348 if (!ob) throw __bufType("otherBuffer",
349 "an instance of Buffer or Uint8Array", other);
350 return this === other || __rawCompare(this, ob) === 0;
351 }
352 compare(target, targetStart, targetEnd, sourceStart, sourceEnd) {
353 const tb = __u8(target);
354 if (!tb) throw __bufType("target",
355 "an instance of Buffer or Uint8Array", target);
356 const ts = targetStart === undefined ? 0
357 : __checkNum("targetStart", targetStart, 0, __kMaxLength);
358 const te = targetEnd === undefined ? tb.length
359 : __checkNum("targetEnd", targetEnd, 0, tb.length);
360 const ss = sourceStart === undefined ? 0
361 : __checkNum("sourceStart", sourceStart, 0, __kMaxLength);
362 const se = sourceEnd === undefined ? this.length
363 : __checkNum("sourceEnd", sourceEnd, 0, this.length);
364 if (ss >= se) return ts >= te ? 0 : -1;
365 if (ts >= te) return 1;
366 return __rawCompare(this.subarray(ss, se), tb.subarray(ts, te));
367 }
368 // Bounds semantics per Node, via Deno's buffer.mjs.
369 copy(target, targetStart, sourceStart, sourceEnd) {
370 if (!ArrayBuffer.isView(this))
371 throw __bufType("source",
372 "an instance of Buffer or Uint8Array", this);
373 const tb = __u8(target);
374 if (!tb) throw __bufType("target",
375 "an instance of Buffer or Uint8Array", target);
376 const toInt = (v) => {
377 const n = Number(v);
378 return Number.isNaN(n) ? 0 : Math.trunc(n);
379 };
380 targetStart = targetStart === undefined ? 0 : toInt(targetStart);
381 if (targetStart < 0)
382 throw __bufRange("targetStart", ">= 0", targetStart);
383 sourceStart = sourceStart === undefined ? 0 : toInt(sourceStart);
384 if (sourceStart < 0)
385 throw __bufRange("sourceStart", ">= 0", sourceStart);
386 if (sourceStart >= 4294967295)
387 throw __bufRange("sourceStart", "< 4294967295", sourceStart);
388 sourceEnd = sourceEnd === undefined ? this.length
389 : toInt(sourceEnd);
390 if (sourceEnd < 0)
391 throw __bufRange("sourceEnd", ">= 0", sourceEnd);
392 if (sourceEnd >= 4294967295)
393 throw __bufRange("sourceEnd", "< 4294967295", sourceEnd);
394 if (targetStart >= tb.length) return 0;
395 sourceEnd = Math.min(sourceEnd, this.length);
396 const n = Math.min(
397 Math.max(sourceEnd - sourceStart, 0),
398 tb.length - targetStart);
399 if (n <= 0) return 0;
400 tb.set(this.subarray(sourceStart, sourceStart + n), targetStart);
401 return n;
402 }
403 // Argument dance and edge cases per Node, via Deno's buffer.mjs.
404 fill(value, start, end, encoding) {
405 if (typeof value === "string") {
406 if (typeof start === "string") {
407 encoding = start; start = 0; end = this.length;
408 } else if (typeof end === "string") {
409 encoding = end; end = undefined;
410 }
411 if (encoding !== undefined && typeof encoding !== "string")
412 throw __bufType("encoding", "of type string", encoding);
413 if (typeof encoding === "string" && !__normEnc(encoding))
414 throw __badEnc(encoding);
415 } else if (typeof start === "string") {
416 encoding = start; start = undefined;
417 }
418 if (start !== undefined) {
419 __checkNum("start", start, 0, __kMaxLength);
420 if (end !== undefined)
421 __checkNum("end", end, 0, this.length);
422 }
423 start = start === undefined ? 0 : start >>> 0;
424 end = end === undefined ? this.length : end >>> 0;
425 if (start > this.length || end > this.length)
426 throw new RangeError("Out of range index");
427 if (end <= start) return this;
428 if (value === undefined || value === null || value === "" ||
429 typeof value === "boolean")
430 value = Number(value) || 0;
431 if (typeof value === "number") {
432 Uint8Array.prototype.fill.call(this, value & 255, start, end);
433 return this;
434 }
435 let pattern;
436 if (typeof value === "string") {
437 pattern = __encodeStr(value, __normEnc(encoding ?? "utf8"));
438 } else {
439 pattern = __u8(value);
440 if (!pattern) { // anything else coerces to a byte, like Node
441 Uint8Array.prototype.fill.call(
442 this, Number(value) & 255, start, end);
443 return this;
444 }
445 }
446 if (pattern.length === 0)
447 throw __bufErr(TypeError, "ERR_INVALID_ARG_VALUE",
448 `The argument 'value' is invalid. Received '${value}'`);
449 for (let i = start; i < end; i++)
450 this[i] = pattern[(i - start) % pattern.length];
451 return this;
452 }
453 // Argument dance per Node lib/buffer.js (via Deno's buffer.mjs).
454 write(string, offset, length, encoding) {
455 if (typeof string !== "string")
456 throw __bufType("argument", "of type string", string);
457 if (offset === undefined) {
458 encoding = "utf8"; length = this.length; offset = 0;
459 } else if (length === undefined && typeof offset === "string") {
460 encoding = offset; length = this.length; offset = 0;
461 } else {
462 if (typeof offset !== "number")
463 throw __bufType("offset", "of type number", offset);
464 if (!(offset >= 0 && offset <= this.length))
465 throw __bufRange("offset",
466 `>= 0 and <= ${this.length}`, offset);
467 const remaining = this.length - offset;
468 if (length === undefined) length = remaining;
469 else if (typeof length === "string") {
470 encoding = length; length = remaining;
471 } else {
472 if (typeof length !== "number")
473 throw __bufType("length", "of type number", length);
474 length = Math.min(Math.max(Math.trunc(length), 0), remaining);
475 }
476 }
477 const enc = __normEnc(encoding ?? "utf8");
478 if (!enc) throw __badEnc(encoding);
479 const bytes = __encodeStr(string, enc);
480 let n = Math.min(bytes.length, length);
481 if (n < bytes.length) {
482 if (enc === "utf8" && (bytes[n] & 0xc0) === 0x80) {
483 // The cut lands inside a multi-byte character: drop it whole.
484 while (n > 0 && (bytes[n - 1] & 0xc0) === 0x80) n--;
485 if (n > 0) n--;
486 } else if (enc === "utf16le") {
487 n &= ~1;
488 }
489 }
490 this.set(bytes.subarray(0, n), offset);
491 return n;
492 }
493 slice(start, end) { return this.subarray(start, end); }
494 indexOf(value, byteOffset, encoding) {
495 return __bufSearch(this, value, byteOffset, encoding, false);
496 }
497 lastIndexOf(value, byteOffset, encoding) {
498 return __bufSearch(this, value, byteOffset, encoding, true);
499 }
500 includes(value, byteOffset, encoding) {
501 return this.indexOf(value, byteOffset, encoding) !== -1;
502 }
503 swap16() {
504 if (this.length % 2 !== 0) throw __swapErr(16);
505 for (let i = 0; i < this.length; i += 2) {
506 const t = this[i]; this[i] = this[i + 1]; this[i + 1] = t;
507 }
508 return this;
509 }
510 swap32() {
511 if (this.length % 4 !== 0) throw __swapErr(32);
512 for (let i = 0; i < this.length; i += 4)
513 this.subarray(i, i + 4).reverse();
514 return this;
515 }
516 swap64() {
517 if (this.length % 8 !== 0) throw __swapErr(64);
518 for (let i = 0; i < this.length; i += 8)
519 this.subarray(i, i + 8).reverse();
520 return this;
521 }
522 toJSON() { return { type: "Buffer", data: Array.from(this) }; }
523 }
524 const __swapErr = (bits) => __bufErr(RangeError,
525 "ERR_INVALID_BUFFER_SIZE",
526 `Buffer size must be a multiple of ${bits}-bits`);
527 // Byte search by delegating to V8's string search over latin1 strings
528 // (one char per byte), which survives the suite's multi-megabyte
529 // lastIndexOf stress. utf16le matches on 16-bit alignment, like Node.
530 const __bufSearch = (buf, value, byteOffset, encoding, last) => {
531 if (typeof byteOffset === "string") {
532 encoding = byteOffset; byteOffset = undefined;
533 }
534 let needle;
535 let enc = "utf8";
536 if (encoding !== undefined) {
537 enc = __normEnc(encoding);
538 if (!enc) throw __badEnc(encoding);
539 }
540 if (typeof value === "number") {
541 needle = String.fromCharCode(value & 255);
542 } else if (typeof value === "string") {
543 needle = __decodeStr(__encodeStr(value, enc), "latin1");
544 } else {
545 const nb = __u8(value);
546 if (!nb) throw __bufType("value",
547 "one of type number or string or an instance of Buffer or " +
548 "Uint8Array", value);
549 needle = __decodeStr(nb, "latin1");
550 }
551 const len = buf.length;
552 let start = Number(byteOffset);
553 if (Number.isNaN(start)) start = last ? len : 0;
554 else if (start < 0) start = len + start;
555 const hay = __decodeStr(buf, "latin1");
556 const even = enc === "utf16le" && typeof value !== "number";
557 if (!last) {
558 if (start < 0) start = 0;
559 let i = hay.indexOf(needle, start);
560 while (even && i > 0 && i % 2 !== 0)
561 i = hay.indexOf(needle, i + 1);
562 return i;
563 }
564 if (start < 0) return -1;
565 let i = hay.lastIndexOf(needle, start);
566 while (even && i > 0 && i % 2 !== 0)
567 i = i === 0 ? -1 : hay.lastIndexOf(needle, i - 1);
568 return i;
569 };
570 // Numeric accessors, generated onto the prototype: DataView-backed,
571 // with Node's offset/value validation. Both UInt and Uint spellings.
572 {
573 const proto = NodeBuffer.prototype;
574 const dv = (b) => new DataView(b.buffer, b.byteOffset, b.byteLength);
575 const checkOffset = (b, offset, width) => {
576 if (typeof offset !== "number")
577 throw __bufType("offset", "of type number", offset);
578 if (!Number.isInteger(offset))
579 throw __bufRange("offset", "an integer", offset);
580 if (b.length < width)
581 throw __bufErr(RangeError, "ERR_BUFFER_OUT_OF_BOUNDS",
582 "Attempt to access memory outside buffer bounds");
583 if (offset < 0 || offset + width > b.length)
584 throw __bufRange("offset",
585 `>= 0 and <= ${b.length - width}`, offset);
586 };
587 const ranges = {
588 UInt8: [0, 255], UInt16: [0, 65535], UInt32: [0, 4294967295],
589 Int8: [-128, 127], Int16: [-32768, 32767],
590 Int32: [-2147483648, 2147483647],
591 };
592 const checkValue = (name, value) => {
593 if (name.startsWith("Big")) {
594 if (typeof value !== "bigint")
595 throw __bufType("value", "of type bigint", value);
596 const [lo, hi, range] = name === "BigInt64"
597 ? [-(2n ** 63n), 2n ** 63n - 1n,
598 ">= -(2n ** 63n) and < 2n ** 63n"]
599 : [0n, 2n ** 64n - 1n, ">= 0n and < 2n ** 64n"];
600 if (value < lo || value > hi)
601 throw __bufRange("value", range, value);
602 return;
603 }
604 const r = ranges[name];
605 if (!r) return; // floats are unchecked, like Node
606 if (typeof value !== "number")
607 throw __bufType("value", "of type number", value);
608 if (!Number.isInteger(value))
609 throw __bufRange("value", "an integer", value);
610 if (value < r[0] || value > r[1])
611 throw __bufRange("value", `>= ${r[0]} and <= ${r[1]}`, value);
612 };
613 const defs = {
614 UInt8: [1, "getUint8", "setUint8"],
615 UInt16: [2, "getUint16", "setUint16"],
616 UInt32: [4, "getUint32", "setUint32"],
617 Int8: [1, "getInt8", "setInt8"],
618 Int16: [2, "getInt16", "setInt16"],
619 Int32: [4, "getInt32", "setInt32"],
620 Float: [4, "getFloat32", "setFloat32"],
621 Double: [8, "getFloat64", "setFloat64"],
622 BigInt64: [8, "getBigInt64", "setBigInt64"],
623 BigUInt64: [8, "getBigUint64", "setBigUint64"],
624 };
625 for (const [name, [width, get, set]] of Object.entries(defs)) {
626 const variants = width === 1 && !name.startsWith("Big")
627 ? [["", undefined]] : [["LE", true], ["BE", false]];
628 for (const [suffix, little] of variants) {
629 proto[`read${name}${suffix}`] = function (offset = 0) {
630 checkOffset(this, offset, width);
631 return dv(this)[get](offset, little);
632 };
633 proto[`write${name}${suffix}`] = function (value, offset = 0) {
634 checkOffset(this, offset, width);
635 checkValue(name, value);
636 dv(this)[set](offset, value, little);
637 return offset + width;
638 };
639 }
640 }
641 // Variable-width forms: read/write(U)Int{LE,BE}(offset, byteLength).
642 for (const signed of [false, true]) {
643 const name = signed ? "Int" : "UInt";
644 for (const [suffix, little] of [["LE", true], ["BE", false]]) {
645 proto[`read${name}${suffix}`] = function (offset, byteLength) {
646 const w = byteLength;
647 if (typeof w !== "number" || !Number.isInteger(w) ||
648 w < 1 || w > 6)
649 throw __bufRange("byteLength", ">= 1 and <= 6", byteLength);
650 checkOffset(this, offset, w);
651 let value = 0;
652 for (let i = 0; i < w; i++)
653 value = value * 256 +
654 this[offset + (little ? w - 1 - i : i)];
655 if (signed && value >= 2 ** (8 * w - 1))
656 value -= 2 ** (8 * w);
657 return value;
658 };
659 proto[`write${name}${suffix}`] = function (value, offset,
660 byteLength) {
661 const w = byteLength;
662 if (typeof w !== "number" || !Number.isInteger(w) ||
663 w < 1 || w > 6)
664 throw __bufRange("byteLength", ">= 1 and <= 6", byteLength);
665 checkOffset(this, offset, w);
666 const [lo, hi] = signed
667 ? [-(2 ** (8 * w - 1)), 2 ** (8 * w - 1) - 1]
668 : [0, 2 ** (8 * w) - 1];
669 if (typeof value !== "number" || !Number.isInteger(value) ||
670 value < lo || value > hi)
671 throw __bufRange("value", `>= ${lo} and <= ${hi}`, value);
672 let v = value < 0 ? value + 2 ** (8 * w) : value;
673 for (let i = 0; i < w; i++) {
674 this[offset + (little ? i : w - 1 - i)] =
675 v % 256;
676 v = Math.floor(v / 256);
677 }
678 return offset + w;
679 };
680 }
681 }
682 // Uint spellings alias UInt, like Node.
683 for (const key of Object.getOwnPropertyNames(proto)) {
684 const alias = key.replace("UInt", "Uint");
685 if (alias !== key) proto[alias] = proto[key];
686 }
687 proto.toLocaleString = proto.toString;
688 // Encoding-specific fast APIs: fooSlice(start, end) decodes a range,
689 // fooWrite(string, offset, length) writes with that encoding.
690 for (const [prefix, enc] of [["utf8", "utf8"], ["ascii", "ascii"],
691 ["latin1", "latin1"], ["base64", "base64"],
692 ["base64url", "base64url"], ["hex", "hex"],
693 ["ucs2", "utf16le"], ["utf16le", "utf16le"]]) {
694 proto[`${prefix}Slice`] = function (start, end) {
695 return this.toString(enc, start ?? 0, end ?? this.length);
696 };
697 proto[`${prefix}Write`] = function (string, offset = 0, length) {
698 return this.write(string, offset,
699 length ?? this.length - offset, enc);
700 };
701 }
702 }
703 Object.defineProperty(NodeBuffer, Symbol.species, { value: NodeBuffer });
704 // The public class name: inspect and error messages must say Buffer.
705 Object.defineProperty(NodeBuffer, "name", { value: "Buffer" });
706 // Node's Buffer is callable: Buffer(n) allocates, Buffer(x) is from().
707 // A proxy keeps statics, prototype, and instanceof identical.
708 const __bufferCallable = new Proxy(NodeBuffer, {
709 apply(_target, _thisArg, args) {
710 return typeof args[0] === "number"
711 ? NodeBuffer.alloc(args[0])
712 : NodeBuffer.from(args[0], args[1], args[2]);
713 },
714 construct(_target, args, newTarget) {
715 if (newTarget !== __bufferCallable)
716 return Reflect.construct(NodeBuffer, args, newTarget);
717 return typeof args[0] === "number"
718 ? NodeBuffer.alloc(args[0])
719 : NodeBuffer.from(args[0], args[1], args[2]);
720 },
721 });
722 // node:buffer module surface beyond the class itself (Node values).
723 function SlowBuffer(size) { return NodeBuffer.alloc(size); }
724 SlowBuffer.prototype = NodeBuffer.prototype;
725 const __asBytes = (input) => {
726 if (input instanceof ArrayBuffer || (typeof SharedArrayBuffer !==
727 "undefined" && input instanceof SharedArrayBuffer))
728 return new Uint8Array(input);
729 if (ArrayBuffer.isView(input))
730 return new Uint8Array(input.buffer, input.byteOffset,
731 input.byteLength);
732 throw __bufType("input",
733 "an instance of ArrayBuffer or ArrayBufferView", input);
734 };
735 globalThis.__buffer = {
736 Buffer: __bufferCallable,
737 SlowBuffer,
738 INSPECT_MAX_BYTES: 50,
739 kMaxLength: __kMaxLength,
740 kStringMaxLength: __kStringMaxLength,
741 constants: {
742 MAX_LENGTH: __kMaxLength,
743 MAX_STRING_LENGTH: __kStringMaxLength,
744 },
745 isAscii: (input) => __asBytes(input).every((b) => b < 0x80),
746 isUtf8: (input) => {
747 const bytes = __asBytes(input); // type errors must escape the try
748 try {
749 new TextDecoder("utf-8", { fatal: true }).decode(bytes);
750 return true;
751 } catch {
752 return false;
753 }
754 },
755 // ascii/latin1/utf16le/utf8 only; unrepresentable characters become
756 // '?', like Node's ICU-backed transcode. The 128 MiB cap mirrors
757 // Workerd's isolate external-memory limit.
758 transcode(source, fromEnc, toEnc) {
759 const src = __u8(source);
760 if (!src) throw __bufType("source",
761 "an instance of Buffer or Uint8Array", source);
762 const from = __normEnc(fromEnc);
763 const to = __normEnc(toEnc);
764 const ok = ["ascii", "latin1", "utf8", "utf16le"];
765 if (!from || !ok.includes(from)) throw __badEnc(fromEnc);
766 if (!to || !ok.includes(to)) throw __badEnc(toEnc);
767 if (src.length >= 134217728)
768 throw new RangeError("Cannot transcode a buffer this large");
769 if (from === "utf16le" && src.length % 2 !== 0)
770 throw __bufErr(RangeError, "ERR_INVALID_ARG_VALUE",
771 "Unable to transcode buffer");
772 let s;
773 if (from === "utf8" && to === "utf16le") {
774 try {
775 s = new TextDecoder("utf-8", { fatal: true }).decode(src);
776 } catch {
777 throw new TypeError("Unable to transcode buffer");
778 }
779 } else if (from === "utf8") {
780 s = new TextDecoder().decode(src); // replacement characters
781 } else {
782 s = __decodeStr(src, from);
783 }
784 if (to === "ascii" || to === "latin1") {
785 const max = to === "ascii" ? 0x7f : 0xff;
786 s = Array.from(s,
787 (c) => c.charCodeAt(0) > max ? "?" : c).join("");
788 }
789 return new NodeBuffer(__encodeStr(s, to));
790 },
791 Blob: globalThis.Blob,
792 File: globalThis.File,
793 atob: globalThis.atob,
794 btoa: globalThis.btoa,
795 };
796})();
797// Completion value for the lazy-global getter.
798({ Buffer: globalThis.__buffer.Buffer });