@orkestrel/sea 0.0.13 → 0.0.15

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.
@@ -7,19 +7,28 @@ import { Emitter } from "@orkestrel/emitter";
7
7
  import { getAssetKeys, getRawAsset, isSea } from "node:sea";
8
8
  import { isArrayBuffer } from "@orkestrel/contract";
9
9
  //#region src/server/constants.ts
10
- /** SEA sentinel fuse value embedded in the Node.js binary */
10
+ /**
11
+ * Holds the SEA sentinel fuse value embedded in the Node.js binary,
12
+ * `NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2`.
13
+ */
11
14
  var SEA_SENTINEL_FUSE = "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2";
12
- /** Resource name for the SEA blob in the executable */
15
+ /** Names the SEA blob resource in the executable, `NODE_SEA_BLOB`. */
13
16
  var SEA_BLOB_RESOURCE = "NODE_SEA_BLOB";
14
- /** Default Brotli compression quality level (maximum) */
17
+ /** Holds the default Brotli compression quality level, 11, the maximum Brotli accepts. */
15
18
  var DEFAULT_SEA_COMPRESSION_QUALITY = 11;
16
- /** Windows PE subsystem value: GUI application (no terminal window) */
19
+ /**
20
+ * Holds the Windows PE subsystem value for a GUI application, 2, which launches
21
+ * without a terminal window.
22
+ */
17
23
  var WINDOWS_SUBSYSTEM_GUI = 2;
18
- /** Windows PE subsystem value: console application */
24
+ /** Holds the Windows PE subsystem value for a console application, 3. */
19
25
  var WINDOWS_SUBSYSTEM_CONSOLE = 3;
20
- /** File extension indicating Brotli compression */
26
+ /** Names the file extension indicating Brotli compression, `.br`. */
21
27
  var BROTLI_EXTENSION = ".br";
22
- /** File extensions that should NOT be Brotli-compressed */
28
+ /**
29
+ * Lists the file extensions Brotli compression skips, the already-compressed
30
+ * archive, image, font, and media formats.
31
+ */
23
32
  var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
24
33
  ".br",
25
34
  ".gz",
@@ -43,51 +52,67 @@ var SKIP_EXTENSIONS = /* @__PURE__ */ new Set([
43
52
  ".zip",
44
53
  ".tar"
45
54
  ]);
46
- /** Default SEA entry point module format when none is specified */
55
+ /** Names the default SEA entry point module format when none is specified, `cjs`. */
47
56
  var DEFAULT_ENTRY_FORMAT = "cjs";
48
- /** Asset key for the raw (uncompressed) client HTML entry */
49
- var CLIENT_ASSET_KEY_RAW = "client.html";
50
- /** Asset key for the Brotli-compressed client HTML entry */
51
- var CLIENT_ASSET_KEY_BR = "client.html.br";
52
- /** DOS MZ header magic (first 2 bytes of a PE file) */
57
+ /** Holds the DOS MZ header magic, 0x5a4d, the first two bytes of a PE file. */
53
58
  var PE_MAGIC = 23117;
54
- /** PE signature: "PE\0\0" as a 32-bit value */
59
+ /** Holds the PE signature, 0x00004550, the bytes `PE\0\0` read as a 32-bit value. */
55
60
  var PE_SIGNATURE = 17744;
56
- /** PE32 optional header magic */
61
+ /** Holds the PE32 optional header magic, 0x10b. */
57
62
  var PE32_MAGIC = 267;
58
- /** PE32+ (64-bit) optional header magic */
63
+ /** Holds the PE32+ optional header magic, 0x20b, the 64-bit form. */
59
64
  var PE32_PLUS_MAGIC = 523;
60
- /** ELF magic: 0x7F 'E' 'L' 'F' as a 32-bit big-endian value */
65
+ /**
66
+ * Holds the ELF magic, 0x7f454c46, the bytes 0x7F `E` `L` `F` read as a 32-bit
67
+ * big-endian value.
68
+ */
61
69
  var ELF_MAGIC = 2135247942;
62
- /** ELF 64-bit class identifier */
70
+ /** Holds the ELF 64-bit class identifier, 2. */
63
71
  var ELF_CLASS_64 = 2;
64
- /** ELF little-endian data encoding */
72
+ /** Holds the ELF little-endian data encoding, 1. */
65
73
  var ELF_DATA_LSB = 1;
66
- /** ELF program header type: note segment */
74
+ /** Holds the ELF program header type for a note segment, 4. */
67
75
  var ELF_PT_NOTE = 4;
68
- /** Mach-O 64-bit magic (little-endian) */
76
+ /** Holds the ELF program header type for a loadable segment, 1. */
77
+ var ELF_PT_LOAD = 1;
78
+ /** Holds the ELF program header type for the program header table itself, 6. */
79
+ var ELF_PT_PHDR = 6;
80
+ /** Holds the ELF segment permission flag marking a segment readable, 4. */
81
+ var ELF_PF_R = 4;
82
+ /** Holds the page size an injected ELF segment is aligned to, 0x1000. */
83
+ var ELF_PAGE_SIZE = 4096;
84
+ /** Holds the Mach-O 64-bit magic, 0xfeedfacf, in little-endian byte order. */
69
85
  var MACHO_MAGIC_64 = 4277009103;
70
- /** Mach-O LC_SEGMENT_64 load command */
86
+ /** Holds the Mach-O `LC_SEGMENT_64` load command, 0x19. */
71
87
  var MACHO_LC_SEGMENT_64 = 25;
72
- /** PE resource type: RT_RCDATA (raw data) */
88
+ /** Holds the PE resource type `RT_RCDATA` for raw data, 10. */
73
89
  var PE_RT_RCDATA = 10;
74
- /** Size of IMAGE_RESOURCE_DIRECTORY in bytes */
90
+ /** Holds the size of `IMAGE_RESOURCE_DIRECTORY` in bytes, 16. */
75
91
  var PE_RESOURCE_DIR_SIZE = 16;
76
- /** Size of IMAGE_RESOURCE_DIRECTORY_ENTRY in bytes */
92
+ /** Holds the size of `IMAGE_RESOURCE_DIRECTORY_ENTRY` in bytes, 8. */
77
93
  var PE_RESOURCE_ENTRY_SIZE = 8;
78
- /** Size of IMAGE_RESOURCE_DATA_ENTRY in bytes */
94
+ /** Holds the size of `IMAGE_RESOURCE_DATA_ENTRY` in bytes, 16. */
79
95
  var PE_RESOURCE_DATA_ENTRY_SIZE = 16;
80
- /** PE section header size in bytes */
96
+ /** Holds the PE section header size in bytes, 40. */
81
97
  var PE_SECTION_HEADER_SIZE = 40;
82
- /** High bit mask for resource directory entry offset (indicates subdirectory) */
98
+ /**
99
+ * Holds the high bit mask marking a resource directory entry offset as a
100
+ * subdirectory, 0x80000000.
101
+ */
83
102
  var PE_RESOURCE_SUBDIR_FLAG = 2147483648;
84
- /** High bit mask for resource name entry (indicates named vs integer ID) */
103
+ /**
104
+ * Holds the high bit mask marking a resource entry as named rather than
105
+ * integer-identified, 0x80000000.
106
+ */
85
107
  var PE_RESOURCE_NAME_FLAG = 2147483648;
86
- /** Section contains initialized data */
108
+ /** Marks a section as containing initialized data, 0x00000040. */
87
109
  var PE_SCN_INITIALIZED_DATA = 64;
88
- /** Section is readable */
110
+ /** Marks a section as readable, 0x40000000. */
89
111
  var PE_SCN_MEM_READ = 1073741824;
