diff --git a/.github/workflows/DeveloperDistribution.yml b/.github/workflows/DeveloperDistribution.yml index 97adb980..7c175075 100644 --- a/.github/workflows/DeveloperDistribution.yml +++ b/.github/workflows/DeveloperDistribution.yml @@ -69,7 +69,7 @@ jobs: echo "::notice::Sources build $building; DeveloperReleaseData.hpp still pins the published $pinned." node js/developer/tools/pin-check.mjs fi - node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs + node --test js/developer/tools/check.mjs js/developer/tools/distribution-check.mjs js/developer/tools/manifest-check.mjs js/developer/tools/restore-check.mjs - name: Check the dedicated release tag if: startsWith(github.ref, 'refs/tags/developer-v') env: diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 48efaf07..fde9409f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -14,9 +14,19 @@ `wf install` now needs `wf init` first, which adopts the roots of an existing lock so a project locked before 0.5.0 keeps its locked graph. A committed publication that cannot be completed does not prevent opening the project: it is reported (`developer::IncompletePublication`) and completed by the next command. +- `wf restore [--offline]` (developer distribution 0.5.0): rebuilds the package cache from the lock alone, at the + locked versions and integrities, idempotent and interruptible; `--offline` only checks the cache and lists the + missing or corrupted packages. Cached packages carry a record of their files' digests. The registry is the + application's option, else the manifest's `registry`, else registry.npmjs.org; `wf install` and `wf restore` + print it with its origin. A reproducible local npm registry fixture (`js/developer/tools/registry-fixture.mjs`) + serves the tests. ### Changed +- `DeveloperBootstrapOptions::registry` is now `std::optional`: unset, the manifest's registry + applies; set, it must be HTTPS or a same-origin path and takes precedence over the manifest. The environment + configuration gains `registryExplicit`; earlier environments keep reading `registry`. + - **Breaking:** library headers moved to `include/webfront/`; include them as ``, ``, `` and so on. The former spellings (``, ``, ``) are removed with no redirect headers, so these generic names no longer diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 13ffedda..0b86db1a 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -200,7 +200,45 @@ the fingerprint of both files as read when the command began: if another browser them meanwhile, it is refused with "The project changed since it was read; run the command again" and nothing is lost. Recovery and group publications also hold an advisory lock on `.webfront/developer/journal/.lock`, so several processes sharing a project (or several stores of one process) are serialized rather than abandoning one -another's publication; other project files stay unprotected against concurrent local modification. `wf restore` (#306) will fill the cache from a consistent lock without ever writing them. +another's publication; other project files stay unprotected against concurrent local modification. `wf restore` fills the cache from the lock without ever writing them. + +## Restoring the cache and choosing the registry (`wf restore`) + +The cache under `.webfront/developer/packages/` is not committed. On a new machine, after a clone, or +when it is damaged, `wf restore` rebuilds it from the lock alone: + +- each locked package is downloaded at its exact locked version (no range is resolved again) and checked + against the lock's SHA-512 integrity; packages already valid in the cache are not downloaded again, so the + command is idempotent; +- every package is published on its own: Ctrl+C or an error (changed archive, package absent from the + registry) keeps the packages already restored and never writes the manifest or the lock; run the command again; +- `wf restore --offline` contacts no registry at all: it checks the cache against the lock and fails with the + list of missing or corrupted packages, without downloading anything. + +Each cached package directory `/` is followed by a record `.json` naming the archive's integrity and the +SHA-256 of every file; the record is written last, so an interrupted copy is *missing*, and a file that differs +from its record, or exceeds the bound below, is *corrupted*. The 256 MiB bound applies to the whole unpacked graph, +packages already in the cache included, and is checked before each package is published, so resuming a restore +cannot exceed it. `wf install` with a consistent lock performs the same restoration. + +The registry used by `wf install` and `wf restore` is, in order of precedence: + +1. the application's `DeveloperBootstrapOptions::registry` (the distributor's trusted channel; a test driver + uses it to impose its local registry), +2. the manifest's `registry`, +3. `https://registry.npmjs.org/`. + +Both commands print the registry in use and where it comes from, for example +`Registry: /mirror/ (application option)`. A registry must use HTTPS or be a path on the application's own +origin, like the environment archive (a path starting with `//` or containing a backslash, which browsers read as +another host, is refused); tarballs must use HTTPS or the registry's origin. The lock's `registry` +field records where the graph was resolved and is not used to restore it, so a mirror can serve a lock resolved +from the public registry. + +Offline provisioning, extending ADR-013's explicit local provisioning: serve a directory of packuments (``) +and tarballs from the application (`fs::NativeDebugFS` or an application provider) and pass its path as +`registry`, then run `wf restore`; or copy `.webfront/developer/packages/` from another machine and check it with +`wf restore --offline`. The environment archive is provisioned the same way (see below). ## Dependencies, storage and limitations @@ -216,8 +254,9 @@ another's publication; other project files stay unprotected against concurrent l - `webfront-packages.lock.json` records exact package versions, dependency edges, source integrities, requested roots and the digest of the manifest dependencies it resolved. Commit it and the source TSX/CSS; the generated provider can also be committed. Preview/embed consume the locked local files without resolving versions again. -- Unpacked packages are cached by name, version and integrity under `.webfront/developer/packages/`. - A failed install can leave unused cached packages, but the lock file remains unchanged. The tools +- Unpacked packages are cached by name, version and integrity under `.webfront/developer/packages/`, + each with a record of its files' digests. A failed install can leave unused cached packages, but the lock + file remains unchanged. A lock naming more than 512 packages is refused. The tools installed by the existing `ToolManager` keep their separate store and `webfront-tools.lock.json`. - Published environment/preview resources are served under `/webfront/developer/`. The protected `/WebFront.js` remains the library's version. Sources, staging and cached archives are not HTTP @@ -229,7 +268,7 @@ another's publication; other project files stay unprotected against concurrent l abandoned, and staging left by a crashed process is removed after an hour. Browser builds time out after 120 seconds. - Installing another package keeps every locked version that still satisfies a requested range and fails if its archive no longer matches the recorded integrity; only new ranges are resolved. Review the resulting lock - changes. Restoring packages from a lockfile on a fresh machine is not yet a separate command. + changes. `wf restore` rebuilds the cache of a lock on a fresh machine (see above). ## Environment distribution and offline tests (maintainers) @@ -265,8 +304,14 @@ The preview command later replaces that directory, but the verified archive is a independently for subsequent launches. These are maintainer provisioning commands; the application's terminal still installs and builds browser dependencies without a local Node/npm installation. -Fixture provisioning packs the pinned React, React DOM and scheduler sources from the maintainer's -npm installation into a fake local registry. No CTest case downloads from the public registry. +Fixture provisioning writes the tests' local npm registry (`js/developer/tools/registry-fixture.mjs`): +packuments and tarballs packed reproducibly from the pinned `jasmine-core`, React, React DOM and scheduler of the +maintainer's npm installation, plus synthetic packages for the edge cases (a newer version under a locked range, +an archive that no longer matches its integrity). The test application serves it from its own origin and imposes +it through the `registry` option. The CEF-off `DeveloperJavaScript` case generates the synthetic part in memory to +test `wf restore`. No CTest case downloads from the public registry. Generating the fixture and the packages' +logic use only browser APIs; reading `node_modules` and writing files (`registry-fixture-node.mjs`) are the +Node-only part, so that `wf` can take the fixture over (#318). ```sh cmake -S . -B build-native -DCMAKE_BUILD_TYPE=Release \ diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index e0b230ee..ec7f4ae2 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -126,7 +126,8 @@ Status snapshot: 2026-07-19. Optional mddlog integration note: 2026-10-02. Newco Pages returned HTTP 200, CORS `*` and byte-identical pinned environment data on 2026-10-20. - Browser packages only: no installation scripts, native modules, Node API shims, optional dependencies or TypeScript type checking. Peers require explicit compatible roots/direct - dependencies. Lockfile restore on a fresh machine and automatic rebuild/watch are future work. + dependencies. Automatic rebuild/watch is future work. `wf restore [--offline]` (0.5.0, #306) rebuilds or checks + the cache from the lock, from the application's registry option, else the manifest's, else npmjs. See [DEVELOPER_ENVIRONMENT](DEVELOPER_ENVIRONMENT.md) for exact commands and limits. ## Embedded dependency refresh (#284, 2026-10-19) diff --git a/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md b/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md index 89828e89..b5a04ee4 100644 --- a/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md +++ b/docs/adr/ADR-013-bootstrap-developpeur-a-la-demande.md @@ -6,6 +6,7 @@ | --- | --- | --- | --- | --- | --- | | 0.1 | 2026-10-20 | Proposée | Ambroise Leclerc | Proposition et première implémentation du bootstrap développeur versionné. | À renseigner après intégration. | | 0.2 | 2026-10-22 | Proposée | Ambroise Leclerc | Alignement sur ADR-016 : la proposition devient la base de l'architecture ; preuves multiplateformes manquantes listées. | [404fed2](https://github.com/ambroise-leclerc/WebFront/commit/404fed2c2145d4faba8efee035e10522ff87a91f) | +| 0.3 | 2026-10-22 | Proposée | Ambroise Leclerc | Provisioning local des paquets (#306) : `wf restore [--offline]`, priorité du registre de l'application sur celui du manifeste. | À renseigner après intégration. | ## Statut et date @@ -60,6 +61,10 @@ trajectoire de retrait de l'ADR-016. - Exécuter une page distante avec le bridge : écarté ; l'environnement validé est servi localement. - Le premier lancement nécessite l'accès au dépôt ou un provisioning local explicite. Le cache vérifié autorise ensuite un lancement hors ligne. +- Les paquets suivent la même règle : `wf restore` reconstruit leur cache depuis le lock, depuis le + registre fixé par l'application (canal de confiance du distributeur), sinon celui du manifeste, sinon + registry.npmjs.org, toujours en HTTPS ou sur l'origine de l'application. Un registre servi par + l'application est leur provisioning local explicite ; `wf restore --offline` vérifie le cache sans réseau. - Le code téléchargé possède l'autorité du bridge et du projet autorisé ; ce n'est pas un sandbox. Le mode distribution n'active pas ces callbacks. Aucun accès au shell n'est ajouté. diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 996d812a..3ba8f550 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -5,6 +5,8 @@ #include "system/DeveloperReleaseData.hpp" #include "WebFront.hpp" +#include + namespace webfront { struct DeveloperBootstrapOptions { @@ -12,7 +14,10 @@ struct DeveloperBootstrapOptions { std::string environment; /// Trusted SHA-512 SRI of that exact tarball, supplied independently of its download. std::string integrity; - std::string registry{"https://registry.npmjs.org/"}; + /// npm registry chosen by the application: HTTPS, or a same-origin path such as "/registry/" for a + /// local mirror. It takes precedence over the project manifest's "registry"; unset, the manifest's + /// registry applies, else registry.npmjs.org. + std::optional registry{}; }; namespace developer { @@ -24,6 +29,11 @@ inline WebFrontConfig projectConfig(WebFrontConfig config, const std::filesystem return config; } +/// A path that stays on the application's origin: browsers read "//host" and "/\\host" as another host. +inline bool sameOriginPath(std::string_view path) { + return path.starts_with('/') && !path.starts_with("//") && !path.contains('\\'); +} + inline void validateBootstrap(std::string_view mode, const std::filesystem::path& project, const DeveloperBootstrapOptions& options) { if (mode != "developer") throw std::invalid_argument("Unknown bootstrap mode"); @@ -31,6 +41,18 @@ inline void validateBootstrap(std::string_view mode, const std::filesystem::path throw std::invalid_argument("Developer bootstrap requires an explicit project directory"); if (options.environment.empty() || !options.integrity.starts_with("sha512-")) throw std::invalid_argument("Developer bootstrap requires an environment URL and trusted SHA-512 integrity"); + if (options.registry && !options.registry->starts_with("https://") && !developer::sameOriginPath(*options.registry)) + throw std::invalid_argument("The developer registry must be an HTTPS URL or a same-origin path"); +} + +inline constexpr std::string_view defaultRegistry{"https://registry.npmjs.org/"}; + +/// The configuration the environment reads. "registry" always names a usable registry, for environments +/// that predate "registryExplicit"; the latter tells whether the application chose it. +inline std::string bootstrapConfig(const DeveloperBootstrapOptions& options) { + return "{\"environment\":" + json::quote(options.environment) + ",\"integrity\":" + json::quote(options.integrity) + + ",\"registry\":" + json::quote(options.registry.value_or(std::string(defaultRegistry))) + + ",\"registryExplicit\":" + (options.registry ? "true" : "false") + "}"; } } // namespace developer @@ -51,8 +73,7 @@ class BasicDeveloperApp : public BasicWF(project); - registerBridge("{\"environment\":" + json::quote(options.environment) + ",\"integrity\":" + json::quote(options.integrity) - + ",\"registry\":" + json::quote(options.registry) + "}"); + registerBridge(developer::bootstrapConfig(options)); } void show(std::string_view page = {}) { diff --git a/js/core/WebFrontAssets.cmake b/js/core/WebFrontAssets.cmake index 03dd8377..ac5ec6bb 100644 --- a/js/core/WebFrontAssets.cmake +++ b/js/core/WebFrontAssets.cmake @@ -102,7 +102,7 @@ function(webfront_add_embedded_assets) find_program(WEBFRONT_NODE_EXECUTABLE NAMES node nodejs REQUIRED) add_test(NAME DeveloperJavaScript COMMAND "${WEBFRONT_NODE_EXECUTABLE}" --test "${root}/js/developer/tools/check.mjs" "${root}/js/developer/tools/distribution-check.mjs" - "${root}/js/developer/tools/manifest-check.mjs") + "${root}/js/developer/tools/manifest-check.mjs" "${root}/js/developer/tools/restore-check.mjs") set_tests_properties(DeveloperJavaScript PROPERTIES TIMEOUT 30) add_test(NAME EmbeddedAssetGenerator COMMAND ${CMAKE_COMMAND} -E env "WEBFRONT_TEST_CMAKE=${CMAKE_COMMAND}" "${WEBFRONT_NODE_EXECUTABLE}" diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 71456a07..04e21bf0 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -1,23 +1,25 @@ { - "js/developer/environment/manifest.mjs": "1cb0c70c87ca31ec81ad0591c0c1d1cb2637ecc491caef9c3d3ec8f1670ea900", + "js/developer/environment/manifest.mjs": "126f0f0e5d64ebb85191c70ff7b42c3c8f9abd5133b4e3e96acc29f089419e6c", "js/developer/environment/project.mjs": "525bc1545f6ff9a70c744c536e46c2404bdc20daa83b25b29419222161003c3b", - "js/developer/environment/installer.mjs": "e02e047f591a539b04c519570902aa6166614958ac96b61e2aff4dc167d8c816", - "js/developer/environment/packages-entry.mjs": "7b5dc8aac408b741ccd3f9098165fca7645c4e88fd7ca7b8822fe37b7ad21fce", + "js/developer/environment/installer.mjs": "f3e919535847c93f62498ee0ad3fec49ff5f7531fb657feaca80e2ccb6da1c0c", + "js/developer/environment/restore.mjs": "cdd22eebd55d68bd705685cd5ee3059e228a35053eaad116ab99c4c05b908098", + "js/developer/environment/cache.mjs": "6fd0e3b760dfc1070a28e2e2eb3c86621c970c775045e7a9ae665da4f6845922", + "js/developer/environment/packages-entry.mjs": "edf47d25099428ea8d33f9fe4552f239035715b98fd2bff6be0f9143ab0cfe8a", "js/developer/environment/bootstrap.mjs": "534af4b3d07891338c3390e1d5e06c2fb6dd8df11ca6547735565b17f1b9cd70", "js/developer/environment/bootstrap-entry.mjs": "ff8084f23f5acc721f97eb1ed0a454e7bfee1894de17d54f0100fa11f7ef8b77", "js/developer/environment/packages.mjs": "faed29500a34c6ce24756d07bd4b47b9168ccec4bd49d12f00096a869637d74d", "js/developer/environment/starter.mjs": "048cf2af36b407bc075323f78a1195b4be91ad7da51f6ce941d9fb230f314ff9", "js/developer/environment/paths.mjs": "6ebb626610756143c58762c87af18980802809d7f0f53d3b588e4b20e8db0161", - "js/developer/environment/runtime.mjs": "8c1eec7e111ac33ad40a33baa7722bcb2f0e5e3301981cc4c14e1d07771946aa", + "js/developer/environment/runtime.mjs": "a8018ff010f17119c90853c883f895bd229ea091bc0edc416467086a34c3b4a3", "js/developer/environment/compiler.mjs": "3f7e187ca9a4c2645ef3823127457cad655919cbea3c7c0f22fb7ae2cc87e0e5", "js/developer/environment/bundler.mjs": "b0ff79a1b0caa012c25ec7b7f121d7d50af1aa1651231d3dcf2f39470c4ea25c", "js/developer/environment/entry.mjs": "b2b942443e3c74ae2c008392ba244d9b7e91db70ba1b4ebbe1357c455ebf51bb", "js/developer/environment/conditions.mjs": "7f0ecba239480831e38985ccffd4c82309949924f4eb9d938e4ad1b09f5f36ed", "js/developer/environment/io.mjs": "21af39f07c7eb863908c1df768e3c31de1c6eb8ff757c2a287c4a47c76855db6", "js/developer/environment/recipe.mjs": "5e7b80cb9090dce63fafafbb852879fce9f6ed2399ac364bbe5af1cf6f4c1758", - "js/developer/environment/registry.mjs": "f566f07ea066155ab7209d925cee2cf12a664ac51b07bc0ca3e3fd8fde49a9c8", + "js/developer/environment/registry.mjs": "717b928b47d1eb8d1635cbfda60473f4a8e0918c1345d5364b6b7d2ffe199195", "js/developer/environment/archive.mjs": "1fb8b9c3c27219858597801104639bba1104c7a7d33973609cd556b5e5f81d2d", - "js/developer/environment/lock.mjs": "60d0ea14d24793cd5e85bbd4bb4bfe90d2c7d76c0d20ffc99f462595a6e57291", + "js/developer/environment/lock.mjs": "d69a3a877b92da52b21dcc78877345015ac31b7dec1c484ee1ff1f97f154d51f", "js/developer/environment/pins.mjs": "df07f6f01edaf86a1052d0e76f6c6745cb6e7a3309bbd256ac720ee8adc85297", "js/developer/environment/peers.mjs": "e1d999892138682fc0134ef1f4d4b19b9a9ad8d7fb16e37fc9c6c684bd853896", "js/developer/environment/resolve.mjs": "8b96b850af215be51f5cb85cc9c69e057afa04dfb8a57e572620c07059c17fa3", @@ -28,11 +30,11 @@ "examples/life/ui/style.css": "9bb55eb0f0a3287e5b7dc78af9d69608b87ff42c4d9c8a653bc83a52fe293c44", "js/developer/components/tools/wf.mjs": "2a8b463b2da223deb8d54d9fdd6037fdd079afeb24e39337693df03cdbcbd0ec", "js/developer/tools/distribution.json": "12b40657d1bc34c4093cd5f793d772bf3fa6fd8615ab7b766ad1756092438f83", - "js/developer/tools/build.mjs": "70ae5acdcd08dcde777c042d1b27f384746530ba97f89a81a91d04c5bd4c8e66", + "js/developer/tools/build.mjs": "3579b0adb2dd92f2cf06874697efa5cf44e1fe80782633b923e9b2a06a8d2123", "js/developer/tools/site.mjs": "1827d3fd7e1e470336aab25ea8686c912c2b674a10f7be496f2f0077fbc45292", "js/developer/tools/archive.mjs": "bfe9feeb5e4d4e1b7c44c4dec4dcbeab4ae59c2bf16a1d2b32cd6910a2b84e7b", "js/developer/vendor/package-lock.json": "eb545112b672f9dbf520125df1f44a878d62cc8e611f0e33baee36470ded4dec", "js/core/bootstrap/bootstrap.bundle.mjs": "792fe7cf564bd12ac47fef419d8c71e2070925764a17706552e7d3f5d6ba2181", - "js/developer/environment/packages.bundle.mjs": "1bd773a901b747e2a38607171b49e7976af4792214c1e50fc7ed3710fed3bf22", + "js/developer/environment/packages.bundle.mjs": "81b575e77911e7a21fb477df84d955aac0c0017969d93c717e0c9622d4eed913", "include/webfront/system/DeveloperReleaseData.hpp": "c97a8c3b21df3306c179f7b46d945159b5854f9d2810f135a4ab224c768c75d7" } diff --git a/js/developer/environment/cache.mjs b/js/developer/environment/cache.mjs new file mode 100644 index 00000000..3aeecf5e --- /dev/null +++ b/js/developer/environment/cache.mjs @@ -0,0 +1,79 @@ +// The package cache: one directory per locked archive, then a record of its files' digests. The record is written +// last, so a package without one (an interrupted store) is missing, and files differing from it are corrupted. +import {call, blockSize, publish, readProject} from './io.mjs'; +import {isPlainObject} from './entry.mjs'; +import {packageRoot} from './project.mjs'; + +export const packageDirectory = node => `${packageRoot}/${node.key}`; +export const recordPath = node => `${packageRoot}/${node.key}.json`; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); +const unreadable = error => error.message.includes('Cannot read project file:'); + +async function sha256(bytes) { + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); + return [...digest].map(byte => byte.toString(16).padStart(2, '0')).join(''); +} + +/** Publishes a verified archive's files, then the record that makes them a cached package. */ +export async function storePackage(bridge, node, files, {signal} = {}) { + const digests = {}; + for (const path of [...files.keys()].sort()) digests[path] = await sha256(files.get(path)); + await publish(bridge, packageDirectory(node), files, {signal}); + const record = JSON.stringify({format: 1, integrity: node.integrity, files: digests}, null, 2) + '\n'; + await publish(bridge, recordPath(node), new Map([['output', encoder.encode(record)]]), {directory: false, signal}); +} + +async function readRecord(bridge, node) { + let bytes; + try { bytes = await readProject(bridge, recordPath(node)); } + catch (error) { + if (unreadable(error)) return null; + throw error; + } + // Only a malformed record is a corruption; a bridge failure is reported as such. + try { return JSON.parse(decoder.decode(bytes)); } catch { return {}; } +} + +const sameFiles = (record, node) => Object.keys(record.files).sort().join('\n') === [...node.files].sort().join('\n'); + +// A cached file, or null when it is missing or larger than `limit`: reading stops as soon as the limit is passed, +// so an oversized file is a corruption to repair, not a read error. +async function readCached(bridge, path, limit) { + const chunks = []; + let size = 0; + for (;;) { + let chunk; + try { chunk = await call(bridge, 'read', path, size); } + catch (error) { + if (unreadable(error)) return null; + throw error; + } + size += chunk.length; + if (size > limit) return null; + chunks.push(chunk); + if (chunk.length < blockSize) return new Uint8Array(await new Blob(chunks).arrayBuffer()); + } +} + +/** + * The cached files of a locked package, checked against its record: {state: 'valid' | 'missing' | 'corrupted', size}. + * `size` is the unpacked size of a valid package; a package larger than `limit` bytes is corrupted. + */ +export async function inspectCache(bridge, node, {signal, limit = Infinity} = {}) { + const record = await readRecord(bridge, node); + if (!record) return {state: 'missing', size: 0}; + if (record.integrity !== node.integrity || !isPlainObject(record.files) || !sameFiles(record, node)) return {state: 'corrupted', size: 0}; + let size = 0; + for (const path of node.files) { + signal?.throwIfAborted(); + const bytes = await readCached(bridge, `${packageDirectory(node)}/${path}`, limit - size); + if (!bytes || await sha256(bytes) !== record.files[path]) return {state: 'corrupted', size: 0}; + size += bytes.length; + } + return {state: 'valid', size}; +} + +/** 'valid', 'missing' or 'corrupted': see inspectCache(). */ +export const cacheState = async (bridge, node, options) => (await inspectCache(bridge, node, options)).state; diff --git a/js/developer/environment/installer.mjs b/js/developer/environment/installer.mjs index 78370ebb..242858bc 100644 --- a/js/developer/environment/installer.mjs +++ b/js/developer/environment/installer.mjs @@ -2,9 +2,11 @@ import semver from 'semver'; import {resolvePackages, downloadPackage} from './packages.mjs'; import {parseSpec} from '../components/tools/wf.mjs'; -import {publish, readProject} from './io.mjs'; +import {publish} from './io.mjs'; import {manifestPath, newManifest, manifestName, serializeManifest, validateManifest, dependenciesDigest} from './manifest.mjs'; -import {loadProject, publishTogether, lockPath, packageRoot, noManifest, desynchronized, textBytes} from './project.mjs'; +import {loadProject, publishTogether, lockPath, noManifest, desynchronized, textBytes} from './project.mjs'; +import {storePackage} from './cache.mjs'; +import {restorePackages, usableRegistry, describeRegistry} from './restore.mjs'; // The spec syntax resolvePackages() reads: a missing version is undefined, resolved as latest. const splitSpec = spec => { @@ -78,31 +80,10 @@ async function resolveLock(dependencies, previous, options) { async function storePackages(bridge, lock, downloads, {signal, progress}) { for (const [id, files] of downloads) { progress(`Storing ${id}`); - await publish(bridge, `${packageRoot}/${lock.packages[id].key}`, files, {signal}); + await storePackage(bridge, lock.packages[id], files, {signal}); } } -async function isCached(bridge, node) { - try { await readProject(bridge, `${packageRoot}/${node.key}/package.json`); return true; } - catch { return false; } -} - -// npm ci: exactly the locked graph, every archive checked against the recorded integrity. Nothing is resolved or written -// besides the cache. -async function restoreLocked(bridge, lock, {signal, progress, fetchImpl}) { - let restored = 0; - for (const [id, node] of Object.entries(lock.packages)) { - signal?.throwIfAborted(); - if (await isCached(bridge, node)) continue; - progress(`Restoring ${id}`); - const pkg = await downloadPackage(node.name, node.version, {registry: lock.registry, fetchImpl, signal}); - if (pkg.integrity !== node.integrity) throw new Error(`${id} no longer matches the integrity recorded in the lock`); - await publish(bridge, `${packageRoot}/${node.key}`, pkg.files, {signal}); - restored++; - } - return restored; -} - function parseOptions(args) { const update = args.includes('--update'); const specs = args.filter(arg => arg !== '--update'); @@ -123,22 +104,25 @@ const withDigest = async (lock, dependencies) => ({format: lock.format, manifest * wf install: the locked graph exactly when the lock agrees with the manifest; resolves it when there is no lock. * wf install --update: resolves the manifest again, keeping nothing from the lock. */ -export async function install(bridge, args, {registry, signal, progress = () => {}, fetchImpl = fetch}) { +export async function install(bridge, args, {registry, registryExplicit, signal, progress = () => {}, fetchImpl = fetch}) { const {update, specs} = parseOptions(args); const project = await loadProject(bridge); if (!project.manifest) throw new Error(noManifest); - const options = {registry: project.manifest.registry ?? registry, signal, fetchImpl, progress}; + const effective = usableRegistry({registry, registryExplicit}, project.manifest); + const options = {registry: effective.url, signal, fetchImpl, progress}; if (specs.length && update) throw new Error('Usage: wf install --update does not take packages'); if (specs.length && project.status === 'desynchronized') throw new Error(desynchronized); if (!specs.length && !update && project.status === 'desynchronized') throw new Error(desynchronized); + progress(describeRegistry(effective)); + // npm ci: exactly the locked graph, every archive checked against the recorded integrity. const locked = project.status === 'consistent' || project.status === 'legacy'; if (!specs.length && !update && locked) { - const restored = await restoreLocked(bridge, project.lock, {signal, progress, fetchImpl: options.fetchImpl}); - if (project.status === 'consistent') return {lock: project.lock, restored}; + const {restored} = await restorePackages(bridge, project.lock, options); + if (project.status === 'consistent') return {lock: project.lock, restored, registry: effective}; // A lock written before the manifest: the same graph, now recording the dependencies it was resolved from. const lock = await withDigest(project.lock, project.manifest.dependencies); await publishResolution(bridge, project, {manifest: null, lock}, {signal}); - return {lock, restored}; + return {lock, restored, registry: effective}; } const request = requestedDependencies(project, specs); // --update ignores the locked versions; installing a package keeps the others where they are. @@ -150,5 +134,5 @@ export async function install(bridge, args, {registry, signal, progress = () => const lock = await withDigest(resolved.lock, dependencies); const manifest = specs.length ? updatedManifest(project, dependencies) : null; await publishResolution(bridge, project, {manifest, lock}, {signal}); - return {lock, restored: 0}; + return {lock, restored: 0, registry: effective}; } diff --git a/js/developer/environment/lock.mjs b/js/developer/environment/lock.mjs index 6b06f858..dcacafec 100644 --- a/js/developer/environment/lock.mjs +++ b/js/developer/environment/lock.mjs @@ -28,6 +28,7 @@ function hasLockShape(lock) { export function validateLock(lock) { if (!hasLockShape(lock)) throw new Error('Unsupported package lock'); + if (Object.keys(lock.packages).length > 512) throw new Error('The package lock exceeds 512 packages'); for (const [id, node] of Object.entries(lock.packages)) validateNode(lock, id, node); if (Object.values(lock.roots).some(root => !lock.packages[root.id])) throw new Error('Dangling locked root'); return lock; diff --git a/js/developer/environment/manifest.mjs b/js/developer/environment/manifest.mjs index 6fb4eae7..1efd3c3e 100644 --- a/js/developer/environment/manifest.mjs +++ b/js/developer/environment/manifest.mjs @@ -47,9 +47,12 @@ function checkDependencies(value) { return dependencies; } +// A path that stays on the application's origin: browsers read "//host" and "/\\host" as another host. +export const sameOriginPath = value => value.startsWith('/') && !value.startsWith('//') && !value.includes('\\'); + function checkRegistry(value) { if (typeof value !== 'string') fail('registry must be a URL'); - if (value.startsWith('/') && !value.startsWith('//')) return value; + if (sameOriginPath(value)) return value; let url; try { url = new URL(value); } catch { return fail('registry must be an https URL or an absolute path'); } if (url.protocol !== 'https:') fail('registry must use https'); diff --git a/js/developer/environment/packages-entry.mjs b/js/developer/environment/packages-entry.mjs index 933bbd76..60120139 100644 --- a/js/developer/environment/packages-entry.mjs +++ b/js/developer/environment/packages-entry.mjs @@ -3,3 +3,5 @@ export * from './packages.mjs'; export * from './manifest.mjs'; export * from './project.mjs'; export * from './installer.mjs'; +export * from './restore.mjs'; +export * from './cache.mjs'; diff --git a/js/developer/environment/packages.bundle.mjs b/js/developer/environment/packages.bundle.mjs index e3243dfe..11eb5cda 100644 --- a/js/developer/environment/packages.bundle.mjs +++ b/js/developer/environment/packages.bundle.mjs @@ -1,7 +1,13 @@ -var En=Object.create;var Qe=Object.defineProperty;var wn=Object.getOwnPropertyDescriptor;var $n=Object.getOwnPropertyNames;var gn=Object.getPrototypeOf,yn=Object.prototype.hasOwnProperty;var m=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Rn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of $n(t))!yn.call(e,s)&&s!==r&&Qe(e,s,{get:()=>t[s],enumerable:!(n=wn(t,s))||n.enumerable});return e};var P=(e,t,r)=>(r=e!=null?En(gn(e)):{},Rn(t||!e||!e.__esModule?Qe(r,"default",{value:e,enumerable:!0}):r,e));var U=m((Oa,it)=>{"use strict";var Sn="2.0.0",Nn=Number.MAX_SAFE_INTEGER||9007199254740991,bn=16,An=250,Tn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];it.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:bn,MAX_SAFE_BUILD_LENGTH:An,MAX_SAFE_INTEGER:Nn,RELEASE_TYPES:Tn,SEMVER_SPEC_VERSION:Sn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var F=m((va,ot)=>{"use strict";var kn=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};ot.exports=kn});var q=m((x,at)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:$e,MAX_SAFE_BUILD_LENGTH:Pn,MAX_LENGTH:qn}=U(),jn=F();x=at.exports={};var Cn=x.re=[],Dn=x.safeRe=[],l=x.src=[],Un=x.safeSrc=[],u=x.t={},Fn=0,ge="[a-zA-Z0-9-]",Gn=[["\\s",1],["\\d",qn],[ge,Pn]],zn=e=>{for(let[t,r]of Gn)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},E=(e,t,r)=>{let n=zn(t),s=Fn++;jn(e,s,t),u[e]=s,l[s]=t,Un[s]=n,Cn[s]=new RegExp(t,r?"g":void 0),Dn[s]=new RegExp(n,r?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*");E("NUMERICIDENTIFIERLOOSE","\\d+");E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${ge}*`);E("MAINVERSION",`(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})\\.(${l[u.NUMERICIDENTIFIER]})`);E("MAINVERSIONLOOSE",`(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})\\.(${l[u.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASEIDENTIFIER",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIER]})`);E("PRERELEASEIDENTIFIERLOOSE",`(?:${l[u.NONNUMERICIDENTIFIER]}|${l[u.NUMERICIDENTIFIERLOOSE]})`);E("PRERELEASE",`(?:-(${l[u.PRERELEASEIDENTIFIER]}(?:\\.${l[u.PRERELEASEIDENTIFIER]})*))`);E("PRERELEASELOOSE",`(?:-?(${l[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${l[u.PRERELEASEIDENTIFIERLOOSE]})*))`);E("BUILDIDENTIFIER",`${ge}+`);E("BUILD",`(?:\\+(${l[u.BUILDIDENTIFIER]}(?:\\.${l[u.BUILDIDENTIFIER]})*))`);E("FULLPLAIN",`v?${l[u.MAINVERSION]}${l[u.PRERELEASE]}?${l[u.BUILD]}?`);E("FULL",`^${l[u.FULLPLAIN]}$`);E("LOOSEPLAIN",`[v=\\s]*${l[u.MAINVERSIONLOOSE]}${l[u.PRERELEASELOOSE]}?${l[u.BUILD]}?`);E("LOOSE",`^${l[u.LOOSEPLAIN]}$`);E("GTLT","((?:<|>)?=?)");E("XRANGEIDENTIFIERLOOSE",`${l[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);E("XRANGEIDENTIFIER",`${l[u.NUMERICIDENTIFIER]}|x|X|\\*`);E("XRANGEPLAIN",`[v=\\s]*(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:\\.(${l[u.XRANGEIDENTIFIER]})(?:${l[u.PRERELEASE]})?${l[u.BUILD]}?)?)?`);E("XRANGEPLAINLOOSE",`[v=\\s]*(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${l[u.XRANGEIDENTIFIERLOOSE]})(?:${l[u.PRERELEASELOOSE]})?${l[u.BUILD]}?)?)?`);E("XRANGE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAIN]}$`);E("XRANGELOOSE",`^${l[u.GTLT]}\\s*${l[u.XRANGEPLAINLOOSE]}$`);E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${$e}})(?:\\.(\\d{1,${$e}}))?(?:\\.(\\d{1,${$e}}))?`);E("COERCE",`${l[u.COERCEPLAIN]}(?:$|[^\\d])`);E("COERCEFULL",l[u.COERCEPLAIN]+`(?:${l[u.PRERELEASE]})?(?:${l[u.BUILD]})?(?:$|[^\\d])`);E("COERCERTL",l[u.COERCE],!0);E("COERCERTLFULL",l[u.COERCEFULL],!0);E("LONETILDE","(?:~>?)");E("TILDETRIM",`(\\s*)${l[u.LONETILDE]}\\s+`,!0);x.tildeTrimReplace="$1~";E("TILDE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAIN]}$`);E("TILDELOOSE",`^${l[u.LONETILDE]}${l[u.XRANGEPLAINLOOSE]}$`);E("LONECARET","(?:\\^)");E("CARETTRIM",`(\\s*)${l[u.LONECARET]}\\s+`,!0);x.caretTrimReplace="$1^";E("CARET",`^${l[u.LONECARET]}${l[u.XRANGEPLAIN]}$`);E("CARETLOOSE",`^${l[u.LONECARET]}${l[u.XRANGEPLAINLOOSE]}$`);E("COMPARATORLOOSE",`^${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]})$|^$`);E("COMPARATOR",`^${l[u.GTLT]}\\s*(${l[u.FULLPLAIN]})$|^$`);E("COMPARATORTRIM",`(\\s*)${l[u.GTLT]}\\s*(${l[u.LOOSEPLAIN]}|${l[u.XRANGEPLAIN]})`,!0);x.comparatorTrimReplace="$1$2$3";E("HYPHENRANGE",`^\\s*(${l[u.XRANGEPLAIN]})\\s+-\\s+(${l[u.XRANGEPLAIN]})\\s*$`);E("HYPHENRANGELOOSE",`^\\s*(${l[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${l[u.XRANGEPLAINLOOSE]})\\s*$`);E("STAR","(<|>)?=?\\s*\\*");E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Y=m((La,ct)=>{"use strict";var Xn=Object.freeze({loose:!0}),Mn=Object.freeze({}),Vn=e=>e?typeof e!="object"?Xn:e:Mn;ct.exports=Vn});var ye=m((xa,ft)=>{"use strict";var lt=/^[0-9]+$/,ut=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:eut(t,e);ft.exports={compareIdentifiers:ut,rcompareIdentifiers:_n}});var y=m((Sa,ht)=>{"use strict";var J=F(),{MAX_LENGTH:pt,MAX_SAFE_INTEGER:Z}=U(),{safeRe:K,t:Q}=q(),Bn=Y(),{compareIdentifiers:Re}=ye(),Ie=class e{constructor(t,r){if(r=Bn(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>pt)throw new TypeError(`version is longer than ${pt} characters`);J("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?K[Q.LOOSE]:K[Q.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Z||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Z||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Z||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&it.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(J("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Re(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(J("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Re(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?K[Q.PRERELEASELOOSE]:K[Q.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let i=[r,s];n===!1&&(i=[r]),Re(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};ht.exports=Ie});var A=m((Na,mt)=>{"use strict";var dt=y(),Hn=(e,t,r=!1)=>{if(e instanceof dt)return e;try{return new dt(e,t)}catch(n){if(!r)return null;throw n}};mt.exports=Hn});var wt=m((ba,Et)=>{"use strict";var Wn=A(),Yn=(e,t)=>{let r=Wn(e,t);return r?r.version:null};Et.exports=Yn});var gt=m((Aa,$t)=>{"use strict";var Jn=A(),Zn=(e,t)=>{let r=Jn(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};$t.exports=Zn});var It=m((Ta,Rt)=>{"use strict";var yt=y(),Kn=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new yt(e instanceof yt?e.version:e,r).inc(t,n,s).version}catch{return null}};Rt.exports=Kn});var Lt=m((ka,vt)=>{"use strict";var Ot=A(),Qn=(e,t)=>{let r=Ot(e,null,!0),n=Ot(t,null,!0),s=r.compare(n);if(s===0)return null;let i=s>0,o=i?r:n,a=i?n:r,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let d=c?"pre":"";return r.major!==n.major?d+"major":r.minor!==n.minor?d+"minor":r.patch!==n.patch?d+"patch":"prerelease"};vt.exports=Qn});var St=m((Pa,xt)=>{"use strict";var es=y(),ts=(e,t)=>new es(e,t).major;xt.exports=ts});var bt=m((qa,Nt)=>{"use strict";var rs=y(),ns=(e,t)=>new rs(e,t).minor;Nt.exports=ns});var Tt=m((ja,At)=>{"use strict";var ss=y(),is=(e,t)=>new ss(e,t).patch;At.exports=is});var Pt=m((Ca,kt)=>{"use strict";var os=A(),as=(e,t)=>{let r=os(e,t);return r&&r.prerelease.length?r.prerelease:null};kt.exports=as});var v=m((Da,jt)=>{"use strict";var qt=y(),cs=(e,t,r)=>new qt(e,r).compare(new qt(t,r));jt.exports=cs});var Dt=m((Ua,Ct)=>{"use strict";var ls=v(),us=(e,t,r)=>ls(t,e,r);Ct.exports=us});var Ft=m((Fa,Ut)=>{"use strict";var fs=v(),ps=(e,t)=>fs(e,t,!0);Ut.exports=ps});var ee=m((Ga,zt)=>{"use strict";var Gt=y(),hs=(e,t,r)=>{let n=new Gt(e,r),s=new Gt(t,r);return n.compare(s)||n.compareBuild(s)};zt.exports=hs});var Mt=m((za,Xt)=>{"use strict";var ds=ee(),ms=(e,t)=>e.sort((r,n)=>ds(r,n,t));Xt.exports=ms});var _t=m((Xa,Vt)=>{"use strict";var Es=ee(),ws=(e,t)=>e.sort((r,n)=>Es(n,r,t));Vt.exports=ws});var G=m((Ma,Bt)=>{"use strict";var $s=v(),gs=(e,t,r)=>$s(e,t,r)>0;Bt.exports=gs});var te=m((Va,Ht)=>{"use strict";var ys=v(),Rs=(e,t,r)=>ys(e,t,r)<0;Ht.exports=Rs});var Oe=m((_a,Wt)=>{"use strict";var Is=v(),Os=(e,t,r)=>Is(e,t,r)===0;Wt.exports=Os});var ve=m((Ba,Yt)=>{"use strict";var vs=v(),Ls=(e,t,r)=>vs(e,t,r)!==0;Yt.exports=Ls});var re=m((Ha,Jt)=>{"use strict";var xs=v(),Ss=(e,t,r)=>xs(e,t,r)>=0;Jt.exports=Ss});var ne=m((Wa,Zt)=>{"use strict";var Ns=v(),bs=(e,t,r)=>Ns(e,t,r)<=0;Zt.exports=bs});var Le=m((Ya,Kt)=>{"use strict";var As=Oe(),Ts=ve(),ks=G(),Ps=re(),qs=te(),js=ne(),Cs=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return As(e,r,n);case"!=":return Ts(e,r,n);case">":return ks(e,r,n);case">=":return Ps(e,r,n);case"<":return qs(e,r,n);case"<=":return js(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};Kt.exports=Cs});var er=m((Ja,Qt)=>{"use strict";var Ds=y(),Us=A(),{safeRe:se,t:ie}=q(),Fs=(e,t)=>{if(e instanceof Ds)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?se[ie.COERCEFULL]:se[ie.COERCE]);else{let c=t.includePrerelease?se[ie.COERCERTLFULL]:se[ie.COERCERTL],f;for(;(f=c.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||f.index+f[0].length!==r.index+r[0].length)&&(r=f),c.lastIndex=f.index+f[1].length+f[2].length;c.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",i=r[4]||"0",o=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Us(`${n}.${s}.${i}${o}${a}`,t)};Qt.exports=Fs});var rr=m((Za,tr)=>{"use strict";var xe=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};tr.exports=xe});var L=m((Ka,or)=>{"use strict";var Gs=/\s+/g,Se=class e{constructor(t,r){if(r=Xs(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Ne)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(Gs," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!sr(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&Ys(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&Hs)|(this.options.loose&&Ws))+":"+t,s=nr.get(n);if(s)return s;let i=this.options.loose,o=i?I[R.HYPHENRANGELOOSE]:I[R.HYPHENRANGE];t=t.replace(o,ii(this.options.includePrerelease)),$("hyphen replace",t),t=t.replace(I[R.COMPARATORTRIM],Vs),$("comparator trim",t),t=t.replace(I[R.TILDETRIM],_s),$("tilde trim",t),t=t.replace(I[R.CARETTRIM],Bs),$("caret trim",t);let a=t.split(" ").map(p=>Js(p,this.options)).join(" ").split(/\s+/).map(p=>si(p,this.options));i&&(a=a.filter(p=>($("loose invalid filter",p,this.options),!!p.match(I[R.COMPARATORLOOSE])))),$("range list",a);let c=new Map,f=a.map(p=>new Ne(p,this.options));for(let p of f){if(sr(p))return[p];c.set(p.value,p)}c.size>1&&c.has("")&&c.delete("");let d=[...c.values()];return nr.set(n,d),d}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>ir(n,r)&&t.set.some(s=>ir(s,r)&&n.every(i=>s.every(o=>i.intersects(o,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new Ms(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",Ys=e=>e.value==="",ir=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(i=>s.intersects(i,t)),s=n.pop();return r},Js=(e,t)=>(e=e.replace(I[R.BUILD],""),$("comp",e,t),e=Qs(e,t),$("caret",e),e=Zs(e,t),$("tildes",e),e=ti(e,t),$("xrange",e),e=ni(e,t),$("stars",e),e),O=e=>!e||e.toLowerCase()==="x"||e==="*",Zs=(e,t)=>e.trim().split(/\s+/).map(r=>Ks(r,t)).join(" "),Ks=(e,t)=>{let r=t.loose?I[R.TILDELOOSE]:I[R.TILDE];return e.replace(r,(n,s,i,o,a)=>{$("tilde",e,n,s,i,o,a);let c;return O(s)?c="":O(i)?c=`>=${s}.0.0 <${+s+1}.0.0-0`:O(o)?c=`>=${s}.${i}.0 <${s}.${+i+1}.0-0`:a?($("replaceTilde pr",a),c=`>=${s}.${i}.${o}-${a} <${s}.${+i+1}.0-0`):c=`>=${s}.${i}.${o} <${s}.${+i+1}.0-0`,$("tilde return",c),c})},Qs=(e,t)=>e.trim().split(/\s+/).map(r=>ei(r,t)).join(" "),ei=(e,t)=>{$("caret",e,t);let r=t.loose?I[R.CARETLOOSE]:I[R.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,i,o,a,c)=>{$("caret",e,s,i,o,a,c);let f;return O(i)?f="":O(o)?f=`>=${i}.0.0${n} <${+i+1}.0.0-0`:O(a)?i==="0"?f=`>=${i}.${o}.0${n} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.0${n} <${+i+1}.0.0-0`:c?($("replaceCaret pr",c),i==="0"?o==="0"?f=`>=${i}.${o}.${a}-${c} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a}-${c} <${+i+1}.0.0-0`):($("no pr"),i==="0"?o==="0"?f=`>=${i}.${o}.${a}${n} <${i}.${o}.${+a+1}-0`:f=`>=${i}.${o}.${a}${n} <${i}.${+o+1}.0-0`:f=`>=${i}.${o}.${a} <${+i+1}.0.0-0`),$("caret return",f),f})},ti=(e,t)=>($("replaceXRanges",e,t),e.split(/\s+/).map(r=>ri(r,t)).join(" ")),ri=(e,t)=>{e=e.trim();let r=t.loose?I[R.XRANGELOOSE]:I[R.XRANGE];return e.replace(r,(n,s,i,o,a,c)=>{$("xRange",e,n,s,i,o,a,c);let f=O(i),d=f||O(o),p=d||O(a),w=p;return s==="="&&w&&(s=""),c=t.includePrerelease?"-0":"",f?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&w?(d&&(o=0),a=0,s===">"?(s=">=",d?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):s==="<="&&(s="<",d?i=+i+1:o=+o+1),s==="<"&&(c="-0"),n=`${s+i}.${o}.${a}${c}`):d?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:p&&(n=`>=${i}.${o}.0${c} <${i}.${+o+1}.0-0`),$("xRange return",n),n})},ni=(e,t)=>($("replaceStars",e,t),e.trim().replace(I[R.STAR],"")),si=(e,t)=>($("replaceGTE0",e,t),e.trim().replace(I[t.includePrerelease?R.GTE0PRE:R.GTE0],"")),ii=e=>(t,r,n,s,i,o,a,c,f,d,p,w)=>(O(n)?r="":O(s)?r=`>=${n}.0.0${e?"-0":""}`:O(i)?r=`>=${n}.${s}.0${e?"-0":""}`:o?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,O(f)?c="":O(d)?c=`<${+f+1}.0.0-0`:O(p)?c=`<${f}.${+d+1}.0-0`:w?c=`<=${f}.${d}.${p}-${w}`:e?c=`<${f}.${d}.${+p+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),oi=(e,t,r)=>{for(let n=0;n0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var z=m((Qa,pr)=>{"use strict";var X=Symbol("SemVer ANY"),Te=class e{static get ANY(){return X}constructor(t,r){if(r=ar(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),Ae("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===X?this.value="":this.value=this.operator+this.semver.version,Ae("comp",this)}parse(t){let r=this.options.loose?cr[lr.COMPARATORLOOSE]:cr[lr.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new ur(n[2],this.options.loose):this.semver=X}toString(){return this.value}test(t){if(Ae("Comparator.test",t,this.options.loose),this.semver===X||t===X)return!0;if(typeof t=="string")try{t=new ur(t,this.options)}catch{return!1}return be(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new fr(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new fr(this.value,r).test(t.semver):(r=ar(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||be(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||be(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};pr.exports=Te;var ar=Y(),{safeRe:cr,t:lr}=q(),be=Le(),Ae=F(),ur=y(),fr=L()});var M=m((ec,hr)=>{"use strict";var ai=L(),ci=(e,t,r)=>{try{t=new ai(t,r)}catch{return!1}return t.test(e)};hr.exports=ci});var mr=m((tc,dr)=>{"use strict";var li=L(),ui=(e,t)=>new li(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));dr.exports=ui});var wr=m((rc,Er)=>{"use strict";var fi=y(),pi=L(),hi=(e,t,r)=>{let n=null,s=null,i=null;try{i=new pi(t,r)}catch{return null}return e.forEach(o=>{i.test(o)&&(!n||s.compare(o)===-1)&&(n=o,s=new fi(n,r))}),n};Er.exports=hi});var gr=m((nc,$r)=>{"use strict";var di=y(),mi=L(),Ei=(e,t,r)=>{let n=null,s=null,i=null;try{i=new mi(t,r)}catch{return null}return e.forEach(o=>{i.test(o)&&(!n||s.compare(o)===1)&&(n=o,s=new di(n,r))}),n};$r.exports=Ei});var Ir=m((sc,Rr)=>{"use strict";var ke=y(),wi=L(),yr=G(),$i=(e,t)=>{e=new wi(e,t);let r=new ke("0.0.0");if(e.test(r)||(r=new ke("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let a=new ke(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!i||yr(a,i))&&(i=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),i&&(!r||yr(r,i))&&(r=i)}return r&&e.test(r)?r:null};Rr.exports=$i});var vr=m((ic,Or)=>{"use strict";var gi=L(),yi=(e,t)=>{try{return new gi(e,t).range||"*"}catch{return null}};Or.exports=yi});var oe=m((oc,Nr)=>{"use strict";var Ri=y(),Sr=z(),{ANY:Ii}=Sr,Oi=L(),vi=M(),Lr=G(),xr=te(),Li=ne(),xi=re(),Si=(e,t,r,n)=>{e=new Ri(e,n),t=new Oi(t,n);let s,i,o,a,c;switch(r){case">":s=Lr,i=Li,o=xr,a=">",c=">=";break;case"<":s=xr,i=xi,o=Lr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(vi(e,t,n))return!1;for(let f=0;f{h.semver===Ii&&(h=new Sr(">=0.0.0")),p=p||h,w=w||h,s(h.semver,p.semver,n)?p=h:o(h.semver,w.semver,n)&&(w=h)}),p.operator===a||p.operator===c||(!w.operator||w.operator===a)&&i(e,w.semver))return!1;if(w.operator===c&&o(e,w.semver))return!1}return!0};Nr.exports=Si});var Ar=m((ac,br)=>{"use strict";var Ni=oe(),bi=(e,t,r)=>Ni(e,t,">",r);br.exports=bi});var kr=m((cc,Tr)=>{"use strict";var Ai=oe(),Ti=(e,t,r)=>Ai(e,t,"<",r);Tr.exports=Ti});var jr=m((lc,qr)=>{"use strict";var Pr=L(),ki=(e,t,r)=>(e=new Pr(e,r),t=new Pr(t,r),e.intersects(t,r));qr.exports=ki});var Dr=m((uc,Cr)=>{"use strict";var Pi=M(),qi=v();Cr.exports=(e,t,r)=>{let n=[],s=null,i=null,o=e.sort((d,p)=>qi(d,p,r));for(let d of o)Pi(d,t,r)?(i=d,s||(s=d)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let a=[];for(let[d,p]of n)d===p?a.push(d):!p&&d===o[0]?a.push("*"):p?d===o[0]?a.push(`<=${p}`):a.push(`${d} - ${p}`):a.push(`>=${d}`);let c=a.join(" || "),f=typeof t.raw=="string"?t.raw:String(t);return c.length{"use strict";var Ur=L(),qe=z(),{ANY:Pe}=qe,V=M(),je=v(),ji=(e,t,r={})=>{if(e===t)return!0;e=new Ur(e,r),t=new Ur(t,r);let n=!1;e:for(let s of e.set){for(let i of t.set){let o=Di(s,i,r);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},Ci=[new qe(">=0.0.0-0")],Fr=[new qe(">=0.0.0")],Di=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===Pe){if(t.length===1&&t[0].semver===Pe)return!0;r.includePrerelease?e=Ci:e=Fr}if(t.length===1&&t[0].semver===Pe){if(r.includePrerelease)return!0;t=Fr}let n=new Set,s,i;for(let h of e)h.operator===">"||h.operator===">="?s=Gr(s,h,r):h.operator==="<"||h.operator==="<="?i=zr(i,h,r):n.add(h.semver);if(n.size>1)return null;let o;if(s&&i){if(o=je(s.semver,i.semver,r),o>0)return null;if(o===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let h of n){if(s&&!V(h,String(s),r)||i&&!V(h,String(i),r))return null;for(let H of t)if(!V(h,String(H),r))return!1;return!0}let a,c,f,d,p=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,w=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;p&&p.prerelease.length===1&&i.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let h of t){if(d=d||h.operator===">"||h.operator===">=",f=f||h.operator==="<"||h.operator==="<=",s){if(w&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===w.major&&h.semver.minor===w.minor&&h.semver.patch===w.patch&&(w=!1),h.operator===">"||h.operator===">="){if(a=Gr(s,h,r),a===h&&a!==s)return!1}else if(s.operator===">="&&!V(s.semver,String(h),r))return!1}if(i){if(p&&h.semver.prerelease&&h.semver.prerelease.length&&h.semver.major===p.major&&h.semver.minor===p.minor&&h.semver.patch===p.patch&&(p=!1),h.operator==="<"||h.operator==="<="){if(c=zr(i,h,r),c===h&&c!==i)return!1}else if(i.operator==="<="&&!V(i.semver,String(h),r))return!1}if(!h.operator&&(i||s)&&o!==0)return!1}return!(s&&f&&!i&&o!==0||i&&d&&!s&&o!==0||w||p)},Gr=(e,t,r)=>{if(!e)return t;let n=je(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},zr=(e,t,r)=>{if(!e)return t;let n=je(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};Xr.exports=ji});var T=m((pc,Br)=>{"use strict";var Ce=q(),Vr=U(),Ui=y(),_r=ye(),Fi=A(),Gi=wt(),zi=gt(),Xi=It(),Mi=Lt(),Vi=St(),_i=bt(),Bi=Tt(),Hi=Pt(),Wi=v(),Yi=Dt(),Ji=Ft(),Zi=ee(),Ki=Mt(),Qi=_t(),eo=G(),to=te(),ro=Oe(),no=ve(),so=re(),io=ne(),oo=Le(),ao=er(),co=z(),lo=L(),uo=M(),fo=mr(),po=wr(),ho=gr(),mo=Ir(),Eo=vr(),wo=oe(),$o=Ar(),go=kr(),yo=jr(),Ro=Dr(),Io=Mr();Br.exports={parse:Fi,valid:Gi,clean:zi,inc:Xi,diff:Mi,major:Vi,minor:_i,patch:Bi,prerelease:Hi,compare:Wi,rcompare:Yi,compareLoose:Ji,compareBuild:Zi,sort:Ki,rsort:Qi,gt:eo,lt:to,eq:ro,neq:no,gte:so,lte:io,cmp:oo,coerce:ao,Comparator:co,Range:lo,satisfies:uo,toComparators:fo,maxSatisfying:po,minSatisfying:ho,minVersion:mo,validRange:Eo,outside:wo,gtr:$o,ltr:go,intersects:yo,simplifyRange:Ro,subset:Io,SemVer:Ui,re:Ce.re,src:Ce.src,tokens:Ce.t,SEMVER_SPEC_VERSION:Vr.SEMVER_SPEC_VERSION,RELEASE_TYPES:Vr.RELEASE_TYPES,compareIdentifiers:_r.compareIdentifiers,rcompareIdentifiers:_r.rcompareIdentifiers}});var we=new TextDecoder;function W(e){let t=e.indexOf("@",e.startsWith("@")?1:0);return t<0?{name:e,version:""}:{name:e.slice(0,t),version:e.slice(t+1)}}async function tt(e,t){let r=String(t??"").split(/\s+/).filter(i=>i.startsWith("sha512-")).map(i=>i.split("?")[0]);if(r.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let n=new Uint8Array(await crypto.subtle.digest("SHA-512",e)),s="sha512-"+btoa(Array.from(n,i=>String.fromCharCode(i)).join(""));if(!r.includes(s))throw new Error(`Integrity check failed: expected ${r[0]}, got ${s}`);return s}async function rt(e,t=268435456){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],s=0;for(let i=await r.read();!i.done;i=await r.read()){if(s+=i.value.length,s>t)throw await r.cancel(),new Error(`The tarball unpacks to more than ${t} bytes`);n.push(i.value)}return new Uint8Array(await new Blob(n).arrayBuffer())}function D(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return we.decode(s<0?n:n.subarray(0,s))}function nt(e,t,r){if(e[t]&128)return e.subarray(t+1,t+r).reduce((s,i)=>s*256+i,e[t]&127);let n=D(e,t,r).trim();if(!/^[0-7]*$/.test(n))throw new Error("Corrupt tar header");return n===""?0:parseInt(n,8)}function In(e){let t=0;for(let r=0;r<512;++r)t+=r>=148&&r<156?32:e[r];if(nt(e,148,8)!==t)throw new Error("Corrupt tar header checksum")}function On(e){let t={},r=0;for(;r0)||r+s>e.length)throw new Error("Corrupt pax header");let i=we.decode(e.subarray(n+1,r+s-1)),o=i.indexOf("=");t[i.slice(0,o)]=i.slice(o+1),r+=s}return t}function vn(e,t){let r=e.subarray(t,t+512);In(r);let n=nt(r,124,12),s=t+512;if(s+n>e.length)throw new Error("Truncated tar archive");return{header:r,type:r[156]===0?"0":String.fromCharCode(r[156]),data:e.subarray(s,s+n),next:s+Math.ceil(n/512)*512}}function Ln(e,t){return t+512>e.length||e.subarray(t,t+512).every(r=>r===0)}function xn(e){let t=D(e,0,100),r=D(e,257,5)==="ustar"?D(e,345,155):"";return r?`${r}/${t}`:t}var et={x:(e,t)=>({...e,pax:On(t).path}),L:(e,t)=>({...e,long:D(t,0,t.length)}),g:e=>e};function st(e){let t=[],r={};for(let n=0;!Ln(e,n);){let{header:s,type:i,data:o,next:a}=vn(e,n);if(n=a,Object.hasOwn(et,i)){r=et[i](r,o);continue}(i==="0"||i==="7")&&t.push({path:r.pax??r.long??xn(s),bytes:o}),r={}}return t}var le=P(T(),1);var S=(e,t,...r)=>e.cppFunction(`webfront.developer.${t}`)(...r);async function ae(e,t){let r=[],n=0;for(;;){let s=await S(e,"read",t,n);if(r.push(s),n+=s.length,s.length<262144)break;if(n>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(r).arrayBuffer())}async function De(e,{id:t,path:r,bytes:n},s){for(let i=0;i{}),a}}async function Oo(e,t){let r=[],n=0;for(;;){let{done:s,value:i}=await e.read();if(s)return r;if(n+=i.length,n>t)throw new Error("Compressed download exceeds its byte limit");r.push(i)}}async function vo(e,t){try{return await Oo(e,t)}catch(r){throw await e.cancel().catch(()=>{}),r}finally{e.releaseLock()}}async function Hr(e,t=64*1024*1024){if(!e.ok)throw new Error(`Download: HTTP ${e.status}`);if(Number(e.headers.get("content-length"))>t)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await vo(e.body.getReader(),t)).arrayBuffer())}var Lo=/[\\\0:*?"<>|]/,xo=e=>e.split("/").some(t=>!t||t==="."||t==="..");function So(e){return typeof e!="string"||!e||Lo.test(e)?!0:xo(e)}function k(e){if(So(e))throw new Error(`Unsafe package path: ${e}`);return e}var No=new TextDecoder,bo=["preinstall","install","postinstall"];async function Wr(e){let t=new Map;for(let r of st(await rt(e))){if(!r.path.startsWith("package/"))throw new Error("Invalid npm tarball root");let n=k(r.path.slice(8));if(t.has(n))throw new Error(`Duplicate package path: ${n}`);t.set(n,r.bytes)}return t}var Ao=e=>bo.some(t=>e.scripts?.[t]),To=e=>e.has("binding.gyp")||[...e.keys()].some(t=>t.endsWith(".node"));function ko(e,t){return Ao(e)||e.gypfile?!0:To(t)}function Yr(e,t,r){let n=JSON.parse(No.decode(e.get("package.json")));if(n.name!==t||n.version!==r)throw new Error("npm archive identity mismatch");if(ko(n,e))throw new Error(`${t} needs an unsupported install script or native module`);return n}var Ue=e=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(e),ue=(e,t)=>`${e.replace("/","+")}@${t}`,Fe=(e,t,r)=>`${ue(e,t)}-${r.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function Po(e,t,{fetchImpl:r,signal:n}){let s=await r(new URL(e.replace("/","%2f"),t),{signal:n});if(!s.ok)throw new Error(`Registry metadata for ${e}: HTTP ${s.status}`);return s.json()}function qo(e,t){let r=e["dist-tags"]?.[t];return r||(le.default.valid(t)?t:le.default.maxSatisfying(Object.keys(e.versions??{}),t))}function jo(e,t,r){let n=r||"latest",s=qo(e,n),i=e.versions?.[s];if(!i||!le.default.valid(s))throw new Error(`Cannot resolve ${t}@${n}`);return{version:s,manifest:i}}async function Co(e,t,r,{fetchImpl:n,signal:s}){let i=new URL(t.dist?.tarball,r);if(i.protocol!=="https:"&&i.origin!==r.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let o=await n(i,{signal:s});if(!o.ok)throw new Error(`Package download for ${e}: HTTP ${o.status}`);let a=await Hr(o);return{bytes:a,integrity:await tt(a,t.dist.integrity)}}function Do(e){let t=new URL(e,globalThis.location?.href);return t.pathname.endsWith("/")||(t.pathname+="/"),t}async function j(e,t,{registry:r,fetchImpl:n=fetch,signal:s}){if(!Ue(e))throw new Error(`Unsupported npm package name: ${e}`);let i=Do(r),o={fetchImpl:n,signal:s},{version:a,manifest:c}=jo(await Po(e,i,o),e,t),{bytes:f,integrity:d}=await Co(e,c,i,o),p=await Wr(f),w=Yr(p,e,a);return{id:ue(e,a),key:Fe(e,a,d),manifest:w,integrity:d,files:p}}var fe=P(T(),1);function Uo(e,t,r){let n=e?.roots?.[t];return n?.requested===r&&e.packages[n.id]?e.packages[n.id]:fe.default.validRange(r)?Object.values(e?.packages??{}).filter(i=>i.name===t&&fe.default.satisfies(i.version,r)).sort((i,o)=>fe.default.rcompare(i.version,o.version))[0]??null:null}function Jr({registry:e="https://registry.npmjs.org/",fetchImpl:t=fetch,signal:r,download:n=j,previous:s}){let i=new Map;return async(o,a)=>{let c=`${o}@${a}`;if(i.has(c))return i.get(c);let f=Uo(s,o,a),d=await n(o,f?.version??a,{registry:e,fetchImpl:t,signal:r});if(f&&d.integrity!==f.integrity)throw new Error(`${d.id} no longer matches the integrity recorded in the lock`);return i.set(c,d),d}}var Zr=P(T(),1),Kr=(e,t,r)=>new Error(`${e.name}@${e.version} requires peer ${t}@${r}; install a compatible root explicitly`);function Fo(e,t,r){if(e.manifest.peerDependenciesMeta?.[t]?.optional)return null;throw Kr(e,t,r)}function Go(e,[t,r],{nodes:n,roots:s}){let i=s[t]?.id??e.dependencies[t];if(!i)return Fo(e,t,r);if(!Zr.default.satisfies(n[i].version,r))throw Kr(e,t,r);return i}function zo(e,t){for(let r of Object.entries(e.manifest.peerDependencies??{})){let n=Go(e,r,t);n&&(e.dependencies[r[0]]=n)}}function Qr(e,t){for(let r of Object.values(e))zo(r,{nodes:e,roots:t})}var en=P(T(),1);function Xo(e,t){return!Ue(t.name)||!en.default.valid(t.version)?!1:e===ue(t.name,t.version)}function Mo(e){return e.integrity?.startsWith("sha512-")?e.key===Fe(e.name,e.version,e.integrity):!1}function Vo(e,t,r){if(!Xo(t,r)||!Mo(r))throw new Error("Invalid locked package");for(let n of r.files)k(n);if(Object.values(r.dependencies).some(n=>!e.packages[n]))throw new Error("Dangling locked dependency")}function _o(e){return e?.format!==1?!1:!!e.roots&&!!e.packages}function Ge(e){if(!_o(e))throw new Error("Unsupported package lock");for(let[t,r]of Object.entries(e.packages))Vo(e,t,r);if(Object.values(e.roots).some(t=>!e.packages[t.id]))throw new Error("Dangling locked root");return e}function Bo(e,t,r){if(Object.keys(e.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let n of r.files.values())e.total+=n.length;if(e.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");e.nodes[r.id]={name:t,version:r.manifest.version,integrity:r.integrity,key:r.key,manifest:r.manifest,files:[...r.files.keys()].sort(),dependencies:{}},e.downloads.set(r.id,r.files)}async function Ho(e,t){let r={};for(let n of e){let{name:s,version:i}=W(n);r[s]={requested:i||"latest",id:await t(s,i||"latest")}}return r}async function tn(e,t={}){let r=Jr(t),n={nodes:{},downloads:new Map,total:0},s=async(o,a)=>{t.signal?.throwIfAborted();let c=await r(o,a);if(n.nodes[c.id])return c.id;Bo(n,o,c);for(let[f,d]of Object.entries(c.manifest.dependencies??{}).sort())n.nodes[c.id].dependencies[f]=await s(f,d);return c.id},i=await Ho(e,s);return Qr(n.nodes,i),{lock:{format:1,registry:t.registry??"https://registry.npmjs.org/",roots:i,packages:n.nodes},downloads:n.downloads}}function ze(e){return!e||typeof e!="object"?!1:!Array.isArray(e)}var N="webfront.project.json",_=1,Xe=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Wo=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Yo=/^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/,rn=/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/,Me=/^[A-Za-z_][A-Za-z0-9_]*$/,nn=["format","name","version","dependencies","registry","scripts","entries","providers","test","permissions"],Jo=["files","publish","fetch"],g=e=>{throw new Error(`${N}: ${e}`)};function b(e,t){return ze(e)||g(`${t} must be an object`),e}function Ve(e,t,r){for(let n of Object.keys(e))t.includes(n)||g(`unknown key "${n}" in ${r}`)}function pe(e,t){typeof e!="string"&&g(`${t} must be a project path`);try{return k(e)}catch{return g(`${t} is not a safe project-relative path: ${e}`)}}function sn(e,t){return(!Array.isArray(e)||e.length>256)&&g(`${t} must be an array of at most 256 paths`),e.map((r,n)=>pe(r,`${t}[${n}]`))}function Zo(e){let t=b(e,"dependencies");for(let[r,n]of Object.entries(t))Xe.test(r)||g(`invalid npm package name "${r}"`),(typeof n!="string"||!Yo.test(n)||n!==n.trim())&&g(`invalid version range for "${r}"`);return t}function Ko(e){if(typeof e!="string"&&g("registry must be a URL"),e.startsWith("/")&&!e.startsWith("//"))return e;let t;try{t=new URL(e)}catch{return g("registry must be an https URL or an absolute path")}return t.protocol!=="https:"&&g("registry must use https"),e}function Qo(e){let t=b(e,"scripts");for(let[r,n]of Object.entries(t))(!rn.test(r)||typeof n!="string"||!n||n.length>1024)&&g(`invalid script "${r}"`);return t}function ea(e){let t=b(e,"entries");for(let[r,n]of Object.entries(t))rn.test(r)||g(`invalid entry name "${r}"`),pe(n,`entries.${r}`);return t}function ta(e,t){let r=b(e,"providers");for(let[n,s]of Object.entries(r))Me.test(n)||g(`invalid provider name "${n}"`),b(s,`providers.${n}`),Ve(s,["entry","output"],`providers.${n}`),typeof s.entry!="string"&&g(`providers.${n}.entry must name an entry or a path`),Object.hasOwn(t,s.entry)||pe(s.entry,`providers.${n}.entry`),pe(s.output,`providers.${n}.output`).endsWith(".hpp")||g(`providers.${n}.output must be a .hpp file`);return r}function ra(e){let t=b(e,"test");return Ve(t,["specs"],"test"),t.specs!==void 0&&sn(t.specs,"test.specs"),t}function na(e,t){let r;try{r=new URL(e)}catch{return g(`${t} must be an https origin`)}return(r.protocol!=="https:"||r.origin!==e)&&g(`${t} must be an https origin without a path`),e}function sa(e){let t=b(e,"permissions");for(let r of Object.keys(t))Jo.includes(r)||g(`unknown permission "${r}"`);for(let r of["files","publish"])t[r]!==void 0&&sn(t[r],`permissions.${r}`);return t.fetch!==void 0&&((!Array.isArray(t.fetch)||t.fetch.length>64)&&g("permissions.fetch must be an array of origins"),t.fetch.forEach((r,n)=>na(r,`permissions.fetch[${n}]`))),t}function ia(e){(typeof e.name!="string"||!Xe.test(e.name))&&g("name must be a lower-case npm package name"),(typeof e.version!="string"||!Wo.test(e.version))&&g("version must be a semantic version")}function oa(e){e.format!==_&&(Number.isInteger(e.format)&&e.format>_&&g(`format ${e.format} is not supported by this environment (it reads format ${_}); update the environment`),g(`format must be ${_}`))}function B(e){b(e,"the manifest"),oa(e),Ve(e,nn,"the manifest"),ia(e);let t=e.entries===void 0?{}:ea(e.entries);return{...e,dependencies:e.dependencies===void 0?{}:Zo(e.dependencies),entries:t,providers:e.providers===void 0?{}:ta(e.providers,t),...e.registry===void 0?{}:{registry:Ko(e.registry)},...e.scripts===void 0?{}:{scripts:Qo(e.scripts)},...e.test===void 0?{}:{test:ra(e.test)},...e.permissions===void 0?{}:{permissions:sa(e.permissions)}}}function _e(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return g("not valid JSON")}return{source:t,manifest:B(t)}}function zc(e){return _e(e).manifest}function Be(e){let t={};for(let r of nn)e[r]!==void 0&&(t[r]=e[r]);return JSON.stringify(t,null,2)+` -`}function on(e){return{format:_,name:e,version:"0.1.0",dependencies:{}}}function an(e){let r=(String(e??"").split("/").filter(Boolean).pop()??"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/-+$/,"");return Xe.test(r)?r:"webfront-app"}async function he(e){let t=JSON.stringify(Object.entries(e).sort(([n],[s])=>ns?1:0)),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}var He=P(T(),1);var C="webfront-packages.lock.json",de=".webfront/developer/packages",aa=new TextDecoder,ca=new TextEncoder,un="No webfront.project.json: run wf init",me="The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again";async function cn(e,t){try{return await ae(e,t)}catch(r){if(r.message.includes("Cannot read project file:"))return null;throw r}}function la(e,t,r){return t?r===t.requested?!0:He.default.validRange(r)!==null&&He.default.satisfies(e.packages[t.id].version,r):!1}function ua(e,t){let r=Object.keys(t);return r.length===Object.keys(e.roots).length&&r.every(n=>la(e,e.roots[n],t[n]))}function fa(e,t,r){return e?t?t.manifestDigest===void 0?ua(t,e.dependencies)?"legacy":"desynchronized":t.manifestDigest===r?"consistent":"desynchronized":"unlocked":"no-manifest"}async function We(e){let t=await S(e,"state",`${N} -${C}`),r=await cn(e,N),n=await cn(e,C),{source:s,manifest:i}=r?_e(r):{source:null,manifest:null},o=n?Ge(JSON.parse(aa.decode(n))):null,a=i?await he(i.dependencies):null;return{manifest:i,source:s,lock:o,token:t,status:fa(i,o,a),digest:a}}var Bc=e=>e.status==="desynchronized"?`Warning: ${me}.\r -`:"";async function fn(e,t,r,{signal:n}={}){let s=[];try{for(let[i,o]of t){n?.throwIfAborted();let a=await S(e,"begin",i,!1);s.push(a),await De(e,{id:a,path:"output",bytes:o},n)}n?.throwIfAborted(),await S(e,"commitGroup",s.join(` -`),`${N} -${C}`,r.token)}catch(i){for(let o of s)await S(e,"abort",o).catch(()=>{});throw i}}function ln(e,t,r){let n=e?.entries??{};if(t!==void 0)return Object.hasOwn(n,t)?n[t]:t;if(Object.hasOwn(n,"main"))return n.main;let s=Object.keys(n);if(s.length===1)return n[s[0]];throw new Error(`Usage: ${r} (declare entries.main in ${N} to omit the entry)`)}function Hc(e,[t,r,n,...s]){if(t&&Object.hasOwn(e?.providers??{},t)&&r===void 0){let o=e.providers[t];return{entry:ln(e,o.entry),output:o.output,className:t}}if(!t||r!=="--output"||s.length||!n?.endsWith(".hpp"))throw new Error("wf embed requires or --output ");let i=n.split("/").pop().slice(0,-4);if(!Me.test(i))throw new Error(`wf embed: ${i} is not a C++ class name; name the output .hpp`);return{entry:ln(e,t),output:n,className:i}}var Ee=e=>ca.encode(e);var Ye=P(T(),1);var dn=e=>{let{name:t,version:r}=W(e);return[t,r||void 0]};function pa(e,t){let{version:r}=e.packages[t.id];return!(Ye.default.valid(t.requested)!==null)&&t.requested!=="latest"&&Ye.default.validRange(t.requested)!==null?t.requested:`^${r}`}async function el(e,[t,...r],{signal:n}={}){if(r.length)throw new Error("Usage: wf init [name]");let{lock:s}=await We(e),i=on(t??an(""));s&&(i.dependencies=Object.fromEntries(Object.entries(s.roots).map(([a,c])=>[a,pa(s,c)]))),B(i),await ce(e,N,new Map([["output",Ee(Be(i))]]),{directory:!1,replace:!1,signal:n});let o=s?` with the ${Object.keys(i.dependencies).length} dependencies of ${C}`:"";return`Created ${N}${o}. Add libraries with wf install .`}function ha(e,t){let r={...e.manifest.dependencies},n=new Set;for(let s of t){let[i,o]=dn(s);r[i]=o??"latest",o&&o!=="latest"&&n.add(i)}return B({...e.source,dependencies:r}),{dependencies:r,explicit:n}}function da(e,t){let r={...e.source,dependencies:t};return B(r),r}function ma({dependencies:e,explicit:t},r,n){let s={...e};for(let i of n){let o=dn(i)[0];t.has(o)||(s[o]=`^${r.packages[r.roots[o].id].version}`)}return s}async function Ea(e,t,r){let n=Object.entries(e).map(([o,a])=>`${o}@${a}`),{lock:s,downloads:i}=await tn(n,{registry:r.registry,signal:r.signal,fetchImpl:r.fetchImpl,previous:t,download:async(...o)=>(r.progress(`Resolving ${o[0]}@${o[1]}`),j(...o))});return{lock:s,downloads:i}}async function wa(e,t,r,{signal:n,progress:s}){for(let[i,o]of r)s(`Storing ${i}`),await ce(e,`${de}/${t.packages[i].key}`,o,{signal:n})}async function $a(e,t){try{return await ae(e,`${de}/${t.key}/package.json`),!0}catch{return!1}}async function ga(e,t,{signal:r,progress:n,fetchImpl:s}){let i=0;for(let[o,a]of Object.entries(t.packages)){if(r?.throwIfAborted(),await $a(e,a))continue;n(`Restoring ${o}`);let c=await j(a.name,a.version,{registry:t.registry,fetchImpl:s,signal:r});if(c.integrity!==a.integrity)throw new Error(`${o} no longer matches the integrity recorded in the lock`);await ce(e,`${de}/${a.key}`,c.files,{signal:r}),i++}return i}function ya(e){let t=e.includes("--update"),r=e.filter(n=>n!=="--update");if(r.some(n=>n.startsWith("-")))throw new Error("Usage: wf install [--update] [[@range] ...]");return{update:t,specs:r}}async function pn(e,t,{manifest:r,lock:n},s){let i=new Map([[C,Ee(JSON.stringify(n,null,2)+` -`)]]);r&&i.set(N,Ee(Be(r))),await fn(e,i,t,s)}var hn=async(e,t)=>({format:e.format,manifestDigest:await he(t),...e});async function tl(e,t,{registry:r,signal:n,progress:s=()=>{},fetchImpl:i=fetch}){let{update:o,specs:a}=ya(t),c=await We(e);if(!c.manifest)throw new Error(un);let f={registry:c.manifest.registry??r,signal:n,fetchImpl:i,progress:s};if(a.length&&o)throw new Error("Usage: wf install --update does not take packages");if(a.length&&c.status==="desynchronized")throw new Error(me);if(!a.length&&!o&&c.status==="desynchronized")throw new Error(me);let d=c.status==="consistent"||c.status==="legacy";if(!a.length&&!o&&d){let Ze=await ga(e,c.lock,{signal:n,progress:s,fetchImpl:f.fetchImpl});if(c.status==="consistent")return{lock:c.lock,restored:Ze};let Ke=await hn(c.lock,c.manifest.dependencies);return await pn(e,c,{manifest:null,lock:Ke},{signal:n}),{lock:Ke,restored:Ze}}let p=ha(c,a),w=d&&!o?c.lock:void 0,h=await Ea(p.dependencies,w,f),H=ma(p,h.lock,a);await wa(e,h.lock,h.downloads,{signal:n,progress:s});let Je=await hn(h.lock,H),mn=a.length?da(c,H):null;return await pn(e,c,{manifest:mn,lock:Je},{signal:n}),{lock:Je,restored:0}}export{he as dependenciesDigest,me as desynchronized,j as downloadPackage,Hc as embedTarget,Wo as exactVersion,Me as identifier,el as initProject,tl as install,We as loadProject,C as lockPath,ua as locksDependencies,_ as manifestFormat,an as manifestName,N as manifestPath,on as newManifest,un as noManifest,Xe as npmName,de as packageRoot,zc as parseManifest,fn as publishTogether,_e as readManifest,ln as resolveEntry,tn as resolvePackages,k as safePackagePath,Be as serializeManifest,Bc as syncNotice,Ee as textBytes,Ge as validateLock,B as validateManifest}; +var Nn=Object.create;var lt=Object.defineProperty;var Tn=Object.getOwnPropertyDescriptor;var An=Object.getOwnPropertyNames;var Pn=Object.getPrototypeOf,qn=Object.prototype.hasOwnProperty;var m=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var jn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of An(t))!qn.call(e,s)&&s!==r&<(e,s,{get:()=>t[s],enumerable:!(n=Tn(t,s))||n.enumerable});return e};var D=(e,t,r)=>(r=e!=null?Nn(Pn(e)):{},jn(t||!e||!e.__esModule?lt(r,"default",{value:e,enumerable:!0}):r,e));var F=m((Ha,mt)=>{"use strict";var Gn="2.0.0",Mn=Number.MAX_SAFE_INTEGER||9007199254740991,Xn=16,Vn=250,Bn=["major","premajor","minor","preminor","patch","prepatch","prerelease"];mt.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:Xn,MAX_SAFE_BUILD_LENGTH:Vn,MAX_SAFE_INTEGER:Mn,RELEASE_TYPES:Bn,SEMVER_SPEC_VERSION:Gn,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var G=m((Wa,wt)=>{"use strict";var _n=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};wt.exports=_n});var U=m((N,Et)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Oe,MAX_SAFE_BUILD_LENGTH:Hn,MAX_LENGTH:Wn}=F(),Yn=G();N=Et.exports={};var Jn=N.re=[],Zn=N.safeRe=[],u=N.src=[],Kn=N.safeSrc=[],f=N.t={},Qn=0,Ie="[a-zA-Z0-9-]",es=[["\\s",1],["\\d",Wn],[Ie,Hn]],ts=e=>{for(let[t,r]of es)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},w=(e,t,r)=>{let n=ts(t),s=Qn++;Yn(e,s,t),f[e]=s,u[s]=t,Kn[s]=n,Jn[s]=new RegExp(t,r?"g":void 0),Zn[s]=new RegExp(n,r?"g":void 0)};w("NUMERICIDENTIFIER","0|[1-9]\\d*");w("NUMERICIDENTIFIERLOOSE","\\d+");w("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Ie}*`);w("MAINVERSION",`(${u[f.NUMERICIDENTIFIER]})\\.(${u[f.NUMERICIDENTIFIER]})\\.(${u[f.NUMERICIDENTIFIER]})`);w("MAINVERSIONLOOSE",`(${u[f.NUMERICIDENTIFIERLOOSE]})\\.(${u[f.NUMERICIDENTIFIERLOOSE]})\\.(${u[f.NUMERICIDENTIFIERLOOSE]})`);w("PRERELEASEIDENTIFIER",`(?:${u[f.NONNUMERICIDENTIFIER]}|${u[f.NUMERICIDENTIFIER]})`);w("PRERELEASEIDENTIFIERLOOSE",`(?:${u[f.NONNUMERICIDENTIFIER]}|${u[f.NUMERICIDENTIFIERLOOSE]})`);w("PRERELEASE",`(?:-(${u[f.PRERELEASEIDENTIFIER]}(?:\\.${u[f.PRERELEASEIDENTIFIER]})*))`);w("PRERELEASELOOSE",`(?:-?(${u[f.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[f.PRERELEASEIDENTIFIERLOOSE]})*))`);w("BUILDIDENTIFIER",`${Ie}+`);w("BUILD",`(?:\\+(${u[f.BUILDIDENTIFIER]}(?:\\.${u[f.BUILDIDENTIFIER]})*))`);w("FULLPLAIN",`v?${u[f.MAINVERSION]}${u[f.PRERELEASE]}?${u[f.BUILD]}?`);w("FULL",`^${u[f.FULLPLAIN]}$`);w("LOOSEPLAIN",`[v=\\s]*${u[f.MAINVERSIONLOOSE]}${u[f.PRERELEASELOOSE]}?${u[f.BUILD]}?`);w("LOOSE",`^${u[f.LOOSEPLAIN]}$`);w("GTLT","((?:<|>)?=?)");w("XRANGEIDENTIFIERLOOSE",`${u[f.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);w("XRANGEIDENTIFIER",`${u[f.NUMERICIDENTIFIER]}|x|X|\\*`);w("XRANGEPLAIN",`[v=\\s]*(${u[f.XRANGEIDENTIFIER]})(?:\\.(${u[f.XRANGEIDENTIFIER]})(?:\\.(${u[f.XRANGEIDENTIFIER]})(?:${u[f.PRERELEASE]})?${u[f.BUILD]}?)?)?`);w("XRANGEPLAINLOOSE",`[v=\\s]*(${u[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[f.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[f.XRANGEIDENTIFIERLOOSE]})(?:${u[f.PRERELEASELOOSE]})?${u[f.BUILD]}?)?)?`);w("XRANGE",`^${u[f.GTLT]}\\s*${u[f.XRANGEPLAIN]}$`);w("XRANGELOOSE",`^${u[f.GTLT]}\\s*${u[f.XRANGEPLAINLOOSE]}$`);w("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Oe}})(?:\\.(\\d{1,${Oe}}))?(?:\\.(\\d{1,${Oe}}))?`);w("COERCE",`${u[f.COERCEPLAIN]}(?:$|[^\\d])`);w("COERCEFULL",u[f.COERCEPLAIN]+`(?:${u[f.PRERELEASE]})?(?:${u[f.BUILD]})?(?:$|[^\\d])`);w("COERCERTL",u[f.COERCE],!0);w("COERCERTLFULL",u[f.COERCEFULL],!0);w("LONETILDE","(?:~>?)");w("TILDETRIM",`(\\s*)${u[f.LONETILDE]}\\s+`,!0);N.tildeTrimReplace="$1~";w("TILDE",`^${u[f.LONETILDE]}${u[f.XRANGEPLAIN]}$`);w("TILDELOOSE",`^${u[f.LONETILDE]}${u[f.XRANGEPLAINLOOSE]}$`);w("LONECARET","(?:\\^)");w("CARETTRIM",`(\\s*)${u[f.LONECARET]}\\s+`,!0);N.caretTrimReplace="$1^";w("CARET",`^${u[f.LONECARET]}${u[f.XRANGEPLAIN]}$`);w("CARETLOOSE",`^${u[f.LONECARET]}${u[f.XRANGEPLAINLOOSE]}$`);w("COMPARATORLOOSE",`^${u[f.GTLT]}\\s*(${u[f.LOOSEPLAIN]})$|^$`);w("COMPARATOR",`^${u[f.GTLT]}\\s*(${u[f.FULLPLAIN]})$|^$`);w("COMPARATORTRIM",`(\\s*)${u[f.GTLT]}\\s*(${u[f.LOOSEPLAIN]}|${u[f.XRANGEPLAIN]})`,!0);N.comparatorTrimReplace="$1$2$3";w("HYPHENRANGE",`^\\s*(${u[f.XRANGEPLAIN]})\\s+-\\s+(${u[f.XRANGEPLAIN]})\\s*$`);w("HYPHENRANGELOOSE",`^\\s*(${u[f.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[f.XRANGEPLAINLOOSE]})\\s*$`);w("STAR","(<|>)?=?\\s*\\*");w("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");w("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Q=m((Ya,gt)=>{"use strict";var rs=Object.freeze({loose:!0}),ns=Object.freeze({}),ss=e=>e?typeof e!="object"?rs:e:ns;gt.exports=ss});var xe=m((Ja,Rt)=>{"use strict";var $t=/^[0-9]+$/,yt=(e,t)=>{if(typeof e=="number"&&typeof t=="number")return e===t?0:eyt(t,e);Rt.exports={compareIdentifiers:yt,rcompareIdentifiers:os}});var y=m((Za,It)=>{"use strict";var ee=G(),{MAX_LENGTH:Ot,MAX_SAFE_INTEGER:te}=F(),{safeRe:re,t:ne}=U(),is=Q(),{compareIdentifiers:ve}=xe(),be=class e{constructor(t,r){if(r=is(r),t instanceof e){if(t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease)return t;t=t.version}else if(typeof t!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>Ot)throw new TypeError(`version is longer than ${Ot} characters`);ee("SemVer",t,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=t.trim().match(r.loose?re[ne.LOOSE]:re[ne.FULL]);if(!n)throw new TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>te||this.major<0)throw new TypeError("Invalid major version");if(this.minor>te||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>te||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let o=+s;if(o>=0&&ot.major?1:this.minort.minor?1:this.patcht.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=t.prerelease[r];if(ee("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ve(n,s)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let n=this.build[r],s=t.build[r];if(ee("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return ve(n,s)}while(++r)}inc(t,r,n){if(t.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?re[ne.PRERELEASELOOSE]:re[ne.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(t){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let o=this.prerelease.length;for(;--o>=0;)typeof this.prerelease[o]=="number"&&(this.prerelease[o]++,o=-2);if(o===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let o=[r,s];n===!1&&(o=[r]),ve(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=o):this.prerelease=o}break}default:throw new Error(`invalid increment argument: ${t}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};It.exports=be});var A=m((Ka,vt)=>{"use strict";var xt=y(),as=(e,t,r=!1)=>{if(e instanceof xt)return e;try{return new xt(e,t)}catch(n){if(!r)return null;throw n}};vt.exports=as});var St=m((Qa,bt)=>{"use strict";var cs=A(),ls=(e,t)=>{let r=cs(e,t);return r?r.version:null};bt.exports=ls});var Lt=m((ec,kt)=>{"use strict";var us=A(),fs=(e,t)=>{let r=us(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};kt.exports=fs});var At=m((tc,Tt)=>{"use strict";var Nt=y(),ps=(e,t,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Nt(e instanceof Nt?e.version:e,r).inc(t,n,s).version}catch{return null}};Tt.exports=ps});var jt=m((rc,qt)=>{"use strict";var Pt=A(),hs=(e,t)=>{let r=Pt(e,null,!0),n=Pt(t,null,!0),s=r.compare(n);if(s===0)return null;let o=s>0,i=o?r:n,a=o?n:r,c=!!i.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(i)===0)return a.minor&&!a.patch?"minor":"patch"}let h=c?"pre":"";return r.major!==n.major?h+"major":r.minor!==n.minor?h+"minor":r.patch!==n.patch?h+"patch":"prerelease"};qt.exports=hs});var Dt=m((nc,Ct)=>{"use strict";var ds=y(),ms=(e,t)=>new ds(e,t).major;Ct.exports=ms});var zt=m((sc,Ut)=>{"use strict";var ws=y(),Es=(e,t)=>new ws(e,t).minor;Ut.exports=Es});var Gt=m((oc,Ft)=>{"use strict";var gs=y(),$s=(e,t)=>new gs(e,t).patch;Ft.exports=$s});var Xt=m((ic,Mt)=>{"use strict";var ys=A(),Rs=(e,t)=>{let r=ys(e,t);return r&&r.prerelease.length?r.prerelease:null};Mt.exports=Rs});var x=m((ac,Bt)=>{"use strict";var Vt=y(),Os=(e,t,r)=>new Vt(e,r).compare(new Vt(t,r));Bt.exports=Os});var Ht=m((cc,_t)=>{"use strict";var Is=x(),xs=(e,t,r)=>Is(t,e,r);_t.exports=xs});var Yt=m((lc,Wt)=>{"use strict";var vs=x(),bs=(e,t)=>vs(e,t,!0);Wt.exports=bs});var se=m((uc,Zt)=>{"use strict";var Jt=y(),Ss=(e,t,r)=>{let n=new Jt(e,r),s=new Jt(t,r);return n.compare(s)||n.compareBuild(s)};Zt.exports=Ss});var Qt=m((fc,Kt)=>{"use strict";var ks=se(),Ls=(e,t)=>e.sort((r,n)=>ks(r,n,t));Kt.exports=Ls});var tr=m((pc,er)=>{"use strict";var Ns=se(),Ts=(e,t)=>e.sort((r,n)=>Ns(n,r,t));er.exports=Ts});var M=m((hc,rr)=>{"use strict";var As=x(),Ps=(e,t,r)=>As(e,t,r)>0;rr.exports=Ps});var oe=m((dc,nr)=>{"use strict";var qs=x(),js=(e,t,r)=>qs(e,t,r)<0;nr.exports=js});var Se=m((mc,sr)=>{"use strict";var Cs=x(),Ds=(e,t,r)=>Cs(e,t,r)===0;sr.exports=Ds});var ke=m((wc,or)=>{"use strict";var Us=x(),zs=(e,t,r)=>Us(e,t,r)!==0;or.exports=zs});var ie=m((Ec,ir)=>{"use strict";var Fs=x(),Gs=(e,t,r)=>Fs(e,t,r)>=0;ir.exports=Gs});var ae=m((gc,ar)=>{"use strict";var Ms=x(),Xs=(e,t,r)=>Ms(e,t,r)<=0;ar.exports=Xs});var Le=m(($c,cr)=>{"use strict";var Vs=Se(),Bs=ke(),_s=M(),Hs=ie(),Ws=oe(),Ys=ae(),Js=(e,t,r,n)=>{switch(t){case"===":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e===r;case"!==":return typeof e=="object"&&(e=e.version),typeof r=="object"&&(r=r.version),e!==r;case"":case"=":case"==":return Vs(e,r,n);case"!=":return Bs(e,r,n);case">":return _s(e,r,n);case">=":return Hs(e,r,n);case"<":return Ws(e,r,n);case"<=":return Ys(e,r,n);default:throw new TypeError(`Invalid operator: ${t}`)}};cr.exports=Js});var ur=m((yc,lr)=>{"use strict";var Zs=y(),Ks=A(),{safeRe:ce,t:le}=U(),Qs=(e,t)=>{if(e instanceof Zs)return e;if(typeof e=="number"&&(e=String(e)),typeof e!="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?ce[le.COERCEFULL]:ce[le.COERCE]);else{let c=t.includePrerelease?ce[le.COERCERTLFULL]:ce[le.COERCERTL],l;for(;(l=c.exec(e))&&(!r||r.index+r[0].length!==e.length);)(!r||l.index+l[0].length!==r.index+r[0].length)&&(r=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",o=r[4]||"0",i=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return Ks(`${n}.${s}.${o}${i}${a}`,t)};lr.exports=Qs});var pr=m((Rc,fr)=>{"use strict";var Ne=class{constructor(){this.max=1e3,this.map=new Map}get(t){let r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(t,r)}return this}};fr.exports=Ne});var v=m((Oc,wr)=>{"use strict";var eo=/\s+/g,Te=class e{constructor(t,r){if(r=ro(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof Ae)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(eo," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!dr(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&lo(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let t=0;t0&&(this.formatted+="||");let r=this.set[t];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(t){let n=((this.options.includePrerelease&&ao)|(this.options.loose&&co))+":"+t,s=hr.get(n);if(s)return s;let o=this.options.loose,i=o?O[R.HYPHENRANGELOOSE]:O[R.HYPHENRANGE];t=t.replace(i,yo(this.options.includePrerelease)),g("hyphen replace",t),t=t.replace(O[R.COMPARATORTRIM],so),g("comparator trim",t),t=t.replace(O[R.TILDETRIM],oo),g("tilde trim",t),t=t.replace(O[R.CARETTRIM],io),g("caret trim",t);let a=t.split(" ").map(p=>uo(p,this.options)).join(" ").split(/\s+/).map(p=>$o(p,this.options));o&&(a=a.filter(p=>(g("loose invalid filter",p,this.options),!!p.match(O[R.COMPARATORLOOSE])))),g("range list",a);let c=new Map,l=a.map(p=>new Ae(p,this.options));for(let p of l){if(dr(p))return[p];c.set(p.value,p)}c.size>1&&c.has("")&&c.delete("");let h=[...c.values()];return hr.set(n,h),h}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Range is required");return this.set.some(n=>mr(n,r)&&t.set.some(s=>mr(s,r)&&n.every(o=>s.every(i=>o.intersects(i,r)))))}test(t){if(!t)return!1;if(typeof t=="string")try{t=new no(t,this.options)}catch{return!1}for(let r=0;re.value==="<0.0.0-0",lo=e=>e.value==="",mr=(e,t)=>{let r=!0,n=e.slice(),s=n.pop();for(;r&&n.length;)r=n.every(o=>s.intersects(o,t)),s=n.pop();return r},uo=(e,t)=>(e=e.replace(O[R.BUILD],""),g("comp",e,t),e=ho(e,t),g("caret",e),e=fo(e,t),g("tildes",e),e=wo(e,t),g("xrange",e),e=go(e,t),g("stars",e),e),I=e=>!e||e.toLowerCase()==="x"||e==="*",fo=(e,t)=>e.trim().split(/\s+/).map(r=>po(r,t)).join(" "),po=(e,t)=>{let r=t.loose?O[R.TILDELOOSE]:O[R.TILDE];return e.replace(r,(n,s,o,i,a)=>{g("tilde",e,n,s,o,i,a);let c;return I(s)?c="":I(o)?c=`>=${s}.0.0 <${+s+1}.0.0-0`:I(i)?c=`>=${s}.${o}.0 <${s}.${+o+1}.0-0`:a?(g("replaceTilde pr",a),c=`>=${s}.${o}.${i}-${a} <${s}.${+o+1}.0-0`):c=`>=${s}.${o}.${i} <${s}.${+o+1}.0-0`,g("tilde return",c),c})},ho=(e,t)=>e.trim().split(/\s+/).map(r=>mo(r,t)).join(" "),mo=(e,t)=>{g("caret",e,t);let r=t.loose?O[R.CARETLOOSE]:O[R.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(s,o,i,a,c)=>{g("caret",e,s,o,i,a,c);let l;return I(o)?l="":I(i)?l=`>=${o}.0.0${n} <${+o+1}.0.0-0`:I(a)?o==="0"?l=`>=${o}.${i}.0${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.0${n} <${+o+1}.0.0-0`:c?(g("replaceCaret pr",c),o==="0"?i==="0"?l=`>=${o}.${i}.${a}-${c} <${o}.${i}.${+a+1}-0`:l=`>=${o}.${i}.${a}-${c} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${a}-${c} <${+o+1}.0.0-0`):(g("no pr"),o==="0"?i==="0"?l=`>=${o}.${i}.${a}${n} <${o}.${i}.${+a+1}-0`:l=`>=${o}.${i}.${a}${n} <${o}.${+i+1}.0-0`:l=`>=${o}.${i}.${a} <${+o+1}.0.0-0`),g("caret return",l),l})},wo=(e,t)=>(g("replaceXRanges",e,t),e.split(/\s+/).map(r=>Eo(r,t)).join(" ")),Eo=(e,t)=>{e=e.trim();let r=t.loose?O[R.XRANGELOOSE]:O[R.XRANGE];return e.replace(r,(n,s,o,i,a,c)=>{g("xRange",e,n,s,o,i,a,c);let l=I(o),h=l||I(i),p=h||I(a),E=p;return s==="="&&E&&(s=""),c=t.includePrerelease?"-0":"",l?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&E?(h&&(i=0),a=0,s===">"?(s=">=",h?(o=+o+1,i=0,a=0):(i=+i+1,a=0)):s==="<="&&(s="<",h?o=+o+1:i=+i+1),s==="<"&&(c="-0"),n=`${s+o}.${i}.${a}${c}`):h?n=`>=${o}.0.0${c} <${+o+1}.0.0-0`:p&&(n=`>=${o}.${i}.0${c} <${o}.${+i+1}.0-0`),g("xRange return",n),n})},go=(e,t)=>(g("replaceStars",e,t),e.trim().replace(O[R.STAR],"")),$o=(e,t)=>(g("replaceGTE0",e,t),e.trim().replace(O[t.includePrerelease?R.GTE0PRE:R.GTE0],"")),yo=e=>(t,r,n,s,o,i,a,c,l,h,p,E)=>(I(n)?r="":I(s)?r=`>=${n}.0.0${e?"-0":""}`:I(o)?r=`>=${n}.${s}.0${e?"-0":""}`:i?r=`>=${r}`:r=`>=${r}${e?"-0":""}`,I(l)?c="":I(h)?c=`<${+l+1}.0.0-0`:I(p)?c=`<${l}.${+h+1}.0-0`:E?c=`<=${l}.${h}.${p}-${E}`:e?c=`<${l}.${h}.${+p+1}-0`:c=`<=${c}`,`${r} ${c}`.trim()),Ro=(e,t,r)=>{for(let n=0;n0){let s=e[n].semver;if(s.major===t.major&&s.minor===t.minor&&s.patch===t.patch)return!0}return!1}return!0}});var X=m((Ic,Or)=>{"use strict";var V=Symbol("SemVer ANY"),je=class e{static get ANY(){return V}constructor(t,r){if(r=Er(r),t instanceof e){if(t.loose===!!r.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(" "),qe("comparator",t,r),this.options=r,this.loose=!!r.loose,this.parse(t),this.semver===V?this.value="":this.value=this.operator+this.semver.version,qe("comp",this)}parse(t){let r=this.options.loose?gr[$r.COMPARATORLOOSE]:gr[$r.COMPARATOR],n=t.match(r);if(!n)throw new TypeError(`Invalid comparator: ${t}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new yr(n[2],this.options.loose):this.semver=V}toString(){return this.value}test(t){if(qe("Comparator.test",t,this.options.loose),this.semver===V||t===V)return!0;if(typeof t=="string")try{t=new yr(t,this.options)}catch{return!1}return Pe(t,this.operator,this.semver,this.options)}intersects(t,r){if(!(t instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Rr(t.value,r).test(this.value):t.operator===""?t.value===""?!0:new Rr(this.value,r).test(t.semver):(r=Er(r),r.includePrerelease&&(this.value==="<0.0.0-0"||t.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||t.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&t.operator.startsWith(">")||this.operator.startsWith("<")&&t.operator.startsWith("<")||this.semver.version===t.semver.version&&this.operator.includes("=")&&t.operator.includes("=")||Pe(this.semver,"<",t.semver,r)&&this.operator.startsWith(">")&&t.operator.startsWith("<")||Pe(this.semver,">",t.semver,r)&&this.operator.startsWith("<")&&t.operator.startsWith(">")))}};Or.exports=je;var Er=Q(),{safeRe:gr,t:$r}=U(),Pe=Le(),qe=G(),yr=y(),Rr=v()});var B=m((xc,Ir)=>{"use strict";var Oo=v(),Io=(e,t,r)=>{try{t=new Oo(t,r)}catch{return!1}return t.test(e)};Ir.exports=Io});var vr=m((vc,xr)=>{"use strict";var xo=v(),vo=(e,t)=>new xo(e,t).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" "));xr.exports=vo});var Sr=m((bc,br)=>{"use strict";var bo=y(),So=v(),ko=(e,t,r)=>{let n=null,s=null,o=null;try{o=new So(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===-1)&&(n=i,s=new bo(n,r))}),n};br.exports=ko});var Lr=m((Sc,kr)=>{"use strict";var Lo=y(),No=v(),To=(e,t,r)=>{let n=null,s=null,o=null;try{o=new No(t,r)}catch{return null}return e.forEach(i=>{o.test(i)&&(!n||s.compare(i)===1)&&(n=i,s=new Lo(n,r))}),n};kr.exports=To});var Ar=m((kc,Tr)=>{"use strict";var Ce=y(),Ao=v(),Nr=M(),Po=(e,t)=>{e=new Ao(e,t);let r=new Ce("0.0.0");if(e.test(r)||(r=new Ce("0.0.0-0"),e.test(r)))return r;r=null;for(let n=0;n{let a=new Ce(i.semver.version);switch(i.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!o||Nr(a,o))&&(o=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${i.operator}`)}}),o&&(!r||Nr(r,o))&&(r=o)}return r&&e.test(r)?r:null};Tr.exports=Po});var qr=m((Lc,Pr)=>{"use strict";var qo=v(),jo=(e,t)=>{try{return new qo(e,t).range||"*"}catch{return null}};Pr.exports=jo});var ue=m((Nc,Ur)=>{"use strict";var Co=y(),Dr=X(),{ANY:Do}=Dr,Uo=v(),zo=B(),jr=M(),Cr=oe(),Fo=ae(),Go=ie(),Mo=(e,t,r,n)=>{e=new Co(e,n),t=new Uo(t,n);let s,o,i,a,c;switch(r){case">":s=jr,o=Fo,i=Cr,a=">",c=">=";break;case"<":s=Cr,o=Go,i=jr,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(zo(e,t,n))return!1;for(let l=0;l{d.semver===Do&&(d=new Dr(">=0.0.0")),p=p||d,E=E||d,s(d.semver,p.semver,n)?p=d:i(d.semver,E.semver,n)&&(E=d)}),p.operator===a||p.operator===c||(!E.operator||E.operator===a)&&o(e,E.semver))return!1;if(E.operator===c&&i(e,E.semver))return!1}return!0};Ur.exports=Mo});var Fr=m((Tc,zr)=>{"use strict";var Xo=ue(),Vo=(e,t,r)=>Xo(e,t,">",r);zr.exports=Vo});var Mr=m((Ac,Gr)=>{"use strict";var Bo=ue(),_o=(e,t,r)=>Bo(e,t,"<",r);Gr.exports=_o});var Br=m((Pc,Vr)=>{"use strict";var Xr=v(),Ho=(e,t,r)=>(e=new Xr(e,r),t=new Xr(t,r),e.intersects(t,r));Vr.exports=Ho});var Hr=m((qc,_r)=>{"use strict";var Wo=B(),Yo=x();_r.exports=(e,t,r)=>{let n=[],s=null,o=null,i=e.sort((h,p)=>Yo(h,p,r));for(let h of i)Wo(h,t,r)?(o=h,s||(s=h)):(o&&n.push([s,o]),o=null,s=null);s&&n.push([s,null]);let a=[];for(let[h,p]of n)h===p?a.push(h):!p&&h===i[0]?a.push("*"):p?h===i[0]?a.push(`<=${p}`):a.push(`${h} - ${p}`):a.push(`>=${h}`);let c=a.join(" || "),l=typeof t.raw=="string"?t.raw:String(t);return c.length{"use strict";var Wr=v(),Ue=X(),{ANY:De}=Ue,_=B(),ze=x(),Jo=(e,t,r={})=>{if(e===t)return!0;e=new Wr(e,r),t=new Wr(t,r);let n=!1;e:for(let s of e.set){for(let o of t.set){let i=Ko(s,o,r);if(n=n||i!==null,i)continue e}if(n)return!1}return!0},Zo=[new Ue(">=0.0.0-0")],Yr=[new Ue(">=0.0.0")],Ko=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===De){if(t.length===1&&t[0].semver===De)return!0;r.includePrerelease?e=Zo:e=Yr}if(t.length===1&&t[0].semver===De){if(r.includePrerelease)return!0;t=Yr}let n=new Set,s,o;for(let d of e)d.operator===">"||d.operator===">="?s=Jr(s,d,r):d.operator==="<"||d.operator==="<="?o=Zr(o,d,r):n.add(d.semver);if(n.size>1)return null;let i;if(s&&o){if(i=ze(s.semver,o.semver,r),i>0)return null;if(i===0&&(s.operator!==">="||o.operator!=="<="))return null}for(let d of n){if(s&&!_(d,String(s),r)||o&&!_(d,String(o),r))return null;for(let C of t)if(!_(d,String(C),r))return!1;return!0}let a,c,l,h,p=o&&!r.includePrerelease&&o.semver.prerelease.length?o.semver:!1,E=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;p&&p.prerelease.length===1&&o.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let d of t){if(h=h||d.operator===">"||d.operator===">=",l=l||d.operator==="<"||d.operator==="<=",s){if(E&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===E.major&&d.semver.minor===E.minor&&d.semver.patch===E.patch&&(E=!1),d.operator===">"||d.operator===">="){if(a=Jr(s,d,r),a===d&&a!==s)return!1}else if(s.operator===">="&&!_(s.semver,String(d),r))return!1}if(o){if(p&&d.semver.prerelease&&d.semver.prerelease.length&&d.semver.major===p.major&&d.semver.minor===p.minor&&d.semver.patch===p.patch&&(p=!1),d.operator==="<"||d.operator==="<="){if(c=Zr(o,d,r),c===d&&c!==o)return!1}else if(o.operator==="<="&&!_(o.semver,String(d),r))return!1}if(!d.operator&&(o||s)&&i!==0)return!1}return!(s&&l&&!o&&i!==0||o&&h&&!s&&i!==0||E||p)},Jr=(e,t,r)=>{if(!e)return t;let n=ze(e.semver,t.semver,r);return n>0?e:n<0||t.operator===">"&&e.operator===">="?t:e},Zr=(e,t,r)=>{if(!e)return t;let n=ze(e.semver,t.semver,r);return n<0?e:n>0||t.operator==="<"&&e.operator==="<="?t:e};Kr.exports=Jo});var P=m((Cc,rn)=>{"use strict";var Fe=U(),en=F(),Qo=y(),tn=xe(),ei=A(),ti=St(),ri=Lt(),ni=At(),si=jt(),oi=Dt(),ii=zt(),ai=Gt(),ci=Xt(),li=x(),ui=Ht(),fi=Yt(),pi=se(),hi=Qt(),di=tr(),mi=M(),wi=oe(),Ei=Se(),gi=ke(),$i=ie(),yi=ae(),Ri=Le(),Oi=ur(),Ii=X(),xi=v(),vi=B(),bi=vr(),Si=Sr(),ki=Lr(),Li=Ar(),Ni=qr(),Ti=ue(),Ai=Fr(),Pi=Mr(),qi=Br(),ji=Hr(),Ci=Qr();rn.exports={parse:ei,valid:ti,clean:ri,inc:ni,diff:si,major:oi,minor:ii,patch:ai,prerelease:ci,compare:li,rcompare:ui,compareLoose:fi,compareBuild:pi,sort:hi,rsort:di,gt:mi,lt:wi,eq:Ei,neq:gi,gte:$i,lte:yi,cmp:Ri,coerce:Oi,Comparator:Ii,Range:xi,satisfies:vi,toComparators:bi,maxSatisfying:Si,minSatisfying:ki,minVersion:Li,validRange:Ni,outside:Ti,gtr:Ai,ltr:Pi,intersects:qi,simplifyRange:ji,subset:Ci,SemVer:Qo,re:Fe.re,src:Fe.src,tokens:Fe.t,SEMVER_SPEC_VERSION:en.SEMVER_SPEC_VERSION,RELEASE_TYPES:en.RELEASE_TYPES,compareIdentifiers:tn.compareIdentifiers,rcompareIdentifiers:tn.rcompareIdentifiers}});var Re=new TextDecoder;function K(e){let t=e.indexOf("@",e.startsWith("@")?1:0);return t<0?{name:e,version:""}:{name:e.slice(0,t),version:e.slice(t+1)}}async function ft(e,t){let r=String(t??"").split(/\s+/).filter(o=>o.startsWith("sha512-")).map(o=>o.split("?")[0]);if(r.length===0)throw new Error("The package has no SHA-512 integrity");if(!globalThis.crypto?.subtle)throw new Error("Integrity checks need a secure context (https or localhost)");let n=new Uint8Array(await crypto.subtle.digest("SHA-512",e)),s="sha512-"+btoa(Array.from(n,o=>String.fromCharCode(o)).join(""));if(!r.includes(s))throw new Error(`Integrity check failed: expected ${r[0]}, got ${s}`);return s}async function pt(e,t=268435456){let r=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip")).getReader(),n=[],s=0;for(let o=await r.read();!o.done;o=await r.read()){if(s+=o.value.length,s>t)throw await r.cancel(),new Error(`The tarball unpacks to more than ${t} bytes`);n.push(o.value)}return new Uint8Array(await new Blob(n).arrayBuffer())}function z(e,t,r){let n=e.subarray(t,t+r),s=n.indexOf(0);return Re.decode(s<0?n:n.subarray(0,s))}function ht(e,t,r){if(e[t]&128)return e.subarray(t+1,t+r).reduce((s,o)=>s*256+o,e[t]&127);let n=z(e,t,r).trim();if(!/^[0-7]*$/.test(n))throw new Error("Corrupt tar header");return n===""?0:parseInt(n,8)}function Cn(e){let t=0;for(let r=0;r<512;++r)t+=r>=148&&r<156?32:e[r];if(ht(e,148,8)!==t)throw new Error("Corrupt tar header checksum")}function Dn(e){let t={},r=0;for(;r0)||r+s>e.length)throw new Error("Corrupt pax header");let o=Re.decode(e.subarray(n+1,r+s-1)),i=o.indexOf("=");t[o.slice(0,i)]=o.slice(i+1),r+=s}return t}function Un(e,t){let r=e.subarray(t,t+512);Cn(r);let n=ht(r,124,12),s=t+512;if(s+n>e.length)throw new Error("Truncated tar archive");return{header:r,type:r[156]===0?"0":String.fromCharCode(r[156]),data:e.subarray(s,s+n),next:s+Math.ceil(n/512)*512}}function zn(e,t){return t+512>e.length||e.subarray(t,t+512).every(r=>r===0)}function Fn(e){let t=z(e,0,100),r=z(e,257,5)==="ustar"?z(e,345,155):"";return r?`${r}/${t}`:t}var ut={x:(e,t)=>({...e,pax:Dn(t).path}),L:(e,t)=>({...e,long:z(t,0,t.length)}),g:e=>e};function dt(e){let t=[],r={};for(let n=0;!zn(e,n);){let{header:s,type:o,data:i,next:a}=Un(e,n);if(n=a,Object.hasOwn(ut,o)){r=ut[o](r,i);continue}(o==="0"||o==="7")&&t.push({path:r.pax??r.long??Fn(s),bytes:i}),r={}}return t}var de=D(P(),1);var b=(e,t,...r)=>e.cppFunction(`webfront.developer.${t}`)(...r);async function fe(e,t){let r=[],n=0;for(;;){let s=await b(e,"read",t,n);if(r.push(s),n+=s.length,s.length<262144)break;if(n>256*1024*1024)throw new Error("Project file is too large")}return new Uint8Array(await new Blob(r).arrayBuffer())}async function Ge(e,{id:t,path:r,bytes:n},s){for(let o=0;o{}),a}}async function Di(e,t){let r=[],n=0;for(;;){let{done:s,value:o}=await e.read();if(s)return r;if(n+=o.length,n>t)throw new Error("Compressed download exceeds its byte limit");r.push(o)}}async function Ui(e,t){try{return await Di(e,t)}catch(r){throw await e.cancel().catch(()=>{}),r}finally{e.releaseLock()}}async function nn(e,t=64*1024*1024){if(!e.ok)throw new Error(`Download: HTTP ${e.status}`);if(Number(e.headers.get("content-length"))>t)throw new Error("Compressed download exceeds its byte limit");return new Uint8Array(await new Blob(await Ui(e.body.getReader(),t)).arrayBuffer())}var zi=/[\\\0:*?"<>|]/,Fi=e=>e.split("/").some(t=>!t||t==="."||t==="..");function Gi(e){return typeof e!="string"||!e||zi.test(e)?!0:Fi(e)}function q(e){if(Gi(e))throw new Error(`Unsafe package path: ${e}`);return e}var Mi=new TextDecoder,Xi=["preinstall","install","postinstall"];async function sn(e){let t=new Map;for(let r of dt(await pt(e))){if(!r.path.startsWith("package/"))throw new Error("Invalid npm tarball root");let n=q(r.path.slice(8));if(t.has(n))throw new Error(`Duplicate package path: ${n}`);t.set(n,r.bytes)}return t}var Vi=e=>Xi.some(t=>e.scripts?.[t]),Bi=e=>e.has("binding.gyp")||[...e.keys()].some(t=>t.endsWith(".node"));function _i(e,t){return Vi(e)||e.gypfile?!0:Bi(t)}function on(e,t,r){let n=JSON.parse(Mi.decode(e.get("package.json")));if(n.name!==t||n.version!==r)throw new Error("npm archive identity mismatch");if(_i(n,e))throw new Error(`${t} needs an unsupported install script or native module`);return n}function W(e){return!e||typeof e!="object"?!1:!Array.isArray(e)}var S="webfront.project.json",Y=1,Me=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/,Hi=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/,Wi=/^[0-9A-Za-z.+\-^~<>=*| ]{1,128}$/,an=/^[A-Za-z0-9][A-Za-z0-9:_.-]{0,63}$/,Xe=/^[A-Za-z_][A-Za-z0-9_]*$/,cn=["format","name","version","dependencies","registry","scripts","entries","providers","test","permissions"],Yi=["files","publish","fetch"],$=e=>{throw new Error(`${S}: ${e}`)};function T(e,t){return W(e)||$(`${t} must be an object`),e}function Ve(e,t,r){for(let n of Object.keys(e))t.includes(n)||$(`unknown key "${n}" in ${r}`)}function pe(e,t){typeof e!="string"&&$(`${t} must be a project path`);try{return q(e)}catch{return $(`${t} is not a safe project-relative path: ${e}`)}}function ln(e,t){return(!Array.isArray(e)||e.length>256)&&$(`${t} must be an array of at most 256 paths`),e.map((r,n)=>pe(r,`${t}[${n}]`))}function Ji(e){let t=T(e,"dependencies");for(let[r,n]of Object.entries(t))Me.test(r)||$(`invalid npm package name "${r}"`),(typeof n!="string"||!Wi.test(n)||n!==n.trim())&&$(`invalid version range for "${r}"`);return t}var Be=e=>e.startsWith("/")&&!e.startsWith("//")&&!e.includes("\\");function Zi(e){if(typeof e!="string"&&$("registry must be a URL"),Be(e))return e;let t;try{t=new URL(e)}catch{return $("registry must be an https URL or an absolute path")}return t.protocol!=="https:"&&$("registry must use https"),e}function Ki(e){let t=T(e,"scripts");for(let[r,n]of Object.entries(t))(!an.test(r)||typeof n!="string"||!n||n.length>1024)&&$(`invalid script "${r}"`);return t}function Qi(e){let t=T(e,"entries");for(let[r,n]of Object.entries(t))an.test(r)||$(`invalid entry name "${r}"`),pe(n,`entries.${r}`);return t}function ea(e,t){let r=T(e,"providers");for(let[n,s]of Object.entries(r))Xe.test(n)||$(`invalid provider name "${n}"`),T(s,`providers.${n}`),Ve(s,["entry","output"],`providers.${n}`),typeof s.entry!="string"&&$(`providers.${n}.entry must name an entry or a path`),Object.hasOwn(t,s.entry)||pe(s.entry,`providers.${n}.entry`),pe(s.output,`providers.${n}.output`).endsWith(".hpp")||$(`providers.${n}.output must be a .hpp file`);return r}function ta(e){let t=T(e,"test");return Ve(t,["specs"],"test"),t.specs!==void 0&&ln(t.specs,"test.specs"),t}function ra(e,t){let r;try{r=new URL(e)}catch{return $(`${t} must be an https origin`)}return(r.protocol!=="https:"||r.origin!==e)&&$(`${t} must be an https origin without a path`),e}function na(e){let t=T(e,"permissions");for(let r of Object.keys(t))Yi.includes(r)||$(`unknown permission "${r}"`);for(let r of["files","publish"])t[r]!==void 0&&ln(t[r],`permissions.${r}`);return t.fetch!==void 0&&((!Array.isArray(t.fetch)||t.fetch.length>64)&&$("permissions.fetch must be an array of origins"),t.fetch.forEach((r,n)=>ra(r,`permissions.fetch[${n}]`))),t}function sa(e){(typeof e.name!="string"||!Me.test(e.name))&&$("name must be a lower-case npm package name"),(typeof e.version!="string"||!Hi.test(e.version))&&$("version must be a semantic version")}function oa(e){e.format!==Y&&(Number.isInteger(e.format)&&e.format>Y&&$(`format ${e.format} is not supported by this environment (it reads format ${Y}); update the environment`),$(`format must be ${Y}`))}function J(e){T(e,"the manifest"),oa(e),Ve(e,cn,"the manifest"),sa(e);let t=e.entries===void 0?{}:Qi(e.entries);return{...e,dependencies:e.dependencies===void 0?{}:Ji(e.dependencies),entries:t,providers:e.providers===void 0?{}:ea(e.providers,t),...e.registry===void 0?{}:{registry:Zi(e.registry)},...e.scripts===void 0?{}:{scripts:Ki(e.scripts)},...e.test===void 0?{}:{test:ta(e.test)},...e.permissions===void 0?{}:{permissions:na(e.permissions)}}}function _e(e){let t;try{t=JSON.parse(new TextDecoder().decode(e))}catch{return $("not valid JSON")}return{source:t,manifest:J(t)}}function Wc(e){return _e(e).manifest}function He(e){let t={};for(let r of cn)e[r]!==void 0&&(t[r]=e[r]);return JSON.stringify(t,null,2)+` +`}function un(e){return{format:Y,name:e,version:"0.1.0",dependencies:{}}}function fn(e){let r=(String(e??"").split("/").filter(Boolean).pop()??"").toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/-+$/,"");return Me.test(r)?r:"webfront-app"}async function he(e){let t=JSON.stringify(Object.entries(e).sort(([n],[s])=>ns?1:0)),r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return[...new Uint8Array(r)].map(n=>n.toString(16).padStart(2,"0")).join("")}var We=e=>/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(e),me=(e,t)=>`${e.replace("/","+")}@${t}`,Ye=(e,t,r)=>`${me(e,t)}-${r.slice(7).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}`;async function ia(e,t,{fetchImpl:r,signal:n}){let s=await r(new URL(e.replace("/","%2f"),t),{signal:n});if(!s.ok)throw new Error(`Registry metadata for ${e}: HTTP ${s.status}`);return s.json()}function aa(e,t){let r=e["dist-tags"]?.[t];return r||(de.default.valid(t)?t:de.default.maxSatisfying(Object.keys(e.versions??{}),t))}function ca(e,t,r){let n=r||"latest",s=aa(e,n),o=e.versions?.[s];if(!o||!de.default.valid(s))throw new Error(`Cannot resolve ${t}@${n}`);return{version:s,manifest:o}}async function la(e,t,r,{fetchImpl:n,signal:s}){let o=new URL(t.dist?.tarball,r);if(o.protocol!=="https:"&&o.origin!==r.origin)throw new Error("Package tarballs must use HTTPS or the registry origin");let i=await n(o,{signal:s});if(!i.ok)throw new Error(`Package download for ${e}: HTTP ${i.status}`);let a=await nn(i);return{bytes:a,integrity:await ft(a,t.dist.integrity)}}function Je(e){let t=new URL(e,globalThis.location?.href),r=t.origin===globalThis.location?.origin;if(e.startsWith("/")?!Be(e)||!r:t.protocol!=="https:"&&!r)throw new Error(`The npm registry must use HTTPS or the application origin: ${e}`);return t.pathname.endsWith("/")||(t.pathname+="/"),t}async function j(e,t,{registry:r,fetchImpl:n=fetch,signal:s}){if(!We(e))throw new Error(`Unsupported npm package name: ${e}`);let o=Je(r),i={fetchImpl:n,signal:s},{version:a,manifest:c}=ca(await ia(e,o,i),e,t),{bytes:l,integrity:h}=await la(e,c,o,i),p=await sn(l),E=on(p,e,a);return{id:me(e,a),key:Ye(e,a,h),manifest:E,integrity:h,files:p}}var we=D(P(),1);function ua(e,t,r){let n=e?.roots?.[t];return n?.requested===r&&e.packages[n.id]?e.packages[n.id]:we.default.validRange(r)?Object.values(e?.packages??{}).filter(o=>o.name===t&&we.default.satisfies(o.version,r)).sort((o,i)=>we.default.rcompare(o.version,i.version))[0]??null:null}function pn({registry:e="https://registry.npmjs.org/",fetchImpl:t=fetch,signal:r,download:n=j,previous:s}){let o=new Map;return async(i,a)=>{let c=`${i}@${a}`;if(o.has(c))return o.get(c);let l=ua(s,i,a),h=await n(i,l?.version??a,{registry:e,fetchImpl:t,signal:r});if(l&&h.integrity!==l.integrity)throw new Error(`${h.id} no longer matches the integrity recorded in the lock`);return o.set(c,h),h}}var hn=D(P(),1),dn=(e,t,r)=>new Error(`${e.name}@${e.version} requires peer ${t}@${r}; install a compatible root explicitly`);function fa(e,t,r){if(e.manifest.peerDependenciesMeta?.[t]?.optional)return null;throw dn(e,t,r)}function pa(e,[t,r],{nodes:n,roots:s}){let o=s[t]?.id??e.dependencies[t];if(!o)return fa(e,t,r);if(!hn.default.satisfies(n[o].version,r))throw dn(e,t,r);return o}function ha(e,t){for(let r of Object.entries(e.manifest.peerDependencies??{})){let n=pa(e,r,t);n&&(e.dependencies[r[0]]=n)}}function mn(e,t){for(let r of Object.values(e))ha(r,{nodes:e,roots:t})}var wn=D(P(),1);function da(e,t){return!We(t.name)||!wn.default.valid(t.version)?!1:e===me(t.name,t.version)}function ma(e){return e.integrity?.startsWith("sha512-")?e.key===Ye(e.name,e.version,e.integrity):!1}function wa(e,t,r){if(!da(t,r)||!ma(r))throw new Error("Invalid locked package");for(let n of r.files)q(n);if(Object.values(r.dependencies).some(n=>!e.packages[n]))throw new Error("Dangling locked dependency")}function Ea(e){return e?.format!==1?!1:!!e.roots&&!!e.packages}function Ze(e){if(!Ea(e))throw new Error("Unsupported package lock");if(Object.keys(e.packages).length>512)throw new Error("The package lock exceeds 512 packages");for(let[t,r]of Object.entries(e.packages))wa(e,t,r);if(Object.values(e.roots).some(t=>!e.packages[t.id]))throw new Error("Dangling locked root");return e}function ga(e,t,r){if(Object.keys(e.nodes).length>=512)throw new Error("Dependency graph exceeds 512 packages");for(let n of r.files.values())e.total+=n.length;if(e.total>256*1024*1024)throw new Error("Dependency graph exceeds 256 MiB");e.nodes[r.id]={name:t,version:r.manifest.version,integrity:r.integrity,key:r.key,manifest:r.manifest,files:[...r.files.keys()].sort(),dependencies:{}},e.downloads.set(r.id,r.files)}async function $a(e,t){let r={};for(let n of e){let{name:s,version:o}=K(n);r[s]={requested:o||"latest",id:await t(s,o||"latest")}}return r}async function En(e,t={}){let r=pn(t),n={nodes:{},downloads:new Map,total:0},s=async(i,a)=>{t.signal?.throwIfAborted();let c=await r(i,a);if(n.nodes[c.id])return c.id;ga(n,i,c);for(let[l,h]of Object.entries(c.manifest.dependencies??{}).sort())n.nodes[c.id].dependencies[l]=await s(l,h);return c.id},o=await $a(e,s);return mn(n.nodes,o),{lock:{format:1,registry:t.registry??"https://registry.npmjs.org/",roots:o,packages:n.nodes},downloads:n.downloads}}var Ke=D(P(),1);var k="webfront-packages.lock.json",Qe=".webfront/developer/packages",ya=new TextDecoder,Ra=new TextEncoder,Ee="No webfront.project.json: run wf init",ge="The lock does not match the dependencies of webfront.project.json; run wf install --update to resolve them again";async function gn(e,t){try{return await fe(e,t)}catch(r){if(r.message.includes("Cannot read project file:"))return null;throw r}}function Oa(e,t,r){return t?r===t.requested?!0:Ke.default.validRange(r)!==null&&Ke.default.satisfies(e.packages[t.id].version,r):!1}function Ia(e,t){let r=Object.keys(t);return r.length===Object.keys(e.roots).length&&r.every(n=>Oa(e,e.roots[n],t[n]))}function xa(e,t,r){return e?t?t.manifestDigest===void 0?Ia(t,e.dependencies)?"legacy":"desynchronized":t.manifestDigest===r?"consistent":"desynchronized":"unlocked":"no-manifest"}async function Z(e){let t=await b(e,"state",`${S} +${k}`),r=await gn(e,S),n=await gn(e,k),{source:s,manifest:o}=r?_e(r):{source:null,manifest:null},i=n?Ze(JSON.parse(ya.decode(n))):null,a=o?await he(o.dependencies):null;return{manifest:o,source:s,lock:i,token:t,status:xa(o,i,a),digest:a}}var yn=e=>e.status==="desynchronized"?`Warning: ${ge}.\r +`:"";async function Rn(e,t,r,{signal:n}={}){let s=[];try{for(let[o,i]of t){n?.throwIfAborted();let a=await b(e,"begin",o,!1);s.push(a),await Ge(e,{id:a,path:"output",bytes:i},n)}n?.throwIfAborted(),await b(e,"commitGroup",s.join(` +`),`${S} +${k}`,r.token)}catch(o){for(let i of s)await b(e,"abort",i).catch(()=>{});throw o}}function $n(e,t,r){let n=e?.entries??{};if(t!==void 0)return Object.hasOwn(n,t)?n[t]:t;if(Object.hasOwn(n,"main"))return n.main;let s=Object.keys(n);if(s.length===1)return n[s[0]];throw new Error(`Usage: ${r} (declare entries.main in ${S} to omit the entry)`)}function El(e,[t,r,n,...s]){if(t&&Object.hasOwn(e?.providers??{},t)&&r===void 0){let i=e.providers[t];return{entry:$n(e,i.entry),output:i.output,className:t}}if(!t||r!=="--output"||s.length||!n?.endsWith(".hpp"))throw new Error("wf embed requires or --output ");let o=n.split("/").pop().slice(0,-4);if(!Xe.test(o))throw new Error(`wf embed: ${o} is not a C++ class name; name the output .hpp`);return{entry:$n(e,t),output:n,className:o}}var $e=e=>Ra.encode(e);var st=D(P(),1);var On=e=>`${Qe}/${e.key}`,In=e=>`${Qe}/${e.key}.json`,ba=new TextEncoder,Sa=new TextDecoder,xn=e=>e.message.includes("Cannot read project file:");async function vn(e){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",e))].map(r=>r.toString(16).padStart(2,"0")).join("")}async function ye(e,t,r,{signal:n}={}){let s={};for(let i of[...r.keys()].sort())s[i]=await vn(r.get(i));await H(e,On(t),r,{signal:n});let o=JSON.stringify({format:1,integrity:t.integrity,files:s},null,2)+` +`;await H(e,In(t),new Map([["output",ba.encode(o)]]),{directory:!1,signal:n})}async function ka(e,t){let r;try{r=await fe(e,In(t))}catch(n){if(xn(n))return null;throw n}try{return JSON.parse(Sa.decode(r))}catch{return{}}}var La=(e,t)=>Object.keys(e.files).sort().join(` +`)===[...t.files].sort().join(` +`);async function Na(e,t,r){let n=[],s=0;for(;;){let o;try{o=await b(e,"read",t,s)}catch(i){if(xn(i))return null;throw i}if(s+=o.length,s>r)return null;if(n.push(o),o.length<262144)return new Uint8Array(await new Blob(n).arrayBuffer())}}async function et(e,t,{signal:r,limit:n=1/0}={}){let s=await ka(e,t);if(!s)return{state:"missing",size:0};if(s.integrity!==t.integrity||!W(s.files)||!La(s,t))return{state:"corrupted",size:0};let o=0;for(let i of t.files){r?.throwIfAborted();let a=await Na(e,`${On(t)}/${i}`,n-o);if(!a||await vn(a)!==s.files[i])return{state:"corrupted",size:0};o+=a.length}return{state:"valid",size:o}}var Ol=async(e,t,r)=>(await et(e,t,r)).state;var Ta="https://registry.npmjs.org/";function Aa({registry:e,registryExplicit:t}={},r){return t&&e?{url:e,source:"application option"}:r?.registry?{url:r.registry,source:S}:{url:e||Ta,source:"default"}}function tt(e,t){let r=Aa(e,t);return Je(r.url),r}var rt=({url:e,source:t})=>`Registry: ${e} (${t})`,Pa=256*1024*1024,qa=e=>[...e.values()].reduce((t,r)=>t+r.length,0),ja=e=>new Error(`The locked packages exceed ${e/(1024*1024)} MiB unpacked`);async function Ca(e,t,{signal:r,limit:n}){let s=[],o=0;for(let[i,a]of Object.entries(t.packages)){r?.throwIfAborted();let c=await et(e,a,{signal:r,limit:n-o});o+=c.size,s.push({id:i,node:a,state:c.state})}return{states:s,size:o}}async function nt(e,t,{registry:r,offline:n=!1,signal:s,progress:o=()=>{},fetchImpl:i=fetch,limit:a=Pa}){let{states:c,size:l}=await Ca(e,t,{signal:s,limit:a}),h=l,p={verified:c.filter(({state:E})=>E==="valid").length,restored:0,problems:[]};for(let{id:E,node:d,state:C}of c.filter(({state:L})=>L!=="valid")){if(n){p.problems.push(`${E} (${C})`);continue}o(`Restoring ${E}${C==="corrupted"?" (corrupted in the cache)":""}`);let L=await j(d.name,d.version,{registry:r,fetchImpl:i,signal:s});if(L.integrity!==d.integrity)throw new Error(`${E} no longer matches the integrity recorded in the lock`);if(h+=qa(L.files),h>a)throw ja(a);await ye(e,d,L.files,{signal:s}),p.restored++}if(p.problems.length)throw new Error(`The cache does not match ${k}; missing or corrupted, nothing downloaded:\r + ${p.problems.join(`\r + `)}\r +Run wf restore to download them.`);return p}function Da(e){let t=e.includes("--offline");if(e.some(r=>r!=="--offline"))throw new Error("Usage: wf restore [--offline]");return{offline:t}}async function kl(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}={}){let{offline:a}=Da(t),c=await Z(e);if(!c.manifest)throw new Error(Ee);if(!c.lock)throw new Error(`No ${k}: run wf install to resolve the dependencies`);let l=a?null:tt({registry:r,registryExplicit:n},c.manifest);o(a?"Offline: no registry is contacted":rt(l));let h=await nt(e,c.lock,{registry:l?.url,offline:a,signal:s,progress:o,fetchImpl:i}),p=Object.keys(c.lock.packages).length,E=a?`Cache verified offline: ${p} packages match ${k}.`:`Restored ${h.restored} of ${p} packages (${h.verified} already in the cache). Lock: ${k}`;return{...h,registry:l,text:yn(c)+E}}var kn=e=>{let{name:t,version:r}=K(e);return[t,r||void 0]};function Ua(e,t){let{version:r}=e.packages[t.id];return!(st.default.valid(t.requested)!==null)&&t.requested!=="latest"&&st.default.validRange(t.requested)!==null?t.requested:`^${r}`}async function Dl(e,[t,...r],{signal:n}={}){if(r.length)throw new Error("Usage: wf init [name]");let{lock:s}=await Z(e),o=un(t??fn(""));s&&(o.dependencies=Object.fromEntries(Object.entries(s.roots).map(([a,c])=>[a,Ua(s,c)]))),J(o),await H(e,S,new Map([["output",$e(He(o))]]),{directory:!1,replace:!1,signal:n});let i=s?` with the ${Object.keys(o.dependencies).length} dependencies of ${k}`:"";return`Created ${S}${i}. Add libraries with wf install .`}function za(e,t){let r={...e.manifest.dependencies},n=new Set;for(let s of t){let[o,i]=kn(s);r[o]=i??"latest",i&&i!=="latest"&&n.add(o)}return J({...e.source,dependencies:r}),{dependencies:r,explicit:n}}function Fa(e,t){let r={...e.source,dependencies:t};return J(r),r}function Ga({dependencies:e,explicit:t},r,n){let s={...e};for(let o of n){let i=kn(o)[0];t.has(i)||(s[i]=`^${r.packages[r.roots[i].id].version}`)}return s}async function Ma(e,t,r){let n=Object.entries(e).map(([i,a])=>`${i}@${a}`),{lock:s,downloads:o}=await En(n,{registry:r.registry,signal:r.signal,fetchImpl:r.fetchImpl,previous:t,download:async(...i)=>(r.progress(`Resolving ${i[0]}@${i[1]}`),j(...i))});return{lock:s,downloads:o}}async function Xa(e,t,r,{signal:n,progress:s}){for(let[o,i]of r)s(`Storing ${o}`),await ye(e,t.packages[o],i,{signal:n})}function Va(e){let t=e.includes("--update"),r=e.filter(n=>n!=="--update");if(r.some(n=>n.startsWith("-")))throw new Error("Usage: wf install [--update] [[@range] ...]");return{update:t,specs:r}}async function bn(e,t,{manifest:r,lock:n},s){let o=new Map([[k,$e(JSON.stringify(n,null,2)+` +`)]]);r&&o.set(S,$e(He(r))),await Rn(e,o,t,s)}var Sn=async(e,t)=>({format:e.format,manifestDigest:await he(t),...e});async function Ul(e,t,{registry:r,registryExplicit:n,signal:s,progress:o=()=>{},fetchImpl:i=fetch}){let{update:a,specs:c}=Va(t),l=await Z(e);if(!l.manifest)throw new Error(Ee);let h=tt({registry:r,registryExplicit:n},l.manifest),p={registry:h.url,signal:s,fetchImpl:i,progress:o};if(c.length&&a)throw new Error("Usage: wf install --update does not take packages");if(c.length&&l.status==="desynchronized")throw new Error(ge);if(!c.length&&!a&&l.status==="desynchronized")throw new Error(ge);o(rt(h));let E=l.status==="consistent"||l.status==="legacy";if(!c.length&&!a&&E){let{restored:at}=await nt(e,l.lock,p);if(l.status==="consistent")return{lock:l.lock,restored:at,registry:h};let ct=await Sn(l.lock,l.manifest.dependencies);return await bn(e,l,{manifest:null,lock:ct},{signal:s}),{lock:ct,restored:at,registry:h}}let d=za(l,c),C=E&&!a?l.lock:void 0,L=await Ma(d.dependencies,C,p),ot=Ga(d,L.lock,c);await Xa(e,L.lock,L.downloads,{signal:s,progress:o});let it=await Sn(L.lock,ot),Ln=c.length?Fa(l,ot):null;return await bn(e,l,{manifest:Ln,lock:it},{signal:s}),{lock:it,restored:0,registry:h}}export{Ol as cacheState,Ta as defaultRegistry,he as dependenciesDigest,rt as describeRegistry,ge as desynchronized,j as downloadPackage,Aa as effectiveRegistry,El as embedTarget,Hi as exactVersion,Xe as identifier,Dl as initProject,et as inspectCache,Ul as install,Z as loadProject,k as lockPath,Ia as locksDependencies,Y as manifestFormat,fn as manifestName,S as manifestPath,un as newManifest,Ee as noManifest,Me as npmName,On as packageDirectory,Qe as packageRoot,Wc as parseManifest,Rn as publishTogether,_e as readManifest,In as recordPath,$n as resolveEntry,En as resolvePackages,kl as restore,nt as restorePackages,q as safePackagePath,Be as sameOriginPath,He as serializeManifest,ye as storePackage,yn as syncNotice,$e as textBytes,Pa as unpackedLimit,tt as usableRegistry,Ze as validateLock,J as validateManifest}; diff --git a/js/developer/environment/registry.mjs b/js/developer/environment/registry.mjs index eb49dd26..66704627 100644 --- a/js/developer/environment/registry.mjs +++ b/js/developer/environment/registry.mjs @@ -3,6 +3,7 @@ import semver from 'semver'; import {responseBytes} from './io.mjs'; import {verifyIntegrity} from '../components/tools/wf.mjs'; import {readArchive, checkedManifest} from './archive.mjs'; +import {sameOriginPath} from './manifest.mjs'; export const safeName = name => /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name); export const idOf = (name, version) => `${name.replace('/', '+')}@${version}`; @@ -39,8 +40,13 @@ async function fetchTarball(name, manifest, base, {fetchImpl, signal}) { return {bytes, integrity: await verifyIntegrity(bytes, manifest.dist.integrity)}; } -function registryBase(registry) { +// Like the environment archive: HTTPS, or the application's own origin for a local mirror. +// A path must also resolve on that origin, whatever the parser makes of it. +export function registryBase(registry) { const base = new URL(registry, globalThis.location?.href); + const local = base.origin === globalThis.location?.origin; + if (registry.startsWith('/') ? !sameOriginPath(registry) || !local : base.protocol !== 'https:' && !local) + throw new Error(`The npm registry must use HTTPS or the application origin: ${registry}`); if (!base.pathname.endsWith('/')) base.pathname += '/'; return base; } diff --git a/js/developer/environment/restore.mjs b/js/developer/environment/restore.mjs new file mode 100644 index 00000000..111555d3 --- /dev/null +++ b/js/developer/environment/restore.mjs @@ -0,0 +1,91 @@ +// wf restore: rebuilds the package cache from the lock alone, from one registry or, with --offline, from nothing. +import {downloadPackage, registryBase} from './registry.mjs'; +import {inspectCache, storePackage} from './cache.mjs'; +import {loadProject, syncNotice, lockPath, noManifest} from './project.mjs'; +import {manifestPath} from './manifest.mjs'; + +export const defaultRegistry = 'https://registry.npmjs.org/'; +/** + * The registry the commands use, and where it comes from: the application's explicit option (the distributor's + * channel, which also lets a test impose its local registry), then the manifest's "registry", then the default. + */ +export function effectiveRegistry({registry, registryExplicit} = {}, manifest) { + if (registryExplicit && registry) return {url: registry, source: 'application option'}; + if (manifest?.registry) return {url: manifest.registry, source: manifestPath}; + return {url: registry || defaultRegistry, source: 'default'}; +} + +/** The effective registry of a command that may download, refused before any request when it is not allowed. */ +export function usableRegistry(options, manifest) { + const effective = effectiveRegistry(options, manifest); + registryBase(effective.url); + return effective; +} + +export const describeRegistry = ({url, source}) => `Registry: ${url} (${source})`; + +export const unpackedLimit = 256 * 1024 * 1024; +const unpackedSize = files => [...files.values()].reduce((total, bytes) => total + bytes.length, 0); +const tooLarge = limit => new Error(`The locked packages exceed ${limit / (1024 * 1024)} MiB unpacked`); + +// Every package's cache state; the valid ones count towards the bound of the graph. +async function inspectAll(bridge, lock, {signal, limit}) { + const states = []; + let size = 0; + for (const [id, node] of Object.entries(lock.packages)) { + signal?.throwIfAborted(); + const inspected = await inspectCache(bridge, node, {signal, limit: limit - size}); + size += inspected.size; + states.push({id, node, state: inspected.state}); + } + return {states, size}; +} + +/** + * Brings the cache to the exact locked graph: each package is checked against its record and, when missing or + * corrupted, downloaded at its locked version (no range is resolved again) and checked against the lock's SHA-512. + * The unpacked graph, cached packages included, is bounded by `limit`, checked before each publication, so a + * restore that is resumed keeps the bound. Each package is published on its own: an interruption or an error keeps + * every package already restored, and the lock is never written. Offline, nothing is downloaded: the packages that + * would be are listed in an error. + */ +export async function restorePackages(bridge, lock, {registry, offline = false, signal, progress = () => {}, fetchImpl = fetch, limit = unpackedLimit}) { + const {states, size: cached} = await inspectAll(bridge, lock, {signal, limit}); + let size = cached; + const result = {verified: states.filter(({state}) => state === 'valid').length, restored: 0, problems: []}; + for (const {id, node, state} of states.filter(({state}) => state !== 'valid')) { + if (offline) { result.problems.push(`${id} (${state})`); continue; } + progress(`Restoring ${id}${state === 'corrupted' ? ' (corrupted in the cache)' : ''}`); + const pkg = await downloadPackage(node.name, node.version, {registry, fetchImpl, signal}); + if (pkg.integrity !== node.integrity) throw new Error(`${id} no longer matches the integrity recorded in the lock`); + size += unpackedSize(pkg.files); + if (size > limit) throw tooLarge(limit); + await storePackage(bridge, node, pkg.files, {signal}); + result.restored++; + } + if (result.problems.length) + throw new Error(`The cache does not match ${lockPath}; missing or corrupted, nothing downloaded:\r\n ${result.problems.join('\r\n ')}\r\nRun wf restore to download them.`); + return result; +} + +function parseOptions(args) { + const offline = args.includes('--offline'); + if (args.some(arg => arg !== '--offline')) throw new Error('Usage: wf restore [--offline]'); + return {offline}; +} + +/** wf restore [--offline]: the cache is rebuilt from the lock; manifest and lock are only read. */ +export async function restore(bridge, args, {registry, registryExplicit, signal, progress = () => {}, fetchImpl = fetch} = {}) { + const {offline} = parseOptions(args); + const project = await loadProject(bridge); + if (!project.manifest) throw new Error(noManifest); + if (!project.lock) throw new Error(`No ${lockPath}: run wf install to resolve the dependencies`); + const effective = offline ? null : usableRegistry({registry, registryExplicit}, project.manifest); + progress(offline ? 'Offline: no registry is contacted' : describeRegistry(effective)); + const result = await restorePackages(bridge, project.lock, {registry: effective?.url, offline, signal, progress, fetchImpl}); + const count = Object.keys(project.lock.packages).length; + const summary = offline + ? `Cache verified offline: ${count} packages match ${lockPath}.` + : `Restored ${result.restored} of ${count} packages (${result.verified} already in the cache). Lock: ${lockPath}`; + return {...result, registry: effective, text: syncNotice(project) + summary}; +} diff --git a/js/developer/environment/runtime.mjs b/js/developer/environment/runtime.mjs index e049b588..870fddad 100644 --- a/js/developer/environment/runtime.mjs +++ b/js/developer/environment/runtime.mjs @@ -5,6 +5,7 @@ import {validateLock} from './packages.mjs'; import {readProject, publish} from './io.mjs'; import {createStarter} from './starter.mjs'; import {install, initProject} from './installer.mjs'; +import {restore, describeRegistry} from './restore.mjs'; import {loadProject, syncNotice, resolveEntry, embedTarget, lockPath, packageRoot} from './project.mjs'; import {generateProvider, applicationPage} from './embed.mjs'; @@ -93,10 +94,19 @@ async function create([starter, directory, ...extra], {bridge, config, signal}) const init = (args, {bridge, signal}) => initProject(bridge, args, {signal}); +const registryOptions = (config, signal, write) => + ({registry: config.registry, registryExplicit: config.registryExplicit === true, signal, progress: text => write(text + '\r\n')}); + async function installCommand(args, {bridge, config, signal, write = () => {}}) { - const {lock, restored} = await install(bridge, args, {registry: config.registry, signal, progress: text => write(text + '\r\n')}); + const {lock, restored, registry} = await install(bridge, args, registryOptions(config, signal, write)); const count = Object.keys(lock.packages).length; - return restored || !args.length ? `Installed ${count} packages (${restored} restored). Lock: ${lockPath}` : `Installed ${count} packages. Lock: ${lockPath}`; + const summary = restored || !args.length ? `Installed ${count} packages (${restored} restored).` : `Installed ${count} packages.`; + return `${summary} ${describeRegistry(registry)}. Lock: ${lockPath}`; +} + +async function restoreCommand(args, {bridge, config, signal, write = () => {}}) { + const result = await restore(bridge, args, registryOptions(config, signal, write)); + return result.registry ? `${result.text}\r\n${describeRegistry(result.registry)}` : result.text; } async function preview(args, {bridge, signal, preview: frame}) { @@ -125,8 +135,8 @@ async function list(_args, {bridge}) { return syncNotice(project) + (names || 'No installed packages.'); } -const help = () => 'wf init [name]\nwf create [directory]\nwf install [--update] [[@range] ...]\nwf list\nwf preview [entry.tsx|name]\nwf embed | --output \nCtrl+C interrupts a browser command. No system shell is exposed.'; -const commands = {init, create, install: installCommand, preview, embed, list, help}; +const help = () => 'wf init [name]\nwf create [directory]\nwf install [--update] [[@range] ...]\nwf restore [--offline]\nwf list\nwf preview [entry.tsx|name]\nwf embed | --output \nCtrl+C interrupts a browser command. No system shell is exposed.'; +const commands = {init, create, install: installCommand, restore: restoreCommand, preview, embed, list, help}; export async function execute(args, context) { const [command = 'help', ...rest] = args; diff --git a/js/developer/tools/build.mjs b/js/developer/tools/build.mjs index 55643a31..8f4d630b 100644 --- a/js/developer/tools/build.mjs +++ b/js/developer/tools/build.mjs @@ -79,7 +79,7 @@ if (refresh) { await copyFile(resolve(root, 'js/developer/vendor/node_modules/semver/LICENSE'), resolve(root, 'js/developer/environment/PACKAGES-LICENSE.txt')); await writeFile(resolve(root, 'include/webfront/system/DeveloperReleaseData.hpp'), header); const inputs = {}; - for (const path of ['js/developer/environment/manifest.mjs', 'js/developer/environment/project.mjs', 'js/developer/environment/installer.mjs', 'js/developer/environment/packages-entry.mjs', 'js/developer/environment/bootstrap.mjs', 'js/developer/environment/bootstrap-entry.mjs', 'js/developer/environment/packages.mjs', 'js/developer/environment/starter.mjs', 'js/developer/environment/paths.mjs', 'js/developer/environment/runtime.mjs', 'js/developer/environment/compiler.mjs', 'js/developer/environment/bundler.mjs', 'js/developer/environment/entry.mjs', 'js/developer/environment/conditions.mjs', 'js/developer/environment/io.mjs', 'js/developer/environment/recipe.mjs', 'js/developer/environment/registry.mjs', 'js/developer/environment/archive.mjs', 'js/developer/environment/lock.mjs', 'js/developer/environment/pins.mjs', 'js/developer/environment/peers.mjs', 'js/developer/environment/resolve.mjs', 'js/developer/environment/embed.mjs', 'js/developer/tools/starters/pi/main.tsx', 'js/developer/tools/starters/pi/style.css', 'examples/life/ui/main.tsx', 'examples/life/ui/style.css', 'js/developer/components/tools/wf.mjs', 'js/developer/tools/distribution.json', 'js/developer/tools/build.mjs', 'js/developer/tools/site.mjs', 'js/developer/tools/archive.mjs', 'js/developer/vendor/package-lock.json', 'js/core/bootstrap/bootstrap.bundle.mjs', 'js/developer/environment/packages.bundle.mjs', 'include/webfront/system/DeveloperReleaseData.hpp']) + for (const path of ['js/developer/environment/manifest.mjs', 'js/developer/environment/project.mjs', 'js/developer/environment/installer.mjs', 'js/developer/environment/restore.mjs', 'js/developer/environment/cache.mjs', 'js/developer/environment/packages-entry.mjs', 'js/developer/environment/bootstrap.mjs', 'js/developer/environment/bootstrap-entry.mjs', 'js/developer/environment/packages.mjs', 'js/developer/environment/starter.mjs', 'js/developer/environment/paths.mjs', 'js/developer/environment/runtime.mjs', 'js/developer/environment/compiler.mjs', 'js/developer/environment/bundler.mjs', 'js/developer/environment/entry.mjs', 'js/developer/environment/conditions.mjs', 'js/developer/environment/io.mjs', 'js/developer/environment/recipe.mjs', 'js/developer/environment/registry.mjs', 'js/developer/environment/archive.mjs', 'js/developer/environment/lock.mjs', 'js/developer/environment/pins.mjs', 'js/developer/environment/peers.mjs', 'js/developer/environment/resolve.mjs', 'js/developer/environment/embed.mjs', 'js/developer/tools/starters/pi/main.tsx', 'js/developer/tools/starters/pi/style.css', 'examples/life/ui/main.tsx', 'examples/life/ui/style.css', 'js/developer/components/tools/wf.mjs', 'js/developer/tools/distribution.json', 'js/developer/tools/build.mjs', 'js/developer/tools/site.mjs', 'js/developer/tools/archive.mjs', 'js/developer/vendor/package-lock.json', 'js/core/bootstrap/bootstrap.bundle.mjs', 'js/developer/environment/packages.bundle.mjs', 'include/webfront/system/DeveloperReleaseData.hpp']) inputs[path] = createHash('sha256').update(await readFile(resolve(root, path))).digest('hex'); await writeFile(resolve(root, 'js/developer/environment/bundles.json'), JSON.stringify(inputs, null, 2) + '\n'); for (const [source, name] of [['js/core/bootstrap/index.html', 'DeveloperIndexHtmlData'], ['js/core/bootstrap/bootstrap.bundle.mjs', 'DeveloperBootstrapData']]) diff --git a/js/developer/tools/fixtures.mjs b/js/developer/tools/fixtures.mjs index 494c9b0e..1355ae80 100644 --- a/js/developer/tools/fixtures.mjs +++ b/js/developer/tools/fixtures.mjs @@ -1,32 +1,15 @@ // Configure offline browser fixtures from the maintainer's pinned npm ci installation. -import {readFile, writeFile, mkdir, readdir, copyFile} from 'node:fs/promises'; +import {mkdir, copyFile} from 'node:fs/promises'; import {resolve} from 'node:path'; import {fileURLToPath} from 'node:url'; -import {createHash} from 'node:crypto'; -import {tar} from './archive.mjs'; -import {compress} from '../environment/embed.mjs'; +import {pinnedPackages, syntheticPackages} from './registry-fixture.mjs'; +import {installedPackage, writeRegistry} from './registry-fixture-node.mjs'; const root = fileURLToPath(new URL('../../../', import.meta.url)); const output = resolve(process.argv[2] ?? 'build-developer-environment'); -await mkdir(resolve(output, 'registry'), {recursive: true}); -for (const name of ['react', 'react-dom', 'scheduler']) { - const directory = resolve(root, 'js/developer/vendor/node_modules', name); - const manifest = JSON.parse(await readFile(resolve(directory, 'package.json'))); - const files = new Map(); - async function walk(path = '') { - for (const entry of await readdir(resolve(directory, path), {withFileTypes: true})) { - if (entry.name === 'node_modules') continue; - const relative = path ? `${path}/${entry.name}` : entry.name; - if (entry.isDirectory()) await walk(relative); - else if (entry.isFile()) files.set(`package/${relative}`, await readFile(resolve(directory, relative))); - } - } - await walk(); - const bytes = compress(tar(files)); - await writeFile(resolve(output, 'registry', `${name}.tgz`), bytes); - const integrity = 'sha512-' + createHash('sha512').update(bytes).digest('base64'); - await writeFile(resolve(output, 'registry', name), JSON.stringify({'dist-tags': {latest: manifest.version}, - versions: {[manifest.version]: {...manifest, dist: {tarball: `./${name}.tgz`, integrity}}}})); -} +await mkdir(output, {recursive: true}); +const nodeModules = resolve(root, 'js/developer/vendor/node_modules'); +const pinned = await Promise.all(pinnedPackages.map(name => installedPackage(nodeModules, name))); +await writeRegistry(resolve(output, 'registry'), [...pinned, ...syntheticPackages()]); await copyFile(resolve(root, 'test/web/developer-specs.mjs'), resolve(output, 'run.mjs')); await copyFile(resolve(root, 'js/developer/tools/starters/pi/main.tsx'), resolve(output, 'main.tsx')); await copyFile(resolve(root, 'js/developer/tools/starters/pi/style.css'), resolve(output, 'style.css')); diff --git a/js/developer/tools/manifest-check.mjs b/js/developer/tools/manifest-check.mjs index 5b284921..a7d59424 100644 --- a/js/developer/tools/manifest-check.mjs +++ b/js/developer/tools/manifest-check.mjs @@ -6,6 +6,7 @@ import {validateManifest, parseManifest, serializeManifest, manifestName, depend import {install, initProject, loadProject, syncNotice, resolveEntry, embedTarget, lockPath, manifestPath} from '../environment/packages.bundle.mjs'; import {compress} from '../environment/embed.mjs'; import {tar} from './archive.mjs'; +import {memoryBridge} from './memory-bridge.mjs'; const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -39,6 +40,7 @@ test('invalid manifests are explicit errors, never silent fallbacks', () => { [{...minimal, dependencies: {'../x': '1.0.0'}}, /invalid npm package name/], [{...minimal, dependencies: {react: 'file:../react'}}, /invalid version range/], [{...minimal, registry: 'http://insecure.test/'}, /registry must use https/], + [{...minimal, registry: '/\\registry.test/'}, /registry must be an https URL or an absolute path/], [{...minimal, entries: {main: '../outside.tsx'}}, /safe project-relative path/], [{...minimal, entries: {main: '/etc/passwd'}}, /safe project-relative path/], [{...minimal, providers: {'not valid': {entry: 'a.tsx', output: 'a.hpp'}}}, /invalid provider name/], @@ -79,46 +81,6 @@ test('wf embed names the generated class after the provider, and refuses a file assert.throws(() => embedTarget(manifest, ['ui/main.tsx']), /--output/); }); -// An in-memory project behind the webfront.developer.* callbacks, with the store's group publication and precondition. -function memoryBridge(storage = new Map()) { - const transactions = new Map(); - let next = 0; - const stateOf = paths => paths.map(path => storage.has(path) ? createHash('sha256').update(storage.get(path)).digest('hex') : '-').join(','); - const operations = { - read: (path, offset) => { - if (!storage.has(path)) throw new Error('Cannot read project file: ' + path); - return storage.get(path).subarray(offset, offset + 256 * 1024); - }, - begin: (destination, directory) => { transactions.set(String(++next), {destination, directory, files: new Map(), replace: true}); return String(next); }, - beginNew: (destination, directory) => { transactions.set(String(++next), {destination, directory, files: new Map(), replace: false}); return String(next); }, - write: (id, path, offset, bytes) => { - const files = transactions.get(id).files; - const previous = files.get(path) ?? new Uint8Array(); - assert.equal(previous.length, offset); - files.set(path, new Uint8Array([...previous, ...bytes])); - }, - commit: id => { - const {destination, directory, files, replace} = transactions.get(id); - if (!replace && (storage.has(destination) || [...storage.keys()].some(key => key.startsWith(destination + '/')))) - throw new Error('Starter destination already exists'); - for (const [path, bytes] of files) storage.set(directory ? `${destination}/${path}` : destination, bytes); - transactions.delete(id); - }, - abort: id => { transactions.delete(id); }, - state: paths => stateOf(paths.split('\n')), - commitGroup: (ids, paths, expected) => { - if (stateOf(paths.split('\n')) !== expected) throw new Error('The project changed since it was read; run the command again'); - for (const id of ids.split('\n')) { - const {destination, files} = transactions.get(id); - storage.set(destination, files.get('output')); - transactions.delete(id); - } - }, - }; - const bridge = {cppFunction: name => async (...args) => operations[name.replace('webfront.developer.', '')](...args)}; - return {bridge, storage, pending: () => transactions.size}; -} - const tagged = (packages, tags) => async url => { const response = await packages(url); const body = response.headers.get('content-type')?.includes('json') ? await response.json() : null; diff --git a/js/developer/tools/memory-bridge.mjs b/js/developer/tools/memory-bridge.mjs new file mode 100644 index 00000000..049f4618 --- /dev/null +++ b/js/developer/tools/memory-bridge.mjs @@ -0,0 +1,45 @@ +// An in-memory project behind the webfront.developer.* callbacks, with the store's directory replacement, group +// publication and precondition. Shared by the Node tests; it uses only browser APIs, so that the tests can move to +// a browser runner. +export function memoryBridge(storage = new Map()) { + const transactions = new Map(); + let next = 0; + // The state of a file is its content: compared synchronously, so that check and publication stay one step. + const stateOf = paths => JSON.stringify(paths.map(path => storage.has(path) ? [...storage.get(path)] : null)); + const inside = destination => [...storage.keys()].filter(key => key.startsWith(destination + '/')); + const operations = { + read: (path, offset) => { + if (!storage.has(path)) throw new Error('Cannot read project file: ' + path); + return storage.get(path).subarray(offset, offset + 256 * 1024); + }, + begin: (destination, directory) => { transactions.set(String(++next), {destination, directory, files: new Map(), replace: true}); return String(next); }, + beginNew: (destination, directory) => { transactions.set(String(++next), {destination, directory, files: new Map(), replace: false}); return String(next); }, + write: (id, path, offset, bytes) => { + const files = transactions.get(id).files; + const previous = files.get(path) ?? new Uint8Array(); + if (previous.length !== offset) throw new Error('Non-sequential developer write'); + files.set(path, new Uint8Array([...previous, ...bytes])); + }, + commit: id => { + const {destination, directory, files, replace} = transactions.get(id); + if (!replace && (storage.has(destination) || inside(destination).length)) + throw new Error('Starter destination already exists'); + // A directory publication replaces the whole directory, as the store does. + if (directory) inside(destination).forEach(key => storage.delete(key)); + for (const [path, bytes] of files) storage.set(directory ? `${destination}/${path}` : destination, bytes); + transactions.delete(id); + }, + abort: id => { transactions.delete(id); }, + state: paths => stateOf(paths.split('\n')), + commitGroup: (ids, paths, expected) => { + if (stateOf(paths.split('\n')) !== expected) throw new Error('The project changed since it was read; run the command again'); + for (const id of ids.split('\n')) { + const {destination, files} = transactions.get(id); + storage.set(destination, files.get('output')); + transactions.delete(id); + } + }, + }; + const bridge = {cppFunction: name => async (...args) => operations[name.replace('webfront.developer.', '')](...args)}; + return {bridge, storage, pending: () => transactions.size}; +} diff --git a/js/developer/tools/registry-fixture-node.mjs b/js/developer/tools/registry-fixture-node.mjs new file mode 100644 index 00000000..6c99e51e --- /dev/null +++ b/js/developer/tools/registry-fixture-node.mjs @@ -0,0 +1,28 @@ +// Node-only part of the registry fixture: packages read from an npm ci installation, files written to a directory. +import {readFile, writeFile, mkdir, readdir} from 'node:fs/promises'; +import {resolve} from 'node:path'; +import {registryFiles} from './registry-fixture.mjs'; + +async function collect(directory, files, path = '') { + const entries = await readdir(resolve(directory, path), {withFileTypes: true}); + for (const entry of entries) { + const relative = path ? `${path}/${entry.name}` : entry.name; + if (entry.isDirectory() && entry.name !== 'node_modules') await collect(directory, files, relative); + else if (entry.isFile()) files.set(relative, await readFile(resolve(directory, relative))); + } + return files; +} + +/** A package installed by npm ci, as the files of its archive. */ +export async function installedPackage(nodeModules, name) { + const directory = resolve(nodeModules, name); + return {manifest: JSON.parse(await readFile(resolve(directory, 'package.json'), 'utf8')), files: await collect(directory, new Map())}; +} + +/** Writes the registry's files into `directory`; returns each package's integrity. */ +export async function writeRegistry(directory, packages) { + const {files, integrities} = await registryFiles(packages); + await mkdir(directory, {recursive: true}); + for (const [name, bytes] of files) await writeFile(resolve(directory, name), bytes); + return integrities; +} diff --git a/js/developer/tools/registry-fixture.mjs b/js/developer/tools/registry-fixture.mjs new file mode 100644 index 00000000..ed9bf11d --- /dev/null +++ b/js/developer/tools/registry-fixture.mjs @@ -0,0 +1,72 @@ +// The local npm registry of the tests: packuments and tarballs as plain files, generated reproducibly from pinned +// versions (the maintainer's npm ci installation) and from synthetic packages for the edge cases. The test +// application serves the directory from its own origin, so no test reaches the public registry. +// registryFiles() and syntheticPackages() use only browser APIs, so that wf can generate the fixture itself; +// reading node_modules and writing the directory are the Node-only part. +import {tar} from './archive.mjs'; +import {compress} from '../environment/embed.mjs'; + +/** Pinned packages copied from js/developer/vendor/node_modules, at the versions of its package-lock.json. */ +export const pinnedPackages = ['jasmine-core', 'react', 'react-dom', 'scheduler']; + +const encoder = new TextEncoder(); +async function integrity(bytes) { + const digest = new Uint8Array(await crypto.subtle.digest('SHA-512', bytes)); + return 'sha512-' + btoa(String.fromCharCode(...digest)); +} +const archive = files => compress(tar(new Map([...files].map(([path, bytes]) => [`package/${path}`, bytes])))); +// The fixture's versions are plain major.minor.patch numbers. +function compareVersions(a, b) { + const [x, y] = [a, b].map(version => version.split('.').map(Number)); + for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i]; + return 0; +} +const newest = versions => versions.toSorted(compareVersions).at(-1); + +function synthetic(name, version, fields = {}) { + const manifest = {name, version, type: 'module', main: 'index.js', ...fields}; + return {manifest, files: new Map([ + ['package.json', encoder.encode(JSON.stringify(manifest, null, 2) + '\n')], + ['index.js', encoder.encode(`export default ${JSON.stringify(`${name}@${version}`)};\n`)], + ])}; +} + +/** + * Edge cases: a dependency range under which a newer version than the locked one exists (a restore must not move + * to it), and a published archive that no longer matches the integrity of its packument. A package absent from the + * registry is simply not generated. + */ +export const syntheticPackages = () => [ + synthetic('webfront-fixture-app', '1.0.0', {dependencies: {'webfront-fixture-lib': '^1.0.0'}}), + synthetic('webfront-fixture-lib', '1.0.0'), + synthetic('webfront-fixture-lib', '1.1.0'), + {...synthetic('webfront-fixture-tampered', '1.0.0'), tampered: true}, +]; + +function byName(packages) { + const names = new Map(); + for (const pkg of packages) { + if (pkg.manifest.name.includes('/')) throw new Error('Scoped packages are not supported by the registry fixture'); + names.set(pkg.manifest.name, [...names.get(pkg.manifest.name) ?? [], pkg]); + } + return names; +} + +/** The registry's files: `` packuments and `-.tgz` archives, and each package's integrity. */ +export async function registryFiles(packages) { + const files = new Map(); + const integrities = {}; + for (const [name, versions] of byName(packages)) { + const described = {}; + for (const {manifest, files: contents, tampered} of versions) { + const file = `${name}-${manifest.version}.tgz`; + const bytes = archive(contents); + files.set(file, tampered ? archive(new Map([...contents, ['TAMPERED', encoder.encode('changed')]])) : bytes); + integrities[`${name}@${manifest.version}`] = await integrity(bytes); + described[manifest.version] = {...manifest, dist: {tarball: `./${file}`, integrity: integrities[`${name}@${manifest.version}`]}}; + } + const packument = {name, 'dist-tags': {latest: newest(Object.keys(described))}, versions: described}; + files.set(name, encoder.encode(JSON.stringify(packument, null, 2) + '\n')); + } + return {files, integrities}; +} diff --git a/js/developer/tools/restore-check.mjs b/js/developer/tools/restore-check.mjs new file mode 100644 index 00000000..8938c316 --- /dev/null +++ b/js/developer/tools/restore-check.mjs @@ -0,0 +1,248 @@ +// Tests of wf restore against the local registry fixture, served as plain files. Apart from node:test and +// node:assert, they use only browser APIs, so that they can move to wf test. +import {test, before} from 'node:test'; +import assert from 'node:assert/strict'; +import {install, initProject, restore, restorePackages, effectiveRegistry, usableRegistry, cacheState, validateLock, lockPath, manifestPath, packageRoot} from '../environment/packages.bundle.mjs'; +import {syntheticPackages, registryFiles} from './registry-fixture.mjs'; +import {memoryBridge} from './memory-bridge.mjs'; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); +const json = (storage, path) => JSON.parse(decoder.decode(storage.get(path))); +const cacheKeys = storage => [...storage.keys()].filter(key => key.startsWith(packageRoot + '/')).sort(); +const snapshot = storage => new Map(storage); + +const registries = {}; +before(async () => { + const packages = syntheticPackages(); + const genuine = packages.map(pkg => ({...pkg, tampered: false})); + registries.local = (await registryFiles(packages)).files; + // The same packages, with the tampered archive still matching its integrity: a lock can be created from it. + registries.genuine = (await registryFiles(genuine)).files; + // A mirror missing a package of the lock. + registries.partial = (await registryFiles(genuine.filter(pkg => pkg.manifest.name !== 'webfront-fixture-lib'))).files; +}); + +// Serves the registry's files at an origin, as a static file server would; records every request. +function served(files, origin = 'https://registry.test') { + const requests = []; + const fetchImpl = async (url, {signal} = {}) => { + signal?.throwIfAborted(); + requests.push(String(url)); + const {origin: requested, pathname} = new URL(url); + if (requested !== origin) return new Response('', {status: 503}); + const bytes = files.get(decodeURIComponent(pathname.slice(1))); + return bytes ? new Response(bytes) : new Response('', {status: 404}); + }; + return {fetchImpl, requests, registry: `${origin}/`}; +} + +const explicit = source => ({registry: source.registry, registryExplicit: true, fetchImpl: source.fetchImpl}); + +// A project locked to webfront-fixture-app@1.0.0 and webfront-fixture-lib@1.0.0, although lib 1.1.0 satisfies ^1.0.0. +async function lockedProject(files = registries.local, specs = ['webfront-fixture-lib@1.0.0', 'webfront-fixture-app@1.0.0']) { + const memory = memoryBridge(); + await initProject(memory.bridge, [], {}); + for (const spec of specs) await install(memory.bridge, [spec], explicit(served(files))); + return memory; +} + +test('lock and empty cache: wf restore rebuilds the exact locked graph from the local registry', async () => { + const {bridge, storage, pending} = await lockedProject(); + const lock = json(storage, lockPath); + assert.deepEqual(Object.keys(lock.packages).sort(), ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0']); + const cached = cacheKeys(storage); + assert.ok(cached.some(key => key.endsWith('.json')), 'each cached package has a record'); + cached.forEach(key => storage.delete(key)); + const before = snapshot(storage); + const source = served(registries.local); + const lines = []; + const result = await restore(bridge, [], {...explicit(source), progress: line => lines.push(line)}); + assert.equal(result.restored, 2); + assert.match(result.text, /Restored 2 of 2 packages \(0 already in the cache\)/); + assert.deepEqual(cacheKeys(storage), cached, 'the cache is the one the installation wrote'); + assert.ok([...before].every(([key, bytes]) => storage.get(key) === bytes), 'manifest and lock are only read'); + assert.ok(source.requests.every(url => !url.includes('1.1.0')), 'no range is resolved again'); + assert.ok(source.requests.every(url => url.startsWith(source.registry))); + assert.equal(lines[0], `Registry: ${source.registry} (application option)`); + assert.equal(pending(), 0); + // Idempotent: a valid cache is verified, not downloaded again. + source.requests.length = 0; + const again = await restore(bridge, [], explicit(source)); + assert.equal(again.restored, 0); + assert.equal(again.verified, 2); + assert.equal(source.requests.length, 0); +}); + +test('wf restore --offline checks the cache without any request and lists what is missing or corrupted', async () => { + const {bridge, storage} = await lockedProject(); + const noNetwork = async () => { throw new Error('network access'); }; + const ok = await restore(bridge, ['--offline'], {fetchImpl: noNetwork}); + assert.match(ok.text, /Cache verified offline: 2 packages match/); + const lock = json(storage, lockPath); + const [app, lib] = ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0'].map(id => lock.packages[id]); + storage.delete(`${packageRoot}/${app.key}.json`); + storage.set(`${packageRoot}/${lib.key}/index.js`, encoder.encode('changed')); + const before = snapshot(storage); + await assert.rejects(restore(bridge, ['--offline'], {fetchImpl: noNetwork}), + error => /webfront-fixture-app@1\.0\.0 \(missing\)/.test(error.message) && /webfront-fixture-lib@1\.0\.0 \(corrupted\)/.test(error.message)); + assert.deepEqual(storage, before, 'an offline check writes nothing'); + assert.equal(await cacheState(bridge, app), 'missing'); + assert.equal(await cacheState(bridge, lib), 'corrupted'); + // Online, the same packages are downloaded again and the cache is valid. + const result = await restore(bridge, [], explicit(served(registries.local))); + assert.equal(result.restored, 2); + assert.equal(await cacheState(bridge, lib), 'valid'); + // Only the files the lock lists are checked; a file added beside them is never read by a build. + storage.set(`${packageRoot}/${lib.key}/extra.js`, encoder.encode('')); + assert.equal(await cacheState(bridge, lib), 'valid'); +}); + +test('the application registry takes precedence over the manifest one, which takes precedence over the default', async () => { + const {bridge, storage} = await lockedProject(); + const manifest = json(storage, manifestPath); + storage.set(manifestPath, encoder.encode(JSON.stringify({...manifest, registry: 'https://manifest.test/'}))); + cacheKeys(storage).forEach(key => storage.delete(key)); + const application = served(registries.local); + const result = await restore(bridge, [], explicit(application)); + assert.deepEqual(result.registry, {url: 'https://registry.test/', source: 'application option'}); + assert.ok(application.requests.length && application.requests.every(url => url.startsWith('https://registry.test/'))); + cacheKeys(storage).forEach(key => storage.delete(key)); + const mirror = served(registries.local, 'https://manifest.test'); + const fromManifest = await restore(bridge, [], {registry: 'https://registry.test/', fetchImpl: mirror.fetchImpl}); + assert.deepEqual(fromManifest.registry, {url: 'https://manifest.test/', source: 'webfront.project.json'}); + assert.deepEqual(effectiveRegistry({}, {}), {url: 'https://registry.npmjs.org/', source: 'default'}); + assert.deepEqual(effectiveRegistry({registry: '/mirror/'}, {}), {url: '/mirror/', source: 'default'}); + await assert.rejects(restore(bridge, [], {registry: 'http://plain.test/', registryExplicit: true, fetchImpl: mirror.fetchImpl}), /HTTPS or the application origin/); +}); + +test('a registry path never leaves the application origin, however a URL parser reads it', () => { + // On an HTTPS page, "/\\host" resolves to https://host/, which an HTTPS check alone would accept. + globalThis.location = new URL('https://app.test/webfront-bootstrap.html'); + try { + assert.equal(usableRegistry({registry: '/mirror/', registryExplicit: true}).url, '/mirror/'); + for (const registry of ['//registry.test/', '/\\registry.test/', '/\\\\registry.test/', 'http://registry.test/']) + assert.throws(() => usableRegistry({registry, registryExplicit: true}), /HTTPS or the application origin/, registry); + assert.equal(usableRegistry({registry: 'https://registry.test/', registryExplicit: true}).url, 'https://registry.test/'); + } finally { delete globalThis.location; } +}); + +test('a bridge failure while reading a record is reported, not taken for a corrupted cache', async () => { + const {bridge} = await lockedProject(); + const failing = {cppFunction: name => async (...args) => { + if (name.endsWith('.read') && args[0].endsWith('.json') && args[0].includes('.webfront/')) throw new Error('Bridge disconnected'); + return bridge.cppFunction(name)(...args); + }}; + const source = served(registries.local); + await assert.rejects(restore(failing, ['--offline'], {}), /Bridge disconnected/); + await assert.rejects(restore(failing, [], explicit(source)), /Bridge disconnected/); + assert.equal(source.requests.length, 0, 'a valid package is not downloaded again'); +}); + +test('a changed archive or a package missing from the registry fails and keeps lock and valid cache intact', async () => { + const {bridge, storage} = await lockedProject(registries.genuine, ['webfront-fixture-lib@1.0.0', 'webfront-fixture-tampered@1.0.0']); + const lock = json(storage, lockPath); + const tampered = lock.packages['webfront-fixture-tampered@1.0.0']; + const lib = lock.packages['webfront-fixture-lib@1.0.0']; + cacheKeys(storage).filter(key => key.includes('tampered')).forEach(key => storage.delete(key)); + const lockBytes = storage.get(lockPath); + await assert.rejects(restore(bridge, [], explicit(served(registries.local))), /Integrity check failed/); + assert.equal(storage.get(lockPath), lockBytes); + assert.equal(await cacheState(bridge, tampered), 'missing'); + assert.equal(await cacheState(bridge, lib), 'valid'); + cacheKeys(storage).filter(key => key.includes('fixture-lib')).forEach(key => storage.delete(key)); + await assert.rejects(restore(bridge, [], explicit(served(registries.partial))), /webfront-fixture-lib: HTTP 404/); + assert.equal(storage.get(lockPath), lockBytes); +}); + +test('an interrupted restore keeps the packages already restored and resumes with the others', async () => { + const {bridge, storage, pending} = await lockedProject(); + cacheKeys(storage).forEach(key => storage.delete(key)); + const controller = new AbortController(); + const source = served(registries.local); + let packuments = 0; + const interrupting = async (url, options) => { + if (!String(url).endsWith('.tgz') && ++packuments === 2) controller.abort(new Error('Interrupted')); + return source.fetchImpl(url, options); + }; + await assert.rejects(restore(bridge, [], {...explicit(source), fetchImpl: interrupting, signal: controller.signal}), /Interrupted/); + assert.equal(pending(), 0, 'no staged transaction is left behind'); + const states = await Promise.all(Object.values(json(storage, lockPath).packages).map(node => cacheState(bridge, node))); + assert.deepEqual(states.sort(), ['missing', 'valid']); + const resumed = await restore(bridge, [], explicit(source)); + assert.equal(resumed.restored, 1); + assert.equal(resumed.verified, 1); +}); + +// Unpacked sizes of the cached packages of a project, from the files the lock lists. +const sizeOf = (storage, node) => node.files.reduce((total, path) => total + storage.get(`${packageRoot}/${node.key}/${path}`).length, 0); + +test('the bound of the unpacked graph counts the cached packages and is checked before publishing', async () => { + const {bridge, storage} = await lockedProject(); + const lock = json(storage, lockPath); + const [app, lib] = ['webfront-fixture-app@1.0.0', 'webfront-fixture-lib@1.0.0'].map(id => lock.packages[id]); + const limit = sizeOf(storage, app) + sizeOf(storage, lib) - 1; + cacheKeys(storage).filter(key => key.includes('fixture-lib')).forEach(key => storage.delete(key)); + const before = snapshot(storage); + const source = served(registries.local); + for (let attempt = 0; attempt < 2; attempt++) { + await assert.rejects(restorePackages(bridge, lock, {...explicit(source), limit}), /exceed .* MiB unpacked/); + assert.deepEqual(storage, before, 'nothing is published past the bound, and a second attempt keeps it'); + } + const restored = await restorePackages(bridge, lock, {...explicit(source), limit: limit + 1}); + assert.equal(restored.restored, 1); +}); + +test('a cached file larger than the bound is a corruption, listed offline and repaired online', async () => { + const {bridge, storage} = await lockedProject(); + const lock = json(storage, lockPath); + const lib = lock.packages['webfront-fixture-lib@1.0.0']; + const limit = 64 * 1024; + storage.set(`${packageRoot}/${lib.key}/index.js`, new Uint8Array(3 * 256 * 1024)); + const reads = []; + const counting = {cppFunction: name => async (...args) => { + if (name.endsWith('.read')) reads.push(args[0]); + return bridge.cppFunction(name)(...args); + }}; + await assert.rejects(restorePackages(counting, lock, {offline: true, limit}), /webfront-fixture-lib@1\.0\.0 \(corrupted\)/); + assert.equal(reads.filter(path => path.endsWith(`${lib.key}/index.js`)).length, 1, 'reading stops at the bound'); + const restored = await restorePackages(bridge, lock, {...explicit(served(registries.local)), limit}); + assert.equal(restored.restored, 1); + assert.equal(await cacheState(bridge, lib), 'valid'); +}); + +test('an invalid or absent lock is refused before any request or write', async () => { + const {bridge, storage} = await lockedProject(); + const source = served(registries.local); + for (const lock of ['{', JSON.stringify({format: 2, roots: {}, packages: {}})]) { + storage.set(lockPath, encoder.encode(lock)); + const before = snapshot(storage); + await assert.rejects(restore(bridge, [], explicit(source))); + assert.deepEqual(storage, before); + } + storage.delete(lockPath); + await assert.rejects(restore(bridge, [], explicit(source)), /No webfront-packages.lock.json: run wf install/); + await assert.rejects(restore(bridge, ['--force'], explicit(source)), /Usage: wf restore \[--offline\]/); + assert.equal(source.requests.length, 0); + const packages = Object.fromEntries(Array.from({length: 513}, (_, i) => [`p${i}@1.0.0`, {}])); + assert.throws(() => validateLock({format: 1, roots: {}, packages}), /exceeds 512 packages/); +}); + +test('wf install of a consistent lock repairs a corrupted cache and names its registry', async () => { + const {bridge, storage} = await lockedProject(); + const lib = json(storage, lockPath).packages['webfront-fixture-lib@1.0.0']; + storage.set(`${packageRoot}/${lib.key}/index.js`, encoder.encode('changed')); + const lines = []; + const result = await install(bridge, [], {...explicit(served(registries.local)), progress: line => lines.push(line)}); + assert.equal(result.restored, 1); + assert.deepEqual(result.registry, {url: 'https://registry.test/', source: 'application option'}); + assert.ok(lines.includes('Registry: https://registry.test/ (application option)')); + assert.equal(await cacheState(bridge, lib), 'valid'); +}); + +test('the registry fixture is reproducible', async () => { + const first = await registryFiles(syntheticPackages()); + const second = await registryFiles(syntheticPackages()); + assert.deepEqual(first, second); + assert.equal(JSON.parse(new TextDecoder().decode(first.files.get('webfront-fixture-lib')))['dist-tags'].latest, '1.1.0'); +}); diff --git a/test/unit/DeveloperTests.cpp b/test/unit/DeveloperTests.cpp index 4a9b3c5c..2ffe21a8 100644 --- a/test/unit/DeveloperTests.cpp +++ b/test/unit/DeveloperTests.cpp @@ -339,6 +339,30 @@ SCENARIO("The developer application needs an explicit project and a trusted envi REQUIRE_NOTHROW(app.bootstrap("developer", trusted)); REQUIRE_THROWS_AS(app.bootstrap("developer", trusted), std::logic_error); } + THEN("a registry that is neither HTTPS nor same-origin is refused") { + for (const auto* registry : {"http://registry.test/", "//registry.test/", "/\\registry.test/", "/mirror\\..\\x/", "registry/", ""}) { + auto options = trusted; + options.registry = registry; + REQUIRE_THROWS_AS(app.bootstrap("developer", options), std::invalid_argument); + } + } + } +} + +SCENARIO("The environment learns whether the application chose the npm registry") { + const DeveloperBootstrapOptions trusted{.environment = "https://example.test/env.tgz", .integrity = "sha512-abc"}; + GIVEN("no registry option") { + THEN("the default registry is passed and marked as not chosen, so the manifest's applies") { + REQUIRE(developer::bootstrapConfig(trusted) + == R"({"environment":"https://example.test/env.tgz","integrity":"sha512-abc","registry":"https://registry.npmjs.org/","registryExplicit":false})"); + } + } + GIVEN("a same-origin mirror chosen by the application") { + auto options = trusted; + options.registry = "/mirror/"; + THEN("it is passed as the application's choice") { + REQUIRE_THAT(developer::bootstrapConfig(options), Catch::Matchers::EndsWith(R"("registry":"/mirror/","registryExplicit":true})")); + } } } @@ -700,16 +724,24 @@ SCENARIO("A second opener of the project waits for a publication in progress ins } } WHEN("another store tries to publish from the state read before the first publication") { - auto competing = std::async(std::launch::async, [&] { - developer::Store other{project.path()}; - publishPair(other, "manifest-3", "lock-3", before); + // The refusal is read in its own thread: an exception object shared across threads by a future is + // reported as a race by ThreadSanitizer, whose runtime does not see libc++abi's reference counting. + auto competing = std::async(std::launch::async, [&]() -> std::string { + try { + developer::Store other{project.path()}; + publishPair(other, "manifest-3", "lock-3", before); + return "published"; + } catch (const std::exception& error) { + return error.what(); + } }); const auto waiting = competing.wait_for(std::chrono::milliseconds(300)); release.open(); publication.get(); THEN("its precondition is checked after the first publication, which wins") { CHECK(waiting == std::future_status::timeout); - REQUIRE_THROWS_WITH(competing.get(), Catch::Matchers::ContainsSubstring("changed since it was read")); + REQUIRE_THAT(competing.get(), Catch::Matchers::ContainsSubstring("changed since it was read")); + REQUIRE(projectState(publisher) == "manifest-2|lock-2"); } } } diff --git a/test/web/developer-specs.mjs b/test/web/developer-specs.mjs index 84b6d947..90183e74 100644 --- a/test/web/developer-specs.mjs +++ b/test/web/developer-specs.mjs @@ -153,6 +153,38 @@ try { delete manifest.dependencies.scheduler; await writeFile('webfront.project.json', JSON.stringify(manifest, null, 2)); assert(/Installed 3 packages/.test(await runtime.execute(['install'], context)), 'A consistent lock must install its exact graph'); + // wf restore rebuilds an emptied cache from the lock alone, from the application's local registry although the + // manifest names another one; --offline only checks the cache, without any request. + const requests = []; + const pageFetch = globalThis.fetch; + globalThis.fetch = (input, init) => { + requests.push(new URL(input instanceof Request ? input.url : input, location.href).href); + return pageFetch(input, init); + }; + try { + const emptied = await call('begin', '.webfront/developer/packages', true); + await call('commit', emptied); + const missing = await runtime.execute(['restore', '--offline'], context).then(() => '', error => error.message); + assert(/react@19\.3\.1 \(missing\)/.test(missing) && requests.length === 0, 'An offline check must list missing packages without any request'); + await writeFile('webfront.project.json', JSON.stringify({...manifest, registry: 'https://registry.invalid/'}, null, 2)); + const restored = await runtime.execute(['restore'], context); + assert(/Restored 3 of 3 packages/.test(restored) && restored.includes('Registry: /fixtures/registry/ (application option)'), `wf restore must use and name the application registry: ${restored}`); + assert(requests.length > 0 && requests.every(url => url.startsWith(`${location.origin}/fixtures/registry/`)), 'wf restore must contact the application registry only'); + requests.length = 0; + assert(/Cache verified offline: 3 packages/.test(await runtime.execute(['restore', '--offline'], context)) && requests.length === 0, 'A complete cache must verify offline'); + } finally { + globalThis.fetch = pageFetch; + } + await writeFile('webfront.project.json', JSON.stringify(manifest, null, 2)); + const previous = frame.contentWindow.location.href; + await runtime.execute(['preview'], context); + const piMounted = () => frame.contentDocument?.querySelector('output') && !frame.contentDocument.querySelector('[data-testid]'); + for (let attempt = 0; frame.contentWindow.location.href === previous || !piMounted(); ++attempt) { + if (attempt === 300) throw new Error('The preview did not build from the restored cache'); + await delay(50); + } + const absent = await runtime.execute(['install', 'webfront-fixture-absent'], context).then(() => '', error => error.message); + assert(/HTTP 404/.test(absent), 'A package absent from the registry must reject'); const failed = await runtime.execute(['install', 'INVALID-NPM-NAME'], context).then(() => false, () => true); assert(failed, 'Missing packages must reject'); assert(JSON.stringify(await runtime.readLock(webFront)) === JSON.stringify(lock), 'A failed install must preserve the lock');