@threenative/runtime-native 0.3.17 → 0.3.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -4
- package/package.json +5 -6
- package/scripts/install-prebuilt.mjs +778 -41
- package/scripts/package-desktop.mjs +35 -5
- package/scripts/package-engine-desktop.mjs +103 -9
package/README.md
CHANGED
|
@@ -31,10 +31,30 @@ portable entry and bundle it as the game's single native module.
|
|
|
31
31
|
|
|
32
32
|
## Where the native binaries come from
|
|
33
33
|
|
|
34
|
-
An installed copy of this package contains no C++ and no build system
|
|
35
|
-
|
|
36
|
-
`prebuilt-lock.json
|
|
37
|
-
|
|
34
|
+
An installed copy of this package contains no C++ and no build system, and **installing it downloads
|
|
35
|
+
nothing**. The first native build fetches what that build needs and verifies it against the SHA-256
|
|
36
|
+
recorded in the release's `prebuilt-lock.json`:
|
|
37
|
+
|
|
38
|
+
| Command | Downloads |
|
|
39
|
+
| --- | --- |
|
|
40
|
+
| `build --target web`, `dev`, `test` | nothing — the Wasm engine is a file in this npm package (`build/web/`), so it arrives with the registry tarball |
|
|
41
|
+
| `build --target desktop` (default engine) | the engine player, about 118 MiB, once per install |
|
|
42
|
+
| `build --target desktop` (`engine: "threejs"`) | the legacy runtime and its build tool helper, about 260 MiB, once per install |
|
|
43
|
+
| `build --target android` / `ios` | that platform's libraries, at package time |
|
|
44
|
+
|
|
45
|
+
A verified download is reused with no network, so a second build is offline. Only an Android SDK
|
|
46
|
+
and a JDK are needed for Android, and nothing is compiled on your machine.
|
|
47
|
+
|
|
48
|
+
To fetch ahead of a build (an offline image, a slow link), run the downloader by hand — it is no
|
|
49
|
+
longer an install hook:
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
node node_modules/@threenative/runtime-native/scripts/install-prebuilt.mjs
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
When a download fails, the error names the asset, the version, the URL and three fixes. Offline,
|
|
56
|
+
set `THREENATIVE_ENGINE_PLAYER` (default engine) or `THREENATIVE_RUNTIME_BINARY` (`engine: "threejs"`)
|
|
57
|
+
to a local binary.
|
|
38
58
|
|
|
39
59
|
Two environment variables change where those artifacts come from.
|
|
40
60
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@threenative/runtime-native",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.18",
|
|
4
4
|
"description": "ThreeNative-owned native host for desktop and Android",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"threenative",
|
|
@@ -80,15 +80,15 @@
|
|
|
80
80
|
"publint": "0.3.22",
|
|
81
81
|
"three": "0.187.0",
|
|
82
82
|
"vitest": "4.1.10",
|
|
83
|
-
"@threenative/playtest": "0.3.
|
|
83
|
+
"@threenative/playtest": "0.3.18"
|
|
84
84
|
},
|
|
85
85
|
"dependencies": {
|
|
86
86
|
"pngjs": "7.0.0",
|
|
87
87
|
"esbuild": "0.27.0",
|
|
88
88
|
"typescript": "npm:@typescript/typescript6@6.0.2",
|
|
89
|
-
"@threenative/
|
|
90
|
-
"@threenative/three-native": "0.3.
|
|
91
|
-
"@threenative/
|
|
89
|
+
"@threenative/assets": "0.3.19",
|
|
90
|
+
"@threenative/three-native": "0.3.18",
|
|
91
|
+
"@threenative/core": "0.3.18"
|
|
92
92
|
},
|
|
93
93
|
"scripts": {
|
|
94
94
|
"deps:download": "node scripts/download-deps.mjs",
|
|
@@ -114,7 +114,6 @@
|
|
|
114
114
|
"native:verify:android:artifact": "node scripts/check-android-16kb-alignment.mjs",
|
|
115
115
|
"profile:production": "node scripts/profile-production.mjs",
|
|
116
116
|
"parity": "node conformance/run-conformance.mjs",
|
|
117
|
-
"install": "node scripts/install-prebuilt.mjs",
|
|
118
117
|
"test": "vitest run --config vitest.config.ts && pnpm native:physics:parity && publint --strict",
|
|
119
118
|
"native:css:licenses": "node scripts/native-css-license-inventory.mjs"
|
|
120
119
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
-
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
import { chmodSync, copyFileSync, existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
|
|
8
8
|
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
@@ -77,7 +77,11 @@ export function toolsFilename(platform = process.platform) {
|
|
|
77
77
|
|
|
78
78
|
export function platformKey(platform = process.platform, arch = process.arch) {
|
|
79
79
|
const key = `${platform}-${arch}`;
|
|
80
|
-
if (!supported.has(key))
|
|
80
|
+
if (!supported.has(key)) {
|
|
81
|
+
const error = new Error(`No prebuilt release is published for '${key}': this platform has no native runtime row.`);
|
|
82
|
+
error.code = 'PREBUILT_RELEASE_UNPUBLISHED';
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
81
85
|
return key;
|
|
82
86
|
}
|
|
83
87
|
|
|
@@ -92,7 +96,7 @@ export function verifyChecksum(contents, expected, key) {
|
|
|
92
96
|
}
|
|
93
97
|
}
|
|
94
98
|
|
|
95
|
-
function releaseFromManifest(manifest, key) {
|
|
99
|
+
function releaseFromManifest(manifest, key, options = {}) {
|
|
96
100
|
if (UNPUBLISHED_PREBUILT_KEYS.includes(key)) {
|
|
97
101
|
const error = new Error(
|
|
98
102
|
`No prebuilt release is published for '${key}'. This platform builds from an engine checkout until its release credentials exist; see PRD-262.`,
|
|
@@ -101,6 +105,33 @@ function releaseFromManifest(manifest, key) {
|
|
|
101
105
|
throw error;
|
|
102
106
|
}
|
|
103
107
|
const release = manifest?.artifacts?.[key];
|
|
108
|
+
// A key the manifest itself promises and does not carry is a broken release, not a platform that
|
|
109
|
+
// ships nothing: warn-and-continue here leaves an offline image that cannot build. Only an
|
|
110
|
+
// explicit `requiredKeys` is a promise; without one, a partial manifest is a fixture (or a local
|
|
111
|
+
// lock), and an absent key stays the pre-existing by-design absence.
|
|
112
|
+
// An official release lock omits `requiredKeys` and promises the whole published cohort; a
|
|
113
|
+
// caller preparing an offline image says so with `requireComplete`, which also covers a scoped
|
|
114
|
+
// lock that forgets a published key it was asked for. A test or local fixture stays permissive.
|
|
115
|
+
const required = declaredRequiredKeys(manifest) ?? [];
|
|
116
|
+
const promised =
|
|
117
|
+
required.includes(key) ||
|
|
118
|
+
(options.requireComplete === true && PUBLISHED_PREBUILT_KEYS.includes(key));
|
|
119
|
+
if (release === undefined && promised) {
|
|
120
|
+
const error = new Error(
|
|
121
|
+
`The prebuilt release manifest requires '${key}' and records no artifact for it.`,
|
|
122
|
+
);
|
|
123
|
+
error.code = 'PREBUILT_RELEASE_MISSING';
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
if (release !== undefined && (!release.url || !release.sha256)) {
|
|
127
|
+
// The lock advertises this asset and does not describe it: a broken release, not a platform
|
|
128
|
+
// that ships nothing, so the prefetch must fail rather than warn and leave the image short.
|
|
129
|
+
const error = new Error(
|
|
130
|
+
`The prebuilt release manifest records an incomplete entry for '${key}' (url and sha256 are required).`,
|
|
131
|
+
);
|
|
132
|
+
error.code = 'PREBUILT_RELEASE_INCOMPLETE';
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
104
135
|
if (!release?.url || !release?.sha256) {
|
|
105
136
|
const error = new Error(`No prebuilt release asset is recorded for '${key}'.`);
|
|
106
137
|
if (key.endsWith('-engine-player')) error.code = 'PREBUILT_RELEASE_UNPUBLISHED';
|
|
@@ -183,7 +214,7 @@ export function validateReleaseManifest(manifest, options = {}) {
|
|
|
183
214
|
// non-iOS consumer, and a scoped local manifest is accepted for exactly the keys it names.
|
|
184
215
|
const requiredKeys = options.requiredKeys ?? declaredRequiredKeys(manifest) ??
|
|
185
216
|
PUBLISHED_PREBUILT_KEYS.filter((key) => !key.startsWith('ios-'));
|
|
186
|
-
for (const key of requiredKeys) releaseFromManifest(manifest, key);
|
|
217
|
+
for (const key of requiredKeys) releaseFromManifest(manifest, key, options);
|
|
187
218
|
for (const key of Object.keys(manifest.artifacts)) validateManifestArtifact(manifest, key, version);
|
|
188
219
|
return manifest;
|
|
189
220
|
}
|
|
@@ -229,19 +260,41 @@ export function generateReleaseManifest(directory, { repository, tag, sourceSha,
|
|
|
229
260
|
);
|
|
230
261
|
}
|
|
231
262
|
|
|
232
|
-
export function readRelease(manifestPath, key) {
|
|
263
|
+
export function readRelease(manifestPath, key, options = {}) {
|
|
233
264
|
if (!existsSync(manifestPath)) {
|
|
234
|
-
|
|
235
|
-
|
|
265
|
+
// A local manifest is always an explicit input (`THREENATIVE_PREBUILT_MANIFEST` or a caller's
|
|
266
|
+
// path): a file that is not there is a broken pin, and a prefetch that warns about it bakes an
|
|
267
|
+
// image with nothing in it.
|
|
268
|
+
const error = new Error(`The prebuilt release manifest ${manifestPath} does not exist (requested for '${key}').`);
|
|
269
|
+
error.code = 'PREBUILT_RELEASE_MISSING';
|
|
236
270
|
throw error;
|
|
237
271
|
}
|
|
238
272
|
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
239
273
|
// Explicit artifact-only local pins predate the envelope. Never downgrade a partially
|
|
240
274
|
// specified candidate, and never allow this compatibility path for a remote default lock.
|
|
241
275
|
if (manifest && ['schemaVersion', 'version', 'sourceSha'].some((field) => Object.hasOwn(manifest, field))) {
|
|
242
|
-
|
|
276
|
+
// The caller's options carry the completeness requirement: an official lock a prefetch was
|
|
277
|
+
// asked to fill must fail when it omits a published asset, exactly as the remote path does.
|
|
278
|
+
validateReleaseManifest(manifest, options);
|
|
243
279
|
}
|
|
244
|
-
|
|
280
|
+
// An artifact-only pin skips the envelope validator, so every size it states is judged here:
|
|
281
|
+
// a `size: 0` on any entry is a pin the build refuses, even when another entry is the one asked
|
|
282
|
+
// for. An omitted size stays valid — that is the legacy single-request shape.
|
|
283
|
+
const declaredArtifacts = manifest?.artifacts;
|
|
284
|
+
for (const [entryKey, entry] of Object.entries(
|
|
285
|
+
declaredArtifacts !== null && typeof declaredArtifacts === 'object' ? declaredArtifacts : {},
|
|
286
|
+
)) {
|
|
287
|
+
const size = entry !== null && typeof entry === 'object' ? entry.size : undefined;
|
|
288
|
+
if (size !== undefined && (!Number.isSafeInteger(size) || size <= 0)) {
|
|
289
|
+
throw new Error(`Prebuilt release size for '${entryKey}' must be a positive integer.`);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return releaseFromManifest(manifest, key, options);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** The pinned manifest, or nothing: an exported empty string means "unset", not the cwd. */
|
|
296
|
+
export function pinnedManifestPath(value = process.env.THREENATIVE_PREBUILT_MANIFEST) {
|
|
297
|
+
return value === undefined || value.length === 0 ? undefined : value;
|
|
245
298
|
}
|
|
246
299
|
|
|
247
300
|
/** The GitHub release tag a version's prebuilt payload is published under. */
|
|
@@ -280,7 +333,7 @@ function createInstallPlan(options) {
|
|
|
280
333
|
const toolsOutput = join(dirname(output), toolsFilename(platform));
|
|
281
334
|
if (toolsOutput === output) throw new Error('Prebuilt runtime and build tool helper paths must differ.');
|
|
282
335
|
return { platform, key, output, statusPath, toolsOutput, toolsKey: toolsKey(key),
|
|
283
|
-
status: { key, url: options.manifestPath ??
|
|
336
|
+
status: { key, url: options.manifestPath ?? pinnedManifestPath() ??
|
|
284
337
|
options.manifestUrl ?? releaseManifestUrl(), version: packageVersion } };
|
|
285
338
|
}
|
|
286
339
|
|
|
@@ -326,7 +379,7 @@ function recordInstallFailure(plan, error) {
|
|
|
326
379
|
}
|
|
327
380
|
}
|
|
328
381
|
|
|
329
|
-
async function fetchRelease(manifestUrl, key) {
|
|
382
|
+
async function fetchRelease(manifestUrl, key, options = {}) {
|
|
330
383
|
const url = new URL(manifestUrl);
|
|
331
384
|
if (url.protocol !== 'https:' && process.env.THREENATIVE_ALLOW_INSECURE_PREBUILT !== '1') {
|
|
332
385
|
throw new Error(`Prebuilt release manifest for '${key}' must use HTTPS.`);
|
|
@@ -343,27 +396,349 @@ async function fetchRelease(manifestUrl, key) {
|
|
|
343
396
|
const error = new Error(
|
|
344
397
|
`Prebuilt release manifest fetch failed for '${key}' at ${url.href}: HTTP ${response.status}.`,
|
|
345
398
|
);
|
|
346
|
-
|
|
399
|
+
// No manifest at this tag: the diagnosis is "not published yet", but a prefetch that was asked
|
|
400
|
+
// to fill an offline image must not exit zero on it, so it is not the by-design class.
|
|
401
|
+
if (response.status === 404) error.code = 'PREBUILT_RELEASE_ABSENT';
|
|
347
402
|
throw error;
|
|
348
403
|
}
|
|
349
|
-
return releaseFromManifest(validateReleaseManifest(await response.json()), key);
|
|
404
|
+
return releaseFromManifest(validateReleaseManifest(await response.json(), options), key, options);
|
|
350
405
|
}
|
|
351
406
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
407
|
+
/**
|
|
408
|
+
* Above this size a release asset is fetched as parallel byte ranges (PRD-902).
|
|
409
|
+
*
|
|
410
|
+
* GitHub throttles one connection, not the host: a single 118 MiB engine player took about nine
|
|
411
|
+
* minutes on the day a downstream loop gave up. Small assets stay on one request because the
|
|
412
|
+
* per-request cost is the whole cost.
|
|
413
|
+
*/
|
|
414
|
+
export const PARALLEL_RANGE_THRESHOLD_BYTES = 8 * 1024 * 1024;
|
|
415
|
+
|
|
416
|
+
/** How many byte ranges one large asset splits into. Measured against the real release in PRD-902. */
|
|
417
|
+
export const PARALLEL_RANGE_COUNT = 16;
|
|
418
|
+
|
|
419
|
+
/** How long a claimed whole-body read may outlive a sibling range's own failure. */
|
|
420
|
+
const CLAIM_GRACE_MS = 5_000;
|
|
421
|
+
|
|
422
|
+
async function fetchArtifact(url, key, init) {
|
|
423
|
+
try {
|
|
424
|
+
return await fetch(url, init);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
throw new Error(
|
|
427
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: ${error instanceof Error ? error.message : String(error)}`,
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Read one part's body, naming the asset, URL and interval when the connection dies mid-read.
|
|
434
|
+
*
|
|
435
|
+
* `response.arrayBuffer()` rejects with a bare `TypeError: terminated` on a dropped connection, and
|
|
436
|
+
* the caller cannot see which part failed: the requested-range and the server-ignored-Range paths
|
|
437
|
+
* both go through here so the failure reads the same either way.
|
|
438
|
+
*/
|
|
439
|
+
async function readRangeBody(response, { end, key, start, url }) {
|
|
440
|
+
try {
|
|
441
|
+
return Buffer.from(await response.arrayBuffer());
|
|
442
|
+
} catch (error) {
|
|
443
|
+
throw new Error(
|
|
444
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: byte range ${start}-${end} was interrupted (${error instanceof Error ? error.message : String(error)}).`,
|
|
445
|
+
{ cause: error },
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* One asset over parallel `Range` requests, assembled at each part's offset in one buffer.
|
|
452
|
+
*
|
|
453
|
+
* A `200` answer means the server ignored `Range`: the first part to see one claims the whole body
|
|
454
|
+
* and cancels the siblings *before* reading it, so a range-ignoring server costs one asset in
|
|
455
|
+
* memory rather than one per request. Any other status, or a short body, fails closed naming the
|
|
456
|
+
* key, the URL and the byte range, and cancels the siblings so a stalled one cannot hold the
|
|
457
|
+
* install lock. The sha256 in the lock is still the only trust decision.
|
|
458
|
+
*/
|
|
459
|
+
/**
|
|
460
|
+
* Copy one ranged response into its own slice of the output, refusing to exceed it.
|
|
461
|
+
*
|
|
462
|
+
* The check happens per chunk, so an over-long body is abandoned the moment it overruns rather
|
|
463
|
+
* than after it has all arrived.
|
|
464
|
+
*/
|
|
465
|
+
async function readRangeInto(response, contents, { end, key, onReader, start, url }) {
|
|
466
|
+
const expected = end - start + 1;
|
|
467
|
+
const reader = response.body?.getReader();
|
|
468
|
+
if (reader === undefined) {
|
|
469
|
+
const body = await readRangeBody(response, { end, key, start, url });
|
|
470
|
+
if (body.length > expected)
|
|
471
|
+
throw new Error(
|
|
472
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: byte range ${start}-${end} answered more than ${expected} bytes.`,
|
|
473
|
+
);
|
|
474
|
+
body.copy(contents, start);
|
|
475
|
+
return body.length;
|
|
476
|
+
}
|
|
477
|
+
onReader?.(reader);
|
|
478
|
+
let written = 0;
|
|
358
479
|
try {
|
|
359
|
-
|
|
480
|
+
for (;;) {
|
|
481
|
+
const { done, value } = await reader.read();
|
|
482
|
+
if (done) break;
|
|
483
|
+
if (value === undefined) continue;
|
|
484
|
+
written += value.length;
|
|
485
|
+
if (written > expected) {
|
|
486
|
+
await reader.cancel().catch(() => undefined);
|
|
487
|
+
throw new Error(
|
|
488
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: byte range ${start}-${end} exceeded its ${expected} bytes.`,
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
contents.set(value, start + written - value.length);
|
|
492
|
+
}
|
|
360
493
|
} catch (error) {
|
|
494
|
+
if (error instanceof Error && error.message.startsWith('Prebuilt release fetch failed')) throw error;
|
|
361
495
|
throw new Error(
|
|
362
|
-
`Prebuilt release fetch failed for '${key}' at ${
|
|
496
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: byte range ${start}-${end} was interrupted (${error instanceof Error ? error.message : String(error)}).`,
|
|
497
|
+
{ cause: error },
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
return written;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Read a claimed whole-body response, re-arming the inactivity deadline as bytes arrive.
|
|
505
|
+
*
|
|
506
|
+
* A sibling's HTTP error must not cap the fallback at a fixed wall time: a slow but progressing
|
|
507
|
+
* body is a working download. A body that stops arriving is what the deadline is for.
|
|
508
|
+
*/
|
|
509
|
+
async function readWholeInto(response, contents, { arm, key, limit, url }) {
|
|
510
|
+
const reader = response.body?.getReader();
|
|
511
|
+
if (reader === undefined) {
|
|
512
|
+
const body = await readRangeBody(response, { end: 0, key, start: 0, url });
|
|
513
|
+
if (limit !== undefined && body.length > limit)
|
|
514
|
+
throw new Error(
|
|
515
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: the whole-file response exceeded the ${limit} bytes the lock declares.`,
|
|
516
|
+
);
|
|
517
|
+
body.copy(contents, 0);
|
|
518
|
+
return body.length;
|
|
519
|
+
}
|
|
520
|
+
let received = 0;
|
|
521
|
+
try {
|
|
522
|
+
for (;;) {
|
|
523
|
+
const { done, value } = await reader.read();
|
|
524
|
+
if (done) break;
|
|
525
|
+
if (value === undefined) continue;
|
|
526
|
+
received += value.length;
|
|
527
|
+
if (limit !== undefined && received > limit) {
|
|
528
|
+
await reader.cancel().catch(() => undefined);
|
|
529
|
+
throw new Error(
|
|
530
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: the whole-file response exceeded the ${limit} bytes the lock declares.`,
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
contents.set(value, received - value.length);
|
|
534
|
+
arm();
|
|
535
|
+
}
|
|
536
|
+
} catch (error) {
|
|
537
|
+
if (error instanceof Error && error.message.startsWith('Prebuilt release fetch failed')) throw error;
|
|
538
|
+
throw new Error(
|
|
539
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: the whole-file response was interrupted (${error instanceof Error ? error.message : String(error)}).`,
|
|
540
|
+
{ cause: error },
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
return received;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
async function downloadRanges(key, url, size, expectedSha256) {
|
|
547
|
+
const chunk = Math.ceil(size / PARALLEL_RANGE_COUNT);
|
|
548
|
+
const parts = Array.from({ length: PARALLEL_RANGE_COUNT }, (_, index) => {
|
|
549
|
+
const start = index * chunk;
|
|
550
|
+
return { end: Math.min(size, start + chunk) - 1, index, start };
|
|
551
|
+
}).filter(({ start }) => start < size);
|
|
552
|
+
const contents = Buffer.allocUnsafe(size);
|
|
553
|
+
const controllers = parts.map(() => new AbortController());
|
|
554
|
+
// The first part to see a `200` claims the whole body synchronously, before any other handler
|
|
555
|
+
// can claim it too (two claims would cancel both readers). The claimed reader is never aborted
|
|
556
|
+
// by a sibling: its body is the download.
|
|
557
|
+
let claimed;
|
|
558
|
+
let whole;
|
|
559
|
+
// The first non-abort failure is the diagnosis: no later reader may overwrite it, and the HTTP
|
|
560
|
+
// status it names is what the caller must see unless a complete body verifies against the lock.
|
|
561
|
+
let failure;
|
|
562
|
+
let claimDeadline;
|
|
563
|
+
// Range streams, so a claimed whole body can cancel them gracefully: aborting their fetches
|
|
564
|
+
// truncated the claim's own socket, and leaving them running copies the asset a second time.
|
|
565
|
+
const rangeReaders = new Map();
|
|
566
|
+
const cancelled = new Set();
|
|
567
|
+
const cancelRangeReaders = (keep) => {
|
|
568
|
+
for (const [index, rangeReader] of rangeReaders) {
|
|
569
|
+
if (index === keep) continue;
|
|
570
|
+
cancelled.add(index);
|
|
571
|
+
void rangeReader.cancel().catch(() => undefined);
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
// A sibling's failure bounds how long the claim may keep the install lock, but the bound is
|
|
575
|
+
// inactivity, not total time: a body that is still arriving reaches checksum verification.
|
|
576
|
+
const armClaimDeadline = (index) => {
|
|
577
|
+
if (claimDeadline !== undefined) clearTimeout(claimDeadline);
|
|
578
|
+
claimDeadline = setTimeout(() => controllers[index]?.abort(), CLAIM_GRACE_MS);
|
|
579
|
+
claimDeadline.unref?.();
|
|
580
|
+
};
|
|
581
|
+
// Chunk re-arming only matters once a sibling has failed: before that nothing is bounded.
|
|
582
|
+
const onClaimProgress = () => {
|
|
583
|
+
if (failure !== undefined && claimed !== undefined) armClaimDeadline(claimed);
|
|
584
|
+
};
|
|
585
|
+
const abortOthers = (keep) => {
|
|
586
|
+
controllers.forEach((controller, other) => {
|
|
587
|
+
if (other !== keep && other !== claimed) controller.abort();
|
|
588
|
+
});
|
|
589
|
+
};
|
|
590
|
+
try {
|
|
591
|
+
await Promise.allSettled(parts.map(async ({ start, end, index }) => {
|
|
592
|
+
try {
|
|
593
|
+
const response = await fetchArtifact(url, key, {
|
|
594
|
+
headers: { Range: `bytes=${start}-${end}` },
|
|
595
|
+
signal: controllers[index].signal,
|
|
596
|
+
});
|
|
597
|
+
if (response.status === 200) {
|
|
598
|
+
if (claimed !== undefined) {
|
|
599
|
+
// A sibling already has the whole file: drop this body instead of reading a second one.
|
|
600
|
+
await response.body?.cancel().catch(() => undefined);
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
claimed = index;
|
|
604
|
+
// The deadline exists to stop a claim from outliving a sibling's failure. With every
|
|
605
|
+
// request healthy a slow mirror is just slow, and the checksum still decides.
|
|
606
|
+
if (failure !== undefined) armClaimDeadline(index);
|
|
607
|
+
// The siblings are not aborted until this body is in memory: they may share its socket,
|
|
608
|
+
// and aborting them mid-read truncated it (a checksum failure, observed). A body that
|
|
609
|
+
// keeps arriving is not stalled, so each chunk re-arms the deadline a failing sibling
|
|
610
|
+
// imposed.
|
|
611
|
+
cancelRangeReaders(index);
|
|
612
|
+
// Straight into the assembly buffer: a second copy of a 118 MiB asset is the memory
|
|
613
|
+
// PRD-902 exists not to spend. `whole` is that same buffer.
|
|
614
|
+
const wholeBytes = await readWholeInto(response, contents, {
|
|
615
|
+
arm: onClaimProgress,
|
|
616
|
+
key,
|
|
617
|
+
limit: size,
|
|
618
|
+
url,
|
|
619
|
+
});
|
|
620
|
+
// A short body would otherwise borrow the suffix the ranges already wrote: the fallback
|
|
621
|
+
// has to be the whole asset, not the tail of one.
|
|
622
|
+
if (size !== undefined && wholeBytes !== size) {
|
|
623
|
+
throw new Error(
|
|
624
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: the whole-file response carried ${wholeBytes} bytes, not the ${size} the lock declares.`,
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
whole = contents;
|
|
628
|
+
abortOthers(index);
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
if (response.status !== 206) {
|
|
632
|
+
const error = new Error(
|
|
633
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: HTTP ${response.status} for byte range ${start}-${end}.`,
|
|
634
|
+
);
|
|
635
|
+
if (response.status === 404) error.code = 'PREBUILT_RELEASE_MISSING';
|
|
636
|
+
error.status = response.status;
|
|
637
|
+
throw error;
|
|
638
|
+
}
|
|
639
|
+
if (claimed !== undefined) {
|
|
640
|
+
// A range that answers after the whole file is already claimed is not needed: cancel its
|
|
641
|
+
// body and record it as intentional so its short read is not a failure.
|
|
642
|
+
cancelled.add(index);
|
|
643
|
+
await response.body?.cancel().catch(() => undefined);
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
// Stream straight into this part's slice: a mirror that answers every range with the whole
|
|
647
|
+
// asset would otherwise be buffered (144 MiB for a 16-part 9 MiB file) before the length
|
|
648
|
+
// check noticed.
|
|
649
|
+
const written = await readRangeInto(response, contents, {
|
|
650
|
+
end,
|
|
651
|
+
key,
|
|
652
|
+
onReader: (rangeReader) => rangeReaders.set(index, rangeReader),
|
|
653
|
+
start,
|
|
654
|
+
url,
|
|
655
|
+
});
|
|
656
|
+
if (cancelled.has(index)) return;
|
|
657
|
+
if (written !== end - start + 1) {
|
|
658
|
+
throw new Error(
|
|
659
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: byte range ${start}-${end} answered ${written} bytes.`,
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
} catch (error) {
|
|
663
|
+
// The claimed reader decides the result even when it fails: its error is the download's.
|
|
664
|
+
// Any other failure is remembered only until a whole body wins, and cancels the siblings
|
|
665
|
+
// so a stalled body cannot hold the install lock.
|
|
666
|
+
// The first non-abort failure is the diagnosis and is never overwritten: a queued 200 that
|
|
667
|
+
// is aborted later, or a 404 that arrives after the 500, must not replace it. Once one is
|
|
668
|
+
// recorded, the claim is bounded so a stalled body cannot hold the install lock.
|
|
669
|
+
// Cancellation is read from the request's own signal, not from the message: a formatted
|
|
670
|
+
// failure carries the asset URL, and a URL may contain "aborted".
|
|
671
|
+
// A status that has already arrived is the mirror's answer, whatever cancellation raced
|
|
672
|
+
// with it: only a body error may be reclassified as intentional.
|
|
673
|
+
const httpAnswer = typeof error?.status === 'number';
|
|
674
|
+
if (!httpAnswer && cancelled.has(index)) return;
|
|
675
|
+
// A reset on a *redundant* request is not an answer about the asset: once a `200` body is
|
|
676
|
+
// claimed, that body is the download, and its checksum decides. The claiming request is the
|
|
677
|
+
// exception — its own read and length errors are the download failing. A status is always an
|
|
678
|
+
// answer and always fails, which is what the "sibling answered 500" rule is about.
|
|
679
|
+
if (!httpAnswer && claimed !== undefined && index !== claimed) return;
|
|
680
|
+
const aborted = !httpAnswer && (controllers[index].signal.aborted || isAbortError(error));
|
|
681
|
+
if (!aborted && failure === undefined) {
|
|
682
|
+
failure = error;
|
|
683
|
+
// Stop reading the whole-body fallback at once: the answer is the range failure, and a
|
|
684
|
+
// body that keeps arriving must not hold the install lock.
|
|
685
|
+
if (claimed !== undefined) controllers[claimed]?.abort();
|
|
686
|
+
} else if (aborted && failure === undefined && (claimed === undefined || index === claimed)) {
|
|
687
|
+
// A claim aborted by its own deadline is the diagnosis when no sibling named a better one.
|
|
688
|
+
failure =
|
|
689
|
+
claimed === index && controllers[index].signal.aborted
|
|
690
|
+
? new Error(
|
|
691
|
+
`Prebuilt release fetch failed for '${key}' at ${url}: the whole-file response stopped arriving for ${Math.round(CLAIM_GRACE_MS / 1000)} s.`,
|
|
692
|
+
)
|
|
693
|
+
: error;
|
|
694
|
+
}
|
|
695
|
+
abortOthers(index);
|
|
696
|
+
throw error;
|
|
697
|
+
}
|
|
698
|
+
}));
|
|
699
|
+
} finally {
|
|
700
|
+
for (const controller of controllers) controller.abort();
|
|
701
|
+
}
|
|
702
|
+
if (claimDeadline !== undefined) clearTimeout(claimDeadline);
|
|
703
|
+
// PRD-902 requires an unexpected status to fail and name its range: a whole body that happens to
|
|
704
|
+
// verify does not mask a sibling mirror answering 500, because the next build would hit it again.
|
|
705
|
+
if (failure !== undefined) throw failure;
|
|
706
|
+
if (whole !== undefined) return whole;
|
|
707
|
+
return contents;
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function isAbortError(error) {
|
|
711
|
+
return error instanceof Error && error.name === 'AbortError';
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
export async function downloadReleaseArtifact(key, options = {}) {
|
|
715
|
+
// A platform this repository deliberately does not publish is a fact, not a download: answering
|
|
716
|
+
// it before the manifest fetch keeps the diagnosis identical online and offline.
|
|
717
|
+
if (UNPUBLISHED_PREBUILT_KEYS.includes(key)) {
|
|
718
|
+
const error = new Error(
|
|
719
|
+
`No prebuilt release is published for '${key}'. This platform builds from an engine checkout until its release credentials exist; see PRD-262.`,
|
|
363
720
|
);
|
|
721
|
+
error.code = 'PREBUILT_RELEASE_UNPUBLISHED';
|
|
722
|
+
throw error;
|
|
364
723
|
}
|
|
724
|
+
const manifestPath = options.manifestPath ?? pinnedManifestPath();
|
|
725
|
+
const release = manifestPath
|
|
726
|
+
? readRelease(resolve(manifestPath), key, options)
|
|
727
|
+
: await fetchRelease(options.manifestUrl ?? releaseManifestUrl(), key, options);
|
|
728
|
+
if (release.size > PARALLEL_RANGE_THRESHOLD_BYTES) {
|
|
729
|
+
const contents = await downloadRanges(key, release.url, release.size, release.sha256);
|
|
730
|
+
verifyChecksum(contents, release.sha256, key);
|
|
731
|
+
if (contents.length === 0 || contents.length !== release.size) {
|
|
732
|
+
throw new Error(`Prebuilt release size verification failed for '${key}': received ${contents.length} bytes.`);
|
|
733
|
+
}
|
|
734
|
+
return contents;
|
|
735
|
+
}
|
|
736
|
+
const response = await fetchArtifact(release.url, key);
|
|
365
737
|
if (!response.ok) {
|
|
366
|
-
|
|
738
|
+
const error = new Error(`Prebuilt release fetch failed for '${key}' at ${release.url}: HTTP ${response.status}.`);
|
|
739
|
+
// A published release that does not carry this asset is a packaging fact, not a bad network.
|
|
740
|
+
if (response.status === 404) error.code = 'PREBUILT_RELEASE_MISSING';
|
|
741
|
+
throw error;
|
|
367
742
|
}
|
|
368
743
|
let contents;
|
|
369
744
|
try {
|
|
@@ -386,8 +761,8 @@ function isVerifiedInstall(plan, options) {
|
|
|
386
761
|
status.version !== plan.status.version || status.url !== plan.status.url) return false;
|
|
387
762
|
// A caller can replace a local lock without changing its path. That explicit pin must
|
|
388
763
|
// still authorize these bytes, and a missing/invalid pin must never be bypassed by cache.
|
|
389
|
-
const manifestPath = options.manifestPath ??
|
|
390
|
-
const pinned = manifestPath ? readRelease(resolve(manifestPath), plan.key) : undefined;
|
|
764
|
+
const manifestPath = options.manifestPath ?? pinnedManifestPath();
|
|
765
|
+
const pinned = manifestPath ? readRelease(resolve(manifestPath), plan.key, options) : undefined;
|
|
391
766
|
if (pinned && pinned.sha256 !== status.sha256) return false;
|
|
392
767
|
const contents = readFileSync(plan.output);
|
|
393
768
|
if (contents.length === 0 || (pinned?.size !== undefined && contents.length !== pinned.size)) return false;
|
|
@@ -395,7 +770,7 @@ function isVerifiedInstall(plan, options) {
|
|
|
395
770
|
if (!plan.toolsKey) return true;
|
|
396
771
|
// A cached runtime without its verified helper is not a reusable desktop install.
|
|
397
772
|
if (typeof status.toolsSha256 !== 'string') return false;
|
|
398
|
-
const pinnedTools = manifestPath ? readRelease(resolve(manifestPath), plan.toolsKey) : undefined;
|
|
773
|
+
const pinnedTools = manifestPath ? readRelease(resolve(manifestPath), plan.toolsKey, options) : undefined;
|
|
399
774
|
if (pinnedTools && pinnedTools.sha256 !== status.toolsSha256) return false;
|
|
400
775
|
const tools = readFileSync(plan.toolsOutput);
|
|
401
776
|
if (tools.length === 0 || (pinnedTools?.size !== undefined && tools.length !== pinnedTools.size)) return false;
|
|
@@ -428,29 +803,391 @@ export async function installPrebuilt(options = {}) {
|
|
|
428
803
|
}
|
|
429
804
|
}
|
|
430
805
|
|
|
431
|
-
|
|
432
|
-
|
|
806
|
+
/** A lock older than this cannot belong to a running install, even one with no recorded pid. */
|
|
807
|
+
const LOCK_STALE_MS = 15 * 60 * 1000;
|
|
808
|
+
|
|
809
|
+
/** How often a waiter re-checks the winner, and the lock. */
|
|
810
|
+
const LOCK_POLL_MS = 250;
|
|
811
|
+
|
|
812
|
+
/** How often a waiting caller says so, so a slow install is never a silent hang. */
|
|
813
|
+
const LOCK_NOTICE_MS = 30 * 1000;
|
|
814
|
+
|
|
815
|
+
/**
|
|
816
|
+
* Hold the install lock for one plan, and own it while doing so.
|
|
817
|
+
*
|
|
818
|
+
* `mkdirSync` is the atomic primitive: exactly one caller creates the directory, every other
|
|
819
|
+
* caller sees `EEXIST` and waits. Two parallel commands used to race here, and the loser's
|
|
820
|
+
* `beginInstall` deleted the winner's output mid-download.
|
|
821
|
+
*
|
|
822
|
+
* Ownership is a token written inside the lock, so releasing deletes only a lock this caller
|
|
823
|
+
* still owns: a waiter that reclaimed a dead owner's lock cannot have it deleted underneath it by
|
|
824
|
+
* the process that died. Waiting ends three ways, none of them spinning: the winner publishes a
|
|
825
|
+
* verified binary (the waiter reuses it at once), the lock's recorded pid is gone (a killed
|
|
826
|
+
* build — reclaimed immediately), or a lock with no pid at all is 15 minutes old. A reclaim
|
|
827
|
+
* re-reads the dead pid before its single `rename`, so two waiters cannot both move it and one
|
|
828
|
+
* cannot move the other's fresh lock.
|
|
829
|
+
*/
|
|
830
|
+
async function withInstallLock(plan, options, callback) {
|
|
831
|
+
const lock = `${plan.statusPath}.lock`;
|
|
832
|
+
mkdirSync(dirname(lock), { recursive: true });
|
|
833
|
+
const owner = randomUUID();
|
|
834
|
+
const deadline = Date.now() + LOCK_STALE_MS;
|
|
835
|
+
let announcedAt = 0;
|
|
836
|
+
for (;;) {
|
|
837
|
+
try {
|
|
838
|
+
mkdirSync(lock);
|
|
839
|
+
} catch (error) {
|
|
840
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
841
|
+
// The winner may have published a verified binary while this caller waited: reuse it. A
|
|
842
|
+
// private-stage request still takes the lock, because the snapshot must be taken under it.
|
|
843
|
+
if (!options.stagePrivate && isVerifiedInstall(plan, options)) return plan.output;
|
|
844
|
+
let age;
|
|
845
|
+
try {
|
|
846
|
+
age = Date.now() - statSync(lock).mtimeMs;
|
|
847
|
+
} catch (error) {
|
|
848
|
+
// Released between the `mkdir` and the `stat`: retry at once. Any other filesystem error
|
|
849
|
+
// is real and must not be turned into a busy loop.
|
|
850
|
+
if (error?.code === 'ENOENT') continue;
|
|
851
|
+
throw error;
|
|
852
|
+
}
|
|
853
|
+
const abandoned = abandonedLockOwner(lock, age);
|
|
854
|
+
if (abandoned !== undefined) {
|
|
855
|
+
// A declined reclaim (another waiter is reaping) still polls, so this cannot spin.
|
|
856
|
+
if (reclaimAbandonedLock(lock, abandoned)) continue;
|
|
857
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, LOCK_POLL_MS));
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
const now = Date.now();
|
|
861
|
+
if (now > deadline) {
|
|
862
|
+
throw new Error(
|
|
863
|
+
`Gave up waiting for another install of '${plan.key}' (${lock} is ${Math.round(age / 1000)}s old). Delete that lock if the process that made it is gone, then rerun.`,
|
|
864
|
+
);
|
|
865
|
+
}
|
|
866
|
+
if (announcedAt === 0 || now - announcedAt >= LOCK_NOTICE_MS) {
|
|
867
|
+
announcedAt = now;
|
|
868
|
+
process.stderr.write(
|
|
869
|
+
`Waiting for another install of '${plan.key}' to finish (${lock} is ${Math.round(age / 1000)}s old).\n`,
|
|
870
|
+
);
|
|
871
|
+
}
|
|
872
|
+
await new Promise((resolveWait) => setTimeout(resolveWait, LOCK_POLL_MS));
|
|
873
|
+
continue;
|
|
874
|
+
}
|
|
875
|
+
// The lock is ours. The token ties cleanup to this caller; the pid lets a later build reclaim
|
|
876
|
+
// it the moment this process is gone, so a killed build never becomes a 15-minute wait.
|
|
877
|
+
try {
|
|
878
|
+
writeFileSync(join(lock, 'owner'), `${owner}\n`, { flag: 'wx' });
|
|
879
|
+
} catch (error) {
|
|
880
|
+
// Without a token this caller cannot prove ownership on release, so it gives the lock back
|
|
881
|
+
// rather than installing unprotected.
|
|
882
|
+
rmSync(lock, { recursive: true, force: true });
|
|
883
|
+
throw error;
|
|
884
|
+
}
|
|
885
|
+
try {
|
|
886
|
+
writeFileSync(join(lock, 'pid'), `${process.pid}\n`, { flag: 'wx' });
|
|
887
|
+
} catch {
|
|
888
|
+
// The pid is an optimisation for a killed build, never a precondition.
|
|
889
|
+
}
|
|
890
|
+
break;
|
|
891
|
+
}
|
|
892
|
+
try {
|
|
893
|
+
return await callback();
|
|
894
|
+
} finally {
|
|
895
|
+
releaseInstallLock(lock, owner);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** Delete the lock only while this caller still owns it. */
|
|
900
|
+
function releaseInstallLock(lock, owner) {
|
|
901
|
+
let recorded;
|
|
902
|
+
try {
|
|
903
|
+
recorded = readFileSync(join(lock, 'owner'), 'utf8').trim();
|
|
904
|
+
} catch {
|
|
905
|
+
// A lock whose token is unreadable is not provably this caller's: leave it to go stale.
|
|
906
|
+
return;
|
|
907
|
+
}
|
|
908
|
+
if (recorded === owner) rmSync(lock, { recursive: true, force: true });
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
/**
|
|
912
|
+
* The identity of a lock nobody owns any more, or `undefined` while it must be respected.
|
|
913
|
+
*
|
|
914
|
+
* A recorded pid that no longer runs is reclaimed at once. A lock with no pid is reclaimed only
|
|
915
|
+
* once it is 15 minutes old — that is a build killed between `mkdir` and the pid write, or a lock
|
|
916
|
+
* from a release that predates the pid. A live pid, an `EPERM` (another user's process) or a
|
|
917
|
+
* malformed pid is respected.
|
|
918
|
+
*/
|
|
919
|
+
function abandonedLockOwner(lock, age) {
|
|
920
|
+
let pidText;
|
|
921
|
+
try {
|
|
922
|
+
pidText = readFileSync(join(lock, 'pid'), 'utf8').trim();
|
|
923
|
+
} catch (error) {
|
|
924
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
925
|
+
return age > LOCK_STALE_MS ? '' : undefined;
|
|
926
|
+
}
|
|
927
|
+
const pid = Number(pidText);
|
|
928
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return age > LOCK_STALE_MS ? pidText : undefined;
|
|
929
|
+
if (pid === process.pid) return undefined;
|
|
930
|
+
try {
|
|
931
|
+
process.kill(pid, 0);
|
|
932
|
+
return undefined;
|
|
933
|
+
} catch (error) {
|
|
934
|
+
return error?.code === 'ESRCH' ? pidText : undefined;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/**
|
|
939
|
+
* Move one dead lock aside, with exactly one reaper at a time.
|
|
940
|
+
*
|
|
941
|
+
* The reaper lock is what makes the claim atomic against a *second waiter*: without it, a waiter
|
|
942
|
+
* paused between its pid check and its `rename` could come back and move a lock a faster waiter
|
|
943
|
+
* had already created, leaving two installers in the same directory. A reaper that dies only
|
|
944
|
+
* blocks reclaiming for its own stale window, and never installs anything.
|
|
945
|
+
*/
|
|
946
|
+
function reclaimAbandonedLock(lock, identity) {
|
|
947
|
+
const reaper = `${lock}.reap`;
|
|
948
|
+
const token = `${randomUUID()}`;
|
|
949
|
+
try {
|
|
950
|
+
mkdirSync(reaper);
|
|
951
|
+
writeFileSync(join(reaper, 'owner'), token);
|
|
952
|
+
} catch (error) {
|
|
953
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
954
|
+
// Somebody else reaps. A guard left by a dead reaper is *renamed*, not deleted: the rename is
|
|
955
|
+
// atomic, so exactly one waiter can claim the stale guard and the rest see ENOENT. Deleting by
|
|
956
|
+
// path would let a waiter remove a guard another waiter had just created.
|
|
957
|
+
let age = 0;
|
|
958
|
+
try {
|
|
959
|
+
age = Date.now() - statSync(reaper).mtimeMs;
|
|
960
|
+
} catch {
|
|
961
|
+
return false;
|
|
962
|
+
}
|
|
963
|
+
if (age <= LOCK_STALE_MS) return false;
|
|
964
|
+
const deadGuard = `${reaper}.${randomUUID()}.stale`;
|
|
965
|
+
try {
|
|
966
|
+
renameSync(reaper, deadGuard);
|
|
967
|
+
} catch {
|
|
968
|
+
return false;
|
|
969
|
+
}
|
|
970
|
+
rmSync(deadGuard, { recursive: true, force: true });
|
|
971
|
+
return false;
|
|
972
|
+
}
|
|
973
|
+
const ownsReaper = () => {
|
|
974
|
+
try {
|
|
975
|
+
return readFileSync(join(reaper, 'owner'), 'utf8') === token;
|
|
976
|
+
} catch {
|
|
977
|
+
return false;
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
try {
|
|
981
|
+
let current;
|
|
982
|
+
try {
|
|
983
|
+
current = readFileSync(join(lock, 'pid'), 'utf8').trim();
|
|
984
|
+
} catch (error) {
|
|
985
|
+
if (error?.code !== 'ENOENT') throw error;
|
|
986
|
+
current = '';
|
|
987
|
+
}
|
|
988
|
+
// Re-informed, not trusted: the lock a paused waiter saw may have been replaced by a live one
|
|
989
|
+
// since, so ownership and staleness are judged again while `.reap` keeps this the only reaper.
|
|
990
|
+
// A fresh lock is younger than `LOCK_STALE_MS` and survives even before its owner writes a pid.
|
|
991
|
+
let age = 0;
|
|
992
|
+
try {
|
|
993
|
+
age = Date.now() - statSync(lock).mtimeMs;
|
|
994
|
+
} catch {
|
|
995
|
+
return false;
|
|
996
|
+
}
|
|
997
|
+
// The guard can be taken from a paused reaper, and the token is how it knows: if another
|
|
998
|
+
// waiter renamed this guard away, the destructive step below is not ours to take.
|
|
999
|
+
if (!ownsReaper()) return false;
|
|
1000
|
+
if (current !== identity || abandonedLockOwner(lock, age) !== identity) return false;
|
|
1001
|
+
const graveyard = `${lock}.${randomUUID()}.stale`;
|
|
1002
|
+
try {
|
|
1003
|
+
renameSync(lock, graveyard);
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
// The lock is already gone: the next `mkdir` decides who owns it.
|
|
1006
|
+
if (error?.code === 'ENOENT' || error?.code === 'ENOTEMPTY') return false;
|
|
1007
|
+
throw error;
|
|
1008
|
+
}
|
|
1009
|
+
rmSync(graveyard, { recursive: true, force: true });
|
|
1010
|
+
return true;
|
|
1011
|
+
} finally {
|
|
1012
|
+
if (ownsReaper()) rmSync(reaper, { recursive: true, force: true });
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* Name a failed ensure, because the bare download error reads like an engine bug.
|
|
1018
|
+
*
|
|
1019
|
+
* Each message names the asset, the version, the URL, the underlying reason, and the only three
|
|
1020
|
+
* fixes that work. `TN_NATIVE_BINARY_UNPUBLISHED` covers every packaging fact — a release with no
|
|
1021
|
+
* such asset, a manifest without the key, a platform whose asset is deliberately unpublished — so
|
|
1022
|
+
* the same absent asset is diagnosed the same way whether or not the host was online.
|
|
1023
|
+
* `TN_NATIVE_BINARY_UNAVAILABLE` is a network, HTTP or checksum failure.
|
|
1024
|
+
*/
|
|
1025
|
+
function unavailableNativeBinary(error, plan) {
|
|
1026
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
1027
|
+
// Two different facts share the UNPUBLISHED name: this platform publishes nothing (warn and move
|
|
1028
|
+
// on) and a release that is missing an asset it promised (a real failure). `unpublished` keeps
|
|
1029
|
+
// them apart for the prefetch command, which cannot see the plan.
|
|
1030
|
+
// By-design means this platform publishes nothing (darwin, linux-arm64, an unsupported host).
|
|
1031
|
+
// A manifest or asset that should exist and does not is a failure, however it is diagnosed.
|
|
1032
|
+
const byDesign =
|
|
1033
|
+
(error instanceof Error && error.code === 'PREBUILT_RELEASE_UNPUBLISHED') ||
|
|
1034
|
+
/is not published for/u.test(reason);
|
|
1035
|
+
const code =
|
|
1036
|
+
error instanceof Error &&
|
|
1037
|
+
(['PREBUILT_RELEASE_ABSENT', 'PREBUILT_RELEASE_MISSING', 'PREBUILT_RELEASE_UNPUBLISHED'].includes(error.code) ||
|
|
1038
|
+
/No prebuilt release (?:asset|manifest)|is not published for/u.test(reason))
|
|
1039
|
+
? 'TN_NATIVE_BINARY_UNPUBLISHED'
|
|
1040
|
+
: 'TN_NATIVE_BINARY_UNAVAILABLE';
|
|
1041
|
+
const asset = PREBUILT_ASSET_NAMES[plan.key] ?? plan.key;
|
|
1042
|
+
const env = plan.key.endsWith('-engine-player') ? 'THREENATIVE_ENGINE_PLAYER' : 'THREENATIVE_RUNTIME_BINARY';
|
|
1043
|
+
const message = code === 'TN_NATIVE_BINARY_UNPUBLISHED'
|
|
1044
|
+
? `${code}: no ${asset} is published for @threenative/runtime-native ${packageVersion} at ${plan.status.url} (${reason}).`
|
|
1045
|
+
: `${code}: ${asset} for @threenative/runtime-native ${packageVersion} could not be downloaded from ${plan.status.url} (${reason}).`;
|
|
1046
|
+
const wrapped = new Error(
|
|
1047
|
+
`${message} Fix it one of three ways: connect (or reconnect) and rerun the same command; set ${env} to a local binary; or build one from an engine checkout (${
|
|
1048
|
+
plan.key.endsWith('-engine-player')
|
|
1049
|
+
? 'run node scripts/download-deps.mjs then node scripts/build-native-physics.mjs --desktop (every desktop preset enables native physics), and for a Linux web HUD node scripts/build-native-ui-overlay.mjs first (CMake needs that library before it accepts the flag); then cmake --preset <platform> -B build/tn-engine-ui -DTN_ENGINE_ONLY=ON -DTN_ENGINE_PLAYER=ON -DTN_ENGINE_PLAYER_UI_OVERLAY=ON; on any other platform or with a "native" HUD use the same command without -DTN_ENGINE_PLAYER_UI_OVERLAY=ON (a web HUD there needs engine: \"threejs\"), then cmake --build build/tn-engine-ui --target tn-native-engine-player-v8'
|
|
1050
|
+
: 'pnpm --filter @threenative/runtime-native native:build'
|
|
1051
|
+
}).`,
|
|
1052
|
+
);
|
|
1053
|
+
wrapped.code = code;
|
|
1054
|
+
if (byDesign) wrapped.unpublished = true;
|
|
1055
|
+
return wrapped;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/**
|
|
1059
|
+
* Download what a native build needs, once, at the moment it needs it (PRD-783).
|
|
1060
|
+
*
|
|
1061
|
+
* Nothing downloads during `pnpm install` any more, so a web game fetches no binary at all. The
|
|
1062
|
+
* first `threenative build --target desktop` calls this: a verified cache returns with no network,
|
|
1063
|
+
* one lock makes parallel callers download once, and a failure carries a name and three fixes.
|
|
1064
|
+
*/
|
|
1065
|
+
export async function ensureNativeBinary(options = {}) {
|
|
1066
|
+
const plan = createInstallPlan(options);
|
|
1067
|
+
try {
|
|
1068
|
+
// Inside the wrapper: an unsupported platform must read like every other absent binary, with
|
|
1069
|
+
// its name and the local-binary recipes, not as a bare platform error.
|
|
1070
|
+
platformKey(plan.platform, options.arch);
|
|
1071
|
+
// A caller that packages the binary can ask for a build-private name taken while the lock is
|
|
1072
|
+
// held: publishing renames a new file into place, so a link made here keeps pointing at the
|
|
1073
|
+
// bytes this call verified even if another install with a different lock replaces the cache.
|
|
1074
|
+
const stage = (path) => {
|
|
1075
|
+
if (!options.stagePrivate) return path;
|
|
1076
|
+
// The helper sits beside the runtime it dispatches from, so a private runtime is only usable
|
|
1077
|
+
// with its own copy of the helper: both are snapshotted into the same directory.
|
|
1078
|
+
// A read-only install (a prefetched image) cannot hold the snapshot beside the cache, so the
|
|
1079
|
+
// caller names the writable directory; the bytes are the cache's either way.
|
|
1080
|
+
// One directory per snapshot: the helper keeps its fixed name, two builds must not share it,
|
|
1081
|
+
// and the caller removes the directory it was handed a path into.
|
|
1082
|
+
const stagedDir = mkdtempSync(
|
|
1083
|
+
join(options.stageDir && options.stageDir.length > 0 ? options.stageDir : dirname(path), 'tn-stage-'),
|
|
1084
|
+
);
|
|
1085
|
+
const staged = join(stagedDir, basename(path));
|
|
1086
|
+
try {
|
|
1087
|
+
linkSync(path, staged);
|
|
1088
|
+
} catch {
|
|
1089
|
+
copyFileSync(path, staged);
|
|
1090
|
+
}
|
|
1091
|
+
const helper = plan.toolsOutput;
|
|
1092
|
+
if (plan.toolsKey && typeof helper === 'string' && existsSync(helper)) {
|
|
1093
|
+
const stagedHelper = join(dirname(staged), basename(helper));
|
|
1094
|
+
try {
|
|
1095
|
+
try {
|
|
1096
|
+
linkSync(helper, stagedHelper);
|
|
1097
|
+
} catch {
|
|
1098
|
+
copyFileSync(helper, stagedHelper);
|
|
1099
|
+
}
|
|
1100
|
+
} catch (error) {
|
|
1101
|
+
// Half a snapshot is worse than none: the caller never sees this path, so the whole
|
|
1102
|
+
// directory goes, including the runtime already linked into it.
|
|
1103
|
+
rmSync(stagedDir, { force: true, recursive: true });
|
|
1104
|
+
throw error;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
return staged;
|
|
1108
|
+
};
|
|
1109
|
+
// Every private request verifies and stages under the same lock: a warm cache read outside it
|
|
1110
|
+
// could be published over between the verification and the link. A lock release that fails
|
|
1111
|
+
// after the snapshot exists must not leave it behind, so the snapshot is tracked out here.
|
|
1112
|
+
let snapshot;
|
|
1113
|
+
if (options.stagePrivate) {
|
|
1114
|
+
try {
|
|
1115
|
+
return await withInstallLock(plan, options, async () => {
|
|
1116
|
+
if (!isVerifiedInstall(plan, options)) await installPrebuilt({ ...options, reuse: true });
|
|
1117
|
+
snapshot = stage(plan.output);
|
|
1118
|
+
return snapshot;
|
|
1119
|
+
});
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
// A read-only install cannot hold a lock file either. The cache it already ships is verified
|
|
1122
|
+
// before and after the snapshot, and nothing else can publish over it here, so the snapshot
|
|
1123
|
+
// is still this build's own bytes; a download stays locked wherever the lock can be made.
|
|
1124
|
+
if (error?.code === 'EROFS' || error?.code === 'EACCES') {
|
|
1125
|
+
if (isVerifiedInstall(plan, options)) {
|
|
1126
|
+
const staged = stage(plan.output);
|
|
1127
|
+
// The snapshot itself must match the receipt, not just the path it was taken from.
|
|
1128
|
+
// No receipt, no snapshot: an unreadable one cannot say which bytes these are.
|
|
1129
|
+
let declared;
|
|
1130
|
+
try {
|
|
1131
|
+
declared = JSON.parse(readFileSync(plan.statusPath, 'utf8')).sha256;
|
|
1132
|
+
} catch {
|
|
1133
|
+
declared = undefined;
|
|
1134
|
+
}
|
|
1135
|
+
const stagedSha = existsSync(staged) ? sha256(readFileSync(staged)) : undefined;
|
|
1136
|
+
if (isVerifiedInstall(plan, options) && stagedSha !== undefined &&
|
|
1137
|
+
declared !== undefined && declared === stagedSha)
|
|
1138
|
+
return staged;
|
|
1139
|
+
rmSync(staged, { force: true });
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
if (snapshot !== undefined) rmSync(snapshot, { force: true });
|
|
1143
|
+
throw error;
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
if (isVerifiedInstall(plan, options)) return plan.output;
|
|
1147
|
+
return await withInstallLock(plan, options, () => installPrebuilt({ ...options, reuse: true }));
|
|
1148
|
+
} catch (error) {
|
|
1149
|
+
throw unavailableNativeBinary(error, plan);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// The explicit "fetch now" command, for an offline image or a link known to be slow. It goes
|
|
1154
|
+
// through the same locked, reuse-aware entry point a build uses: run beside a desktop build it
|
|
1155
|
+
// waits instead of racing, and a failed refresh never deletes a verified cache.
|
|
1156
|
+
//
|
|
1157
|
+
// Real paths on both sides: this is invoked through a symlinked `node_modules` path, and a plain
|
|
1158
|
+
// comparison with the module's real URL silently skipped the install.
|
|
433
1159
|
if (process.argv[1] && existsSync(process.argv[1]) &&
|
|
434
1160
|
realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1])) {
|
|
435
1161
|
const sourceCheckout = existsSync(join(packageRoot, 'src')) && existsSync(join(packageRoot, 'CMakeLists.txt'));
|
|
436
1162
|
if (sourceCheckout) {
|
|
437
1163
|
console.log('ThreeNative runtime source checkout detected; prebuilt install is deferred to package testing.');
|
|
438
1164
|
} else {
|
|
439
|
-
|
|
440
|
-
|
|
1165
|
+
// Both targets are attempted independently: a manifest that carries the engine player but no
|
|
1166
|
+
// legacy runtime must still fill the cache, and one that omits either must not hide the other.
|
|
1167
|
+
Promise.allSettled([
|
|
1168
|
+
ensureNativeBinary({ requireComplete: true }),
|
|
1169
|
+
ensureNativeBinary({ enginePlayer: true, requireComplete: true }),
|
|
1170
|
+
]).then((results) => {
|
|
1171
|
+
let failures = 0;
|
|
1172
|
+
for (const result of results) {
|
|
1173
|
+
if (result.status === 'fulfilled') continue;
|
|
1174
|
+
const error = result.reason;
|
|
441
1175
|
const reason = error instanceof Error ? error.message : String(error);
|
|
442
|
-
//
|
|
443
|
-
//
|
|
444
|
-
//
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
return;
|
|
1176
|
+
// A release that carries no asset for this platform is a packaging-state fact, not a
|
|
1177
|
+
// broken download: report it, and count it only as something this platform cannot fetch.
|
|
1178
|
+
// Only an absence this platform publishes nothing for is a warning. A published asset the
|
|
1179
|
+
// release is missing (404, no manifest entry) must fail the prefetch: an offline image
|
|
1180
|
+
// built on exit 0 would break at the game's first desktop build.
|
|
1181
|
+
if (error instanceof Error && (error.unpublished === true || error.code === 'PREBUILT_RELEASE_UNPUBLISHED')) {
|
|
1182
|
+
console.warn(reason);
|
|
1183
|
+
continue;
|
|
451
1184
|
}
|
|
1185
|
+
failures += 1;
|
|
452
1186
|
console.error(reason);
|
|
453
|
-
|
|
454
|
-
|
|
1187
|
+
}
|
|
1188
|
+
// Any target this platform publishes that was not cached is a prefetch that did not happen:
|
|
1189
|
+
// an offline image built on exit 0 would fail at the game's first desktop build instead.
|
|
1190
|
+
if (failures > 0) process.exitCode = 1;
|
|
1191
|
+
});
|
|
455
1192
|
}
|
|
456
1193
|
}
|
|
@@ -20,7 +20,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
20
20
|
|
|
21
21
|
import { assertNativeAssetsDecodable, deriveDesktopWebpSupport } from './asset-preflight.mjs';
|
|
22
22
|
import { listFiles, selectManifestAssets } from './asset-manifest.mjs';
|
|
23
|
-
import {
|
|
23
|
+
import { ensureNativeBinary } from './install-prebuilt.mjs';
|
|
24
24
|
|
|
25
25
|
// The container helper is imported lazily by the release path only, so a debug build never loads
|
|
26
26
|
// it, and it ships in package.json `files` so a published `--mode release` run resolves it.
|
|
@@ -72,7 +72,7 @@ export function stripDesktopRuntime(file, { platform = process.platform, run = e
|
|
|
72
72
|
/**
|
|
73
73
|
* Resolve the desktop runtime binary a consumer build compiles against.
|
|
74
74
|
*
|
|
75
|
-
* A published install ships no compiled runtime until the
|
|
75
|
+
* A published install ships no compiled runtime until the first native build fetches one, so a
|
|
76
76
|
* missing `--runtime` installs from the release manifest rather than failing with a bare
|
|
77
77
|
* "missing file". `THREENATIVE_RUNTIME_SOURCE` remains the decoder-preflight source only: it
|
|
78
78
|
* never selects or substitutes the runtime binary, and no code path here reads a checkout as
|
|
@@ -90,7 +90,13 @@ export async function resolveDesktopRuntime(explicit, options = {}) {
|
|
|
90
90
|
'Pass the checkout-built --runtime explicitly for a maintainer build; consumer builds unset the override and install from the release manifest.',
|
|
91
91
|
);
|
|
92
92
|
}
|
|
93
|
-
|
|
93
|
+
// A private snapshot, with its helper beside it: the shared cache can be republished by another
|
|
94
|
+
// build under a different lock while this one cooks assets.
|
|
95
|
+
// Staged beside the artifact, not in the system temp root: a hardened host can mount /tmp
|
|
96
|
+
// `noexec`, and this runtime has to run to produce the artifact.
|
|
97
|
+
// The resolver passes the request through and defaults to no staging: a capability probe reads
|
|
98
|
+
// the cache path, and a caller that must execute the binary asks for its own snapshot.
|
|
99
|
+
return ensureNativeBinary({ ...options.install });
|
|
94
100
|
}
|
|
95
101
|
|
|
96
102
|
/**
|
|
@@ -215,8 +221,32 @@ export function packageDesktop(options) {
|
|
|
215
221
|
}
|
|
216
222
|
return compileOrPackage(options, options.runtime);
|
|
217
223
|
}
|
|
218
|
-
return resolveDesktopRuntime(undefined, {
|
|
219
|
-
|
|
224
|
+
return resolveDesktopRuntime(undefined, {
|
|
225
|
+
runtimeSource: options.runtimeSource,
|
|
226
|
+
install: options.install,
|
|
227
|
+
output: options.output,
|
|
228
|
+
}).then(
|
|
229
|
+
async (runtime) => {
|
|
230
|
+
// The packager owns its executable copy: taken beside the artifact, removed in `finally`.
|
|
231
|
+
const stageDir = dirname(options.output);
|
|
232
|
+
let executable = runtime;
|
|
233
|
+
let stagedDir;
|
|
234
|
+
try {
|
|
235
|
+
// A cache path is the one the installer publishes: anything else is the caller's own file.
|
|
236
|
+
if (/[\\/]prebuilt[\\/][^\\/]+[\\/]/u.test(runtime)) {
|
|
237
|
+
mkdirSync(stageDir, { recursive: true });
|
|
238
|
+
executable = await ensureNativeBinary({
|
|
239
|
+
...options.install,
|
|
240
|
+
stageDir,
|
|
241
|
+
stagePrivate: true,
|
|
242
|
+
});
|
|
243
|
+
stagedDir = dirname(executable);
|
|
244
|
+
}
|
|
245
|
+
return await compileOrPackage(options, executable);
|
|
246
|
+
} finally {
|
|
247
|
+
if (stagedDir !== undefined) rmSync(stagedDir, { force: true, recursive: true });
|
|
248
|
+
}
|
|
249
|
+
},
|
|
220
250
|
);
|
|
221
251
|
}
|
|
222
252
|
|
|
@@ -3,12 +3,15 @@
|
|
|
3
3
|
// engine's own three, its cooked assets and its built UI, in one directory with a launcher. The
|
|
4
4
|
// player reads `native/assets.tnpk` and `ui/index.html` beside the bundle, so the layout is the contract.
|
|
5
5
|
import { createHash } from "node:crypto";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { readFileSync, readdirSync, chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
9
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
10
|
import { bundleNativeEngine, cookNativeEngineAssets } from "./bundle-native-engine.mjs";
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
// A Windows build has to contain a runnable image: the same bytes under the `.exe` name the
|
|
13
|
+
// operating system will spawn, and the path the playtest launcher resolver looks for there.
|
|
14
|
+
const PLAYER = process.platform === "win32" ? "tn-native-engine-player-v8.exe" : "tn-native-engine-player-v8";
|
|
12
15
|
|
|
13
16
|
/**
|
|
14
17
|
* The launcher: the window opens with the game's title and size, the player takes the game's CPU priority
|
|
@@ -35,13 +38,71 @@ export function launcher(width, height, title, priority = "game", fullscreen = t
|
|
|
35
38
|
* Writes `output` as a directory: `<name>` (launcher), the player, `game.js`, `native/assets.tnpk`
|
|
36
39
|
* and, for a web UI, `ui/`. `bundle` and `cook` are the engine bundler's, injectable for the unit test.
|
|
37
40
|
*/
|
|
41
|
+
/** A path with every symlink resolved, including the ones above a file that does not exist yet. */
|
|
42
|
+
function resolvedPath(target) {
|
|
43
|
+
const absolute = resolve(target);
|
|
44
|
+
const rest = [];
|
|
45
|
+
let current = absolute;
|
|
46
|
+
for (;;) {
|
|
47
|
+
try {
|
|
48
|
+
return join(realpathSync(current), ...rest.reverse());
|
|
49
|
+
} catch {
|
|
50
|
+
const parent = dirname(current);
|
|
51
|
+
if (parent === current) return absolute;
|
|
52
|
+
rest.push(basename(current));
|
|
53
|
+
current = parent;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Whether two paths name the same file, through symlinks and through a file not yet written. */
|
|
59
|
+
function samePath(left, right) {
|
|
60
|
+
return resolvedPath(left) === resolvedPath(right);
|
|
61
|
+
}
|
|
62
|
+
|
|
38
63
|
export async function packageEngineDesktop(
|
|
39
|
-
{ project, entry, player, ui, output, buildReceipt, width = 1280, height = 720, title, priority, fullscreen },
|
|
64
|
+
{ project, entry, player, ui, output, buildReceipt, width = 1280, height = 720, title, priority = "game", fullscreen = true },
|
|
40
65
|
{ bundle = bundleNativeEngine, cook = cookNativeEngineAssets } = {},
|
|
41
66
|
) {
|
|
67
|
+
// An older CLI passes the canonical cache path without ever downloading it: this packager can
|
|
68
|
+
// fill that cache itself, through the same locked entry point a build uses, instead of sending
|
|
69
|
+
// the reader to a recipe for a binary the release publishes.
|
|
70
|
+
// Only the package's own cache path: an explicit `--player` elsewhere is the caller's file, and
|
|
71
|
+
// downloading a player into a different directory would still leave packaging to fail.
|
|
72
|
+
const canonicalPlayer = join(
|
|
73
|
+
fileURLToPath(new URL('../prebuilt/', import.meta.url)),
|
|
74
|
+
`${process.platform}-${process.arch}`,
|
|
75
|
+
PLAYER,
|
|
76
|
+
);
|
|
77
|
+
// A snapshot this packager took, and where it lives: removed in `finally` however packaging ends,
|
|
78
|
+
// because a cross-filesystem hard link fell back to a full 118 MiB copy.
|
|
79
|
+
let snapshot;
|
|
80
|
+
try {
|
|
81
|
+
// A canonical cache path is always passed through the verifier: a file that exists is not a file
|
|
82
|
+
// that verifies, and an install killed before writing its receipt leaves exactly that. Compared
|
|
83
|
+
// through symlinks, because pnpm hands the CLI a linked `node_modules/@threenative/...` path.
|
|
84
|
+
if (player && !process.env.THREENATIVE_ENGINE_PLAYER &&
|
|
85
|
+
samePath(player, canonicalPlayer)) {
|
|
86
|
+
// `new URL` needs no import of its own and resolves beside this file however it is symlinked.
|
|
87
|
+
const installer = new URL('./install-prebuilt.mjs', import.meta.url);
|
|
88
|
+
if (existsSync(installer)) {
|
|
89
|
+
const { ensureNativeBinary } = await import(installer.href);
|
|
90
|
+
if (typeof ensureNativeBinary === 'function') {
|
|
91
|
+
// Verified and snapshotted under the lock, into a directory the packager can write even
|
|
92
|
+
// when the install itself is read-only.
|
|
93
|
+
player = await ensureNativeBinary({
|
|
94
|
+
enginePlayer: true,
|
|
95
|
+
stageDir: tmpdir(),
|
|
96
|
+
stagePrivate: true,
|
|
97
|
+
});
|
|
98
|
+
// The snapshot is this packager's own copy: it is removed however packaging ends.
|
|
99
|
+
snapshot = player;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
42
103
|
if (!player || !existsSync(player)) {
|
|
43
104
|
throw new Error(
|
|
44
|
-
`TN_ENGINE_PLAYER_MISSING: engine "threenative" on desktop needs the engine player (${PLAYER}) at ${player ?? "(not set)"}.
|
|
105
|
+
`TN_ENGINE_PLAYER_MISSING: engine "threenative" on desktop needs the engine player (${PLAYER}) at ${player ?? "(not set)"}. The first \`threenative build --target desktop\` downloads it (about 118 MiB, checksum-verified) unless THREENATIVE_ENGINE_PLAYER names a local file; build one from an engine checkout: run \`node scripts/download-deps.mjs\` and \`node scripts/build-native-physics.mjs --desktop\` first (every desktop preset enables native physics), and for a Linux web HUD \`node scripts/build-native-ui-overlay.mjs\` (CMake needs that library before it accepts the flag), then \`cmake --preset <platform> -B build/tn-engine-ui -DTN_ENGINE_ONLY=ON -DTN_ENGINE_PLAYER=ON -DTN_ENGINE_PLAYER_UI_OVERLAY=ON\`; on any other platform or with a \"native\" HUD use the same command without the overlay flag (a web HUD there needs engine: \"threejs\"), then \`cmake --build build/tn-engine-ui --target tn-native-engine-player-v8\` (the legacy host's \`native:build\` does not produce it), or set engine: "threejs" in threenative.config.ts to package with the legacy host.`,
|
|
45
106
|
);
|
|
46
107
|
}
|
|
47
108
|
rmSync(output, { force: true, recursive: true });
|
|
@@ -56,8 +117,39 @@ export async function packageEngineDesktop(
|
|
|
56
117
|
throw new Error(`TN_UI_BUNDLE_MISSING: ${ui} has no index.html, which is the page the overlay loads.`);
|
|
57
118
|
cpSync(ui, join(output, "ui"), { recursive: true });
|
|
58
119
|
}
|
|
59
|
-
|
|
60
|
-
|
|
120
|
+
// Windows cannot run the POSIX launcher, and the raw player exits without its bundle: a `.cmd`
|
|
121
|
+
// beside the player is what a person double-clicking the folder can actually start.
|
|
122
|
+
const windows = process.platform === "win32";
|
|
123
|
+
const start = windows ? join(output, `${basename(output)}.cmd`) : join(output, basename(output));
|
|
124
|
+
const startContents = windows
|
|
125
|
+
? [
|
|
126
|
+
"@echo off",
|
|
127
|
+
`if exist "%~dp0title.txt" set /p TN_PLAYER_TITLE=<"%~dp0title.txt"`,
|
|
128
|
+
// The title never appears in the batch text: cmd expands `%…%` inside quoted `set` values
|
|
129
|
+
// and treats a caret as an escape. It is read from a sidecar as data instead, which is the
|
|
130
|
+
// one form a batch file cannot mangle.
|
|
131
|
+
`set "TN_PLAYER_WIDTH=${width}"`,
|
|
132
|
+
`set "TN_PLAYER_HEIGHT=${height}"`,
|
|
133
|
+
`set "TN_PLAYER_PRIORITY=${priority}"`,
|
|
134
|
+
`set "TN_PLAYER_FULLSCREEN=${fullscreen ? 1 : 0}"`,
|
|
135
|
+
`"%~dp0${PLAYER}" "%~dp0game.js" %*`,
|
|
136
|
+
"",
|
|
137
|
+
].join("\r\n")
|
|
138
|
+
: launcher(width, height, title, priority, fullscreen);
|
|
139
|
+
// Write the launcher exclusively: on a case-insensitive filesystem a name that differs only in
|
|
140
|
+
// case is the packaged player, and opening it for writing would destroy the binary. Existence is
|
|
141
|
+
// the question the filesystem answers, not a string comparison.
|
|
142
|
+
try {
|
|
143
|
+
writeFileSync(start, startContents, { flag: 'wx' });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (error.code === 'EEXIST')
|
|
146
|
+
throw new Error(
|
|
147
|
+
`TN_ENGINE_LAUNCHER_COLLIDES: the launcher path ${start} is already taken by the packaged player (${PLAYER}). Rename the game or its desktop output directory.`,
|
|
148
|
+
);
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
if (windows && title)
|
|
152
|
+
writeFileSync(join(output, "title.txt"), `${title}\n`, { encoding: "utf8", flag: "wx" });
|
|
61
153
|
chmodSync(start, 0o755);
|
|
62
154
|
if (buildReceipt) {
|
|
63
155
|
const receipt = JSON.parse(readFileSync(buildReceipt, "utf8"));
|
|
@@ -80,8 +172,10 @@ export async function packageEngineDesktop(
|
|
|
80
172
|
}
|
|
81
173
|
console.log(`ThreeNative desktop artifact: ${output}`);
|
|
82
174
|
return output;
|
|
175
|
+
} finally {
|
|
176
|
+
if (snapshot !== undefined) rmSync(snapshot, { force: true });
|
|
177
|
+
}
|
|
83
178
|
}
|
|
84
|
-
|
|
85
179
|
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
|
86
180
|
const args = process.argv.slice(2);
|
|
87
181
|
const flags = new Map();
|