90
- /** Platform-specific SEA build configurations */
112
+ /**
113
+ * Holds the platform-specific SEA build configurations, keyed by
114
+ * `process.platform` for `win32`, `darwin`, and `linux`.
115
+ */
91
116
  var SEA_PLATFORMS = Object.freeze({
92
117
  win32: Object.freeze({
93
118
  executable: "node.exe",
@@ -113,7 +138,10 @@ var SEA_PLATFORMS = Object.freeze({
113
138
  }),
114
139
  linux: Object.freeze({ executable: "node" })
115
140
  });
116
- /** Maps a {@link SEACompressionMode} to its numeric Brotli mode value */
141
+ /**
142
+ * Maps a {@link SEACompressionMode} to its numeric Brotli mode value: `generic`
143
+ * to 0, `text` to 1, and `font` to 2.
144
+ */
117
145
  var SEA_COMPRESSION_MODE_VALUES = Object.freeze({
118
146
  generic: 0,
119
147
  text: 1,
@@ -122,7 +150,7 @@ var SEA_COMPRESSION_MODE_VALUES = Object.freeze({
122
150
  //#endregion
123
151
  //#region src/server/errors.ts
124
152
  /**
125
- * The coded base error for every failure raised by the seal build.
153
+ * Represents the coded base error for every failure raised by the SEA build.
126
154
  *
127
155
  * @remarks
128
156
  * Carries a machine-readable {@link SEAErrorCode} and optional `context`
@@ -131,7 +159,7 @@ var SEA_COMPRESSION_MODE_VALUES = Object.freeze({
131
159
  * @example
132
160
  * ```ts
133
161
  * try {
134
- * seal.execute()
162
+ * sea.execute()
135
163
  * } catch (error) {
136
164
  * if (isSEAError(error)) {
137
165
  * console.error(error.code, error.context)
@@ -150,10 +178,10 @@ var SEAError = class extends Error {
150
178
  }
151
179
  };
152
180
  /**
153
- * Whether a value is a {@link SEAError}.
181
+ * Checks whether a value is a {@link SEAError}.
154
182
  *
155
183
  * @param value - The value to test
156
- * @returns `true` when `value` is a `SEAError`
184
+ * @returns True if `value` is a `SEAError`; false otherwise
157
185
  *
158
186
  * @example
159
187
  * ```ts
@@ -166,7 +194,7 @@ function isSEAError(value) {
166
194
  return value instanceof SEAError;
167
195
  }
168
196
  /**
169
- * An error thrown when a shell command run via `runShell` exits non-zero.
197
+ * Represents an error thrown when a shell command executed through `executeShell` exits non-zero.
170
198
  *
171
199
  * @remarks
172
200
  * Carries the captured `stdout` and `stderr` buffers from the failed process.
@@ -176,7 +204,7 @@ function isSEAError(value) {
176
204
  * @example
177
205
  * ```ts
178
206
  * try {
179
- * runShell(['codesign', '--sign', '-', path])
207
+ * executeShell(['codesign', '--sign', '-', path])
180
208
  * } catch (error) {
181
209
  * if (isShellError(error)) {
182
210
  * console.error(error.stderr.toString())
@@ -195,10 +223,10 @@ var ShellError = class extends SEAError {
195
223
  }
196
224
  };
197
225
  /**
198
- * Whether a value is a {@link ShellError}.
226
+ * Checks whether a value is a {@link ShellError}.
199
227
  *
200
228
  * @param value - The value to test
201
- * @returns `true` when `value` is a `ShellError`
229
+ * @returns True if `value` is a `ShellError`; false otherwise
202
230
  *
203
231
  * @example
204
232
  * ```ts
@@ -211,56 +239,67 @@ function isShellError(value) {
211
239
  return value instanceof ShellError;
212
240
  }
213
241
  //#endregion
214
- //#region src/server/helpers.ts
242
+ //#region src/server/validators.ts
215
243
  /**
216
- * Check if a value is a valid {@link ExecutableFormat}.
244
+ * Checks whether a value is a valid {@link ExecutableFormat}.
217
245
  *
218
246
  * @param value - Value to check
219
- * @returns True when value is `'pe'`, `'elf'`, or `'macho'`
247
+ * @returns True if value is `'pe'`, `'elf'`, or `'macho'`; false otherwise
248
+ *
249
+ * @example
250
+ * ```ts
251
+ * isExecutableFormat('elf') // true
252
+ * isExecutableFormat('coff') // false
253
+ * ```
220
254
  */
221
255
  function isExecutableFormat(value) {
222
256
  return value === "pe" || value === "elf" || value === "macho";
223
257
  }
258
+ //#endregion
259
+ //#region src/server/helpers.ts
224
260
  /**
225
- * Get the platform configuration for the current OS.
261
+ * Resolves the effective platform configuration.
226
262
  *
227
263
  * @param platform - Platform identifier. Default: `process.platform`.
228
264
  * @returns Platform configuration, or undefined if unsupported
229
265
  */
230
- function platformConfig(platform) {
266
+ function resolvePlatform(platform) {
231
267
  return SEA_PLATFORMS[platform ?? process.platform];
232
268
  }
233
269
  /**
234
- * Check if the current or specified platform is supported for SEA builds.
270
+ * Checks whether the current or named platform is supported for SEA builds.
235
271
  *
236
272
  * @param platform - Platform identifier to check
237
- * @returns True when the platform has a known configuration
273
+ * @returns True if the platform has a known configuration; false otherwise
238
274
  */
239
275
  function isPlatformSupported(platform) {
240
276
  return (platform ?? process.platform) in SEA_PLATFORMS;
241
277
  }
242
278
  /**
243
- * Assert that a path exists, throwing a coded {@link SEAError} if not.
279
+ * Asserts that a path exists, throwing a coded {@link SEAError} if not.
244
280
  *
245
281
  * @param path - Absolute or relative path to check
246
282
  * @param message - Error message when path is missing
247
283
  * @param code - Error code to throw with. Default: `'STATE'`.
284
+ * @throws SEAError with `code` (default `'STATE'`) when `path` does not exist
248
285
  */
249
286
  function ensureExists(path, message, code) {
250
287
  if (!existsSync(path)) throw new SEAError(code ?? "STATE", message, { path });
251
288
  }
252
289
  /**
253
- * Check if a file should be Brotli-compressed based on its extension.
290
+ * Checks whether a file's extension is outside `SKIP_EXTENSIONS`, so Brotli
291
+ * compression applies to it.
254
292
  *
255
293
  * @param path - Path to the file
256
- * @returns True when the file type benefits from compression
294
+ * @returns True if the file type benefits from compression; false otherwise
257
295
  */
258
296
  function isCompressible(path) {
259
297
  const ext = extname(path).toLowerCase();
260
298
  return !SKIP_EXTENSIONS.has(ext);
261
299
  }
262
300
  /**
263
- * Recursively walk a directory and return all file paths.
301
+ * Walks a directory recursively and returns every file path it finds, relative to
302
+ * the base and skipping symlinks.
264
303
  *
265
304
  * @param directory - Directory to walk
266
305
  * @param base - Base directory for relative path calculation
@@ -280,7 +319,8 @@ function walkDirectory(directory, base) {
280
319
  return result;
281
320
  }
282
321
  /**
283
- * Redact password arguments from a shell command.
322
+ * Redacts password arguments from a shell command, so the command is safe to
323
+ * include in an error message.
284
324
  *
285
325
  * @param command - Command arguments to redact
286
326
  * @returns A copy with values following password flags replaced by a marker
@@ -298,7 +338,7 @@ function redactCommand(command) {
298
338
  });
299
339
  }
300
340
  /**
301
- * Run a command synchronously and return stdout.
341
+ * Executes a command synchronously and returns stdout.
302
342
  *
303
343
  * @param command - Command to execute (first element is the binary)
304
344
  * @param options - Shell options (cwd, env, timeout, signal)
@@ -308,7 +348,7 @@ function redactCommand(command) {
308
348
  * @throws SEAError with code `'TIMEOUT'` when the command exceeds `options.timeout`
309
349
  * @throws ShellError when the command exits with non-zero status
310
350
  */
311
- function runShell(command, options) {
351
+ function executeShell(command, options) {
312
352
  const [cmd, ...args] = command;
313
353
  if (cmd === void 0) throw new SEAError("STATE", "Command array must not be empty");
314
354
  if (options?.signal?.aborted === true) throw new SEAError("ABORT", "Shell command aborted", { command: redactCommand(command) });
@@ -329,7 +369,7 @@ function runShell(command, options) {
329
369
  return Buffer.from(result.stdout, "utf-8");
330
370
  }
331
371
  /**
332
- * Compute a size comparison between original and compressed byte counts.
372
+ * Computes a size comparison between original and compressed byte counts.
333
373
  *
334
374
  * @param original - Original byte count
335
375
  * @param compressed - Compressed byte count
@@ -343,12 +383,13 @@ function computeSize(original, compressed) {
343
383
  };
344
384
  }
345
385
  /**
346
- * Brotli-compress a single file, writing the output alongside it.
386
+ * Brotli-compresses a single file, writing the output alongside it.
347
387
  *
348
388
  * @param input - Absolute path to the source file
349
389
  * @param output - Absolute path for the compressed output
350
- * @param options - Compression options (quality, mode)
390
+ * @param options - Brotli options (quality, mode)
351
391
  * @returns Compression result with size comparison
392
+ * @throws SEAError with code `'OUTPUT'` when `output` is an existing symlink
352
393
  */
353
394
  function compressFile(input, output, options) {
354
395
  const quality = options?.quality ?? 11;
@@ -373,10 +414,10 @@ function compressFile(input, output, options) {
373
414
  };
374
415
  }
375
416
  /**
376
- * Compress all compressible files in a directory tree.
417
+ * Compresses all compressible files in a directory tree.
377
418
  *
378
419
  * @param directory - Absolute path to the directory
379
- * @param options - Compression options
420
+ * @param options - Brotli options (quality, mode)
380
421
  * @param progress - Optional callback invoked after each file is compressed
381
422
  * @returns Compression manifest with all results
382
423
  */
@@ -400,39 +441,218 @@ function compressDirectory(directory, options, progress) {
400
441
  };
401
442
  }
402
443
  /**
403
- * Check whether a number is a nonzero power of two.
444
+ * Rounds a value up to the next multiple of an alignment boundary.
445
+ *
446
+ * @remarks
447
+ * The shared alignment leaf behind every binary-format writer in this package:
448
+ * PE section and file alignment, ELF note and page alignment, and Mach-O page
449
+ * alignment all round the same way. `alignment` must be a nonzero power of two
450
+ * ({@link isPowerOfTwo} is the guard the PE injector applies before using a
451
+ * value read out of a header as a divisor).
452
+ *
453
+ * @param value - Value to align
454
+ * @param alignment - Alignment boundary to round up to
455
+ * @returns The value rounded up to the next multiple of `alignment`
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * alignTo(10, 4) // 12
460
+ * alignTo(4096, 4096) // 4096 — already aligned
461
+ * ```
462
+ */
463
+ function alignTo(value, alignment) {
464
+ const remainder = value % alignment;
465
+ return remainder === 0 ? value : value + (alignment - remainder);
466
+ }
467
+ /**
468
+ * Reads a 32-bit unsigned little-endian integer from a file descriptor.
469
+ *
470
+ * @param fd - Open file descriptor
471
+ * @param offset - Byte offset to read from
472
+ * @returns The 32-bit value
473
+ * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `offset`
474
+ *
475
+ * @example
476
+ * ```ts
477
+ * const fd = openSync('app.exe', 'r')
478
+ * readU32(fd, 0x3c) // the PE header offset
479
+ * ```
480
+ */
481
+ function readU32(fd, offset) {
482
+ const buf = Buffer.alloc(4);
483
+ const read = readSync(fd, buf, 0, 4, offset);
484
+ if (read < 4) throw new SEAError("FORMAT", "Short read", {
485
+ offset,
486
+ expected: 4,
487
+ read
488
+ });
489
+ return buf.readUInt32LE(0);
490
+ }
491
+ /**
492
+ * Reads a 64-bit unsigned little-endian integer from a file descriptor.
493
+ *
494
+ * @param fd - Open file descriptor
495
+ * @param offset - Byte offset to read from
496
+ * @returns The 64-bit value, as a `bigint`
497
+ * @throws SEAError with code `'FORMAT'` when fewer than eight bytes are readable at `offset`
498
+ *
499
+ * @example
500
+ * ```ts
501
+ * const fd = openSync('app', 'r')
502
+ * readU64(fd, 32) // the ELF program header table offset
503
+ * ```
504
+ */
505
+ function readU64(fd, offset) {
506
+ const buf = Buffer.alloc(8);
507
+ const read = readSync(fd, buf, 0, 8, offset);
508
+ if (read < 8) throw new SEAError("FORMAT", "Short read", {
509
+ offset,
510
+ expected: 8,
511
+ read
512
+ });
513
+ return buf.readBigUInt64LE(0);
514
+ }
515
+ /**
516
+ * Writes a 32-bit unsigned little-endian integer to a file descriptor.
517
+ *
518
+ * @remarks
519
+ * Coerces `value` with `>>> 0` before writing, so a negative or out-of-range
520
+ * number lands as its unsigned 32-bit representation rather than throwing.
521
+ *
522
+ * @param fd - Open file descriptor
523
+ * @param offset - Byte offset to write at
524
+ * @param value - The 32-bit value to write
525
+ *
526
+ * @example
527
+ * ```ts
528
+ * const fd = openSync('app.exe', 'r+')
529
+ * writeU32(fd, 0x3c, 0x100)
530
+ * ```
531
+ */
532
+ function writeU32(fd, offset, value) {
533
+ const buf = Buffer.alloc(4);
534
+ buf.writeUInt32LE(value >>> 0, 0);
535
+ writeSync(fd, buf, 0, 4, offset);
536
+ }
537
+ /**
538
+ * Writes a 64-bit unsigned little-endian integer to a file descriptor.
539
+ *
540
+ * @param fd - Open file descriptor
541
+ * @param offset - Byte offset to write at
542
+ * @param value - The 64-bit value to write
543
+ *
544
+ * @example
545
+ * ```ts
546
+ * const fd = openSync('app', 'r+')
547
+ * writeU64(fd, 32, 8192n)
548
+ * ```
549
+ */
550
+ function writeU64(fd, offset, value) {
551
+ const buf = Buffer.alloc(8);
552
+ buf.writeBigUInt64LE(value, 0);
553
+ writeSync(fd, buf, 0, 8, offset);
554
+ }
555
+ /**
556
+ * Appends a source file to a target file, streaming in fixed-size chunks.
557
+ *
558
+ * @remarks
559
+ * Reads `source` in `chunk`-sized reads and appends each chunk to `target`, so
560
+ * a multi-hundred-megabyte blob is never fully buffered. A read returning zero
561
+ * bytes ends the copy, which is the normal end-of-file signal for a source that
562
+ * shrank between the size read and the copy.
563
+ *
564
+ * @param target - Path of the file to append to
565
+ * @param source - Path of the file to append
566
+ * @param chunk - Read/append chunk size in bytes. Default: 4 MB.
567
+ *
568
+ * @example
569
+ * ```ts
570
+ * appendFile('dist/sea/app', 'dist/sea/sea-prep.blob')
571
+ * ```
572
+ */
573
+ function appendFile(target, source, chunk = 4194304) {
574
+ const fd = openSync(source, "r");
575
+ try {
576
+ const size = statSync(source).size;
577
+ const buffer = Buffer.alloc(Math.min(chunk, size));
578
+ let offset = 0;
579
+ while (offset < size) {
580
+ const toRead = Math.min(chunk, size - offset);
581
+ const bytesRead = readSync(fd, buffer, 0, toRead, offset);
582
+ if (bytesRead === 0) break;
583
+ appendFileSync(target, buffer.subarray(0, bytesRead));
584
+ offset += bytesRead;
585
+ }
586
+ } finally {
587
+ closeSync(fd);
588
+ }
589
+ }
590
+ /**
591
+ * Truncates a NUL-padded binary name field at its first NUL character.
592
+ *
593
+ * @remarks
594
+ * Binary name fields (PE section names, Mach-O segment and section names, ELF
595
+ * note names) are fixed-width and NUL-padded, so the decoded string carries
596
+ * trailing NUL characters that no comparison against a literal name matches.
597
+ *
598
+ * @param value - Decoded fixed-width name field
599
+ * @returns The value up to, but excluding, its first NUL character
600
+ *
601
+ * @example
602
+ * ```ts
603
+ * stripTrailingNulls('.rsrc\0\0\0') // '.rsrc'
604
+ * ```
605
+ */
606
+ function stripTrailingNulls(value) {
607
+ const index = value.indexOf("\0");
608
+ return index === -1 ? value : value.slice(0, index);
609
+ }
610
+ /**
611
+ * Checks whether a number is a nonzero power of two.
404
612
  *
405
613
  * @param value - Number to check
406
- * @returns True when the value is a positive power of two
614
+ * @returns True if the value is a positive power of two; false otherwise
407
615
  */
408
616
  function isPowerOfTwo(value) {
409
617
  return value > 0 && (value & value - 1) === 0;
410
618
  }
411
619
  /**
412
- * Parse the PE header offset from a Windows executable.
620
+ * Reads the PE header offset from a Windows executable.
413
621
  *
414
622
  * @param fd - Open file descriptor
415
623
  * @returns The offset to the PE signature
624
+ * @throws SEAError with code `'FORMAT'` when fewer than four bytes are readable at `0x3c`
416
625
  */
417
- function parsePEOffset(fd) {
626
+ function readPEOffset(fd) {
418
627
  const buf = Buffer.alloc(4);
419
- readSync(fd, buf, 0, 4, 60);
628
+ const read = readSync(fd, buf, 0, 4, 60);
629
+ if (read < 4) throw new SEAError("FORMAT", "Short read", {
630
+ offset: 60,
631
+ expected: 4,
632
+ read
633
+ });
420
634
  return buf.readUInt32LE(0);
421
635
  }
422
636
  /**
423
- * Read a 16-bit unsigned integer from a file descriptor.
637
+ * Reads a 16-bit unsigned integer from a file descriptor.
424
638
  *
425
639
  * @param fd - Open file descriptor
426
640
  * @param offset - Byte offset to read from
427
641
  * @returns The 16-bit value
642
+ * @throws SEAError with code `'FORMAT'` when fewer than two bytes are readable at `offset`
428
643
  */
429
644
  function readU16(fd, offset) {
430
645
  const buf = Buffer.alloc(2);
431
- readSync(fd, buf, 0, 2, offset);
646
+ const read = readSync(fd, buf, 0, 2, offset);
647
+ if (read < 2) throw new SEAError("FORMAT", "Short read", {
648
+ offset,
649
+ expected: 2,
650
+ read
651
+ });
432
652
  return buf.readUInt16LE(0);
433
653
  }
434
654
  /**
435
- * Write a 16-bit unsigned integer to a file descriptor.
655
+ * Writes a 16-bit unsigned integer to a file descriptor.
436
656
  *
437
657
  * @param fd - Open file descriptor
438
658
  * @param offset - Byte offset to write at
@@ -444,16 +664,16 @@ function writeU16(fd, offset, value) {
444
664
  writeSync(fd, buf, 0, 2, offset);
445
665
  }
446
666
  /**
447
- * Check if a file is a Windows PE executable.
667
+ * Checks whether a file is a Windows PE executable.
448
668
  *
449
669
  * @param path - Path to the file
450
- * @returns True when the file has a valid PE signature
670
+ * @returns True if the file has a valid PE signature; false otherwise
451
671
  */
452
672
  function isPEExecutable(path) {
453
673
  let fd;
454
674
  try {
455
675
  fd = openSync(path, "r");
456
- const peOffset = parsePEOffset(fd);
676
+ const peOffset = readPEOffset(fd);
457
677
  const sig = Buffer.alloc(4);
458
678
  readSync(fd, sig, 0, 4, peOffset);
459
679
  return sig.toString("ascii") === "PE\0\0";
@@ -464,7 +684,7 @@ function isPEExecutable(path) {
464
684
  }
465
685
  }
466
686
  /**
467
- * Patch the PE subsystem field in a Windows executable.
687
+ * Patches the PE subsystem field in a Windows executable.
468
688
  *
469
689
  * @param path - Path to the executable
470
690
  * @param subsystem - Numeric subsystem value (2 = GUI, 3 = Console)
@@ -472,30 +692,30 @@ function isPEExecutable(path) {
472
692
  function patchPESubsystem(path, subsystem) {
473
693
  const fd = openSync(path, "r+");
474
694
  try {
475
- writeU16(fd, parsePEOffset(fd) + 92, subsystem);
695
+ writeU16(fd, readPEOffset(fd) + 92, subsystem);
476
696
  } finally {
477
697
  closeSync(fd);
478
698
  }
479
699
  }
480
700
  /**
481
- * Remove the Authenticode signature from a PE executable by zeroing
701
+ * Removes the Authenticode signature from a PE executable by zeroing
482
702
  * the security directory entry in the optional header.
483
703
  *
484
704
  * @remarks
485
705
  * If the certificate overlay described by the security directory sits at the
486
706
  * very end of the file (the common case for `signtool`-signed binaries), the
487
- * file is truncated to the certificate's start FIRST so the overlay bytes are
707
+ * file is truncated to the certificate's start first so the overlay bytes are
488
708
  * discarded rather than left as dead weight for a downstream injector to
489
709
  * bury mid-file. The directory read is bounds-checked so a malformed or
490
- * truncated security directory cannot throw unexpectedly — it is simply
491
- * skipped and only the directory entry is zeroed.
710
+ * truncated security directory cannot throw unexpectedly — it is skipped
711
+ * and only the directory entry is zeroed.
492
712
  *
493
713
  * @param path - Path to the executable
494
714
  */
495
715
  function stripPESignature(path) {
496
716
  const fd = openSync(path, "r+");
497
717
  try {
498
- const peOffset = parsePEOffset(fd);
718
+ const peOffset = readPEOffset(fd);
499
719
  const securityDirOffset = readU16(fd, peOffset + 24) === 523 ? peOffset + 168 : peOffset + 152;
500
720
  const dirBuf = Buffer.alloc(8);
501
721
  if (readSync(fd, dirBuf, 0, 8, securityDirOffset) === 8) {
@@ -513,21 +733,21 @@ function stripPESignature(path) {
513
733
  }
514
734
  }
515
735
  /**
516
- * Build the `signtool sign` argv for signing a Windows executable.
736
+ * Builds the `signtool sign` argv for signing a Windows executable.
517
737
  *
518
738
  * @remarks
519
- * Requires EXACTLY ONE certificate source — `sign.file` (a `.pfx`/`.p12`
739
+ * Requires exactly one certificate source — `sign.file` (a `.pfx`/`.p12`
520
740
  * file, paired with `sign.password` when present) XOR `sign.thumbprint` (a
521
741
  * certificate already installed in the Windows store). When `sign.timestamp`
522
742
  * is set it is parsed with the `URL` constructor and must be an `http:` or
523
- * `https:` URL. The returned argv is passed directly to `runShell` — never
743
+ * `https:` URL. The returned argv is passed directly to `executeShell` — never
524
744
  * through a shell — so nothing in `sign` can be interpreted as a flag or
525
- * injected into a command line. `sign.password` is NEVER included in a
745
+ * injected into a command line. `sign.password` is never included in a
526
746
  * thrown error's message or `context`.
527
747
  *
528
748
  * @param sign - Windows signing options
529
749
  * @param target - Absolute path to the executable to sign
530
- * @returns The `signtool` argv, ready for `runShell`
750
+ * @returns The `signtool` argv, ready for `executeShell`
531
751
  * @throws SEAError with code `'SIGN'` when neither `file` nor `thumbprint` is set
532
752
  * @throws SEAError with code `'SIGN'` when both `file` and `thumbprint` are set
533
753
  * @throws SEAError with code `'SIGN'` when `timestamp` is not a parseable http(s) URL
@@ -535,11 +755,11 @@ function stripPESignature(path) {
535
755
  *
536
756
  * @example
537
757
  * ```ts
538
- * createSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')
758
+ * buildSignCommand({ thumbprint: 'AABBCCDDEEFF00112233445566778899AABBCCDD' }, 'dist/sea/app.exe')
539
759
  * // ['signtool', 'sign', '/fd', 'sha256', '/sha1', 'AABBCCDDEEFF00112233445566778899AABBCCDD', 'dist/sea/app.exe']
540
760
  * ```
541
761
  */
542
- function createSignCommand(sign, target) {
762
+ function buildSignCommand(sign, target) {
543
763
  const hasFile = sign.file !== void 0;
544
764
  const hasThumbprint = sign.thumbprint !== void 0;
545
765
  if (!hasFile && !hasThumbprint) throw new SEAError("SIGN", "Windows signing requires exactly one of sign.file or sign.thumbprint");
@@ -581,10 +801,10 @@ function createSignCommand(sign, target) {
581
801
  ];
582
802
  }
583
803
  /**
584
- * Format a byte count as a human-readable string.
804
+ * Formats a byte count as a human-readable string.
585
805
  *
586
806
  * @param bytes - Byte count
587
- * @returns Formatted string (e.g. `"1.23 MB"`, `"456 KB"`)
807
+ * @returns Formatted string (for example `"1.23 MB"`, `"456 KB"`)
588
808
  */
589
809
  function formatSize(bytes) {
590
810
  if (bytes < 1024) return `${String(bytes)} B`;
@@ -592,11 +812,11 @@ function formatSize(bytes) {
592
812
  return `${(bytes / 1048576).toFixed(2)} MB`;
593
813
  }
594
814
  /**
595
- * Assert that an asset key is safe to use as a relative filesystem/archive key.
815
+ * Asserts that an asset key is safe to use as a relative filesystem/archive key.
596
816
  *
597
817
  * @remarks
598
818
  * Rejects an empty key, an absolute path, a key containing a backslash, a
599
- * Windows drive-relative specifier (e.g. `'C:foo'`), or any `/`-separated
819
+ * Windows drive-relative specifier (for example `'C:foo'`), or any `/`-separated
600
820
  * segment equal to `'..'` — all of which could escape the intended asset root.
601
821
  *
602
822
  * @param key - Asset key to validate
@@ -617,17 +837,17 @@ function ensureSafeKey(key) {
617
837
  if (key.split("/").includes("..")) throw new SEAError("ASSET", "Asset key must not contain a \"..\" segment", { key });
618
838
  }
619
839
  /**
620
- * Assert that `path` (resolved against `base`) real-path-resolves to a
840
+ * Asserts that `path` (resolved against `base`) real-path-resolves to a
621
841
  * location inside `base`, defeating a symlink escape.
622
842
  *
623
843
  * @remarks
624
844
  * Resolves `path` against `base`, then dereferences both the resolved path
625
845
  * and `base` with `realpathSync` and requires the real resolved path to
626
846
  * equal the real base or begin with the real base plus a path separator.
627
- * Dereferencing BOTH sides means a symlinked base itself (e.g. macOS `/tmp`
847
+ * Dereferencing both sides means a symlinked base itself (for example macOS `/tmp`
628
848
  * -> `/private/tmp`) still matches, while a symlink inside the tree that
629
849
  * points outside the real base is correctly rejected. A `realpathSync`
630
- * failure (e.g. `ENOENT`) is wrapped as a coded `SEAError` rather than
850
+ * failure (for example `ENOENT`) is wrapped as a coded `SEAError` rather than
631
851
  * leaking the raw Node error.
632
852
  *
633
853
  * @param base - Absolute path to the containing root
@@ -662,13 +882,13 @@ function ensureContained(base, path) {
662
882
  return real;
663
883
  }
664
884
  /**
665
- * Assert that `name` is a single safe path segment suitable as an output
885
+ * Asserts that `name` is a single safe path segment suitable as an output
666
886
  * executable base name.
667
887
  *
668
888
  * @remarks
669
889
  * Rejects an empty name, `'.'`, `'..'`, a name containing a `/` or `\`
670
- * separator, an absolute path, or a Windows drive-relative specifier (e.g.
671
- * `'C:foo'`) — all of which could redirect the output executable outside
890
+ * separator, an absolute path, or a Windows drive-relative specifier (for
891
+ * example `'C:foo'`) — all of which could redirect the output executable outside
672
892
  * the intended output directory.
673
893
  *
674
894
  * @param name - Output executable base name to validate
@@ -687,17 +907,17 @@ function ensureSafeName(name) {
687
907
  if (/^[A-Za-z]:/.test(name)) throw new SEAError("ASSET", "Executable name must not be a drive-relative specifier", { name });
688
908
  }
689
909
  /**
690
- * Fsync a directory to durably persist a prior file rename/create within it.
910
+ * Fsyncs a directory to durably persist a prior file rename/create within it.
691
911
  *
692
912
  * @remarks
693
- * A `rename`/`create` is only durable once its CONTAINING directory entry is
913
+ * A `rename`/`create` is only durable once its containing directory entry is
694
914
  * flushed — fsyncing the file itself is not enough. `path` is the directory
695
915
  * to fsync (callers pass `dirname(target)`, not the file itself). On Windows
696
916
  * there is no directory file handle to fsync, so this is a no-op there (the
697
917
  * platform lacks the primitive, not a failure). Some filesystems/platforms
698
918
  * return a benign errno for a directory fsync attempt (`EINVAL`, `ENOTSUP`,
699
919
  * `EISDIR`, `EPERM`, `EACCES`) — those are treated as "fsync unsupported
700
- * here" and swallowed; anything else (e.g. `ENOENT`, meaning the directory
920
+ * here" and swallowed; anything else (for example `ENOENT`, meaning the directory
701
921
  * itself is missing) is a genuine failure and is thrown as a coded `SEAError`.
702
922
  *
703
923
  * @param path - Directory path to fsync
@@ -728,7 +948,7 @@ function syncDirectory(path) {
728
948
  }
729
949
  }
730
950
  /**
731
- * Finalize a built executable by durably flushing it to disk and atomically
951
+ * Finalizes a built executable by durably flushing it to disk and atomically
732
952
  * moving it into place.
733
953
  *
734
954
  * @remarks
@@ -766,12 +986,12 @@ function finalizeExecutable(source, target) {
766
986
  syncDirectory(dirname(target));
767
987
  }
768
988
  /**
769
- * Build the Node.js `--experimental-sea-config` JSON object for a SEA blob.
989
+ * Builds the Node.js `--experimental-sea-config` JSON object for a SEA blob.
770
990
  *
771
991
  * @remarks
772
992
  * A pure leaf extracted from the SEA build orchestrator. The `mainFormat`
773
993
  * field (`'commonjs' | 'module'`) exists only in Node >= 25.7 — for a `'cjs'`
774
- * entry (the default) `mainFormat` is OMITTED entirely so the config still
994
+ * entry (the default) `mainFormat` is omitted entirely so the config still
775
995
  * builds on older Node hosts where `'commonjs'` is already the implicit
776
996
  * default; for an `'esm'` entry `mainFormat: 'module'` is set explicitly
777
997
  * (this requires a Node >= 25.7 build host). Node also documents that
@@ -786,10 +1006,10 @@ function finalizeExecutable(source, target) {
786
1006
  *
787
1007
  * @example
788
1008
  * ```ts
789
- * const config = createBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)
1009
+ * const config = buildBlobConfig({ path: 'dist/bin/serve.cjs' }, 'dist/bin/sea-prep.blob', undefined)
790
1010
  * ```
791
1011
  */
792
- function createBlobConfig(entry, blob, assets, options) {
1012
+ function buildBlobConfig(entry, blob, assets, options) {
793
1013
  const format = entry.format ?? "cjs";
794
1014
  const snapshot = options?.snapshot ?? false;
795
1015
  if (format === "esm" && snapshot) throw new SEAError("BLOB", "useSnapshot cannot be combined with an ESM entry (mainFormat module)");
@@ -804,17 +1024,16 @@ function createBlobConfig(entry, blob, assets, options) {
804
1024
  };
805
1025
  }
806
1026
  /**
807
- * Align an ELF note component size to its four-byte boundary.
1027
+ * Aligns an ELF note component size to its four-byte boundary.
808
1028
  *
809
1029
  * @param value - Component size to align
810
1030
  * @returns The value rounded up to the next multiple of four
811
1031
  */
812
1032
  function alignELFNoteSize(value) {
813
- const remainder = value % 4;
814
- return remainder === 0 ? value : value + (4 - remainder);
1033
+ return alignTo(value, 4);
815
1034
  }
816
1035
  /**
817
- * Build an ELF `PT_NOTE` entry's header bytes (namesz/descsz/type + padded
1036
+ * Builds an ELF `PT_NOTE` entry's header bytes (namesz/descsz/type + padded
818
1037
  * name) for the SEA blob note, without the blob body itself.
819
1038
  *
820
1039
  * @remarks
@@ -827,13 +1046,13 @@ function alignELFNoteSize(value) {
827
1046
  * (`strncmp(name, "NODE_SEA", 8)`), so `resource` is written in full but
828
1047
  * only needs to begin with those 8 bytes to be found at runtime.
829
1048
  *
830
- * @param resource - Note name (SEA resource identifier, e.g. `NODE_SEA_BLOB`)
1049
+ * @param resource - Note name (SEA resource identifier, for example `NODE_SEA_BLOB`)
831
1050
  * @param blobSize - Size in bytes of the SEA blob that will follow the header
832
1051
  * @returns The note header bytes and the total on-disk size of header + blob
833
1052
  *
834
1053
  * @example
835
1054
  * ```ts
836
- * const { header, entryTotal } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)
1055
+ * const { header, total } = buildELFNoteHeader('NODE_SEA_BLOB', 4096)
837
1056
  * ```
838
1057
  */
839
1058
  function buildELFNoteHeader(resource, blobSize) {
@@ -847,11 +1066,11 @@ function buildELFNoteHeader(resource, blobSize) {
847
1066
  const alignedDescSize = alignELFNoteSize(blobSize);
848
1067
  return {
849
1068
  header,
850
- entryTotal: header.length + alignedDescSize
1069
+ total: header.length + alignedDescSize
851
1070
  };
852
1071
  }
853
1072
  /**
854
- * Copy a byte range from one open file descriptor to another, streaming in
1073
+ * Copies a byte range from one open file descriptor to another, streaming in
855
1074
  * fixed-size chunks instead of buffering the whole range in memory.
856
1075
  *
857
1076
  * @remarks
@@ -899,15 +1118,19 @@ function copyRange(source, target, start, length, chunk = 4194304) {
899
1118
  }
900
1119
  }
901
1120
  /**
902
- * Patch the sentinel fuse in a binary from `:0` to `:1`.
1121
+ * Patches the sentinel fuse in a binary from `:0` to `:1`.
903
1122
  *
904
- * Searches the file in 64 MB chunks with overlap to handle any file size.
905
- * The fuse signals to the Node.js runtime that a SEA blob is present.
906
- * This is normally handled by the Injector but is also available standalone
907
- * when using native PE resource injection.
1123
+ * @remarks
1124
+ * Searches the file in 64 MB chunks with overlap to handle any file size. The fuse
1125
+ * signals to the Node.js runtime that a SEA blob is present. The `Injector` class
1126
+ * normally applies this patch, and it stays available standalone for a build that
1127
+ * injects the PE resource natively instead.
908
1128
  *
909
1129
  * @param executable - Absolute path to the executable
910
1130
  * @param fuse - Sentinel fuse string (without the `:0` suffix)
1131
+ * @throws SEAError with code `'FUSE'` when the fuse value cannot be read
1132
+ * @throws SEAError with code `'FUSE'` when the fuse carries a value other than `:0` or `:1`
1133
+ * @throws SEAError with code `'FUSE'` when the fuse is not found in the executable
911
1134
  */
912
1135
  function patchSentinelFuse(executable, fuse) {
913
1136
  const fd = openSync(executable, "r+");
@@ -950,7 +1173,7 @@ function patchSentinelFuse(executable, fuse) {
950
1173
  }
951
1174
  }
952
1175
  /**
953
- * Launch the system default browser at an http(s) URL.
1176
+ * Launches the system default browser at an http(s) URL.
954
1177
  *
955
1178
  * @remarks
956
1179
  * A best-effort launch for bundled local-UI apps: dispatches by
@@ -962,7 +1185,7 @@ function patchSentinelFuse(executable, fuse) {
962
1185
  * outlives the host app and never keeps it alive, and it swallows the async
963
1186
  * host fault an absent opener binary raises. Only `http:` and `https:` URLs
964
1187
  * are accepted — any other scheme (including a string that merely looks like a
965
- * CLI flag, e.g. `'-e ...'`) fails to parse as an http(s) URL and is rejected
1188
+ * CLI flag, for example `'-e ...'`) fails to parse as an http(s) URL and is rejected
966
1189
  * before anything is spawned.
967
1190
  *
968
1191
  * @param url - Absolute http or https URL to open
@@ -999,6 +1222,32 @@ function openBrowser(url) {
999
1222
  }
1000
1223
  //#endregion
1001
1224
  //#region src/server/injectors/Injector.ts
1225
+ /**
1226
+ * Writes a named resource into a PE, ELF, or Mach-O executable in place.
1227
+ *
1228
+ * @remarks
1229
+ * The format is detected from the file's magic bytes at construction, and each
1230
+ * format takes its own strategy: PE adds an `RT_RCDATA` resource by rebuilding the
1231
+ * resource directory, ELF appends a `PT_NOTE` segment carrying the blob as note
1232
+ * data, and Mach-O appends an `LC_SEGMENT_64` load command with one section. The
1233
+ * blob is streamed from disk in every case, so its size is bounded by the
1234
+ * filesystem rather than by memory.
1235
+ *
1236
+ * @param options - Injector options: the target executable, the resource name, the
1237
+ * blob path, and the optional sentinel fuse and Mach-O segment
1238
+ *
1239
+ * @example
1240
+ * ```ts
1241
+ * const injector = new Injector({
1242
+ * executable: 'dist/sea/myapp.exe',
1243
+ * resource: 'NODE_SEA_BLOB',
1244
+ * blob: 'dist/sea/sea-prep.blob',
1245
+ * fuse: 'NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2',
1246
+ * })
1247
+ * injector.format // 'pe' | 'elf' | 'macho'
1248
+ * injector.inject()
1249
+ * ```
1250
+ */
1002
1251
  var Injector = class {
1003
1252
  #options;
1004
1253
  #format;
@@ -1013,12 +1262,12 @@ var Injector = class {
1013
1262
  let peOptionalOffset;
1014
1263
  switch (this.#format) {
1015
1264
  case "pe":
1016
- peOptionalOffset = this.#injectPe();
1265
+ peOptionalOffset = this.#injectPE();
1017
1266
  break;
1018
1267
  case "elf":
1019
- this.#injectElf();
1268
+ this.#injectELF();
1020
1269
  break;
1021
- case "macho": this.#injectMacho();
1270
+ case "macho": this.#injectMachO();
1022
1271
  }
1023
1272
  if (this.#options.fuse !== void 0) patchSentinelFuse(this.#options.executable, this.#options.fuse);
1024
1273
  if (peOptionalOffset !== void 0) this.#patchChecksum(peOptionalOffset);
@@ -1050,32 +1299,32 @@ var Injector = class {
1050
1299
  closeSync(fd);
1051
1300
  }
1052
1301
  }
1053
- #injectPe() {
1302
+ #injectPE() {
1054
1303
  const fd = openSync(this.#options.executable, "r+");
1055
1304
  try {
1056
- const peOffset = this.#readU32(fd, 60);
1057
- const sig = this.#readU32(fd, peOffset);
1305
+ const peOffset = readU32(fd, 60);
1306
+ const sig = readU32(fd, peOffset);
1058
1307
  if (sig !== 17744) throw new SEAError("FORMAT", "Invalid PE signature", {
1059
1308
  executable: this.#options.executable,
1060
1309
  signature: sig
1061
1310
  });
1062
1311
  const coffOffset = peOffset + 4;
1063
- const numberOfSections = this.#readU16(fd, coffOffset + 2);
1064
- const optionalHeaderSize = this.#readU16(fd, coffOffset + 16);
1312
+ const numberOfSections = readU16(fd, coffOffset + 2);
1313
+ const optionalHeaderSize = readU16(fd, coffOffset + 16);
1065
1314
  const optionalOffset = coffOffset + 20;
1066
- const optMagic = this.#readU16(fd, optionalOffset);
1315
+ const optMagic = readU16(fd, optionalOffset);
1067
1316
  const is64 = optMagic === 523;
1068
1317
  if (optMagic !== 267 && optMagic !== 523) throw new SEAError("FORMAT", `Unsupported PE optional header magic: 0x${optMagic.toString(16)}`, {
1069
1318
  executable: this.#options.executable,
1070
1319
  optionalHeaderMagic: optMagic
1071
1320
  });
1072
- const sectionAlignment = this.#readU32(fd, optionalOffset + 32);
1073
- const fileAlignment = this.#readU32(fd, optionalOffset + 36);
1321
+ const sectionAlignment = readU32(fd, optionalOffset + 32);
1322
+ const fileAlignment = readU32(fd, optionalOffset + 36);
1074
1323
  this.#ensureValidPEAlignment(sectionAlignment, fileAlignment);
1075
1324
  const sizeOfImageOffset = optionalOffset + 56;
1076
1325
  const resourceDirRvaOffset = optionalOffset + (is64 ? 112 : 96) + 16;
1077
1326
  const resourceDirSizeOffset = resourceDirRvaOffset + 4;
1078
- const existingResourceRva = this.#readU32(fd, resourceDirRvaOffset);
1327
+ const existingResourceRVA = readU32(fd, resourceDirRvaOffset);
1079
1328
  const sectionTableOffset = optionalOffset + optionalHeaderSize;
1080
1329
  const sections = [];
1081
1330
  let rsrcSectionIndex = -1;
@@ -1083,12 +1332,12 @@ var Injector = class {
1083
1332
  const off = sectionTableOffset + i * 40;
1084
1333
  const nameBuf = Buffer.alloc(8);
1085
1334
  readSync(fd, nameBuf, 0, 8, off);
1086
- const name = this.#stripTrailingNulls(nameBuf.toString("ascii"));
1087
- const virtualSize = this.#readU32(fd, off + 8);
1088
- const virtualAddress = this.#readU32(fd, off + 12);
1089
- const rawSize = this.#readU32(fd, off + 16);
1090
- const rawOffset = this.#readU32(fd, off + 20);
1091
- const characteristics = this.#readU32(fd, off + 36);
1335
+ const name = stripTrailingNulls(nameBuf.toString("ascii"));
1336
+ const virtualSize = readU32(fd, off + 8);
1337
+ const virtualAddress = readU32(fd, off + 12);
1338
+ const rawSize = readU32(fd, off + 16);
1339
+ const rawOffset = readU32(fd, off + 20);
1340
+ const characteristics = readU32(fd, off + 36);
1092
1341
  sections.push({
1093
1342
  name,
1094
1343
  virtualSize,
@@ -1098,19 +1347,19 @@ var Injector = class {
1098
1347
  characteristics,
1099
1348
  headerOffset: off
1100
1349
  });
1101
- if (existingResourceRva >= virtualAddress && existingResourceRva < virtualAddress + Math.max(virtualSize, rawSize)) rsrcSectionIndex = i;
1350
+ if (existingResourceRVA >= virtualAddress && existingResourceRVA < virtualAddress + Math.max(virtualSize, rawSize)) rsrcSectionIndex = i;
1102
1351
  }
1103
1352
  const sectionTableEnd = sectionTableOffset + numberOfSections * 40;
1104
1353
  const availableHeaderSpace = sections.reduce((min, s) => s.rawOffset > 0 && s.rawOffset < min ? s.rawOffset : min, Infinity) - sectionTableEnd;
1105
- if (availableHeaderSpace < 40) throw new SEAError("INJECT", `No room in PE header for a new section entry (${String(availableHeaderSpace)} bytes available, need ${String(40)})`, {
1354
+ if (availableHeaderSpace < 40) throw new SEAError("ROOM", `No room in PE header for a new section entry (${String(availableHeaderSpace)} bytes available, need ${String(40)})`, {
1106
1355
  executable: this.#options.executable,
1107
1356
  availableHeaderSpace,
1108
1357
  requiredHeaderSpace: 40
1109
1358
  });
1110
1359
  const existingLeaves = [];
1111
- if (rsrcSectionIndex !== -1 && existingResourceRva !== 0) {
1360
+ if (rsrcSectionIndex !== -1 && existingResourceRVA !== 0) {
1112
1361
  const rsrc = sections[rsrcSectionIndex];
1113
- if (rsrc !== void 0) this.#parseResourceDirectory(fd, rsrc.rawOffset, existingResourceRva, 0, existingLeaves, 0, 0, void 0, 0, void 0);
1362
+ if (rsrc !== void 0) this.#parseResourceDirectory(fd, rsrc.rawOffset, existingResourceRVA, 0, existingLeaves, 0, 0, void 0, 0, void 0);
1114
1363
  }
1115
1364
  const overwrite = this.#options.overwrite !== false;
1116
1365
  const upperName = this.#options.resource.toUpperCase();
@@ -1123,7 +1372,7 @@ var Injector = class {
1123
1372
  for (let i = 0; i < filteredLeaves.length; i++) {
1124
1373
  const leaf = filteredLeaves[i];
1125
1374
  if (leaf === void 0) continue;
1126
- const fileOffset = this.#rvaToFileOffset(leaf.dataRva, sections);
1375
+ const fileOffset = this.#rvaToFileOffset(leaf.dataRVA, sections);
1127
1376
  if (fileOffset >= 0) {
1128
1377
  const buf = Buffer.alloc(leaf.dataSize);
1129
1378
  readSync(fd, buf, 0, leaf.dataSize, fileOffset);
@@ -1134,16 +1383,16 @@ var Injector = class {
1134
1383
  const tree = this.#buildResourceTree(filteredLeaves, upperName, blobSize);
1135
1384
  const { directoryBuffer, dataRegionSize } = this.#serializeResourceTree(tree, leafDataMap, blobSize);
1136
1385
  const totalRawSize = directoryBuffer.length + dataRegionSize;
1137
- const alignedRawSize = this.#align(totalRawSize, fileAlignment);
1386
+ const alignedRawSize = alignTo(totalRawSize, fileAlignment);
1138
1387
  let highestVaEnd = 0;
1139
1388
  for (const s of sections) {
1140
1389
  const end = s.virtualAddress + Math.max(s.virtualSize, s.rawSize);
1141
1390
  if (end > highestVaEnd) highestVaEnd = end;
1142
1391
  }
1143
- const newVa = this.#align(highestVaEnd, sectionAlignment);
1392
+ const newVa = alignTo(highestVaEnd, sectionAlignment);
1144
1393
  const newVirtualSize = totalRawSize;
1145
1394
  const fileSize = statSync(this.#options.executable).size;
1146
- const newRawOffset = this.#align(fileSize, fileAlignment);
1395
+ const newRawOffset = alignTo(fileSize, fileAlignment);
1147
1396
  const newHeaderOffset = sectionTableEnd;
1148
1397
  const headerBuf = Buffer.alloc(40);
1149
1398
  headerBuf.write(".rsrc2", 0, 6, "ascii");
@@ -1157,28 +1406,27 @@ var Injector = class {
1157
1406
  headerBuf.writeUInt16LE(0, 34);
1158
1407
  headerBuf.writeUInt32LE(64 | PE_SCN_MEM_READ, 36);
1159
1408
  writeSync(fd, headerBuf, 0, 40, newHeaderOffset);
1160
- this.#writeU16(fd, coffOffset + 2, numberOfSections + 1);
1161
- this.#writeU32(fd, resourceDirRvaOffset, newVa);
1162
- this.#writeU32(fd, resourceDirSizeOffset, directoryBuffer.length);
1163
- const newSizeOfImage = this.#align(newVa + Math.max(newVirtualSize, alignedRawSize), sectionAlignment);
1164
- this.#writeU32(fd, sizeOfImageOffset, newSizeOfImage);
1409
+ writeU16(fd, coffOffset + 2, numberOfSections + 1);
1410
+ writeU32(fd, resourceDirRvaOffset, newVa);
1411
+ writeU32(fd, resourceDirSizeOffset, directoryBuffer.length);
1412
+ writeU32(fd, sizeOfImageOffset, alignTo(newVa + Math.max(newVirtualSize, alignedRawSize), sectionAlignment));
1165
1413
  closeSync(fd);
1166
1414
  const currentFileSize = statSync(this.#options.executable).size;
1167
1415
  if (newRawOffset > currentFileSize) {
1168
1416
  const padding = Buffer.alloc(newRawOffset - currentFileSize);
1169
1417
  appendFileSync(this.#options.executable, padding);
1170
1418
  }
1171
- this.#fixupDirectoryRvas(directoryBuffer, newVa);
1419
+ this.#fixupDataEntries(directoryBuffer, 0, newVa);
1172
1420
  appendFileSync(this.#options.executable, directoryBuffer);
1173
1421
  for (let i = 0; i < filteredLeaves.length; i++) {
1174
1422
  const data = leafDataMap.get(i);
1175
1423
  if (data !== void 0) {
1176
1424
  appendFileSync(this.#options.executable, data);
1177
- const padLen = this.#align(data.length, 4) - data.length;
1425
+ const padLen = alignTo(data.length, 4) - data.length;
1178
1426
  if (padLen > 0) appendFileSync(this.#options.executable, Buffer.alloc(padLen));
1179
1427
  }
1180
1428
  }
1181
- this.#appendFile(this.#options.executable, this.#options.blob);
1429
+ appendFile(this.#options.executable, this.#options.blob);
1182
1430
  const writtenSize = statSync(this.#options.executable).size - newRawOffset;
1183
1431
  if (writtenSize < alignedRawSize) appendFileSync(this.#options.executable, Buffer.alloc(alignedRawSize - writtenSize));
1184
1432
  return optionalOffset;
@@ -1191,11 +1439,11 @@ var Injector = class {
1191
1439
  }
1192
1440
  #parseResourceDirectory(fd, sectionFileOffset, sectionRva, dirOffset, leaves, depth, currentTypeId, currentTypeName, currentNameId, currentNameName) {
1193
1441
  const absOffset = sectionFileOffset + dirOffset;
1194
- const totalEntries = this.#readU16(fd, absOffset + 12) + this.#readU16(fd, absOffset + 14);
1442
+ const totalEntries = readU16(fd, absOffset + 12) + readU16(fd, absOffset + 14);
1195
1443
  for (let i = 0; i < totalEntries; i++) {
1196
1444
  const entryOffset = absOffset + 16 + i * 8;
1197
- const nameOrId = this.#readU32(fd, entryOffset);
1198
- const offsetOrData = this.#readU32(fd, entryOffset + 4);
1445
+ const nameOrId = readU32(fd, entryOffset);
1446
+ const offsetOrData = readU32(fd, entryOffset + 4);
1199
1447
  let entryId = 0;
1200
1448
  let entryName;
1201
1449
  if ((nameOrId & 2147483648) !== 0) {
@@ -1218,9 +1466,9 @@ var Injector = class {
1218
1466
  this.#parseResourceDirectory(fd, sectionFileOffset, sectionRva, subDirOffset, leaves, depth + 1, typeId, typeName, nameId, nameName);
1219
1467
  } else {
1220
1468
  const dataEntryFileOffset = sectionFileOffset + offsetOrData;
1221
- const dataRva = this.#readU32(fd, dataEntryFileOffset);
1222
- const dataSize = this.#readU32(fd, dataEntryFileOffset + 4);
1223
- const codePage = this.#readU32(fd, dataEntryFileOffset + 8);
1469
+ const dataRVA = readU32(fd, dataEntryFileOffset);
1470
+ const dataSize = readU32(fd, dataEntryFileOffset + 4);
1471
+ const codePage = readU32(fd, dataEntryFileOffset + 8);
1224
1472
  const language = depth === 2 ? entryId : 0;
1225
1473
  leaves.push({
1226
1474
  typeId,
@@ -1229,7 +1477,7 @@ var Injector = class {
1229
1477
  nameName,
1230
1478
  language,
1231
1479
  codePage,
1232
- dataRva,
1480
+ dataRVA,
1233
1481
  dataSize
1234
1482
  });
1235
1483
  }
@@ -1306,7 +1554,7 @@ var Injector = class {
1306
1554
  value: str
1307
1555
  });
1308
1556
  stringPoolSize += 2 + str.length * 2;
1309
- stringPoolSize = this.#align(stringPoolSize, 2);
1557
+ stringPoolSize = alignTo(stringPoolSize, 2);
1310
1558
  }
1311
1559
  for (const [nameKey, langEntries] of nameMap) {
1312
1560
  dirTableSize += 16 + langEntries.length * 8;
@@ -1317,7 +1565,7 @@ var Injector = class {
1317
1565
  value: str
1318
1566
  });
1319
1567
  stringPoolSize += 2 + str.length * 2;
1320
- stringPoolSize = this.#align(stringPoolSize, 2);
1568
+ stringPoolSize = alignTo(stringPoolSize, 2);
1321
1569
  }
1322
1570
  for (const entry of langEntries) {
1323
1571
  allLeafEntries.push({
@@ -1340,7 +1588,7 @@ var Injector = class {
1340
1588
  const data = leafDataMap.get(entry.leafIndex);
1341
1589
  if (data !== void 0) {
1342
1590
  leafFileOffsets.set(entry.leafIndex, dataRegionOffset);
1343
- dataRegionOffset += this.#align(data.length, 4);
1591
+ dataRegionOffset += alignTo(data.length, 4);
1344
1592
  }
1345
1593
  }
1346
1594
  const blobDataOffset = dataRegionOffset;
@@ -1356,7 +1604,7 @@ var Injector = class {
1356
1604
  buf.writeUInt16LE(value.length, stringPos);
1357
1605
  buf.write(value, stringPos + 2, value.length * 2, "utf16le");
1358
1606
  stringPos += 2 + value.length * 2;
1359
- stringPos = this.#align(stringPos, 2);
1607
+ stringPos = alignTo(stringPos, 2);
1360
1608
  }
1361
1609
  const sortedTypeKeys = this.#sortResourceKeys([...tree.keys()]);
1362
1610
  const nextDirOffset = 16 + tree.size * 8;
@@ -1447,10 +1695,7 @@ var Injector = class {
1447
1695
  blobDataOffset
1448
1696
  };
1449
1697
  }
1450
- #fixupDirectoryRvas(directoryBuffer, sectionVa) {
1451
- this.#fixupDataEntries(directoryBuffer, 0, 0, sectionVa);
1452
- }
1453
- #fixupDataEntries(buf, dirOffset, depth, sectionVa) {
1698
+ #fixupDataEntries(buf, dirOffset, sectionVA) {
1454
1699
  if (dirOffset + 16 > buf.length) return;
1455
1700
  const totalEntries = buf.readUInt16LE(dirOffset + 12) + buf.readUInt16LE(dirOffset + 14);
1456
1701
  for (let i = 0; i < totalEntries; i++) {
@@ -1459,10 +1704,10 @@ var Injector = class {
1459
1704
  const offsetOrData = buf.readUInt32LE(entryOffset + 4);
1460
1705
  if ((offsetOrData & 2147483648) !== 0) {
1461
1706
  const subOffset = offsetOrData & ~PE_RESOURCE_SUBDIR_FLAG;
1462
- this.#fixupDataEntries(buf, subOffset, depth + 1, sectionVa);
1707
+ this.#fixupDataEntries(buf, subOffset, sectionVA);
1463
1708
  } else if (offsetOrData + 4 <= buf.length) {
1464
1709
  const currentRva = buf.readUInt32LE(offsetOrData);
1465
- buf.writeUInt32LE(currentRva + sectionVa >>> 0, offsetOrData);
1710
+ buf.writeUInt32LE(currentRva + sectionVA >>> 0, offsetOrData);
1466
1711
  }
1467
1712
  }
1468
1713
  }
@@ -1491,8 +1736,7 @@ var Injector = class {
1491
1736
  offset += bytesRead;
1492
1737
  }
1493
1738
  sum = (sum & 65535) + (sum >>> 16);
1494
- const checksum = sum + fileSize >>> 0;
1495
- this.#writeU32(fd, checksumOffset, checksum);
1739
+ writeU32(fd, checksumOffset, sum + fileSize >>> 0);
1496
1740
  } finally {
1497
1741
  closeSync(fd);
1498
1742
  }
@@ -1504,14 +1748,10 @@ var Injector = class {
1504
1748
  });
1505
1749
  return [...named, ...ids];
1506
1750
  }
1507
- #injectElf() {
1751
+ #injectELF() {
1508
1752
  const exePath = this.#options.executable;
1509
1753
  const resource = this.#options.resource;
1510
1754
  const overwrite = this.#options.overwrite !== false;
1511
- const PT_LOAD = 1;
1512
- const PT_PHDR = 6;
1513
- const PF_R = 4;
1514
- const PAGE = 4096;
1515
1755
  let phdrOffset;
1516
1756
  let phdrEntrySize;
1517
1757
  let phdrCount;
@@ -1530,61 +1770,67 @@ var Injector = class {
1530
1770
  executable: exePath,
1531
1771
  elfData
1532
1772
  });
1533
- phdrOffset = Number(this.#readU64(fd, 32));
1534
- phdrEntrySize = this.#readU16(fd, 54);
1535
- phdrCount = this.#readU16(fd, 56);
1536
- headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1537
- for (const header of headers) {
1538
- if (header.type !== 4) continue;
1539
- const existingName = this.#readElfNoteName(fd, header.offset, header.filesz);
1773
+ phdrOffset = Number(readU64(fd, 32));
1774
+ phdrEntrySize = readU16(fd, 54);
1775
+ phdrCount = readU16(fd, 56);
1776
+ headers = this.#readELFProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1777
+ const stale = /* @__PURE__ */ new Set();
1778
+ for (let i = 0; i < headers.length; i++) {
1779
+ const header = headers[i];
1780
+ if (header === void 0 || header.type !== 4) continue;
1781
+ const existingName = this.#readELFNoteName(fd, header.offset, header.filesz);
1540
1782
  if (existingName === void 0 || !existingName.startsWith("NODE_SEA")) continue;
1541
1783
  if (!overwrite) throw new SEAError("INJECT", `Note with name "${resource}" already exists`, {
1542
1784
  executable: exePath,
1543
1785
  resource
1544
1786
  });
1545
- header.type = 0;
1787
+ stale.add(i);
1546
1788
  }
1789
+ headers = headers.map((header, index) => stale.has(index) ? {
1790
+ ...header,
1791
+ type: 0
1792
+ } : header);
1547
1793
  } finally {
1548
1794
  closeSync(fd);
1549
1795
  }
1550
1796
  let maxVaddrEnd = 0;
1551
1797
  for (const header of headers) {
1552
- if (header.type !== PT_LOAD) continue;
1798
+ if (header.type !== 1) continue;
1553
1799
  const end = header.vaddr + header.memsz;
1554
1800
  if (end > maxVaddrEnd) maxVaddrEnd = end;
1555
1801
  }
1556
- const regionVaddr = this.#align(maxVaddrEnd, PAGE);
1802
+ const regionVaddr = alignTo(maxVaddrEnd, ELF_PAGE_SIZE);
1557
1803
  const blobSize = statSync(this.#options.blob).size;
1558
- const { header: noteHeader, entryTotal: noteEntryTotal } = buildELFNoteHeader(resource, blobSize);
1559
- const noteAreaSize = this.#align(noteEntryTotal, 8);
1804
+ const { header: noteHeader, total: noteTotal } = buildELFNoteHeader(resource, blobSize);
1805
+ const noteAreaSize = alignTo(noteTotal, 8);
1560
1806
  const newEntryCount = headers.length + 2;
1561
1807
  const phtSize = newEntryCount * phdrEntrySize;
1562
1808
  const regionSize = noteAreaSize + phtSize;
1563
1809
  const fileSize = statSync(exePath).size;
1564
- const regionStart = this.#align(fileSize, PAGE);
1810
+ const regionStart = alignTo(fileSize, ELF_PAGE_SIZE);
1565
1811
  const phtOff = regionStart + noteAreaSize;
1566
1812
  const newLoad = {
1567
- type: PT_LOAD,
1568
- flags: PF_R,
1813
+ type: 1,
1814
+ flags: 4,
1569
1815
  offset: regionStart,
1570
1816
  vaddr: regionVaddr,
1571
1817
  paddr: regionVaddr,
1572
1818
  filesz: regionSize,
1573
1819
  memsz: regionSize,
1574
- align: PAGE
1820
+ align: ELF_PAGE_SIZE
1575
1821
  };
1576
1822
  const newNote = {
1577
1823
  type: 4,
1578
- flags: PF_R,
1824
+ flags: 4,
1579
1825
  offset: regionStart,
1580
1826
  vaddr: regionVaddr,
1581
1827
  paddr: regionVaddr,
1582
- filesz: noteEntryTotal,
1583
- memsz: noteEntryTotal,
1828
+ filesz: noteTotal,
1829
+ memsz: noteTotal,
1584
1830
  align: 4
1585
1831
  };
1586
1832
  const finalHeaders = headers.map((header) => {
1587
- if (header.type !== PT_PHDR) return header;
1833
+ if (header.type !== 6) return header;
1588
1834
  const relVaddr = regionVaddr + (phtOff - regionStart);
1589
1835
  return {
1590
1836
  ...header,
@@ -1600,43 +1846,43 @@ var Injector = class {
1600
1846
  for (let i = 0; i < finalHeaders.length; i++) {
1601
1847
  const entry = finalHeaders[i];
1602
1848
  if (entry === void 0) continue;
1603
- this.#writeElfProgramHeaderEntry(phtBuffer, i * phdrEntrySize, entry);
1849
+ this.#writeELFProgramHeaderEntry(phtBuffer, i * phdrEntrySize, entry);
1604
1850
  }
1605
1851
  if (regionStart > fileSize) appendFileSync(exePath, Buffer.alloc(regionStart - fileSize));
1606
1852
  appendFileSync(exePath, noteHeader);
1607
- this.#appendFile(exePath, this.#options.blob);
1608
- const descPadding = this.#align(blobSize, 4) - blobSize;
1853
+ appendFile(exePath, this.#options.blob);
1854
+ const descPadding = alignTo(blobSize, 4) - blobSize;
1609
1855
  if (descPadding > 0) appendFileSync(exePath, Buffer.alloc(descPadding));
1610
- const trailingPad = noteAreaSize - noteEntryTotal;
1856
+ const trailingPad = noteAreaSize - noteTotal;
1611
1857
  if (trailingPad > 0) appendFileSync(exePath, Buffer.alloc(trailingPad));
1612
1858
  appendFileSync(exePath, phtBuffer);
1613
1859
  const fd2 = openSync(exePath, "r+");
1614
1860
  try {
1615
- this.#writeU64(fd2, 32, BigInt(phtOff));
1616
- this.#writeU16(fd2, 56, newEntryCount);
1617
- this.#verifyElfNoteMapping(fd2, phtOff, newEntryCount, phdrEntrySize);
1861
+ writeU64(fd2, 32, BigInt(phtOff));
1862
+ writeU16(fd2, 56, newEntryCount);
1863
+ this.#verifyELFNoteMapping(fd2, phtOff, newEntryCount, phdrEntrySize);
1618
1864
  } finally {
1619
1865
  closeSync(fd2);
1620
1866
  }
1621
1867
  }
1622
- #readElfProgramHeaders(fd, phdrOffset, entrySize, count) {
1868
+ #readELFProgramHeaders(fd, phdrOffset, entrySize, count) {
1623
1869
  const headers = [];
1624
1870
  for (let i = 0; i < count; i++) {
1625
1871
  const off = phdrOffset + i * entrySize;
1626
1872
  headers.push({
1627
- type: this.#readU32(fd, off),
1628
- flags: this.#readU32(fd, off + 4),
1629
- offset: Number(this.#readU64(fd, off + 8)),
1630
- vaddr: Number(this.#readU64(fd, off + 16)),
1631
- paddr: Number(this.#readU64(fd, off + 24)),
1632
- filesz: Number(this.#readU64(fd, off + 32)),
1633
- memsz: Number(this.#readU64(fd, off + 40)),
1634
- align: Number(this.#readU64(fd, off + 48))
1873
+ type: readU32(fd, off),
1874
+ flags: readU32(fd, off + 4),
1875
+ offset: Number(readU64(fd, off + 8)),
1876
+ vaddr: Number(readU64(fd, off + 16)),
1877
+ paddr: Number(readU64(fd, off + 24)),
1878
+ filesz: Number(readU64(fd, off + 32)),
1879
+ memsz: Number(readU64(fd, off + 40)),
1880
+ align: Number(readU64(fd, off + 48))
1635
1881
  });
1636
1882
  }
1637
1883
  return headers;
1638
1884
  }
1639
- #writeElfProgramHeaderEntry(buf, pos, entry) {
1885
+ #writeELFProgramHeaderEntry(buf, pos, entry) {
1640
1886
  buf.writeUInt32LE(entry.type >>> 0, pos);
1641
1887
  buf.writeUInt32LE(entry.flags >>> 0, pos + 4);
1642
1888
  buf.writeBigUInt64LE(BigInt(entry.offset), pos + 8);
@@ -1646,22 +1892,22 @@ var Injector = class {
1646
1892
  buf.writeBigUInt64LE(BigInt(entry.memsz), pos + 40);
1647
1893
  buf.writeBigUInt64LE(BigInt(entry.align), pos + 48);
1648
1894
  }
1649
- #readElfNoteName(fd, offset, size) {
1895
+ #readELFNoteName(fd, offset, size) {
1650
1896
  if (size < 12) return void 0;
1651
- const namesz = this.#readU32(fd, offset);
1652
- const descsz = this.#readU32(fd, offset + 4);
1897
+ const namesz = readU32(fd, offset);
1898
+ const descsz = readU32(fd, offset + 4);
1653
1899
  if (namesz === 0 || namesz > 256) return void 0;
1654
- if (12 + this.#align(namesz, 4) + this.#align(descsz, 4) > size) return void 0;
1900
+ if (12 + alignTo(namesz, 4) + alignTo(descsz, 4) > size) return void 0;
1655
1901
  const nameBuf = Buffer.alloc(namesz);
1656
1902
  readSync(fd, nameBuf, 0, namesz, offset + 12);
1657
- return this.#stripTrailingNulls(nameBuf.toString("utf-8"));
1903
+ return stripTrailingNulls(nameBuf.toString("utf-8"));
1658
1904
  }
1659
- #verifyElfNoteMapping(fd, phdrOffset, phdrCount, phdrEntrySize) {
1660
- const headers = this.#readElfProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1905
+ #verifyELFNoteMapping(fd, phdrOffset, phdrCount, phdrEntrySize) {
1906
+ const headers = this.#readELFProgramHeaders(fd, phdrOffset, phdrEntrySize, phdrCount);
1661
1907
  const loads = headers.filter((h) => h.type === 1);
1662
1908
  const notes = headers.filter((h) => h.type === 4);
1663
1909
  for (const note of notes) {
1664
- const name = this.#readElfNoteName(fd, note.offset, note.filesz);
1910
+ const name = this.#readELFNoteName(fd, note.offset, note.filesz);
1665
1911
  if (name === void 0 || !name.startsWith("NODE_SEA")) continue;
1666
1912
  const covering = loads.find((load) => note.offset >= load.offset && note.offset < load.offset + load.filesz);
1667
1913
  if (covering === void 0) continue;
@@ -1672,7 +1918,7 @@ var Injector = class {
1672
1918
  resource: this.#options.resource
1673
1919
  });
1674
1920
  }
1675
- #injectMacho() {
1921
+ #injectMachO() {
1676
1922
  const exePath = this.#options.executable;
1677
1923
  const fileSize = statSync(exePath).size;
1678
1924
  let srcFd = openSync(exePath, "r");
@@ -1722,7 +1968,7 @@ var Injector = class {
1722
1968
  for (let i = 0; i < commands.length; i++) {
1723
1969
  const cmd = commands[i];
1724
1970
  if (cmd === void 0 || cmd.type !== 25) continue;
1725
- const segName = this.#stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii"));
1971
+ const segName = stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii"));
1726
1972
  if (segName === "__LINKEDIT") linkeditIndex = i;
1727
1973
  if (segName === segmentName) existingSegmentIndices.push(i);
1728
1974
  }
@@ -1731,13 +1977,12 @@ var Injector = class {
1731
1977
  segmentName
1732
1978
  });
1733
1979
  const linkeditCmd = linkeditIndex === -1 ? void 0 : commands[linkeditIndex];
1734
- if (linkeditCmd === void 0) throw new SEAError("INJECT", "Mach-O binary has no __LINKEDIT segment", { executable: exePath });
1735
- const Loff = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40));
1736
- const Lsize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48));
1737
- const Lvm = buf.readBigUInt64LE(linkeditCmd.offset + 24);
1980
+ if (linkeditCmd === void 0) throw new SEAError("ROOM", "Mach-O binary has no __LINKEDIT segment", { executable: exePath });
1981
+ const linkeditOffset = Number(buf.readBigUInt64LE(linkeditCmd.offset + 40));
1982
+ const linkeditSize = Number(buf.readBigUInt64LE(linkeditCmd.offset + 48));
1983
+ const linkeditAddress = buf.readBigUInt64LE(linkeditCmd.offset + 24);
1738
1984
  const blobSize = statSync(this.#options.blob).size;
1739
- const pageSize = cputype === 16777228 ? 16384 : 4096;
1740
- const shift = this.#align(blobSize, pageSize);
1985
+ const shift = alignTo(blobSize, cputype === 16777228 ? 16384 : 4096);
1741
1986
  let firstSectionOffset = fileSize;
1742
1987
  for (const cmd of commands) {
1743
1988
  if (cmd.type !== 25) continue;
@@ -1754,7 +1999,7 @@ var Injector = class {
1754
1999
  const removedSize = commands.filter((_c, i) => existingSegmentIndices.includes(i)).reduce((sum, c) => sum + c.size, 0);
1755
2000
  const newNcmds = commands.length - existingSegmentIndices.length + 1;
1756
2001
  const newSizeofcmds = sizeofcmds - removedSize + newCmdSize;
1757
- if (headerSize + newSizeofcmds + 16 > firstSectionOffset) throw new SEAError("INJECT", `Not enough header space for new Mach-O load command (need offset ${String(headerSize + newSizeofcmds + 16)}, first section at ${String(firstSectionOffset)})`, {
2002
+ if (headerSize + newSizeofcmds + 16 > firstSectionOffset) throw new SEAError("ROOM", `Not enough header space for new Mach-O load command (need offset ${String(headerSize + newSizeofcmds + 16)}, first section at ${String(firstSectionOffset)})`, {
1758
2003
  executable: exePath,
1759
2004
  firstSectionOffset,
1760
2005
  requiredOffset: headerSize + newSizeofcmds + 16
@@ -1763,14 +2008,14 @@ var Injector = class {
1763
2008
  const cmd = commands[i];
1764
2009
  if (cmd === void 0 || existingSegmentIndices.includes(i)) continue;
1765
2010
  if (cmd.type === 25) {
1766
- if (this.#stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii")) === "__LINKEDIT") {
1767
- if (buf.readUInt32LE(cmd.offset + 64) > 0) throw new SEAError("INJECT", "__LINKEDIT segment with sections is not supported", { executable: exePath });
1768
- buf.writeBigUInt64LE(Lvm + BigInt(shift), cmd.offset + 24);
1769
- buf.writeBigUInt64LE(BigInt(Loff + shift), cmd.offset + 40);
2011
+ if (stripTrailingNulls(buf.subarray(cmd.offset + 8, cmd.offset + 24).toString("ascii")) === "__LINKEDIT") {
2012
+ if (buf.readUInt32LE(cmd.offset + 64) > 0) throw new SEAError("ROOM", "__LINKEDIT segment with sections is not supported", { executable: exePath });
2013
+ buf.writeBigUInt64LE(linkeditAddress + BigInt(shift), cmd.offset + 24);
2014
+ buf.writeBigUInt64LE(BigInt(linkeditOffset + shift), cmd.offset + 40);
1770
2015
  }
1771
2016
  continue;
1772
2017
  }
1773
- this.#shiftMachoLinkeditOffsets(buf, cmd, Loff, shift);
2018
+ this.#shiftMachOLinkeditOffsets(buf, cmd, linkeditOffset, shift);
1774
2019
  }
1775
2020
  buf.writeUInt32LE(newNcmds, 16);
1776
2021
  buf.writeUInt32LE(newSizeofcmds, 20);
@@ -1778,9 +2023,9 @@ var Injector = class {
1778
2023
  cmd.writeUInt32LE(25, 0);
1779
2024
  cmd.writeUInt32LE(newCmdSize, 4);
1780
2025
  cmd.write(segmentName, 8, 16, "ascii");
1781
- cmd.writeBigUInt64LE(Lvm, 24);
2026
+ cmd.writeBigUInt64LE(linkeditAddress, 24);
1782
2027
  cmd.writeBigUInt64LE(BigInt(shift), 32);
1783
- cmd.writeBigUInt64LE(BigInt(Loff), 40);
2028
+ cmd.writeBigUInt64LE(BigInt(linkeditOffset), 40);
1784
2029
  cmd.writeBigUInt64LE(BigInt(shift), 48);
1785
2030
  cmd.writeUInt32LE(1, 56);
1786
2031
  cmd.writeUInt32LE(1, 60);
@@ -1788,9 +2033,9 @@ var Injector = class {
1788
2033
  cmd.writeUInt32LE(0, 68);
1789
2034
  cmd.write(sectionName, 72, 16, "ascii");
1790
2035
  cmd.write(segmentName, 88, 16, "ascii");
1791
- cmd.writeBigUInt64LE(Lvm, 104);
2036
+ cmd.writeBigUInt64LE(linkeditAddress, 104);
1792
2037
  cmd.writeBigUInt64LE(BigInt(blobSize), 112);
1793
- cmd.writeUInt32LE(Loff, 120);
2038
+ cmd.writeUInt32LE(linkeditOffset, 120);
1794
2039
  cmd.writeUInt32LE(0, 124);
1795
2040
  cmd.writeUInt32LE(0, 128);
1796
2041
  cmd.writeUInt32LE(0, 132);
@@ -1813,14 +2058,14 @@ var Injector = class {
1813
2058
  destFd = openSync(injTemp, "w", mode);
1814
2059
  writeSync(destFd, buf.subarray(0, headerSize));
1815
2060
  writeSync(destFd, newLoadCmdsBuf);
1816
- copyRange(srcFd, destFd, headerSize + newSizeofcmds, Loff - (headerSize + newSizeofcmds));
2061
+ copyRange(srcFd, destFd, headerSize + newSizeofcmds, linkeditOffset - (headerSize + newSizeofcmds));
1817
2062
  blobFd = openSync(this.#options.blob, "r");
1818
2063
  copyRange(blobFd, destFd, 0, blobSize);
1819
2064
  closeSync(blobFd);
1820
2065
  blobFd = void 0;
1821
2066
  const blobPadding = shift - blobSize;
1822
2067
  if (blobPadding > 0) writeSync(destFd, Buffer.alloc(blobPadding));
1823
- copyRange(srcFd, destFd, Loff, Lsize);
2068
+ copyRange(srcFd, destFd, linkeditOffset, linkeditSize);
1824
2069
  closeSync(destFd);
1825
2070
  destFd = void 0;
1826
2071
  closeSync(srcFd);
@@ -1828,7 +2073,7 @@ var Injector = class {
1828
2073
  chmodSync(injTemp, mode & 4095);
1829
2074
  finalizeExecutable(injTemp, exePath);
1830
2075
  injTemp = void 0;
1831
- this.#verifyMachoSection(exePath, segmentName, sectionName, Loff, blobSize);
2076
+ this.#verifyMachOSection(exePath, segmentName, sectionName, linkeditOffset, blobSize);
1832
2077
  } finally {
1833
2078
  for (const fd of [
1834
2079
  blobFd,
@@ -1840,7 +2085,7 @@ var Injector = class {
1840
2085
  if (injTemp !== void 0) rmSync(injTemp, { force: true });
1841
2086
  }
1842
2087
  }
1843
- #shiftMachoLinkeditOffsets(buf, cmd, threshold, shift) {
2088
+ #shiftMachOLinkeditOffsets(buf, cmd, threshold, shift) {
1844
2089
  let offsets;
1845
2090
  switch (cmd.type) {
1846
2091
  case 2:
@@ -1883,7 +2128,7 @@ var Injector = class {
1883
2128
  if (value >= threshold && value > 0) buf.writeUInt32LE(value + shift, fieldOffset);
1884
2129
  }
1885
2130
  }
1886
- #verifyMachoSection(exePath, segmentName, sectionName, expectedOffset, expectedSize) {
2131
+ #verifyMachOSection(exePath, segmentName, sectionName, expectedOffset, expectedSize) {
1887
2132
  const fd = openSync(exePath, "r");
1888
2133
  try {
1889
2134
  const header = Buffer.alloc(32);
@@ -1898,12 +2143,12 @@ var Injector = class {
1898
2143
  if (cmdType === 25 && cmdSize >= 72) {
1899
2144
  const segBuf = Buffer.alloc(cmdSize);
1900
2145
  readSync(fd, segBuf, 0, cmdSize, offset);
1901
- if (this.#stripTrailingNulls(segBuf.subarray(8, 24).toString("ascii")) === segmentName) {
2146
+ if (stripTrailingNulls(segBuf.subarray(8, 24).toString("ascii")) === segmentName) {
1902
2147
  const nsects = segBuf.readUInt32LE(64);
1903
2148
  for (let s = 0; s < nsects; s++) {
1904
2149
  const sectOff = 72 + s * 80;
1905
2150
  if (sectOff + 80 > segBuf.length) continue;
1906
- if (this.#stripTrailingNulls(segBuf.subarray(sectOff, sectOff + 16).toString("ascii")) !== sectionName) continue;
2151
+ if (stripTrailingNulls(segBuf.subarray(sectOff, sectOff + 16).toString("ascii")) !== sectionName) continue;
1907
2152
  const secSize = Number(segBuf.readBigUInt64LE(sectOff + 40));
1908
2153
  if (segBuf.readUInt32LE(sectOff + 48) === expectedOffset && secSize === expectedSize) return;
1909
2154
  }
@@ -1920,40 +2165,6 @@ var Injector = class {
1920
2165
  sectionName
1921
2166
  });
1922
2167
  }
1923
- #readU16(fd, offset) {
1924
- const b = Buffer.alloc(2);
1925
- readSync(fd, b, 0, 2, offset);
1926
- return b.readUInt16LE(0);
1927
- }
1928
- #readU32(fd, offset) {
1929
- const b = Buffer.alloc(4);
1930
- readSync(fd, b, 0, 4, offset);
1931
- return b.readUInt32LE(0);
1932
- }
1933
- #readU64(fd, offset) {
1934
- const b = Buffer.alloc(8);
1935
- readSync(fd, b, 0, 8, offset);
1936
- return b.readBigUInt64LE(0);
1937
- }
1938
- #writeU16(fd, offset, value) {
1939
- const b = Buffer.alloc(2);
1940
- b.writeUInt16LE(value, 0);
1941
- writeSync(fd, b, 0, 2, offset);
1942
- }
1943
- #writeU32(fd, offset, value) {
1944
- const b = Buffer.alloc(4);
1945
- b.writeUInt32LE(value >>> 0, 0);
1946
- writeSync(fd, b, 0, 4, offset);
1947
- }
1948
- #writeU64(fd, offset, value) {
1949
- const b = Buffer.alloc(8);
1950
- b.writeBigUInt64LE(value, 0);
1951
- writeSync(fd, b, 0, 8, offset);
1952
- }
1953
- #align(value, alignment) {
1954
- const remainder = value % alignment;
1955
- return remainder === 0 ? value : value + (alignment - remainder);
1956
- }
1957
2168
  #ensureValidPEAlignment(sectionAlignment, fileAlignment) {
1958
2169
  if (!isPowerOfTwo(sectionAlignment) || !isPowerOfTwo(fileAlignment)) throw new SEAError("FORMAT", "PE section/file alignment must be a nonzero power of two", {
1959
2170
  executable: this.#options.executable,
@@ -1966,35 +2177,35 @@ var Injector = class {
1966
2177
  fileAlignment
1967
2178
  });
1968
2179
  }
1969
- /** Append sourceFile to targetFile by streaming in 4 MB chunks */
1970
- #appendFile(targetPath, sourcePath) {
1971
- const chunkSize = 4194304;
1972
- const srcFd = openSync(sourcePath, "r");
1973
- try {
1974
- const srcSize = statSync(sourcePath).size;
1975
- const chunk = Buffer.alloc(Math.min(chunkSize, srcSize));
1976
- let offset = 0;
1977
- while (offset < srcSize) {
1978
- const toRead = Math.min(chunkSize, srcSize - offset);
1979
- const bytesRead = readSync(srcFd, chunk, 0, toRead, offset);
1980
- if (bytesRead === 0) break;
1981
- appendFileSync(targetPath, chunk.subarray(0, bytesRead));
1982
- offset += bytesRead;
1983
- }
1984
- } finally {
1985
- closeSync(srcFd);
1986
- }
1987
- }
1988
- #stripTrailingNulls(value) {
1989
- const idx = value.indexOf(String.fromCharCode(0));
1990
- return idx === -1 ? value : value.slice(0, idx);
1991
- }
1992
2180
  };
1993
2181
  //#endregion
1994
- //#region src/server/seals/SEA.ts
2182
+ //#region src/server/seas/SEA.ts
2183
+ /**
2184
+ * Runs a Node.js single executable application build to completion.
2185
+ *
2186
+ * @remarks
2187
+ * `execute` compresses the configured directories, generates the SEA blob, copies
2188
+ * the host Node binary, injects the blob with an {@link Injector}, signs the
2189
+ * result where the platform supports it, and moves the finished executable into
2190
+ * place atomically. Each stage reports on `emitter`, and every failure throws a
2191
+ * coded `SEAError` after an `error` event carrying it.
2192
+ *
2193
+ * @param options - SEA build options: the output name, the entry point, the output
2194
+ * directory, and the optional assets, compression, Windows, and blob settings
2195
+ *
2196
+ * @example
2197
+ * ```ts
2198
+ * const sea = new SEA({
2199
+ * name: 'myapp',
2200
+ * entry: { path: 'dist/server/serve.cjs' },
2201
+ * output: 'dist/sea',
2202
+ * })
2203
+ * const result = await sea.execute()
2204
+ * sea.destroy()
2205
+ * ```
2206
+ */
1995
2207
  var SEA = class {
1996
2208
  #status = "idle";
1997
- #destroyed = false;
1998
2209
  #options;
1999
2210
  #emitter;
2000
2211
  constructor(options) {
@@ -2011,9 +2222,9 @@ var SEA = class {
2011
2222
  return this.#status;
2012
2223
  }
2013
2224
  async execute() {
2014
- if (this.#destroyed) throw new SEAError("STATE", "SEA is destroyed");
2225
+ if (this.#emitter.destroyed) throw new SEAError("STATE", "SEA is destroyed");
2015
2226
  if (this.#status === "active") throw new SEAError("STATE", "SEA build already in progress");
2016
- if (platformConfig() === void 0 || !isPlatformSupported()) {
2227
+ if (resolvePlatform() === void 0) {
2017
2228
  const error = new SEAError("PLATFORM", `Unsupported platform: ${process.platform}`, { platform: process.platform });
2018
2229
  this.#status = "error";
2019
2230
  this.#emitter.emit("error", error);
@@ -2028,7 +2239,7 @@ var SEA = class {
2028
2239
  this.#check();
2029
2240
  const compression = this.#compress(root);
2030
2241
  this.#check();
2031
- const blob = this.#blob(root, compression);
2242
+ const blob = this.#buildBlob(root, compression);
2032
2243
  this.#check();
2033
2244
  const assembled = this.#assemble(root, blob);
2034
2245
  const size = statSync(assembled.executable).size;
@@ -2053,8 +2264,6 @@ var SEA = class {
2053
2264
  }
2054
2265
  }
2055
2266
  destroy() {
2056
- if (this.#destroyed) return;
2057
- this.#destroyed = true;
2058
2267
  this.#emitter.destroy();
2059
2268
  }
2060
2269
  #check() {
@@ -2065,16 +2274,12 @@ var SEA = class {
2065
2274
  ensureSafeName(this.#options.name);
2066
2275
  for (const [key, path] of Object.entries(this.#options.assets ?? {})) {
2067
2276
  ensureSafeKey(key);
2068
- ensureSafeKey(path);
2069
2277
  ensureContained(base, path);
2070
2278
  }
2071
- for (const path of this.#options.compression?.paths ?? []) {
2072
- ensureSafeKey(path);
2073
- if (existsSync(resolve(base, path))) ensureContained(base, path);
2074
- }
2279
+ for (const path of this.#options.compression?.paths ?? []) if (existsSync(resolve(base, path))) ensureContained(base, path);
2075
2280
  const sign = this.#options.windows?.sign;
2076
2281
  if (sign !== void 0) {
2077
- createSignCommand(sign, "placeholder");
2282
+ buildSignCommand(sign, "placeholder");
2078
2283
  if (sign.file !== void 0) ensureExists(resolve(base, sign.file), "Certificate file not found", "SIGN");
2079
2284
  }
2080
2285
  }
@@ -2123,19 +2328,19 @@ var SEA = class {
2123
2328
  this.#emitter.emit("compress", manifest);
2124
2329
  return manifest;
2125
2330
  }
2126
- #blob(root, compression) {
2331
+ #buildBlob(root, compression) {
2127
2332
  const entry = resolve(root, this.#options.entry.path);
2128
2333
  ensureExists(entry, `Entry not found: ${this.#options.entry.path}`, "ENTRY");
2129
2334
  const output = resolve(root, this.#options.output);
2130
2335
  mkdirSync(output, { recursive: true });
2131
2336
  const configPath = join(output, "sea-config.json");
2132
2337
  const blob = join(output, "sea-prep.blob");
2133
- const config = createBlobConfig({
2338
+ const config = buildBlobConfig({
2134
2339
  path: entry,
2135
2340
  ...this.#options.entry.format === void 0 ? {} : { format: this.#options.entry.format }
2136
- }, blob, this.#assets(root, compression), this.#options.blob);
2341
+ }, blob, this.#resolveAssets(root, compression), this.#options.blob);
2137
2342
  writeFileSync(configPath, JSON.stringify(config, null, 2));
2138
- runShell([
2343
+ executeShell([
2139
2344
  process.execPath,
2140
2345
  "--experimental-sea-config",
2141
2346
  configPath
@@ -2149,7 +2354,7 @@ var SEA = class {
2149
2354
  return blob;
2150
2355
  }
2151
2356
  #assemble(root, blob) {
2152
- const platform = platformConfig();
2357
+ const platform = resolvePlatform();
2153
2358
  if (platform === void 0) throw new SEAError("PLATFORM", `Unsupported platform: ${process.platform}`, { platform: process.platform });
2154
2359
  const output = resolve(root, this.#options.output);
2155
2360
  const ext = process.platform === "win32" ? ".exe" : "";
@@ -2171,7 +2376,7 @@ var SEA = class {
2171
2376
  if (platform.remove !== void 0) {
2172
2377
  this.#check();
2173
2378
  try {
2174
- runShell([...platform.remove, temp], shell);
2379
+ executeShell([...platform.remove, temp], shell);
2175
2380
  } catch (thrown) {
2176
2381
  throw new SEAError("SIGN", "Failed to strip existing signature", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2177
2382
  }
@@ -2188,14 +2393,14 @@ var SEA = class {
2188
2393
  if (platform.sign !== void 0) {
2189
2394
  this.#check();
2190
2395
  try {
2191
- runShell([...platform.sign, temp], shell);
2396
+ executeShell([...platform.sign, temp], shell);
2192
2397
  } catch (thrown) {
2193
2398
  throw new SEAError("SIGN", "Failed to sign executable", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2194
2399
  }
2195
2400
  if (platform.verify !== void 0) {
2196
2401
  this.#check();
2197
2402
  try {
2198
- runShell([...platform.verify, temp], shell);
2403
+ executeShell([...platform.verify, temp], shell);
2199
2404
  } catch (thrown) {
2200
2405
  throw new SEAError("SIGN", "Signature verification failed", { cause: thrown instanceof Error ? thrown.message : String(thrown) });
2201
2406
  }
@@ -2221,12 +2426,12 @@ var SEA = class {
2221
2426
  const sign = this.#options.windows?.sign;
2222
2427
  if (sign !== void 0) {
2223
2428
  this.#check();
2224
- const signArgs = createSignCommand(sign.file !== void 0 ? {
2429
+ const signArgs = buildSignCommand(sign.file !== void 0 ? {
2225
2430
  ...sign,
2226
2431
  file: resolve(root, sign.file)
2227
2432
  } : sign, temp);
2228
2433
  try {
2229
- runShell(signArgs, shell);
2434
+ executeShell(signArgs, shell);
2230
2435
  } catch {
2231
2436
  throw new SEAError("SIGN", "Windows signing failed", { executable: temp });
2232
2437
  }
@@ -2234,7 +2439,7 @@ var SEA = class {
2234
2439
  if (platform.verify !== void 0) {
2235
2440
  this.#check();
2236
2441
  try {
2237
- runShell([...platform.verify, temp], shell);
2442
+ executeShell([...platform.verify, temp], shell);
2238
2443
  } catch {
2239
2444
  throw new SEAError("SIGN", "Signature verification failed", { executable: temp });
2240
2445
  }
@@ -2265,7 +2470,7 @@ var SEA = class {
2265
2470
  ...terminal === void 0 ? {} : { terminal }
2266
2471
  };
2267
2472
  }
2268
- #assets(root, compression) {
2473
+ #resolveAssets(root, compression) {
2269
2474
  const outputs = /* @__PURE__ */ new Map();
2270
2475
  for (const result of compression?.assets ?? []) outputs.set(result.input, result.output);
2271
2476
  const assets = {};
@@ -2278,6 +2483,23 @@ var SEA = class {
2278
2483
  };
2279
2484
  //#endregion
2280
2485
  //#region src/server/assets/Asset.ts
2486
+ /**
2487
+ * Holds one named asset's key, bytes, and compression state.
2488
+ *
2489
+ * @remarks
2490
+ * `compressed` is inferred from a `.br` suffix on the key whenever the input
2491
+ * leaves it unset, so a Brotli output registered under its own name reports itself
2492
+ * correctly without the caller restating it.
2493
+ *
2494
+ * @param input - The asset's key, content bytes, and optional compression flag
2495
+ *
2496
+ * @example
2497
+ * ```ts
2498
+ * const asset = new Asset({ key: 'client.html.br', content: compressedBuffer })
2499
+ * asset.key // 'client.html.br'
2500
+ * asset.compressed // true
2501
+ * ```
2502
+ */
2281
2503
  var Asset = class {
2282
2504
  key;
2283
2505
  content;
@@ -2291,24 +2513,41 @@ var Asset = class {
2291
2513
  //#endregion
2292
2514
  //#region src/server/assets/AssetManager.ts
2293
2515
  /**
2294
- * AssetManager
2516
+ * Collects named assets from a SEA blob or from disk and serves them by key.
2295
2517
  *
2296
- * Named asset collection with SEA and disk loading.
2297
- * In SEA mode, embedded assets are loaded automatically at construction.
2298
- * In development, `load()` reads client assets from disk.
2518
+ * @remarks
2519
+ * Construction registers every asset embedded in the running SEA blob, so an
2520
+ * executable built by this package reaches its assets without touching the
2521
+ * filesystem. Outside SEA mode that step registers nothing, and `load()` reads
2522
+ * the paths `options.assets` configures instead.
2523
+ *
2524
+ * @param options - Asset manager options: the project root, the key→path mapping
2525
+ * `load()` reads, and the event hooks
2526
+ *
2527
+ * @example
2528
+ * ```ts
2529
+ * const manager = new AssetManager({
2530
+ * root: process.cwd(),
2531
+ * assets: { 'client.html.br': 'dist/client/client.html.br' },
2532
+ * })
2533
+ * manager.load()
2534
+ * manager.asset('client.html.br')
2535
+ * manager.destroy()
2536
+ * ```
2299
2537
  */
2300
2538
  var AssetManager = class {
2301
2539
  #emitter;
2302
2540
  #assets = /* @__PURE__ */ new Map();
2303
- #keys = [];
2304
2541
  #root;
2542
+ #paths;
2305
2543
  constructor(options) {
2306
2544
  this.#root = options?.root ?? process.cwd();
2545
+ this.#paths = options?.assets ?? {};
2307
2546
  this.#emitter = new Emitter({
2308
2547
  ...options?.on === void 0 ? {} : { on: options.on },
2309
2548
  ...options?.error === void 0 ? {} : { error: options.error }
2310
2549
  });
2311
- this.#loadSea();
2550
+ this.#loadSEA();
2312
2551
  }
2313
2552
  get emitter() {
2314
2553
  return this.#emitter;
@@ -2323,7 +2562,7 @@ var AssetManager = class {
2323
2562
  return [...this.#assets.values()];
2324
2563
  }
2325
2564
  keys() {
2326
- return [...this.#keys];
2565
+ return [...this.#assets.keys()];
2327
2566
  }
2328
2567
  register(input) {
2329
2568
  const items = Array.isArray(input) ? input : [input];
@@ -2335,46 +2574,31 @@ var AssetManager = class {
2335
2574
  }
2336
2575
  load() {
2337
2576
  if (isSea()) return;
2338
- const devPath = resolve(this.#root, "client", CLIENT_ASSET_KEY_RAW);
2339
- const builtBrPath = resolve(this.#root, "dist", "client", CLIENT_ASSET_KEY_BR);
2340
- if (existsSync(devPath)) {
2341
- try {
2342
- const raw = readFileSync(devPath, "utf-8");
2343
- const content = new TextEncoder().encode(raw).buffer;
2344
- if (!isArrayBuffer(content)) throw new Error("Failed to encode client asset");
2345
- this.register({
2346
- key: CLIENT_ASSET_KEY_RAW,
2347
- content,
2348
- compressed: false
2349
- });
2350
- this.#emitter.emit("load", [CLIENT_ASSET_KEY_RAW]);
2351
- } catch (thrown) {
2352
- this.#emitter.emit("error", thrown);
2577
+ const registered = [];
2578
+ for (const [key, path] of Object.entries(this.#paths)) {
2579
+ const resolved = resolve(this.#root, path);
2580
+ if (!existsSync(resolved)) {
2581
+ this.#emitter.emit("error", /* @__PURE__ */ new Error(`Asset not found: ${path}`));
2582
+ continue;
2353
2583
  }
2354
- return;
2355
- }
2356
- if (existsSync(builtBrPath)) {
2357
2584
  try {
2358
- const buffer = readFileSync(builtBrPath);
2585
+ const buffer = readFileSync(resolved);
2359
2586
  const bufferData = buffer.buffer;
2360
- if (!isArrayBuffer(bufferData)) throw new Error("Failed to read client asset");
2587
+ if (!isArrayBuffer(bufferData)) throw new Error(`Failed to read asset: ${path}`);
2361
2588
  const content = bufferData.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
2362
2589
  this.register({
2363
- key: CLIENT_ASSET_KEY_BR,
2364
- content,
2365
- compressed: true
2590
+ key,
2591
+ content
2366
2592
  });
2367
- this.#emitter.emit("load", [CLIENT_ASSET_KEY_BR]);
2593
+ registered.push(key);
2368
2594
  } catch (thrown) {
2369
2595
  this.#emitter.emit("error", thrown);
2370
2596
  }
2371
- return;
2372
2597
  }
2373
- this.#emitter.emit("error", /* @__PURE__ */ new Error("Client assets not found"));
2598
+ if (registered.length > 0) this.#emitter.emit("load", registered);
2374
2599
  }
2375
2600
  clear() {
2376
2601
  this.#assets.clear();
2377
- this.#keys = [];
2378
2602
  this.#emitter.emit("clear");
2379
2603
  }
2380
2604
  destroy() {
@@ -2383,9 +2607,8 @@ var AssetManager = class {
2383
2607
  }
2384
2608
  #add(asset) {
2385
2609
  this.#assets.set(asset.key, asset);
2386
- if (!this.#keys.includes(asset.key)) this.#keys.push(asset.key);
2387
2610
  }
2388
- #loadSea() {
2611
+ #loadSEA() {
2389
2612
  if (isSea()) {
2390
2613
  const assetKeys = getAssetKeys();
2391
2614
  const registered = [];
@@ -2404,32 +2627,43 @@ var AssetManager = class {
2404
2627
  //#endregion
2405
2628
  //#region src/server/factories.ts
2406
2629
  /**
2407
- * Create a new SEA build orchestrator.
2630
+ * Creates a SEA build orchestrator over the given options and returns it as a
2631
+ * `SEAInterface`, the published contract a caller holds instead of the `SEA` class.
2408
2632
  *
2409
2633
  * @param options - SEA build options
2410
2634
  * @returns a new `SEAInterface`
2411
2635
  *
2412
- * @example
2636
+ * @example Build a single executable
2413
2637
  * ```ts
2414
- * const seal = createSEA({
2415
- * name: 'orkestrel',
2416
- * entry: { path: 'dist/bin/serve.cjs' },
2417
- * output: 'dist/sea',
2418
- * assets: { 'index.html.br': 'dist/client/index.html.br' },
2419
- * compression: { paths: ['dist/client'] },
2638
+ * import { createSEA, formatSize } from '@orkestrel/sea'
2639
+ *
2640
+ * const sea = createSEA({
2641
+ * name: 'myapp',
2642
+ * entry: { path: 'dist/server/serve.cjs' },
2643
+ * output: 'dist/sea',
2644
+ * assets: { 'model.gguf': 'models/model.gguf' },
2645
+ * compression: { paths: ['dist/app/browser'], mode: 'text' },
2646
+ * windows: { terminal: false },
2647
+ * timeout: 30_000,
2420
2648
  * })
2421
- * const result = await seal.execute()
2649
+ *
2650
+ * const result = await sea.execute()
2651
+ * process.stdout.write(
2652
+ * `${result.executable} ${formatSize(result.size)} ${String(result.duration)}ms\n`,
2653
+ * )
2422
2654
  * ```
2423
2655
  */
2424
2656
  function createSEA(options) {
2425
2657
  return new SEA(options);
2426
2658
  }
2427
2659
  /**
2428
- * Create a cross-platform binary resource injector.
2660
+ * Creates a resource injector bound to one target executable and returns it as an
2661
+ * `InjectorInterface`, with the executable's format already detected from its header.
2429
2662
  *
2430
- * Detects the executable format (PE, ELF, Mach-O) from the file header
2431
- * and injects the blob using pure TypeScript file I/O — no WASM, no
2432
- * external tools.
2663
+ * @remarks
2664
+ * The format detected at construction — PE, ELF, or Mach-O — selects the strategy
2665
+ * `inject` takes. Every write runs through pure TypeScript file I/O, so the injector
2666
+ * needs no WASM and no external tool.
2433
2667
  *
2434
2668
  * @param options - Injector options
2435
2669
  * @returns a new `InjectorInterface`
@@ -2449,7 +2683,9 @@ function createInjector(options) {
2449
2683
  return new Injector(options);
2450
2684
  }
2451
2685
  /**
2452
- * Create a single named asset.
2686
+ * Creates one named asset from a key and a content buffer and returns it as an
2687
+ * `AssetInterface`, with `compressed` inferred from the key where the input leaves
2688
+ * it unset.
2453
2689
  *
2454
2690
  * @param input - Asset key, content, and optional compression flag
2455
2691
  * @returns a new `AssetInterface`
@@ -2463,7 +2699,8 @@ function createAsset(input) {
2463
2699
  return new Asset(input);
2464
2700
  }
2465
2701
  /**
2466
- * Create an asset manager for SEA-embedded or disk-loaded assets.
2702
+ * Creates an asset collection and returns it as an `AssetManagerInterface`, already
2703
+ * carrying whatever assets the running SEA blob embeds.
2467
2704
  *
2468
2705
  * @param options - Asset manager options (root, event hooks)
2469
2706
  * @returns a new `AssetManagerInterface`
@@ -2478,6 +2715,6 @@ function createAssetManager(options) {
2478
2715
  return new AssetManager(options);
2479
2716
  }
2480
2717
  //#endregion
2481
- export { Asset, AssetManager, BROTLI_EXTENSION, CLIENT_ASSET_KEY_BR, CLIENT_ASSET_KEY_RAW, DEFAULT_ENTRY_FORMAT, DEFAULT_SEA_COMPRESSION_QUALITY, ELF_CLASS_64, ELF_DATA_LSB, ELF_MAGIC, ELF_PT_NOTE, Injector, MACHO_LC_SEGMENT_64, MACHO_MAGIC_64, PE32_MAGIC, PE32_PLUS_MAGIC, PE_MAGIC, PE_RESOURCE_DATA_ENTRY_SIZE, PE_RESOURCE_DIR_SIZE, PE_RESOURCE_ENTRY_SIZE, PE_RESOURCE_NAME_FLAG, PE_RESOURCE_SUBDIR_FLAG, PE_RT_RCDATA, PE_SCN_INITIALIZED_DATA, PE_SCN_MEM_READ, PE_SECTION_HEADER_SIZE, PE_SIGNATURE, SEA, SEAError, SEA_BLOB_RESOURCE, SEA_COMPRESSION_MODE_VALUES, SEA_PLATFORMS, SEA_SENTINEL_FUSE, SKIP_EXTENSIONS, ShellError, WINDOWS_SUBSYSTEM_CONSOLE, WINDOWS_SUBSYSTEM_GUI, alignELFNoteSize, buildELFNoteHeader, compressDirectory, compressFile, computeSize, copyRange, createAsset, createAssetManager, createBlobConfig, createInjector, createSEA, createSignCommand, ensureContained, ensureExists, ensureSafeKey, ensureSafeName, finalizeExecutable, formatSize, isCompressible, isExecutableFormat, isPEExecutable, isPlatformSupported, isPowerOfTwo, isSEAError, isShellError, openBrowser, parsePEOffset, patchPESubsystem, patchSentinelFuse, platformConfig, readU16, redactCommand, runShell, stripPESignature, syncDirectory, walkDirectory, writeU16 };
2718
+ export { Asset, AssetManager, BROTLI_EXTENSION, DEFAULT_ENTRY_FORMAT, DEFAULT_SEA_COMPRESSION_QUALITY, ELF_CLASS_64, ELF_DATA_LSB, ELF_MAGIC, ELF_PAGE_SIZE, ELF_PF_R, ELF_PT_LOAD, ELF_PT_NOTE, ELF_PT_PHDR, Injector, MACHO_LC_SEGMENT_64, MACHO_MAGIC_64, PE32_MAGIC, PE32_PLUS_MAGIC, PE_MAGIC, PE_RESOURCE_DATA_ENTRY_SIZE, PE_RESOURCE_DIR_SIZE, PE_RESOURCE_ENTRY_SIZE, PE_RESOURCE_NAME_FLAG, PE_RESOURCE_SUBDIR_FLAG, PE_RT_RCDATA, PE_SCN_INITIALIZED_DATA, PE_SCN_MEM_READ, PE_SECTION_HEADER_SIZE, PE_SIGNATURE, SEA, SEAError, SEA_BLOB_RESOURCE, SEA_COMPRESSION_MODE_VALUES, SEA_PLATFORMS, SEA_SENTINEL_FUSE, SKIP_EXTENSIONS, ShellError, WINDOWS_SUBSYSTEM_CONSOLE, WINDOWS_SUBSYSTEM_GUI, alignELFNoteSize, alignTo, appendFile, buildBlobConfig, buildELFNoteHeader, buildSignCommand, compressDirectory, compressFile, computeSize, copyRange, createAsset, createAssetManager, createInjector, createSEA, ensureContained, ensureExists, ensureSafeKey, ensureSafeName, executeShell, finalizeExecutable, formatSize, isCompressible, isExecutableFormat, isPEExecutable, isPlatformSupported, isPowerOfTwo, isSEAError, isShellError, openBrowser, patchPESubsystem, patchSentinelFuse, readPEOffset, readU16, readU32, readU64, redactCommand, resolvePlatform, stripPESignature, stripTrailingNulls, syncDirectory, walkDirectory, writeU16, writeU32, writeU64 };
2482
2719
 
2483
2720
  //# sourceMappingURL=index.js.map