emsdk-env 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/build-BbwVl0T6.js +1379 -0
  2. package/dist/build-BbwVl0T6.js.map +1 -0
  3. package/dist/build-TpHGBYTu.cjs +1388 -0
  4. package/dist/build-TpHGBYTu.cjs.map +1 -0
  5. package/dist/build.d.ts +22 -0
  6. package/dist/build.d.ts.map +1 -0
  7. package/dist/commands.d.ts +14 -0
  8. package/dist/commands.d.ts.map +1 -0
  9. package/dist/emsdk.d.ts +22 -0
  10. package/dist/emsdk.d.ts.map +1 -0
  11. package/dist/env.d.ts +16 -0
  12. package/dist/env.d.ts.map +1 -0
  13. package/dist/fs-utils.d.ts +13 -0
  14. package/dist/fs-utils.d.ts.map +1 -0
  15. package/dist/generated/packageMetadata.d.ts +18 -0
  16. package/dist/generated/packageMetadata.d.ts.map +1 -0
  17. package/dist/index.cjs +11 -14
  18. package/dist/index.d.ts +17 -338
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.mjs +10 -15
  21. package/dist/logger.d.ts +13 -0
  22. package/dist/logger.d.ts.map +1 -0
  23. package/dist/{vite.d.ts → types.d.ts} +299 -268
  24. package/dist/types.d.ts.map +1 -0
  25. package/dist/vite/index.d.ts +24 -0
  26. package/dist/vite/index.d.ts.map +1 -0
  27. package/dist/vite/logger.d.ts +14 -0
  28. package/dist/vite/logger.d.ts.map +1 -0
  29. package/dist/vite/types.d.ts +17 -0
  30. package/dist/vite/types.d.ts.map +1 -0
  31. package/dist/vite.cjs +735 -712
  32. package/dist/vite.cjs.map +1 -1
  33. package/dist/vite.mjs +729 -712
  34. package/dist/vite.mjs.map +1 -1
  35. package/package.json +22 -21
  36. package/dist/build-BOZTStIM.js +0 -1660
  37. package/dist/build-BOZTStIM.js.map +0 -1
  38. package/dist/build-CgmcFNSR.cjs +0 -1681
  39. package/dist/build-CgmcFNSR.cjs.map +0 -1
  40. package/dist/index.cjs.map +0 -1
  41. package/dist/index.mjs.map +0 -1
@@ -1,1681 +0,0 @@
1
- /*!
2
- * name: emsdk-env
3
- * version: 0.9.0
4
- * description: Emscripten environment builder
5
- * author: Kouji Matsui (@kekyo@mi.kekyo.net)
6
- * license: MIT
7
- * repository.url: https://github.com/kekyo/emsdk-env
8
- * git.commit.hash: 73d7e217903f020ef22daa9289362dcd19bddac1
9
- */
10
-
11
- "use strict";
12
- var __create = Object.create;
13
- var __defProp = Object.defineProperty;
14
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
15
- var __getOwnPropNames = Object.getOwnPropertyNames;
16
- var __getProtoOf = Object.getPrototypeOf;
17
- var __hasOwnProp = Object.prototype.hasOwnProperty;
18
- var __copyProps = (to, from, except, desc) => {
19
- if (from && typeof from === "object" || typeof from === "function") {
20
- for (let key of __getOwnPropNames(from))
21
- if (!__hasOwnProp.call(to, key) && key !== except)
22
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
- }
24
- return to;
25
- };
26
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
- mod
33
- ));
34
- const promises = require("fs/promises");
35
- const os = require("os");
36
- const glob = require("glob");
37
- const path = require("path");
38
- const child_process = require("child_process");
39
- const __NOOP_HANDLER = () => {
40
- };
41
- const __NOOP_RELEASABLE = {
42
- release: __NOOP_HANDLER,
43
- [Symbol.dispose]: __NOOP_HANDLER
44
- };
45
- const toAbortError = (reason) => {
46
- if (reason instanceof Error) {
47
- return reason;
48
- }
49
- if (typeof reason === "string") {
50
- return new Error(reason);
51
- }
52
- return new Error("Operation aborted");
53
- };
54
- const onAbort = (signal, callback) => {
55
- if (!signal) {
56
- return __NOOP_RELEASABLE;
57
- }
58
- if (signal.aborted) {
59
- try {
60
- callback(toAbortError(signal.reason));
61
- } catch (error) {
62
- console.warn("AbortHook callback error: ", error);
63
- }
64
- return __NOOP_RELEASABLE;
65
- }
66
- let abortHandler;
67
- abortHandler = () => {
68
- if (abortHandler) {
69
- const reason = signal.reason;
70
- signal.removeEventListener("abort", abortHandler);
71
- abortHandler = void 0;
72
- try {
73
- callback(toAbortError(reason));
74
- } catch (error) {
75
- console.warn("AbortHook callback error: ", error);
76
- }
77
- }
78
- };
79
- const release = () => {
80
- if (abortHandler) {
81
- signal.removeEventListener("abort", abortHandler);
82
- abortHandler = void 0;
83
- }
84
- };
85
- signal.addEventListener("abort", abortHandler, { once: true });
86
- const handle = {
87
- release,
88
- [Symbol.dispose]: release
89
- };
90
- return handle;
91
- };
92
- const defer = (fn) => {
93
- if (typeof setImmediate === "function") {
94
- setImmediate(fn);
95
- } else {
96
- setTimeout(fn, 0);
97
- }
98
- };
99
- const ABORTED_ERROR$2 = () => new Error("Lock acquisition was aborted");
100
- const createLockHandle = (releaseCallback) => {
101
- let isActive = true;
102
- const release = () => {
103
- if (!isActive) {
104
- return;
105
- }
106
- isActive = false;
107
- releaseCallback();
108
- };
109
- return {
110
- get isActive() {
111
- return isActive;
112
- },
113
- release,
114
- [Symbol.dispose]: release
115
- };
116
- };
117
- const createMutex = (maxConsecutiveCalls = 20) => {
118
- let isLocked = false;
119
- const queue = [];
120
- let count = 0;
121
- const processQueue = () => {
122
- var _a;
123
- if (isLocked || queue.length === 0) {
124
- return;
125
- }
126
- const item = queue.shift();
127
- if ((_a = item.signal) == null ? void 0 : _a.aborted) {
128
- item.reject(ABORTED_ERROR$2());
129
- scheduleNextProcess();
130
- return;
131
- }
132
- isLocked = true;
133
- const lockHandle = createLockHandle(releaseLock);
134
- item.resolve(lockHandle);
135
- };
136
- const scheduleNextProcess = () => {
137
- count++;
138
- if (count >= maxConsecutiveCalls) {
139
- count = 0;
140
- defer(processQueue);
141
- } else {
142
- processQueue();
143
- }
144
- };
145
- const releaseLock = () => {
146
- if (!isLocked) {
147
- return;
148
- }
149
- isLocked = false;
150
- scheduleNextProcess();
151
- };
152
- const removeFromQueue = (item) => {
153
- const index = queue.indexOf(item);
154
- if (index !== -1) {
155
- queue.splice(index, 1);
156
- }
157
- };
158
- const lock = async (signal) => {
159
- if (signal) {
160
- if (signal.aborted) {
161
- throw ABORTED_ERROR$2();
162
- }
163
- return new Promise((resolve, reject) => {
164
- const queueItem = {
165
- resolve: void 0,
166
- reject: void 0,
167
- signal
168
- };
169
- const abortHandle = onAbort(signal, () => {
170
- removeFromQueue(queueItem);
171
- reject(ABORTED_ERROR$2());
172
- });
173
- queueItem.resolve = (handle) => {
174
- abortHandle.release();
175
- resolve(handle);
176
- };
177
- queueItem.reject = (error) => {
178
- abortHandle.release();
179
- reject(error);
180
- };
181
- queue.push(queueItem);
182
- processQueue();
183
- });
184
- } else {
185
- return new Promise((resolve, reject) => {
186
- queue.push({
187
- resolve,
188
- reject
189
- });
190
- processQueue();
191
- });
192
- }
193
- };
194
- const result = {
195
- lock,
196
- waiter: {
197
- wait: lock
198
- },
199
- get isLocked() {
200
- return isLocked;
201
- },
202
- get pendingCount() {
203
- return queue.length;
204
- }
205
- };
206
- return result;
207
- };
208
- const createAbortError = () => {
209
- const error = new Error("The operation was aborted.");
210
- error.name = "AbortError";
211
- return error;
212
- };
213
- const runCommand = async (command, args, cwd, signal) => {
214
- signal == null ? void 0 : signal.throwIfAborted();
215
- return new Promise((resolvePromise, rejectPromise) => {
216
- const child = child_process.spawn(command, args, {
217
- cwd,
218
- stdio: "inherit"
219
- });
220
- let settled = false;
221
- const onAbort2 = () => {
222
- if (settled) {
223
- return;
224
- }
225
- settled = true;
226
- child.kill();
227
- rejectPromise(createAbortError());
228
- };
229
- signal == null ? void 0 : signal.addEventListener("abort", onAbort2, { once: true });
230
- const cleanup = () => {
231
- signal == null ? void 0 : signal.removeEventListener("abort", onAbort2);
232
- };
233
- child.once("error", (error) => {
234
- if (settled) {
235
- return;
236
- }
237
- settled = true;
238
- cleanup();
239
- rejectPromise(error);
240
- });
241
- child.once("close", (code) => {
242
- if (settled) {
243
- return;
244
- }
245
- settled = true;
246
- cleanup();
247
- if (code === 0) {
248
- resolvePromise();
249
- return;
250
- }
251
- rejectPromise(
252
- new Error(
253
- `Command failed: ${command} ${args.join(" ")} (exit code ${code})`
254
- )
255
- );
256
- });
257
- });
258
- };
259
- const runCommandWithEnv = async (command, args, cwd, env, signal) => {
260
- signal == null ? void 0 : signal.throwIfAborted();
261
- return new Promise((resolvePromise, rejectPromise) => {
262
- const child = child_process.spawn(command, args, {
263
- cwd,
264
- env,
265
- stdio: "inherit"
266
- });
267
- let settled = false;
268
- const onAbort2 = () => {
269
- if (settled) {
270
- return;
271
- }
272
- settled = true;
273
- child.kill();
274
- rejectPromise(createAbortError());
275
- };
276
- signal == null ? void 0 : signal.addEventListener("abort", onAbort2, { once: true });
277
- const cleanup = () => {
278
- signal == null ? void 0 : signal.removeEventListener("abort", onAbort2);
279
- };
280
- child.once("error", (error) => {
281
- if (settled) {
282
- return;
283
- }
284
- settled = true;
285
- cleanup();
286
- rejectPromise(error);
287
- });
288
- child.once("close", (code) => {
289
- if (settled) {
290
- return;
291
- }
292
- settled = true;
293
- cleanup();
294
- if (code === 0) {
295
- resolvePromise();
296
- return;
297
- }
298
- rejectPromise(
299
- new Error(
300
- `Command failed: ${command} ${args.join(" ")} (exit code ${code})`
301
- )
302
- );
303
- });
304
- });
305
- };
306
- const runCommandCapture = async (command, args, cwd, signal) => {
307
- signal == null ? void 0 : signal.throwIfAborted();
308
- return new Promise((resolvePromise, rejectPromise) => {
309
- const stdoutChunks = [];
310
- const stderrChunks = [];
311
- const child = child_process.spawn(command, args, {
312
- cwd,
313
- stdio: ["ignore", "pipe", "pipe"]
314
- });
315
- let settled = false;
316
- const onAbort2 = () => {
317
- if (settled) {
318
- return;
319
- }
320
- settled = true;
321
- child.kill();
322
- rejectPromise(createAbortError());
323
- };
324
- signal == null ? void 0 : signal.addEventListener("abort", onAbort2, { once: true });
325
- const cleanup = () => {
326
- signal == null ? void 0 : signal.removeEventListener("abort", onAbort2);
327
- };
328
- child.stdout.on("data", (chunk) => {
329
- stdoutChunks.push(chunk);
330
- });
331
- child.stderr.on("data", (chunk) => {
332
- stderrChunks.push(chunk);
333
- });
334
- child.once("error", (error) => {
335
- if (settled) {
336
- return;
337
- }
338
- settled = true;
339
- cleanup();
340
- rejectPromise(error);
341
- });
342
- child.once("close", (code) => {
343
- if (settled) {
344
- return;
345
- }
346
- settled = true;
347
- cleanup();
348
- if (code === 0) {
349
- resolvePromise(Buffer.concat(stdoutChunks));
350
- return;
351
- }
352
- const stderrText = Buffer.concat(stderrChunks).toString("utf8");
353
- rejectPromise(
354
- new Error(
355
- `Command failed: ${command} ${args.join(" ")} (exit code ${code})${stderrText ? `
356
- ${stderrText}` : ""}`
357
- )
358
- );
359
- });
360
- });
361
- };
362
- const pathExists = async (targetPath) => {
363
- try {
364
- await promises.access(targetPath, promises.constants.F_OK);
365
- return true;
366
- } catch (e) {
367
- return false;
368
- }
369
- };
370
- const ensureDirectory = async (targetPath) => {
371
- await promises.mkdir(targetPath, { recursive: true });
372
- };
373
- const DEFAULT_REPO_URL = "https://github.com/emscripten-core/emsdk.git";
374
- const DEFAULT_GIT_REF = "main";
375
- const DEFAULT_CACHE_DIR = path.join(os.homedir(), ".cache", "emsdk-env");
376
- const DEFAULT_TARGET_VERSION = "latest";
377
- const versionMutexes = /* @__PURE__ */ new Map();
378
- const getVersionMutex = (key) => {
379
- let mutex = versionMutexes.get(key);
380
- if (!mutex) {
381
- mutex = createMutex();
382
- versionMutexes.set(key, mutex);
383
- }
384
- return mutex;
385
- };
386
- const ensureNonEmpty = (value, label) => {
387
- if (value.trim().length === 0) {
388
- throw new TypeError(`${label} must be a non-empty string.`);
389
- }
390
- };
391
- const sanitizeSegment = (value) => {
392
- const trimmed = value.trim();
393
- ensureNonEmpty(trimmed, "targetVersion");
394
- const sanitized = trimmed.replace(/[^A-Za-z0-9._-]/g, "_");
395
- if (sanitized === "." || sanitized === ".." || sanitized.length === 0) {
396
- throw new TypeError("targetVersion results in an unsafe path segment.");
397
- }
398
- return sanitized;
399
- };
400
- const resolveEmsdkCommand = () => process.platform === "win32" ? "emsdk.bat" : "./emsdk";
401
- const runEmsdk = async (repoDir, args, signal) => {
402
- if (process.platform === "win32") {
403
- await runCommand("cmd", ["/c", "emsdk.bat", ...args], repoDir, signal);
404
- return;
405
- }
406
- await runCommand(resolveEmsdkCommand(), args, repoDir, signal);
407
- };
408
- const runGitClone = async (gitPath, repoUrl, targetDir, cwd, signal) => {
409
- await runCommand(
410
- gitPath,
411
- ["clone", repoUrl, targetDir, "--depth", "1", "--branch", DEFAULT_GIT_REF],
412
- cwd,
413
- signal
414
- );
415
- };
416
- const isAlreadyExistsError = (error) => error instanceof Error && "code" in error && error.code !== void 0 && ["EEXIST", "ENOTEMPTY", "EISDIR"].includes(
417
- String(error.code)
418
- );
419
- const prepareEmsdk = async (options) => {
420
- var _a, _b, _c, _d, _e, _f, _g, _h;
421
- if (!options) {
422
- throw new TypeError("options must be provided.");
423
- }
424
- if (options.targetVersion !== void 0 && typeof options.targetVersion !== "string") {
425
- throw new TypeError("targetVersion must be a string.");
426
- }
427
- const targetVersion = (_a = options.targetVersion) != null ? _a : DEFAULT_TARGET_VERSION;
428
- ensureNonEmpty(targetVersion, "targetVersion");
429
- (_b = options.signal) == null ? void 0 : _b.throwIfAborted();
430
- const cacheDir = path.resolve((_c = options.cacheDir) != null ? _c : DEFAULT_CACHE_DIR);
431
- const repoUrl = (_d = options.repoUrl) != null ? _d : DEFAULT_REPO_URL;
432
- const gitPath = (_e = options.gitPath) != null ? _e : "git";
433
- const versionDir = sanitizeSegment(targetVersion);
434
- const finalDir = path.resolve(cacheDir, versionDir);
435
- const mutex = getVersionMutex(finalDir);
436
- const lock = await mutex.lock(options.signal);
437
- try {
438
- (_f = options.signal) == null ? void 0 : _f.throwIfAborted();
439
- if (await pathExists(finalDir)) {
440
- return finalDir;
441
- }
442
- await ensureDirectory(cacheDir);
443
- const tempRoot = await promises.mkdtemp(path.join(cacheDir, ".tmp-"));
444
- const tempRepoDir = path.join(tempRoot, "emsdk");
445
- try {
446
- await runGitClone(
447
- gitPath,
448
- repoUrl,
449
- tempRepoDir,
450
- cacheDir,
451
- options.signal
452
- );
453
- (_g = options.signal) == null ? void 0 : _g.throwIfAborted();
454
- await runEmsdk(tempRepoDir, ["install", targetVersion], options.signal);
455
- try {
456
- await promises.rename(tempRepoDir, finalDir);
457
- } catch (error) {
458
- if (isAlreadyExistsError(error)) {
459
- return finalDir;
460
- }
461
- throw error;
462
- }
463
- } finally {
464
- await promises.rm(tempRoot, { recursive: true, force: true });
465
- }
466
- (_h = options.signal) == null ? void 0 : _h.throwIfAborted();
467
- await runEmsdk(finalDir, ["activate", targetVersion], options.signal);
468
- return finalDir;
469
- } finally {
470
- lock.release();
471
- }
472
- };
473
- const shellQuote = (value) => `'${String(value).replace(/'/g, `'"'"'`)}'`;
474
- const parseEnvBuffer = (buffer) => {
475
- const entries = buffer.toString("utf8").split("\0");
476
- const env = {};
477
- for (const entry of entries) {
478
- if (!entry) {
479
- continue;
480
- }
481
- const delimiterIndex = entry.indexOf("=");
482
- if (delimiterIndex <= 0) {
483
- continue;
484
- }
485
- const key = entry.slice(0, delimiterIndex);
486
- const value = entry.slice(delimiterIndex + 1);
487
- env[key] = value;
488
- }
489
- return env;
490
- };
491
- const loadEmsdkEnv = async (emsdkRoot, logger, signal) => {
492
- if (process.platform === "win32") {
493
- throw new Error(
494
- "Emscripten environment extraction on Windows is not implemented yet."
495
- );
496
- }
497
- const envScript = path.resolve(emsdkRoot, "emsdk_env.sh");
498
- if (!await pathExists(envScript)) {
499
- throw new Error(`emsdk_env.sh not found: ${envScript}`);
500
- }
501
- const command = `. ${shellQuote(envScript)} >/dev/null 2>&1; env -0`;
502
- logger.debug(`Loading emsdk environment: ${envScript}`);
503
- const output = await runCommandCapture(
504
- "bash",
505
- ["-lc", command],
506
- emsdkRoot,
507
- signal
508
- );
509
- return parseEnvBuffer(output);
510
- };
511
- const resolveEmccCommand = async (env, emsdkRoot) => {
512
- if (env.EMCC) {
513
- return env.EMCC;
514
- }
515
- if (env.EMSCRIPTEN) {
516
- const candidate = path.join(env.EMSCRIPTEN, "emcc");
517
- if (await pathExists(candidate)) {
518
- return candidate;
519
- }
520
- }
521
- const fallback = path.join(emsdkRoot, "upstream", "emscripten", "emcc");
522
- if (await pathExists(fallback)) {
523
- return fallback;
524
- }
525
- return "emcc";
526
- };
527
- const resolveEmarCommand = async (env, emsdkRoot) => {
528
- if (env.EMAR) {
529
- return env.EMAR;
530
- }
531
- if (env.EMSCRIPTEN) {
532
- const candidate = path.join(env.EMSCRIPTEN, "emar");
533
- if (await pathExists(candidate)) {
534
- return candidate;
535
- }
536
- }
537
- const fallback = path.join(emsdkRoot, "upstream", "emscripten", "emar");
538
- if (await pathExists(fallback)) {
539
- return fallback;
540
- }
541
- return "emar";
542
- };
543
- const resolveWasmOptCommand = async (env, emsdkRoot) => {
544
- var _a;
545
- if (env.WASM_OPT) {
546
- return env.WASM_OPT;
547
- }
548
- const binaryenRoot = (_a = env.BINARYEN_ROOT) != null ? _a : env.BINARYEN;
549
- if (binaryenRoot) {
550
- const candidate = path.join(binaryenRoot, "bin", "wasm-opt");
551
- if (await pathExists(candidate)) {
552
- return candidate;
553
- }
554
- }
555
- const fallback = path.join(emsdkRoot, "upstream", "bin", "wasm-opt");
556
- if (await pathExists(fallback)) {
557
- return fallback;
558
- }
559
- return "wasm-opt";
560
- };
561
- const createConsoleLogger = (prefix) => {
562
- return {
563
- debug: (msg) => console.debug(`[${prefix}]: ${msg}`),
564
- info: (msg) => console.info(`[${prefix}]: ${msg}`),
565
- warn: (msg) => console.warn(`[${prefix}]: ${msg}`),
566
- error: (msg) => console.error(`[${prefix}]: ${msg}`)
567
- };
568
- };
569
- const DEFAULT_WASM_SRC_DIR = "wasm";
570
- const DEFAULT_WASM_INCLUDE_DIR = "include";
571
- const DEFAULT_WASM_OUT_DIR = path.join("src", "wasm");
572
- const DEFAULT_WASM_LIB_DIR = "lib";
573
- const DEFAULT_IMPORT_INCLUDE_DIR = "include";
574
- const DEFAULT_IMPORT_LIB_DIR = "lib";
575
- const DEFAULT_WASM_BUILD_DIR = path.join(os.tmpdir(), "emsdk-env");
576
- const DEFAULT_EMSDK_TARGET_VERSION = "latest";
577
- const DEFAULT_WASM_OPT_ARGS = ["-Oz"];
578
- const DEFAULT_GENERATED_LOADER_OUT_FILE = path.join(
579
- "src",
580
- "generated",
581
- "wasm-loader.ts"
582
- );
583
- let buildSequence = 0;
584
- const padNumber = (value, length = 2) => String(value).padStart(length, "0");
585
- const formatTimestamp = (date) => {
586
- const year = date.getFullYear();
587
- const month = padNumber(date.getMonth() + 1);
588
- const day = padNumber(date.getDate());
589
- const hour = padNumber(date.getHours());
590
- const minute = padNumber(date.getMinutes());
591
- const second = padNumber(date.getSeconds());
592
- return `${year}${month}${day}_${hour}${minute}${second}`;
593
- };
594
- const createBuildId = () => {
595
- buildSequence += 1;
596
- const timestamp = formatTimestamp(/* @__PURE__ */ new Date());
597
- const seq = String(buildSequence).padStart(4, "0");
598
- return `${timestamp}_${seq}_${process.pid}`;
599
- };
600
- const ensureArray = (value) => value != null ? value : [];
601
- const resolveTargetType = (value) => value != null ? value : "wasm";
602
- const normalizePrepareOptions = (options) => {
603
- const { targetVersion, ...rest } = options != null ? options : {};
604
- return {
605
- targetVersion: targetVersion != null ? targetVersion : DEFAULT_EMSDK_TARGET_VERSION,
606
- ...rest
607
- };
608
- };
609
- const parseStringKeyValueInput = (values) => {
610
- const parsed = {};
611
- for (const entry of values) {
612
- const index = entry.indexOf("=");
613
- if (index === -1) {
614
- parsed[entry] = void 0;
615
- continue;
616
- }
617
- const key = entry.slice(0, index);
618
- const value = entry.slice(index + 1);
619
- parsed[key] = value;
620
- }
621
- return parsed;
622
- };
623
- const isDefineMap = (input) => input instanceof Map;
624
- const normalizeDefineInput = (input) => {
625
- if (!input) {
626
- return {};
627
- }
628
- if (Array.isArray(input)) {
629
- return parseStringKeyValueInput(input);
630
- }
631
- if (isDefineMap(input)) {
632
- return Object.fromEntries(input);
633
- }
634
- return { ...input };
635
- };
636
- const isLinkDirectiveMap = (input) => input instanceof Map;
637
- const normalizeLinkDirectiveInput = (input) => {
638
- if (!input) {
639
- return {};
640
- }
641
- if (Array.isArray(input)) {
642
- return parseStringKeyValueInput(input);
643
- }
644
- if (isLinkDirectiveMap(input)) {
645
- return Object.fromEntries(input);
646
- }
647
- return { ...input };
648
- };
649
- const mergeDefines = (common, target) => ({
650
- ...normalizeDefineInput(common),
651
- ...normalizeDefineInput(target)
652
- });
653
- const mergeLinkDirectives = (common, target) => ({
654
- ...normalizeLinkDirectiveInput(common),
655
- ...normalizeLinkDirectiveInput(target)
656
- });
657
- const resolveWasmOptEnabled = (common, target) => {
658
- var _a, _b;
659
- return (_b = (_a = target == null ? void 0 : target.enable) != null ? _a : common == null ? void 0 : common.enable) != null ? _b : false;
660
- };
661
- const resolveWasmOptArgs = (common, target, env) => {
662
- var _a, _b;
663
- const commonArgs = (_a = common == null ? void 0 : common.options) != null ? _a : DEFAULT_WASM_OPT_ARGS;
664
- const targetArgs = (_b = target == null ? void 0 : target.options) != null ? _b : [];
665
- const mergedArgs = [...commonArgs, ...targetArgs];
666
- return expandArray(mergedArgs, env, "wasmOpt.options");
667
- };
668
- const stripOuterQuotes = (value) => {
669
- const trimmed = value.trim();
670
- if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
671
- return trimmed.slice(1, -1);
672
- }
673
- return trimmed;
674
- };
675
- const extractWasmBinaryFile = (value) => {
676
- if (value.startsWith("WASM_BINARY_FILE=")) {
677
- return value.slice("WASM_BINARY_FILE=".length);
678
- }
679
- const match = value.match(/^(?:-s|--settings)(?:=)?WASM_BINARY_FILE=(.+)$/);
680
- if (match) {
681
- return match[1];
682
- }
683
- return void 0;
684
- };
685
- const resolveWasmBinaryFileFromLinkOptions = (linkOptions) => {
686
- for (let index = 0; index < linkOptions.length; index += 1) {
687
- const option = linkOptions[index];
688
- if (!option) {
689
- continue;
690
- }
691
- if (option === "-s" || option === "--settings") {
692
- const next = linkOptions[index + 1];
693
- if (!next) {
694
- continue;
695
- }
696
- const extracted2 = extractWasmBinaryFile(next);
697
- if (extracted2) {
698
- return stripOuterQuotes(extracted2);
699
- }
700
- }
701
- const extracted = extractWasmBinaryFile(option);
702
- if (extracted) {
703
- return stripOuterQuotes(extracted);
704
- }
705
- }
706
- return void 0;
707
- };
708
- const resolveWasmOptInputFile = (resolvedOutFile, resolvedLinkOptions) => {
709
- const wasmBinaryFile = resolveWasmBinaryFileFromLinkOptions(resolvedLinkOptions);
710
- if (wasmBinaryFile) {
711
- return path.isAbsolute(wasmBinaryFile) ? wasmBinaryFile : path.resolve(path.dirname(resolvedOutFile), wasmBinaryFile);
712
- }
713
- const parsed = path.parse(resolvedOutFile);
714
- if (parsed.ext.toLowerCase() === ".wasm") {
715
- return resolvedOutFile;
716
- }
717
- const baseName = parsed.name.toLowerCase().endsWith(".wasm") ? parsed.name : `${parsed.name}.wasm`;
718
- return path.join(parsed.dir, baseName);
719
- };
720
- const resolvePath = (rootDir, value) => path.isAbsolute(value) ? value : path.resolve(rootDir, value);
721
- const expandPlaceholders = (value, env, label) => value.replace(/\{([A-Z0-9_]+)\}/g, (_match, key) => {
722
- const replacement = env[key];
723
- if (replacement === void 0) {
724
- throw new Error(`Unknown placeholder {${key}} in ${label}.`);
725
- }
726
- return replacement;
727
- });
728
- const expandArray = (values, env, label) => values.map((value) => expandPlaceholders(value, env, label));
729
- const resolveDefines = (defines, env) => {
730
- const resolved = {};
731
- for (const [key, value] of Object.entries(defines)) {
732
- if (typeof value === "string") {
733
- resolved[key] = expandPlaceholders(value, env, `defines.${key}`);
734
- } else {
735
- resolved[key] = value;
736
- }
737
- }
738
- return resolved;
739
- };
740
- const resolveLinkDirectiveValue = (value, env, label) => {
741
- if (typeof value === "string") {
742
- return expandPlaceholders(value, env, label);
743
- }
744
- if (Array.isArray(value)) {
745
- return value.map(
746
- (entry, index) => expandPlaceholders(entry, env, `${label}[${index}]`)
747
- );
748
- }
749
- return value;
750
- };
751
- const resolveLinkDirectives = (directives, env) => {
752
- const resolved = {};
753
- for (const [key, value] of Object.entries(directives)) {
754
- resolved[key] = resolveLinkDirectiveValue(
755
- value,
756
- env,
757
- `linkDirectives.${key}`
758
- );
759
- }
760
- return resolved;
761
- };
762
- const resolveIncludeDirs = (includeDirs, env, rootDir) => {
763
- const expanded = expandArray(includeDirs, env, "includeDirs");
764
- return expanded.map((value) => resolvePath(rootDir, value));
765
- };
766
- const resolveOutFile = (outFile, env, outDir) => {
767
- const expanded = expandPlaceholders(outFile, env, "outFile");
768
- return resolvePath(outDir, expanded);
769
- };
770
- const resolveSourcesFromPatterns = async (patterns, env, srcDir, label) => {
771
- const expanded = expandArray(patterns, env, label);
772
- const resolvedPatterns = expanded.map((value) => resolvePath(srcDir, value));
773
- const results = await Promise.all(
774
- resolvedPatterns.map((pattern) => glob.glob(pattern, { nodir: true }))
775
- );
776
- const sources = results.flat();
777
- sources.sort();
778
- return sources;
779
- };
780
- const buildDefineFlags = (defines) => Object.entries(defines).flatMap(
781
- ([key, value]) => value === null || value === void 0 ? [`-D${key}`] : [`-D${key}=${String(value)}`]
782
- );
783
- const serializeLinkDirectiveValue = (value) => Array.isArray(value) ? JSON.stringify(value) : String(value);
784
- const buildLinkDirectiveFlags = (directives) => {
785
- if (Object.keys(directives).length === 0) {
786
- return [];
787
- }
788
- return Object.entries(directives).flatMap(
789
- ([key, value]) => value === null || value === void 0 ? ["-s", key] : ["-s", `${key}=${serializeLinkDirectiveValue(value)}`]
790
- );
791
- };
792
- const buildExportFlags = (exports$1) => {
793
- if (exports$1.length === 0) {
794
- return [];
795
- }
796
- return ["-s", `EXPORTED_FUNCTIONS=${JSON.stringify(exports$1)}`];
797
- };
798
- const createEnvForBuild = (baseEnv, overrides) => ({
799
- ...process.env,
800
- ...baseEnv,
801
- ...overrides
802
- });
803
- const resolveTargetOutFile = (targetName, targetOutFile, env, baseDir, extension) => {
804
- if (targetOutFile) {
805
- return resolveOutFile(targetOutFile, env, baseDir);
806
- }
807
- return path.resolve(baseDir, `${targetName}.${extension}`);
808
- };
809
- const resolveTargetSources = async (targetSources, env, srcDir) => {
810
- const patterns = targetSources && targetSources.length > 0 ? targetSources : [path.join(srcDir, "**", "*.c"), path.join(srcDir, "**", "*.cpp")];
811
- return resolveSourcesFromPatterns(patterns, env, srcDir, "sources");
812
- };
813
- const toSafeObjectName = (rootDir, sourcePath, groupIndex) => {
814
- const baseName = path.relative(rootDir, sourcePath).replace(/[\\/]/g, "_").replace(/[^A-Za-z0-9._-]/g, "_");
815
- if (groupIndex === void 0) {
816
- return baseName;
817
- }
818
- return `${baseName}__g${groupIndex}`;
819
- };
820
- const dedupeSources = (sources) => {
821
- const seen = /* @__PURE__ */ new Set();
822
- const deduped = [];
823
- for (const source of sources) {
824
- if (seen.has(source)) {
825
- continue;
826
- }
827
- seen.add(source);
828
- deduped.push(source);
829
- }
830
- return deduped;
831
- };
832
- const dedupeValues = (values) => {
833
- const seen = /* @__PURE__ */ new Set();
834
- const deduped = [];
835
- for (const value of values) {
836
- if (seen.has(value)) {
837
- continue;
838
- }
839
- seen.add(value);
840
- deduped.push(value);
841
- }
842
- return deduped;
843
- };
844
- const isSubPath = (parentDir, targetPath) => {
845
- const rel = path.relative(parentDir, targetPath);
846
- if (rel === "") {
847
- return true;
848
- }
849
- return !rel.startsWith("..") && !path.isAbsolute(rel);
850
- };
851
- const readTextIfExists = async (filePath) => {
852
- try {
853
- return await promises.readFile(filePath, "utf8");
854
- } catch (error) {
855
- const nodeError = error;
856
- if (nodeError.code === "ENOENT") {
857
- return void 0;
858
- }
859
- throw error;
860
- }
861
- };
862
- const writeTextIfChanged = async (filePath, content) => {
863
- const existing = await readTextIfExists(filePath);
864
- if (existing === content) {
865
- return false;
866
- }
867
- await ensureDirectory(path.dirname(filePath));
868
- await promises.writeFile(filePath, content, "utf8");
869
- return true;
870
- };
871
- const toPascalCaseIdentifier = (value) => {
872
- const tokens = value.split(/[^A-Za-z0-9]+/).map((token) => token.trim()).filter((token) => token.length > 0);
873
- if (tokens.length === 0) {
874
- throw new Error(`Cannot derive loader function name from target: ${value}`);
875
- }
876
- const pascal = tokens.map((token) => token.charAt(0).toUpperCase() + token.slice(1)).join("");
877
- return /^[0-9]/.test(pascal) ? `Target${pascal}` : pascal;
878
- };
879
- const toRelativeImportSpecifier = (fromFile, toFile) => {
880
- const rel = path.relative(path.dirname(fromFile), toFile).replace(/\\/g, "/");
881
- return rel.startsWith(".") ? rel : `./${rel}`;
882
- };
883
- const buildGeneratedLoaderContent = (generatedLoaderFile, targets) => {
884
- const targetBlocks = targets.map((target) => {
885
- const specifier = JSON.stringify(
886
- toRelativeImportSpecifier(generatedLoaderFile, target.outFile)
887
- );
888
- return `export const ${target.functionName} = async <T extends object>(
889
- options?: TargetWasmLoadOptions
890
- ): Promise<WasmInstance<T>> => {
891
- const source = options?.url ?? new URL(${specifier}, import.meta.url);
892
- return await loadWasm<T>(source, {
893
- imports: options?.imports,
894
- });
895
- };`;
896
- }).join("\n\n");
897
- return `// Generated by emsdk-env. DO NOT EDIT.
898
-
899
- export type WasmSource =
900
- | string
901
- | URL
902
- | ArrayBuffer
903
- | ArrayBufferView
904
- | Response;
905
-
906
- export interface WasmLoadOptions {
907
- readonly imports?: WebAssembly.Imports;
908
- }
909
-
910
- export interface TargetWasmLoadOptions extends WasmLoadOptions {
911
- readonly url?: string | URL;
912
- }
913
-
914
- export interface WasmInstance<T extends object> {
915
- readonly exports: T;
916
- readonly memory: WebAssembly.Memory;
917
- readonly table: WebAssembly.Table | undefined;
918
- readonly rawExports: WebAssembly.Exports;
919
- readonly module: WebAssembly.Module;
920
- readonly instance: WebAssembly.Instance;
921
- readonly initialize: (() => unknown) | undefined;
922
- readonly start: (() => unknown) | undefined;
923
- }
924
-
925
- const resolveWasmBytes = async (source: WasmSource): Promise<ArrayBuffer> => {
926
- if (typeof Response !== 'undefined' && source instanceof Response) {
927
- return await source.arrayBuffer();
928
- }
929
- if (source instanceof URL || typeof source === 'string') {
930
- const response = await fetch(source);
931
- if (!response.ok) {
932
- throw new Error(\`Failed to fetch wasm: \${response.url}\`);
933
- }
934
- return await response.arrayBuffer();
935
- }
936
- if (ArrayBuffer.isView(source)) {
937
- const view = new Uint8Array(
938
- source.buffer,
939
- source.byteOffset,
940
- source.byteLength
941
- );
942
- return view.slice().buffer;
943
- }
944
- return source;
945
- };
946
-
947
- const getImportValue = (
948
- imports: WebAssembly.Imports | undefined,
949
- moduleName: string,
950
- name: string
951
- ) => {
952
- const moduleImports = imports?.[moduleName];
953
- if (!moduleImports || typeof moduleImports !== 'object') {
954
- return undefined;
955
- }
956
- return (moduleImports as Record<string, unknown>)[name];
957
- };
958
-
959
- const resolveMemory = (
960
- module: WebAssembly.Module,
961
- instance: WebAssembly.Instance,
962
- imports: WebAssembly.Imports | undefined
963
- ) => {
964
- let memory: WebAssembly.Memory | undefined;
965
- for (const entry of WebAssembly.Module.exports(module)) {
966
- if (entry.kind !== 'memory') {
967
- continue;
968
- }
969
- if (memory) {
970
- throw new Error('Multiple wasm memories are not supported.');
971
- }
972
- const value = instance.exports[entry.name];
973
- if (!(value instanceof WebAssembly.Memory)) {
974
- throw new Error(\`Export is not a WebAssembly.Memory: \${entry.name}\`);
975
- }
976
- memory = value;
977
- }
978
- if (memory) {
979
- return memory;
980
- }
981
- for (const entry of WebAssembly.Module.imports(module)) {
982
- if (entry.kind !== 'memory') {
983
- continue;
984
- }
985
- if (memory) {
986
- throw new Error('Multiple wasm memories are not supported.');
987
- }
988
- const value = getImportValue(imports, entry.module, entry.name);
989
- if (!(value instanceof WebAssembly.Memory)) {
990
- throw new Error(
991
- \`Imported value is not a WebAssembly.Memory: \${entry.module}.\${entry.name}\`
992
- );
993
- }
994
- memory = value;
995
- }
996
- if (!memory) {
997
- throw new Error('WASM memory export/import was not resolved.');
998
- }
999
- return memory;
1000
- };
1001
-
1002
- const resolveTable = (
1003
- module: WebAssembly.Module,
1004
- instance: WebAssembly.Instance,
1005
- imports: WebAssembly.Imports | undefined
1006
- ) => {
1007
- let table: WebAssembly.Table | undefined;
1008
- for (const entry of WebAssembly.Module.exports(module)) {
1009
- if (entry.kind !== 'table') {
1010
- continue;
1011
- }
1012
- if (table) {
1013
- throw new Error('Multiple wasm tables are not supported.');
1014
- }
1015
- const value = instance.exports[entry.name];
1016
- if (!(value instanceof WebAssembly.Table)) {
1017
- throw new Error(\`Export is not a WebAssembly.Table: \${entry.name}\`);
1018
- }
1019
- table = value;
1020
- }
1021
- if (table) {
1022
- return table;
1023
- }
1024
- for (const entry of WebAssembly.Module.imports(module)) {
1025
- if (entry.kind !== 'table') {
1026
- continue;
1027
- }
1028
- if (table) {
1029
- throw new Error('Multiple wasm tables are not supported.');
1030
- }
1031
- const value = getImportValue(imports, entry.module, entry.name);
1032
- if (!(value instanceof WebAssembly.Table)) {
1033
- throw new Error(
1034
- \`Imported value is not a WebAssembly.Table: \${entry.module}.\${entry.name}\`
1035
- );
1036
- }
1037
- table = value;
1038
- }
1039
- return table;
1040
- };
1041
-
1042
- export const loadWasm = async <T extends object>(
1043
- source: WasmSource,
1044
- options?: WasmLoadOptions
1045
- ): Promise<WasmInstance<T>> => {
1046
- const bytes = await resolveWasmBytes(source);
1047
- const module = await WebAssembly.compile(bytes);
1048
- const instance = await WebAssembly.instantiate(module, options?.imports ?? {});
1049
-
1050
- const functionExports: Record<string, (...args: unknown[]) => unknown> = {};
1051
- for (const entry of WebAssembly.Module.exports(module)) {
1052
- if (entry.kind !== 'function') {
1053
- continue;
1054
- }
1055
- const value = instance.exports[entry.name];
1056
- if (typeof value !== 'function') {
1057
- throw new Error(\`Export is not a function: \${entry.name}\`);
1058
- }
1059
- functionExports[entry.name] = value as (...args: unknown[]) => unknown;
1060
- }
1061
-
1062
- const initialize =
1063
- typeof instance.exports._initialize === 'function'
1064
- ? (instance.exports._initialize as () => unknown)
1065
- : undefined;
1066
- const start =
1067
- typeof instance.exports._start === 'function'
1068
- ? (instance.exports._start as () => unknown)
1069
- : undefined;
1070
-
1071
- return {
1072
- exports: functionExports as T,
1073
- memory: resolveMemory(module, instance, options?.imports),
1074
- table: resolveTable(module, instance, options?.imports),
1075
- rawExports: instance.exports,
1076
- module,
1077
- instance,
1078
- initialize,
1079
- start,
1080
- };
1081
- };
1082
-
1083
- ${targetBlocks}
1084
- `;
1085
- };
1086
- const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
1087
- const resolvePackageJsonPath = async (startPath, packageName) => {
1088
- let current = path.dirname(startPath);
1089
- for (; ; ) {
1090
- const candidate = path.join(current, "package.json");
1091
- if (await pathExists(candidate)) {
1092
- return candidate;
1093
- }
1094
- const parent = path.dirname(current);
1095
- if (parent === current) {
1096
- throw new Error(`package.json not found for import: ${packageName}`);
1097
- }
1098
- current = parent;
1099
- }
1100
- };
1101
- const loadPackageJson = async (packageJsonPath, packageName) => {
1102
- try {
1103
- const raw = await promises.readFile(packageJsonPath, "utf8");
1104
- const parsed = JSON.parse(raw);
1105
- if (!isRecord(parsed)) {
1106
- throw new Error("package.json must be an object.");
1107
- }
1108
- return parsed;
1109
- } catch (error) {
1110
- const message = error instanceof Error ? error.message : String(error);
1111
- throw new Error(
1112
- `Failed to read package.json for import ${packageName}: ${message}`
1113
- );
1114
- }
1115
- };
1116
- const resolveImportPaths = async (resolver, packageName) => {
1117
- let resolvedEntry;
1118
- try {
1119
- resolvedEntry = resolver.resolve(packageName);
1120
- } catch (error) {
1121
- const message = error instanceof Error ? error.message : String(error);
1122
- throw new Error(`Failed to resolve import ${packageName}: ${message}`);
1123
- }
1124
- const packageJsonPath = await resolvePackageJsonPath(
1125
- resolvedEntry,
1126
- packageName
1127
- );
1128
- const packageRoot = path.dirname(packageJsonPath);
1129
- const packageJson = await loadPackageJson(packageJsonPath, packageName);
1130
- const emsdkConfigRaw = packageJson["emsdk-env"];
1131
- if (emsdkConfigRaw !== void 0 && !isRecord(emsdkConfigRaw)) {
1132
- throw new Error(
1133
- `Invalid emsdk-env config for import ${packageName}: expected an object.`
1134
- );
1135
- }
1136
- const includeRaw = isRecord(emsdkConfigRaw) ? emsdkConfigRaw.include : void 0;
1137
- if (includeRaw !== void 0 && typeof includeRaw !== "string") {
1138
- throw new Error(
1139
- `Invalid emsdk-env include for import ${packageName}: expected a string.`
1140
- );
1141
- }
1142
- const libRaw = isRecord(emsdkConfigRaw) ? emsdkConfigRaw.lib : void 0;
1143
- if (libRaw !== void 0 && typeof libRaw !== "string") {
1144
- throw new Error(
1145
- `Invalid emsdk-env lib for import ${packageName}: expected a string.`
1146
- );
1147
- }
1148
- const includeRel = includeRaw != null ? includeRaw : DEFAULT_IMPORT_INCLUDE_DIR;
1149
- const libRel = libRaw != null ? libRaw : DEFAULT_IMPORT_LIB_DIR;
1150
- const includeDir = path.resolve(packageRoot, includeRel);
1151
- const libDir = path.resolve(packageRoot, libRel);
1152
- const includeExists = await pathExists(includeDir);
1153
- const libExists = await pathExists(libDir);
1154
- if (!includeExists && !libExists) {
1155
- throw new Error(
1156
- `Import ${packageName} does not provide include or lib directories.`
1157
- );
1158
- }
1159
- return {
1160
- includeDir: includeExists ? includeDir : void 0,
1161
- libDir: libExists ? libDir : void 0
1162
- };
1163
- };
1164
- const resolveImportDirectories = async (rootDir, imports) => {
1165
- if (imports.length === 0) {
1166
- return { includeDirs: [], libDirs: [] };
1167
- }
1168
- const moduleApi = await import("node:module");
1169
- const resolver = moduleApi.createRequire(path.resolve(rootDir, "package.json"));
1170
- const includeDirs = [];
1171
- const libDirs = [];
1172
- for (const packageName of imports) {
1173
- const resolved = await resolveImportPaths(resolver, packageName);
1174
- if (resolved.includeDir) {
1175
- includeDirs.push(resolved.includeDir);
1176
- }
1177
- if (resolved.libDir) {
1178
- libDirs.push(resolved.libDir);
1179
- }
1180
- }
1181
- return {
1182
- includeDirs: dedupeValues(includeDirs),
1183
- libDirs: dedupeValues(libDirs)
1184
- };
1185
- };
1186
- const resolveGeneratedLoaderOutFile = (rootDir, env, generatedLoader) => {
1187
- var _a;
1188
- if (!(generatedLoader == null ? void 0 : generatedLoader.enable)) {
1189
- return void 0;
1190
- }
1191
- const rawOutFile = expandPlaceholders(
1192
- (_a = generatedLoader.outFile) != null ? _a : DEFAULT_GENERATED_LOADER_OUT_FILE,
1193
- env,
1194
- "generatedLoader.outFile"
1195
- );
1196
- return resolvePath(rootDir, rawOutFile);
1197
- };
1198
- const resolveGeneratedLoaderWatchDirs = (rootDir, srcDir, commonIncludeDirs, env, targetEntries, importIncludeDirs) => {
1199
- const dirs = [srcDir, ...resolveIncludeDirs(commonIncludeDirs, env, rootDir)];
1200
- for (const [targetName, target] of targetEntries) {
1201
- if (!target.includeDirs || target.includeDirs.length === 0) {
1202
- continue;
1203
- }
1204
- const targetEnv = {
1205
- ...env,
1206
- TARGET_NAME: targetName
1207
- };
1208
- dirs.push(...resolveIncludeDirs(target.includeDirs, targetEnv, rootDir));
1209
- }
1210
- dirs.push(...importIncludeDirs);
1211
- return dedupeValues(dirs);
1212
- };
1213
- const validateGeneratedLoaderOutFile = (generatedLoaderFile, watchDirs) => {
1214
- for (const dir of watchDirs) {
1215
- if (isSubPath(dir, generatedLoaderFile)) {
1216
- throw new Error(
1217
- `generatedLoader.outFile must not be placed under watched directory: ${generatedLoaderFile}`
1218
- );
1219
- }
1220
- }
1221
- };
1222
- const buildCompileArgs = (options, includeDirs, defines, env, rootDir) => {
1223
- const resolvedOptions = expandArray(options, env, "options");
1224
- const includeArgs = resolveIncludeDirs(includeDirs, env, rootDir).map(
1225
- (dir) => `-I${dir}`
1226
- );
1227
- const defineArgs = buildDefineFlags(resolveDefines(defines, env));
1228
- return { resolvedOptions, includeArgs, defineArgs };
1229
- };
1230
- const buildWasm = async (options) => {
1231
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
1232
- if (!options) {
1233
- throw new TypeError("options must be provided.");
1234
- }
1235
- if (!options.rule || !options.rule.targets) {
1236
- throw new TypeError("rule targets must be provided.");
1237
- }
1238
- const targetEntries = Object.entries(options.rule.targets);
1239
- if (targetEntries.length === 0) {
1240
- throw new TypeError("rule targets must not be empty.");
1241
- }
1242
- const logger = (_a = options.logger) != null ? _a : createConsoleLogger("emsdk-env");
1243
- const rootDir = path.resolve((_b = options.root) != null ? _b : process.cwd());
1244
- const emsdkOptions = normalizePrepareOptions(options.emsdk);
1245
- const emsdkRoot = await prepareEmsdk(emsdkOptions);
1246
- const emsdkEnv = await loadEmsdkEnv(emsdkRoot, logger, emsdkOptions.signal);
1247
- const baseEnv = {
1248
- ...emsdkEnv,
1249
- ROOT: rootDir
1250
- };
1251
- const rawSrcDir = expandPlaceholders(
1252
- (_c = options.srcDir) != null ? _c : DEFAULT_WASM_SRC_DIR,
1253
- baseEnv,
1254
- "srcDir"
1255
- );
1256
- const rawIncludeDir = expandPlaceholders(
1257
- (_d = options.includeDir) != null ? _d : DEFAULT_WASM_INCLUDE_DIR,
1258
- baseEnv,
1259
- "includeDir"
1260
- );
1261
- const rawOutDir = expandPlaceholders(
1262
- (_e = options.outDir) != null ? _e : DEFAULT_WASM_OUT_DIR,
1263
- baseEnv,
1264
- "outDir"
1265
- );
1266
- const rawLibDir = expandPlaceholders(
1267
- (_f = options.libDir) != null ? _f : DEFAULT_WASM_LIB_DIR,
1268
- baseEnv,
1269
- "libDir"
1270
- );
1271
- const rawBuildDir = expandPlaceholders(
1272
- (_g = options.buildDir) != null ? _g : DEFAULT_WASM_BUILD_DIR,
1273
- baseEnv,
1274
- "buildDir"
1275
- );
1276
- const srcDir = resolvePath(rootDir, rawSrcDir);
1277
- const includeDir = resolvePath(rootDir, rawIncludeDir);
1278
- const outDir = resolvePath(rootDir, rawOutDir);
1279
- const libDir = resolvePath(rootDir, rawLibDir);
1280
- const buildDir = resolvePath(rootDir, rawBuildDir);
1281
- const buildId = createBuildId();
1282
- const buildRunDir = path.resolve(buildDir, buildId);
1283
- const cleanupBuildDir = (_h = options.cleanupBuildDir) != null ? _h : true;
1284
- const parallel = (_i = options.parallel) != null ? _i : true;
1285
- const envWithDirs = {
1286
- ...emsdkEnv,
1287
- ROOT: rootDir,
1288
- SRC_DIR: srcDir,
1289
- INCLUDE_DIR: includeDir,
1290
- OUT_DIR: outDir,
1291
- LIB_DIR: libDir,
1292
- BUILD_DIR: buildDir
1293
- };
1294
- const emccCommand = await resolveEmccCommand(envWithDirs, emsdkRoot);
1295
- const common = (_j = options.rule.common) != null ? _j : {};
1296
- const commonIncludeDirs = common.includeDirs === void 0 ? [includeDir] : common.includeDirs;
1297
- const importDirectories = await resolveImportDirectories(
1298
- rootDir,
1299
- ensureArray(options.imports)
1300
- );
1301
- const importIncludeDirs = importDirectories.includeDirs;
1302
- const importLibDirs = importDirectories.libDirs;
1303
- const linkLibDirs = dedupeValues([libDir, ...importLibDirs]);
1304
- const generatedLoaderFile = resolveGeneratedLoaderOutFile(
1305
- rootDir,
1306
- envWithDirs,
1307
- options.generatedLoader
1308
- );
1309
- if (generatedLoaderFile) {
1310
- const watchDirs = resolveGeneratedLoaderWatchDirs(
1311
- rootDir,
1312
- srcDir,
1313
- commonIncludeDirs,
1314
- envWithDirs,
1315
- targetEntries,
1316
- importIncludeDirs
1317
- );
1318
- validateGeneratedLoaderOutFile(generatedLoaderFile, watchDirs);
1319
- }
1320
- logger.debug(`Detected rootDir: '${rootDir}'`);
1321
- logger.debug(`Detected srcDir: '${srcDir}'`);
1322
- logger.debug(`Detected outDir: '${outDir}'`);
1323
- logger.debug(`Detected libDir: '${libDir}'`);
1324
- logger.debug(`Detected buildDir: '${buildDir}'`);
1325
- logger.debug(`Detected buildId: '${buildId}'`);
1326
- logger.debug(`Detected buildRunDir: '${buildRunDir}'`);
1327
- logger.debug(`Detected cleanupBuildDir: ${cleanupBuildDir}`);
1328
- logger.debug(`Detected parallel: ${parallel}`);
1329
- logger.debug(`Detected emccCommand: '${emccCommand}'`);
1330
- logger.debug(
1331
- `Detected importIncludeDirs: [${importIncludeDirs.map((p) => `'${p}'`).join(",")}]`
1332
- );
1333
- logger.debug(
1334
- `Detected importLibDirs: [${importLibDirs.map((p) => `'${p}'`).join(",")}]`
1335
- );
1336
- if (generatedLoaderFile) {
1337
- logger.debug(`Detected generatedLoaderFile: '${generatedLoaderFile}'`);
1338
- }
1339
- await ensureDirectory(outDir);
1340
- await ensureDirectory(libDir);
1341
- await ensureDirectory(buildDir);
1342
- await promises.rm(buildRunDir, { recursive: true, force: true });
1343
- await ensureDirectory(buildRunDir);
1344
- const hasArchiveTargets = targetEntries.some(
1345
- ([, target]) => resolveTargetType(target.type) === "archive"
1346
- );
1347
- const emarCommand = hasArchiveTargets ? await resolveEmarCommand(envWithDirs, emsdkRoot) : void 0;
1348
- if (emarCommand) {
1349
- logger.debug(`Detected emarCommand: '${emarCommand}'`);
1350
- }
1351
- let wasmOptCommand;
1352
- const getWasmOptCommand = async () => {
1353
- if (wasmOptCommand) {
1354
- return wasmOptCommand;
1355
- }
1356
- wasmOptCommand = await resolveWasmOptCommand(envWithDirs, emsdkRoot);
1357
- logger.debug(`Detected wasmOptCommand: '${wasmOptCommand}'`);
1358
- return wasmOptCommand;
1359
- };
1360
- const outFiles = {};
1361
- let resultGeneratedLoaderFile;
1362
- const buildTargets = async (expectedType) => {
1363
- var _a2;
1364
- for (const [targetName, target] of targetEntries) {
1365
- const targetType = resolveTargetType(target.type);
1366
- if (targetType !== expectedType) {
1367
- continue;
1368
- }
1369
- if (targetType === "archive") {
1370
- if (target.linkOptions !== void 0) {
1371
- throw new Error(
1372
- `linkOptions is not supported for archive target: ${targetName}`
1373
- );
1374
- }
1375
- if (target.linkDirectives !== void 0) {
1376
- throw new Error(
1377
- `linkDirectives is not supported for archive target: ${targetName}`
1378
- );
1379
- }
1380
- if (target.exports !== void 0) {
1381
- throw new Error(
1382
- `exports is not supported for archive target: ${targetName}`
1383
- );
1384
- }
1385
- if (target.wasmOpt !== void 0) {
1386
- throw new Error(
1387
- `wasmOpt is not supported for archive target: ${targetName}`
1388
- );
1389
- }
1390
- }
1391
- const mergedLinkOptions = targetType === "archive" ? [] : [
1392
- ...ensureArray(common.linkOptions),
1393
- ...ensureArray(target.linkOptions)
1394
- ];
1395
- const mergedLinkDirectives = targetType === "archive" ? {} : mergeLinkDirectives(common.linkDirectives, target.linkDirectives);
1396
- const mergedExports = targetType === "archive" ? [] : [...ensureArray(common.exports), ...ensureArray(target.exports)];
1397
- const wasmOptEnabled = targetType === "archive" ? false : resolveWasmOptEnabled(common.wasmOpt, target.wasmOpt);
1398
- const baseCompileOptions = [
1399
- ...ensureArray(common.options),
1400
- ...ensureArray(target.options)
1401
- ];
1402
- const baseIncludeDirs = [
1403
- ...ensureArray(commonIncludeDirs),
1404
- ...ensureArray(target.includeDirs),
1405
- ...importIncludeDirs
1406
- ];
1407
- const baseDefines = mergeDefines(common.defines, target.defines);
1408
- const sourceGroups = (_a2 = target.sourceGroups) != null ? _a2 : [];
1409
- const targetEnv = {
1410
- ...envWithDirs,
1411
- TARGET_NAME: targetName
1412
- };
1413
- const buildEnv = createEnvForBuild(targetEnv, {});
1414
- const resolvedOutFile = resolveTargetOutFile(
1415
- targetName,
1416
- target.outFile,
1417
- targetEnv,
1418
- targetType === "archive" ? libDir : outDir,
1419
- targetType === "archive" ? "a" : "wasm"
1420
- );
1421
- const sources = await resolveTargetSources(
1422
- target.sources,
1423
- targetEnv,
1424
- srcDir
1425
- );
1426
- const groupSources = sourceGroups.map(() => []);
1427
- const groupSourceSet = /* @__PURE__ */ new Set();
1428
- for (let index = 0; index < sourceGroups.length; index += 1) {
1429
- const group = sourceGroups[index];
1430
- if (!group) {
1431
- continue;
1432
- }
1433
- const resolved = await resolveSourcesFromPatterns(
1434
- group.sources,
1435
- targetEnv,
1436
- srcDir,
1437
- `sourceGroups[${index}].sources`
1438
- );
1439
- const deduped = dedupeSources(resolved);
1440
- groupSources[index] = deduped;
1441
- for (const source of deduped) {
1442
- groupSourceSet.add(source);
1443
- }
1444
- }
1445
- const baseSources = sources.filter(
1446
- (source) => !groupSourceSet.has(source)
1447
- );
1448
- const groupedSources = groupSources.flat();
1449
- if (baseSources.length + groupedSources.length === 0) {
1450
- throw new Error(`No sources matched for target: ${targetName}`);
1451
- }
1452
- const targetBuildDir = path.resolve(buildRunDir, targetName);
1453
- await promises.rm(targetBuildDir, { recursive: true, force: true });
1454
- await ensureDirectory(targetBuildDir);
1455
- const resolvedLinkDirectives = targetType === "archive" ? {} : resolveLinkDirectives(mergedLinkDirectives, targetEnv);
1456
- const linkDirectiveArgs = buildLinkDirectiveFlags(resolvedLinkDirectives);
1457
- const resolvedLinkOptions = targetType === "archive" ? [] : [
1458
- ...linkDirectiveArgs,
1459
- ...expandArray(mergedLinkOptions, targetEnv, "linkOptions")
1460
- ];
1461
- const resolvedExports = targetType === "archive" ? [] : expandArray(mergedExports, targetEnv, "exports");
1462
- const exportArgs = buildExportFlags(resolvedExports);
1463
- const resolvedWasmOptArgs = wasmOptEnabled ? resolveWasmOptArgs(common.wasmOpt, target.wasmOpt, targetEnv) : [];
1464
- const baseCompileArgs = buildCompileArgs(
1465
- baseCompileOptions,
1466
- baseIncludeDirs,
1467
- baseDefines,
1468
- targetEnv,
1469
- rootDir
1470
- );
1471
- const groupCompileArgs = sourceGroups.map((group) => {
1472
- const groupOptions = [
1473
- ...baseCompileOptions,
1474
- ...ensureArray(group == null ? void 0 : group.options)
1475
- ];
1476
- const groupIncludeDirs = [
1477
- ...baseIncludeDirs,
1478
- ...ensureArray(group == null ? void 0 : group.includeDirs)
1479
- ];
1480
- const groupDefines = mergeDefines(baseDefines, group == null ? void 0 : group.defines);
1481
- return buildCompileArgs(
1482
- groupOptions,
1483
- groupIncludeDirs,
1484
- groupDefines,
1485
- targetEnv,
1486
- rootDir
1487
- );
1488
- });
1489
- const compileSource = async (source, args, groupIndex) => {
1490
- const objectName = toSafeObjectName(rootDir, source, groupIndex);
1491
- const outputObject = path.resolve(targetBuildDir, `${objectName}.o`);
1492
- const compileArgs = [
1493
- "-c",
1494
- source,
1495
- "-o",
1496
- outputObject,
1497
- ...args.resolvedOptions,
1498
- ...args.includeArgs,
1499
- ...args.defineArgs
1500
- ];
1501
- const sourcePath = path.relative(rootDir, source);
1502
- logger.info(`Compiling source: ${sourcePath} --> $tmp/${objectName}.o`);
1503
- logger.debug(`emcc ${compileArgs.join(" ")}`);
1504
- await runCommandWithEnv(
1505
- emccCommand,
1506
- compileArgs,
1507
- rootDir,
1508
- buildEnv,
1509
- emsdkOptions.signal
1510
- );
1511
- return outputObject;
1512
- };
1513
- const buildObjectsSequential = async () => {
1514
- const objectFiles2 = [];
1515
- for (const source of baseSources) {
1516
- objectFiles2.push(
1517
- await compileSource(source, baseCompileArgs, void 0)
1518
- );
1519
- }
1520
- for (let index = 0; index < groupSources.length; index += 1) {
1521
- const sourcesInGroup = groupSources[index];
1522
- if (!sourcesInGroup) {
1523
- continue;
1524
- }
1525
- const groupArgs = groupCompileArgs[index];
1526
- if (!groupArgs) {
1527
- continue;
1528
- }
1529
- for (const source of sourcesInGroup) {
1530
- objectFiles2.push(await compileSource(source, groupArgs, index));
1531
- }
1532
- }
1533
- return objectFiles2;
1534
- };
1535
- const compileJobs = [];
1536
- for (const source of baseSources) {
1537
- compileJobs.push({
1538
- source,
1539
- args: baseCompileArgs,
1540
- groupIndex: void 0
1541
- });
1542
- }
1543
- for (let index = 0; index < groupSources.length; index += 1) {
1544
- const sourcesInGroup = groupSources[index];
1545
- if (!sourcesInGroup) {
1546
- continue;
1547
- }
1548
- const groupArgs = groupCompileArgs[index];
1549
- if (!groupArgs) {
1550
- continue;
1551
- }
1552
- for (const source of sourcesInGroup) {
1553
- compileJobs.push({ source, args: groupArgs, groupIndex: index });
1554
- }
1555
- }
1556
- logger.info(
1557
- parallel ? `Building target: '${targetName}' [${compileJobs.length} files, in parallel]` : `Building target: '${targetName}' [${compileJobs.length} files]`
1558
- );
1559
- const objectFiles = parallel ? await Promise.all(
1560
- compileJobs.map(
1561
- (job) => compileSource(job.source, job.args, job.groupIndex)
1562
- )
1563
- ) : await buildObjectsSequential();
1564
- if (targetType === "archive") {
1565
- if (!emarCommand) {
1566
- throw new Error("emar command is required for archive targets.");
1567
- }
1568
- logger.info(`Archiving target: ${targetName}.a`);
1569
- const archiveArgs = ["rcs", resolvedOutFile, ...objectFiles];
1570
- logger.debug(`emar ${archiveArgs.join(" ")}`);
1571
- await runCommandWithEnv(
1572
- emarCommand,
1573
- archiveArgs,
1574
- rootDir,
1575
- buildEnv,
1576
- emsdkOptions.signal
1577
- );
1578
- } else {
1579
- logger.info(`Linking target: ${targetName}.wasm`);
1580
- const linkArgs = [
1581
- ...objectFiles,
1582
- "-o",
1583
- resolvedOutFile,
1584
- ...linkLibDirs.map((dir) => `-L${dir}`),
1585
- ...resolvedLinkOptions,
1586
- ...exportArgs
1587
- ];
1588
- logger.debug(`emcc ${linkArgs.join(" ")}`);
1589
- await runCommandWithEnv(
1590
- emccCommand,
1591
- linkArgs,
1592
- rootDir,
1593
- buildEnv,
1594
- emsdkOptions.signal
1595
- );
1596
- if (wasmOptEnabled) {
1597
- const wasmOptInput = resolveWasmOptInputFile(
1598
- resolvedOutFile,
1599
- resolvedLinkOptions
1600
- );
1601
- if (!await pathExists(wasmOptInput)) {
1602
- throw new Error(
1603
- `wasm-opt enabled but wasm binary not found: ${wasmOptInput}`
1604
- );
1605
- }
1606
- const tempOutFile = `${wasmOptInput}.opt`;
1607
- const wasmOptArgs = [
1608
- wasmOptInput,
1609
- "-o",
1610
- tempOutFile,
1611
- ...resolvedWasmOptArgs
1612
- ];
1613
- const wasmOptCommand2 = await getWasmOptCommand();
1614
- logger.info(`Optimizing target: ${targetName}.wasm`);
1615
- logger.debug(`wasm-opt ${wasmOptArgs.join(" ")}`);
1616
- await runCommandWithEnv(
1617
- wasmOptCommand2,
1618
- wasmOptArgs,
1619
- rootDir,
1620
- buildEnv,
1621
- emsdkOptions.signal
1622
- );
1623
- await promises.rm(wasmOptInput, { force: true });
1624
- await promises.rename(tempOutFile, wasmOptInput);
1625
- }
1626
- }
1627
- outFiles[targetName] = resolvedOutFile;
1628
- }
1629
- };
1630
- try {
1631
- await buildTargets("archive");
1632
- await buildTargets("wasm");
1633
- if (generatedLoaderFile) {
1634
- const generatedTargets = [];
1635
- const functionNames = /* @__PURE__ */ new Set();
1636
- for (const [targetName, target] of targetEntries) {
1637
- if (resolveTargetType(target.type) !== "wasm") {
1638
- continue;
1639
- }
1640
- const outFile = outFiles[targetName];
1641
- if (!outFile) {
1642
- continue;
1643
- }
1644
- const functionName = `load${toPascalCaseIdentifier(targetName)}Wasm`;
1645
- if (functionNames.has(functionName)) {
1646
- throw new Error(
1647
- `Generated loader function name collision: ${functionName}`
1648
- );
1649
- }
1650
- functionNames.add(functionName);
1651
- generatedTargets.push({
1652
- targetName,
1653
- functionName,
1654
- outFile
1655
- });
1656
- }
1657
- const content = buildGeneratedLoaderContent(
1658
- generatedLoaderFile,
1659
- generatedTargets
1660
- );
1661
- const didWrite = await writeTextIfChanged(generatedLoaderFile, content);
1662
- logger.info(
1663
- didWrite ? `Generated loader: ${path.relative(rootDir, generatedLoaderFile)}` : `Generated loader unchanged: ${path.relative(rootDir, generatedLoaderFile)}`
1664
- );
1665
- resultGeneratedLoaderFile = generatedLoaderFile;
1666
- }
1667
- } finally {
1668
- if (cleanupBuildDir) {
1669
- await promises.rm(buildRunDir, { recursive: true, force: true });
1670
- }
1671
- }
1672
- return {
1673
- emsdkRoot,
1674
- outFiles,
1675
- ...resultGeneratedLoaderFile ? { generatedLoaderFile: resultGeneratedLoaderFile } : {}
1676
- };
1677
- };
1678
- exports.buildWasm = buildWasm;
1679
- exports.createConsoleLogger = createConsoleLogger;
1680
- exports.prepareEmsdk = prepareEmsdk;
1681
- //# sourceMappingURL=build-CgmcFNSR.cjs.map