An open-source, self-hosted system for apps built with web technologies.
Unify verification and consume released SDK contracts
zohayrslileh8a6e5494cc28
diff --git a/README.md b/README.mdindex e148fe9..22cb3db 100644--- a/README.md+++ b/README.md@@ -54,6 +54,12 @@ bun run pack`verify` checks the source contracts and validates the packed System from aclean installation.+`check` performs static checks, `build` creates distributable output, and `test`+runs Vitest assertions from `tests/`. Run `build` before testing built artifacts.+`verify` runs `check`, `build`, and `test` in order. Operational tooling belongs+in `scripts/`; tests and their fixtures belong in `tests/`. Verification uses+the committed dependency graph without local package substitutions.+## Related repositories- [`@phreshos/core`](https://github.com/PhreshOS/core) owns the public contractsdiff --git a/bun.lock b/bun.lockindex 8a58835..140d9f2 100644--- a/bun.lock+++ b/bun.lock@@ -7,8 +7,8 @@"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",- "@phreshos/core": "^0.1.42",- "@phreshos/react-ui": "^0.1.18",+ "@phreshos/core": "^0.1.43",+ "@phreshos/react-ui": "^0.1.19","@the-link/core": "^0.3.0","@the-link/http": "^0.1.1","@the-link/ipc": "^0.2.1",@@ -42,6 +42,7 @@"typescript": "^6.0.3","vite": "^8.2.1","vite-node": "^6.0.0",+ "vitest": "^4.1.10",},},},@@ -234,9 +235,9 @@"@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-nuhZIOLuI6TFQ32I/WnUx+SCPY7SdSKwgnFHydAuoS1+Z4BRcaP+RRJmGzl9lw+0OFF7UmaESf7KQRXaNLHypg=="],- "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-4Dd8Qnt76qnjzdaFs+HEcc8uWtdLfKmO7+g584XCEV9cjCvzaQReHU9C2SA8l1TKFCjD5shu7p2lI7FrCVM9Eg=="],+ "@phreshos/core": ["@phreshos/[email protected]", "", {}, "sha512-Z424mPzQ02azTsBDamBrxe+4iHW3UuromKqyvWBdZteGaPJff+XHXaRY4YJNruIXIuoe+vXz1Bni5ULTlXu/NQ=="],- "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@phreshos/core": "^0.1.42", "colorjs.io": "^0.7.1", "motion": "^13.2.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-IdSz2WDVhrNPMNnMQEHan5jzhhafyx7inwzShXugWa67hOFTgOTGbPd3jDzZOr7Kw4ruYja0c0xFUgA/wZ/w5Q=="],+ "@phreshos/react-ui": ["@phreshos/[email protected]", "", { "dependencies": { "@phreshos/core": "^0.1.43", "colorjs.io": "^0.7.1", "motion": "^13.2.0", "react-aria-components": "^1.20.0" }, "peerDependencies": { "react": "^19.2.0", "react-dom": "^19.2.0" } }, "sha512-F4xiDGvOrgEomSSy3HwieFOI3eiyhDQAbJeQNWHVXXVekT1lUonr86z0crEQigXEIqdFWBQg+GKf9mkcjlYKOw=="],"@react-types/shared": ["@react-types/[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" } }, "sha512-AzsuD9OfxTOZMMvTRhlN3oHBwOmFN7tDh27LzqmHt4+uOgPhJT7ZM7/kVs/8/o0WxayMUIk3hBmCFRHv1FUoag=="],@@ -272,6 +273,8 @@"@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],+ "@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],+"@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="],"@tailwindcss/node": ["@tailwindcss/[email protected]", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],@@ -316,6 +319,12 @@"@types/adm-zip": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q=="],+ "@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],++ "@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],++ "@types/estree": ["@types/[email protected]", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],+"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg=="],"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w=="],@@ -326,10 +335,26 @@"@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-BOVzne/NL162sMdResB25mUv+vWMF5NoAjNf09TeGlE7ZpszZWSD3winycicLJw72yeVsoCn/2kOhEuCvEShMA=="],+ "@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="],++ "@vitest/mocker": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ=="],++ "@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw=="],++ "@vitest/runner": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/utils": "4.1.11", "pathe": "^2.0.3" } }, "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw=="],++ "@vitest/snapshot": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog=="],++ "@vitest/spy": ["@vitest/[email protected]", "", {}, "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA=="],++ "@vitest/utils": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="],+"adm-zip": ["[email protected]", "", {}, "sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg=="],"aria-hidden": ["[email protected]", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],+ "assertion-error": ["[email protected]", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="],+"babel-plugin-react-compiler": ["[email protected]", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw=="],"baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-FwMjJJ7HnyZpWe+oWxegG0fezZyBZUagI5LZEoO3GCbtbKNwRfMH9Ue5d5v01PNePBy1QSfPSDTTeVL0Hb9EzA=="],@@ -342,6 +367,8 @@"cfonts": ["[email protected]", "", { "dependencies": { "supports-color": "^8", "window-size": "^1" }, "bin": { "cfonts": "bin/index.js" } }, "sha512-ZGEmN3W9mViWEDjsuPo4nK4h39sfh6YtoneFYp9WLPI/rw8BaSSrfQC6jkrGW3JMvV3ZnExJB/AEqXc/nHYxkw=="],+ "chai": ["[email protected]", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="],+"client-only": ["[email protected]", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="],"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],@@ -368,6 +395,10 @@"escalade": ["[email protected]", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],+ "estree-walker": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="],++ "expect-type": ["[email protected]", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="],+"fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],"framer-motion": ["[email protected]", "", { "dependencies": { "motion-dom": "^13.2.0", "motion-utils": "^13.0.0", "tslib": "^2.4.0" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["react", "react-dom"] }, "sha512-9E33ebgMaO33w1nN/jEdW8z3/GO483fMi4rqbMG9rt83XgW9QLKRe4NcmJ8s+fQ3O34++UHrIQwlIWGIWTITjA=="],@@ -478,16 +509,28 @@"sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.3", "@img/sharp-darwin-x64": "0.35.3", "@img/sharp-freebsd-wasm32": "0.35.3", "@img/sharp-libvips-darwin-arm64": "1.3.2", "@img/sharp-libvips-darwin-x64": "1.3.2", "@img/sharp-libvips-linux-arm": "1.3.2", "@img/sharp-libvips-linux-arm64": "1.3.2", "@img/sharp-libvips-linux-ppc64": "1.3.2", "@img/sharp-libvips-linux-riscv64": "1.3.2", "@img/sharp-libvips-linux-s390x": "1.3.2", "@img/sharp-libvips-linux-x64": "1.3.2", "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", "@img/sharp-libvips-linuxmusl-x64": "1.3.2", "@img/sharp-linux-arm": "0.35.3", "@img/sharp-linux-arm64": "0.35.3", "@img/sharp-linux-ppc64": "0.35.3", "@img/sharp-linux-riscv64": "0.35.3", "@img/sharp-linux-s390x": "0.35.3", "@img/sharp-linux-x64": "0.35.3", "@img/sharp-linuxmusl-arm64": "0.35.3", "@img/sharp-linuxmusl-x64": "0.35.3", "@img/sharp-webcontainers-wasm32": "0.35.3", "@img/sharp-win32-arm64": "0.35.3", "@img/sharp-win32-ia32": "0.35.3", "@img/sharp-win32-x64": "0.35.3" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q=="],+ "siginfo": ["[email protected]", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="],+"source-map-js": ["[email protected]", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],+ "stackback": ["[email protected]", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="],++ "std-env": ["[email protected]", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="],+"supports-color": ["[email protected]", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="],"tailwindcss": ["[email protected]", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="],"tapable": ["[email protected]", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],+ "tinybench": ["[email protected]", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="],++ "tinyexec": ["[email protected]", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="],+"tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],+ "tinyrainbow": ["[email protected]", "", {}, "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw=="],+"tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],"tsx": ["[email protected]", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-FDf4L4sYzKtzWYhU/Xm0AQFdTjdIxNo9ElTf2mxXM6k8YMHXzYUe4yODVaXP4V9uMFbVg8c0qyBccK2OOxb45Q=="],@@ -506,13 +549,16 @@"vite-node": ["[email protected]", "", { "dependencies": { "cac": "^7.0.0", "es-module-lexer": "^2.0.0", "obug": "^2.1.1", "pathe": "^2.0.3", "vite": "^8.0.0" }, "bin": { "vite-node": "dist/cli.mjs" } }, "sha512-oj4PVrT+pDh6GYf5wfUXkcZyekYS8kKPfLPXVl8qe324Ec6l4K2DUKNadRbZ3LQl0qGcDz+PyOo7ZAh00Y+JjQ=="],+ "vitest": ["[email protected]", "", { "dependencies": { "@vitest/expect": "4.1.11", "@vitest/mocker": "4.1.11", "@vitest/pretty-format": "4.1.11", "@vitest/runner": "4.1.11", "@vitest/snapshot": "4.1.11", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.11", "@vitest/browser-preview": "4.1.11", "@vitest/browser-webdriverio": "4.1.11", "@vitest/coverage-istanbul": "4.1.11", "@vitest/coverage-v8": "4.1.11", "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw=="],++ "why-is-node-running": ["[email protected]", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="],+"window-size": ["[email protected]", "", { "dependencies": { "define-property": "^1.0.0", "is-number": "^3.0.0" }, "bin": { "window-size": "cli.js" } }, "sha512-5D/9vujkmVQ7pSmc0SCBmHXbkv6eaHwXEx65MywhmUMsI8sGqJ972APq1lotfcwMKPFLuCFfL8xGHLIp7jaBmA=="],"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],"yallist": ["[email protected]", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],-"@tailwindcss/node/lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="],diff --git a/package.json b/package.jsonindex ca4f42f..7759143 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "phreshos","displayName": "PhreshOS",- "version": "0.1.63",+ "version": "0.1.64","description": "The PhreshOS server, desktop, and authoritative system runtime.","type": "module","private": true,@@ -30,15 +30,14 @@"build": "vite-node scripts/build.ts","start": "node --run build && NODE_ENV=development node dist/server/main.js","pack": "node --run build && vite-node scripts/pack.ts",- "verify:contracts": "vite-node scripts/verify-contracts.ts",- "verify:distribution": "node scripts/verify-distribution.mjs",- "verify": "node --run check && node --run verify:contracts && node --run verify:distribution"+ "verify": "node --run check && node --run build && node --run test",+ "test": "vitest run --project default"},"dependencies": {"@fontsource/roboto": "^5.3.0","@hono/node-server": "^2.1.1",- "@phreshos/core": "^0.1.42",- "@phreshos/react-ui": "^0.1.18",+ "@phreshos/core": "^0.1.43",+ "@phreshos/react-ui": "^0.1.19","@the-link/core": "^0.3.0","@the-link/http": "^0.1.1","@the-link/ipc": "^0.2.1",@@ -71,6 +70,7 @@"tailwindcss": "^4.3.3","typescript": "^6.0.3","vite": "^8.2.1",- "vite-node": "^6.0.0"+ "vite-node": "^6.0.0",+ "vitest": "^4.1.10"}}diff --git a/scripts/contracts/appearance.ts b/scripts/contracts/appearance.tsdeleted file mode 100644index cabcacb..0000000--- a/scripts/contracts/appearance.ts+++ /dev/null@@ -1,93 +0,0 @@-import assert from "node:assert/strict"-import Keyv from "keyv"-import { defaultAppearance, parseAppearance } from "@phreshos/core"-import AppearanceManager from "@server/core/appearance-manager"-import FileManager from "@libs/file-manager"-import UploadManager from "@server/core/upload-manager"-import { mkdtemp, rm } from "node:fs/promises"-import { tmpdir } from "node:os"-import { join } from "node:path"--assert.deepEqual(parseAppearance(defaultAppearance), defaultAppearance)-assert.throws(() => parseAppearance({}))-assert.throws(() => parseAppearance({- ...defaultAppearance,- colors: { ...defaultAppearance.colors, accent: defaultAppearance.colors.light.primary }-}))-assert.throws(() => parseAppearance({ ...defaultAppearance, spacing: { light: 12, dark: 12 } }))-assert.throws(() => parseAppearance({- ...defaultAppearance,- material: {- ...defaultAppearance.material,- dark: { ...defaultAppearance.material.dark, grain: 1.01 }- }-}))-assert.throws(() => parseAppearance({- ...defaultAppearance,- transaction: { duration: 120 }-}))--const store = new Keyv()-const directory = await mkdtemp(join(tmpdir(), "phresh-appearance-"))-const uploads = new UploadManager(new FileManager(directory))-const manager = await AppearanceManager.open(store, uploads)--assert.deepEqual(manager.value, defaultAppearance)-assert(Object.isFrozen(manager.value))-assert.deepEqual(await store.get("appearance"), defaultAppearance)--for (const theme of ["light", "dark"] as const) {- for (const role of ["background", "foreground", "primary", "secondary", "success", "warning", "danger", "info"] as const) {- const color = "oklch(60% 0.2 260)"- const colors = {- ...manager.value.colors,- [theme]: { ...manager.value.colors[theme], [role]: color }- }-- await manager.update({ ...manager.value, colors })- assert.equal(manager.value.colors[theme][role], color)- assert.equal((await store.get("appearance")).colors[theme][role], color)- assert(Object.isFrozen(manager.value.colors[theme]))-- const current = manager.value- const invalidColors = {- ...current.colors,- [theme]: { ...current.colors[theme], [role]: "" }- }-- await assert.rejects(manager.update({ ...current, colors: invalidColors }))- assert.equal(manager.value, current)- assert.deepEqual(await store.get("appearance"), current)- }-}--const reopened = await AppearanceManager.open(store, uploads)-assert.deepEqual(reopened.value, manager.value)--const shadow = {- light: { x: -3, y: 12, blur: 30, spread: 2, opacity: 0.25 },- dark: { x: 2, y: 6, blur: 18, spread: -1, opacity: 0.12 }-}-await manager.update({ ...manager.value, shadow })-assert.deepEqual(manager.value.shadow, shadow)-assert.deepEqual((await store.get("appearance")).shadow, shadow)-assert.deepEqual((await AppearanceManager.open(store, uploads)).value.shadow, shadow)--for (const invalid of [{ ...shadow.light, blur: -1 }, { ...shadow.light, opacity: 1.1 }, { ...shadow.light, x: Infinity }]) {- await assert.rejects(manager.update({ ...manager.value, shadow: { ...shadow, light: invalid } }))- assert.deepEqual(manager.value.shadow, shadow)-}--const updated = {- ...manager.value,- transaction: { duration: 180, easing: [0.25, 0.1, 0.25, 1] as const }-}--await manager.update(updated)--assert.deepEqual(manager.value, updated)-assert.deepEqual(await store.get("appearance"), updated)-assert.equal(await store.get("appearance:colors"), undefined)-assert.equal(await store.get("appearance:theme"), undefined)--await rm(directory, { recursive: true, force: true })diff --git a/scripts/contracts/client-launch.ts b/scripts/contracts/client-launch.tsdeleted file mode 100644index b42d1b4..0000000--- a/scripts/contracts/client-launch.ts+++ /dev/null@@ -1,27 +0,0 @@-import assert from "node:assert/strict"-import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"-import type { ClientLaunch } from "@phreshos/core"-import type Program from "@server/core/link-manager/auth-manager/program-manager/program"--const manager = {- authManager: {- processManager: {- processes: new Map()- }- }-}--const program = {- client: {},- title: "Declared title"-}--const shape = (overrides: ClientLaunch) => ProgramManager.prototype.clientShape.call(- manager as unknown as ProgramManager,- program as unknown as Program,- overrides-)--assert.equal(shape({ title: "Fetched title" }).title, "Fetched title")-assert.equal(shape({}).title, "Declared title")-assert.throws(() => shape({ title: 42 } as unknown as ClientLaunch), /title must be text/)diff --git a/scripts/contracts/client-sandbox.ts b/scripts/contracts/client-sandbox.tsdeleted file mode 100644index ed690a4..0000000--- a/scripts/contracts/client-sandbox.ts+++ /dev/null@@ -1,44 +0,0 @@-import assert from "node:assert/strict"-import Process from "@server/core/link-manager/auth-manager/process-manager/process"-import Window from "@server/core/link-manager/auth-manager/process-manager/window"-import type Program from "@server/core/link-manager/auth-manager/program-manager/program"-import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"--const process = new Process(-- "process",-- null,-- { identity: "program" } as Program,-- {},-- { server: null, client: null, options: {} },-- null,-- {} as HostTraffic,-- false-)--process.startClient(new Window(-- { title: "Client", layer: "window" },-- { x: 0, y: 0 },-- { width: 640, height: 480 },-- 1,-- false-), false)--assert.equal(process.hosted().client?.sameOrigin, false)--assert.equal(process.setClientSameOrigin(true), true)-assert.equal(process.setClientSameOrigin(true), false)--assert.equal(process.hosted().client?.sameOrigin, true)diff --git a/scripts/contracts/client-surface.ts b/scripts/contracts/client-surface.tsdeleted file mode 100644index 6da936c..0000000--- a/scripts/contracts/client-surface.ts+++ /dev/null@@ -1,326 +0,0 @@-import assert from "node:assert/strict"-import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"-import ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"-import { parseLocalWindowTransaction } from "@client/view/components/desktop-host/local-window"-import host from "@client/view/components/desktop-host/host"-import LocalWindows from "@client/view/components/window-manager/local-windows"-import type { LocalWindowEntry } from "@client/view/components/window-manager/local-windows"-import ServerWindow from "@server/core/link-manager/auth-manager/process-manager/window"-import type { LocalWindowState } from "@client/view/components/desktop-host/local-window"-import type { AppearanceTransaction, WaitedTransaction, WindowLayer } from "@phreshos/core"--type RequestedTransaction = AppearanceTransaction | WaitedTransaction--const authoritativeWindow = new ServerWindow(- { title: "Target", layer: "over" },- { x: 0, y: 0 },- { width: 100, height: 100 },- 1,- false-)--assert.equal("surface" in authoritativeWindow, false)-assert.equal("surface" in authoritativeWindow.toJSON(), false)--const transaction = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })-const visibility = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })!--assert.throws(() => parseLocalWindowTransaction({}), /must provide duration and easing/)-assert.throws(() => parseLocalWindowTransaction({ wait: true }), /must provide duration and easing/)-assert.throws(() => parseLocalWindowTransaction({ duration: 60_001, easing: "linear" }), /0 to 60000/)-assert.throws(() => parseLocalWindowTransaction({ duration: 120 }), /must provide duration and easing/)-assert.throws(() => parseLocalWindowTransaction({ duration: 120, easing: "linear", wait: false }), /must be true/)-assert.throws(() => parseLocalWindowTransaction({ unknown: true }), /no "unknown" field/)--const ordinary = client("window")-const bare = client("over")-const clients = new Map([- ["ordinary", { identity: "ordinary:0", client: ordinary }],- ["bare", { identity: "bare:0", client: bare }]-]) as unknown as ReadonlyMap<string, LocalWindowEntry>-const byProcess = new Map([["ordinary", ordinary], ["bare", bare]])-const first = new LocalWindows(clients, identity => byProcess.get(identity) as never ?? null)-const second = new LocalWindows(clients, identity => byProcess.get(identity) as never ?? null)--await first.move("ordinary", { x: 40, y: 50 })-await first.move("bare", { x: 60, y: 70 })--assert.deepEqual(first.state("ordinary").position, { x: 40, y: 50 })-assert.deepEqual(first.state("bare").position, { x: 60, y: 70 })-assert.deepEqual(second.state("ordinary").position, { x: 0, y: 0 })-assert.deepEqual(ordinary.window.position, { x: 0, y: 0 })--// A reader reports the rectangle currently painted by the browser. Policy-// such as fill/restore still needs the underlying projection, because a-// relative full-surface value and its measured pixels are not equivalent.-first.represent("ordinary", () => ({ position: { x: 0, y: 0 }, size: { width: 1200, height: 800 } }))-assert.deepEqual(first.state("ordinary").size, { width: 1200, height: 800 })-assert.deepEqual(first.projection("ordinary").size, { width: 300, height: 200 })-first.represent("ordinary", null)--first.represent("bare", () => ({ position: { x: 65, y: 75 }, size: { width: 290, height: 190 } }))-assert.deepEqual(first.state("bare").position, { x: 65, y: 75 })-assert.deepEqual(first.state("bare").size, { width: 290, height: 190 })-first.represent("bare", null)--// An unrelated full snapshot is not a Window change and must not erase a-// local ordinary-window command.-first.reconcile(clients)-assert.deepEqual(first.state("ordinary").position, { x: 40, y: 50 })--ordinary.window.position = { x: 15, y: 25 }-bare.window.position = { x: 20, y: 30 }-first.reconcile(clients)--assert.deepEqual(first.state("ordinary").position, { x: 15, y: 25 })-assert.deepEqual(first.state("bare").position, { x: 60, y: 70 })--const matchingAuthority = first.move("ordinary", { x: 30, y: 40 }, { duration: 120, easing: "ease-out", wait: true })-const matchingRevision = represented(first, "ordinary:0").geometryAnimation!.revision-ordinary.window.position = { x: 30, y: 40 }-first.reconcile(clients)-assert.equal(represented(first, "ordinary:0").geometryAnimation!.revision, matchingRevision)-first.complete("ordinary", "geometry", matchingRevision)-await matchingAuthority--const waiting = first.geometry("bare", {- position: { x: 80, y: 90 },- size: { width: 320, height: 240 }-}, transaction)-const geometryRevision = represented(first, "bare:0").geometryAnimation!.revision-first.complete("bare", "geometry", geometryRevision)-await waiting-assert.equal(represented(first, "bare:0").geometryAnimation, null)--const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, easing: "ease-out", wait: true })-await first.move("bare", { x: 120, y: 130 })-await assert.rejects(interrupted, /interrupted/)--const following = first.follow("bare", "ordinary", transaction)-const followRevision = represented(first, "bare:0").geometryAnimation!.revision-first.reconcile(clients)-assert.equal(represented(first, "bare:0").geometryAnimation!.revision, followRevision)-first.complete("bare", "geometry", followRevision)-await following-assert.deepEqual(first.state("bare").position, first.state("ordinary").position)--// Following reads authority, never another Desktop-local representation.-await first.move("ordinary", { x: 150, y: 160 })-assert.deepEqual(first.state("bare").position, ordinary.window.position)-ordinary.window.position = { x: 170, y: 180 }-first.reconcile(clients)-assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })--await first.unfollow("bare", transaction)-assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })-ordinary.window.position = { x: 190, y: 200 }-first.reconcile(clients)-assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })--// Default following can be disabled on ordinary windows and enabled on bare ones.-await first.unfollow("ordinary")-ordinary.window.position = { x: 210, y: 220 }-first.reconcile(clients)-assert.deepEqual(first.state("ordinary").position, { x: 190, y: 200 })-await first.follow("ordinary", "ordinary")-assert.deepEqual(first.state("ordinary").position, { x: 210, y: 220 })-await first.follow("bare", "ordinary")-await first.move("bare", { x: 125, y: 135 })-ordinary.window.title = "Renamed"-first.reconcile(clients)-assert.equal(first.state("bare").title, "Renamed")-assert.deepEqual(first.state("bare").position, { x: 125, y: 135 })-ordinary.window.position = { x: 230, y: 240 }-first.reconcile(clients)-assert.deepEqual(first.state("bare").position, ordinary.window.position)--// Stored geometry cannot cancel an in-progress maximize presentation.-const maximizing = first.maximize("bare", true, transaction)-const maximizeRevision = represented(first, "bare:0").geometryAnimation!.revision-await first.move("bare", { x: 9, y: 10 }, transaction)-assert.equal(represented(first, "bare:0").geometryAnimation!.revision, maximizeRevision)-first.complete("bare", "geometry", maximizeRevision)-await maximizing-await first.maximize("bare", false)-const toInterrupt = first.maximize("bare", true, transaction)-await first.minimize("bare", true)-await assert.rejects(toInterrupt, /was minimized/)-await first.minimize("bare", false)-await first.maximize("bare", false)--// Minimize and maximize never overwrite the retained geometry or each other.-await first.maximize("bare", true)-await first.minimize("bare", true)-await first.geometry("bare", { position: { x: 11, y: 12 }, size: { width: 111, height: 112 } }, transaction)-assert.equal(first.projection("bare").geometryAnimation, null)-assert.equal(first.state("bare").maximized, true)-assert.equal(first.state("bare").minimized, true)-await first.minimize("bare", false)-assert.equal(first.state("bare").maximized, true)-await first.maximize("bare", false)-assert.deepEqual(first.state("bare").position, { x: 11, y: 12 })-assert.deepEqual(first.state("bare").size, { width: 111, height: 112 })-await first.follow("bare", "ordinary")-ordinary.window.maximized = true-ordinary.window.minimized = true-first.reconcile(clients)-assert.equal(first.state("bare").maximized, true)-assert.equal(first.state("bare").minimized, true)-ordinary.window.maximized = false-ordinary.window.minimized = false-first.reconcile(clients)--const surfaceWaiting = first.addSurface("bare", visibility)-const surfaceRevision = surface(first, "bare:0").transition!.revision-first.complete("bare", "surface", surfaceRevision)-await surfaceWaiting-assert.equal(surface(first, "bare:0").transition, null)-assert.equal(surface(first, "bare:0").visible, true)--const surfaceRemoval = first.removeSurface("bare", visibility)-const removalRevision = surface(first, "bare:0").transition!.revision-assert.equal(surface(first, "bare:0").visible, false)-first.complete("bare", "surface", removalRevision)-await surfaceRemoval-assert.equal(represented(first, "bare:0").surface, null)--assert.equal(represented(second, "bare:0").surface, null)--first.release("bare")-assert.deepEqual(first.state("bare").position, bare.window.position)-assert.equal(represented(first, "bare:0").surface, null)--const removed = first.move("bare", { x: 140, y: 150 }, { duration: 200, easing: "ease-out", wait: true })-const remaining = clients.get("ordinary")-assert(remaining)-first.reconcile(new Map([["ordinary", remaining]]))-await assert.rejects(removed, /representation was removed/)--const parent = {- identity: "parent",- reference: "parent-reference",- name: "manager",- program: "program",- options: {},- startedAt: new Date(),- server: null,- client: null-}-const requester = {- identity: "requester",- reference: "requester-reference",- program: "program",- parent,- client: { window: { process: "requester", layer: "over" } }-}-const target = {- identity: "target",- reference: "target-reference",- program: "program",- client: { window: { process: "target", layer: "over", position: { x: 10, y: 20 } } }-}-const processes = new Map<string, object>([[parent.identity, parent], [requester.identity, requester], [target.identity, target]])-const calls: unknown[][] = []-const localWindow = {- state(identity: string) { return { position: identity === "target" ? { x: 70, y: 80 } : { x: 0, y: 0 } } },- move(identity: string, value: unknown, motion: RequestedTransaction | undefined) { calls.push(["move", identity, value, motion]) },- follow(identity: string, followed: string, motion: RequestedTransaction | undefined) { calls.push(["follow", identity, followed, motion]) },- unfollow(identity: string, motion: RequestedTransaction | undefined) { calls.push(["unfollow", identity, motion]) },- addSurface(identity: string, motion: RequestedTransaction) { calls.push(["add", identity, motion]) },- removeSurface(identity: string, motion: RequestedTransaction) { calls.push(["remove", identity, motion]) }-}-const processManager = {- processes,- front: ClientProcessManager.prototype.front,- async ownFrame() {},- async releaseFrame() {},- async unsubscribeFrame() {}-}-const authManager = {- processManager,- programManager: { programs: new Map([["program", {- reference: "program-reference",- identity: "program",- assetId: "00000000-0000-4000-8000-000000000000",- installed: true,- name: "Program",- version: null,- description: null,- hasAgent: false,- server: null,- client: null- }]]) },-}-const request = host(authManager as never, requester.identity, () => ({ size: { width: 1, height: 1 } }), () => "owner", localWindow as never)--assert.deepEqual(await request("desktopViewport"), [{ size: { width: 1, height: 1 } }])-const targetAddress = { identity: target.identity, reference: target.reference }-const requesterAddress = { identity: requester.identity, reference: requester.reference }-processes.delete(parent.identity)-const parentAnswer = await request("parent", requesterAddress)-assert(Array.isArray(parentAnswer))-const retainedParent = parentAnswer[0] as { identity: string }-assert.equal(retainedParent.identity, parent.identity)-await request("windowLocalMove", requesterAddress, { x: 70, y: 80 })-await request("windowLocalFollow", requesterAddress, targetAddress, visibility)-await request("windowLocalUnfollow", requesterAddress, visibility)-await request("windowLocalSurfaceAdd", requesterAddress, undefined, visibility)-await request("windowLocalSurfaceRemove", requesterAddress, undefined, visibility)--assert.deepEqual(calls, [- ["move", "requester", { x: 70, y: 80 }, undefined],- ["follow", "requester", "target", visibility],- ["unfollow", "requester", visibility],- ["add", "requester", visibility],- ["remove", "requester", visibility]-])-assert.deepEqual(target.client.window.position, { x: 10, y: 20 })-await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress, undefined, { identity: "unexpected" }), /no "identity" field/)-await assert.rejects(request("windowLocalSurfaceAdd", targetAddress), /current Client Context/)-await assert.rejects(request("windowLocalSurfaceAdd", { ...requesterAddress, reference: "wrong" }), /represented by this handle does not exist/)-requester.client.window.layer = "window"-await request("windowLocalMove", requesterAddress, { x: 0, y: 0 })-await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress), /already owns its host Surface/)-await assert.rejects(request("windowLocalSurfaceRemove", requesterAddress), /already owns its host Surface/)-requester.client.window.layer = "over"--const lifecycle: string[] = []-const boundary = new ClientProcessBoundary(- "requester",- { contentWindow: null } as unknown as HTMLIFrameElement,- authManager as never,- () => ({ size: { width: 1, height: 1 } }),- {} as never,- { release(identity: string) { lifecycle.push(identity) } } as never-)--await boundary.own("first-owner")-await boundary.own("second-owner")-await boundary.release()--assert.deepEqual(lifecycle, ["requester", "requester"])--function client(layer: WindowLayer) {- return {- window: {- title: "Window",- position: { x: 0, y: 0 },- size: { width: 300, height: 200 },- minimized: false, maximized: false,- layer,- depth: 1- }- }-}--function represented(windows: LocalWindows, identity: string): LocalWindowState {- const value = windows.windows.get(identity)- assert(value)- return value-}--function surface(windows: LocalWindows, identity: string) {- const value = represented(windows, identity).surface- assert(value)- return value-}diff --git a/scripts/contracts/client-system-access.ts b/scripts/contracts/client-system-access.tsdeleted file mode 100644index e549fe6..0000000--- a/scripts/contracts/client-system-access.ts+++ /dev/null@@ -1,128 +0,0 @@-import assert from "node:assert/strict"-import { homedir } from "node:os"-import { resolve } from "node:path"-import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"-import SystemAccess from "@client/view/components/desktop-host/system-access"-import { permissionCatalog } from "@server/core/permissions"-import type { PermissionName, Permissions } from "@phreshos/core"--const owner = { identity: "process:owner", program: "owner" }-const sibling = { identity: "process:sibling", program: "owner" }-const outside = { identity: "process:outside", program: "outside" }-let permissions: Permissions = {}--const authManager = {- processManager: { processes: new Map([- [owner.identity, owner],- [sibling.identity, sibling],- [outside.identity, outside]- ]) },- async grantsPermission(process: string, name: PermissionName, values: readonly string[]) {-- assert.equal(process, owner.identity)-- return permissionCatalog.allows(name, values as never, permissions)- },- async grantsStorage(process: string, path: string, operation?: "read" | "write" | "delete") {-- assert.equal(process, owner.identity)-- return permissionCatalog.allowsStorage(permissions.all ?? null, permissions.storage ?? null, path, operation)- }-} as unknown as AuthManager--const access = new SystemAccess(authManager, owner.identity)-const ownProgram = { identity: "owner" }-const outsideProgram = { identity: "outside" }-const ownService = { program: "owner", process: "main", endpoint: "server" } as const-const ownExactService = { process: sibling.identity, endpoint: "client" } as const-const outsideService = { program: "outside", process: "main", endpoint: "server" } as const--assert(access.ownsProgram(ownProgram))-assert(!access.ownsProgram(outsideProgram))-assert(access.ownsProcess(sibling))-assert(!access.ownsProcess(outside))-assert(access.ownsService(ownService))-assert(access.ownsService(ownExactService))-assert(!access.ownsService(outsideService))-assert.equal(await access.program(ownProgram as never), ownProgram)-assert.equal(await access.service(ownService), ownService)-assert.equal(await access.service(ownExactService), ownExactService)-await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)-await assert.rejects(access.process(outside), /Execution is not permitted/)-await assert.rejects(access.service(outsideService), /Execution is not permitted/)-await assert.rejects(access.requirePrograms(), /Execution is not permitted/)-await assert.rejects(access.requireNetwork("https://api.example.com/v1/users"), /Execution is not permitted/)-await assert.rejects(access.requireStorage("/Users/person/Documents/report.txt", "read"), /Execution is not permitted/)-await assert.rejects(access.require("uploads", []), /Execution is not permitted/)-await assert.rejects(access.require("appearance", []), /Execution is not permitted/)-await assert.rejects(access.require("desktopPreferences", []), /Execution is not permitted/)--permissions = { services: ["outside"] }--assert.equal(await access.service(outsideService), outsideService)-await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)-await assert.rejects(access.process(outside), /Execution is not permitted/)-await assert.rejects(access.requirePrograms(), /Execution is not permitted/)--permissions = { services: [] }--assert.equal(await access.service(outsideService), outsideService)-await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)-await assert.rejects(access.requirePrograms(), /Execution is not permitted/)--permissions = { programs: ["outside"] }--assert.equal(await access.program(outsideProgram as never), outsideProgram)-assert.equal(await access.process(outside), outside)-assert.equal(await access.service(outsideService), outsideService)-await assert.rejects(access.requirePrograms(), /Execution is not permitted/)--permissions = { programs: [] }--await access.requirePrograms()-assert.equal(await access.program(outsideProgram as never), outsideProgram)-assert.equal(await access.service(outsideService), outsideService)--permissions = { appearance: [], desktopPreferences: [] }--await access.require("appearance", [])-await access.require("desktopPreferences", [])-await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)--permissions = { uploads: [] }--await access.require("uploads", [])-await assert.rejects(access.requireAll(), /Execution is not permitted/)--permissions = { network: ["https://*.example.com/v1/**"] }--await access.requireNetwork("https://api.example.com/v1/users")-await assert.rejects(access.requireNetwork("https://example.com/v1/users"), /Execution is not permitted/)-await assert.rejects(access.requireNetwork("https://api.example.com/v2/users"), /Execution is not permitted/)--permissions = { storage: ["read:Documents/**", "write:Documents/report.txt"] }--await access.requireStorage(resolve(homedir(), "Documents/report.txt"))-await access.requireStorage(resolve(homedir(), "Documents/report.txt"), "read")-await access.requireStorage(resolve(homedir(), "Documents/report.txt"), "write")-await assert.rejects(access.requireStorage(resolve(homedir(), "Documents/other.txt"), "write"), /Execution is not permitted/)-await assert.rejects(access.requireStorage(resolve(homedir(), "Documents/report.txt"), "delete"), /Execution is not permitted/)-await assert.rejects(access.requireStorage(homedir()), /Execution is not permitted/)--permissions = { storage: [] }--await access.requireStorage(homedir())--permissions = { all: [] }--assert.equal((await access.program(outsideProgram as never)).identity, "outside")-assert.equal((await access.process(outside)).identity, outside.identity)-assert.equal(await access.service(outsideService), outsideService)-await access.requirePrograms()-await access.require("appearance", [])-await access.require("desktopPreferences", [])-await access.requireNetwork("wss://events.example.com/socket")-await access.requireStorage("/any/native/path", "delete")-await access.require("uploads", [])-await access.requireAll()diff --git a/scripts/contracts/endpoint-services.ts b/scripts/contracts/endpoint-services.tsdeleted file mode 100644index 170cec0..0000000--- a/scripts/contracts/endpoint-services.ts+++ /dev/null@@ -1,125 +0,0 @@-import assert from "node:assert/strict"-import EndpointServices from "@server/core/link-manager/auth-manager/process-manager/endpoint-services"-import Program from "@server/core/link-manager/auth-manager/program-manager/program"-import type Process from "@server/core/link-manager/auth-manager/process-manager/process"-import type { ServiceKey } from "@phreshos/core"--const privateProgram = new Program({- identity: "private-program",- server: { location: ".", startCommand: "true" }-})-const documentedProgram = new Program({- identity: "documented-program",- agent: "agent.md",- server: { location: ".", startCommand: "true" },- client: { location: "." }-})--assert.equal(privateProgram.record().hasAgent, false)-assert.equal(documentedProgram.record().hasAgent, true)-assert.throws(() => new Program({- identity: "invalid-program",- agent: "",- server: { location: ".", startCommand: "true" }-}), /agent documentation/)--const program = new Program({- identity: "program",- server: { location: ".", startCommand: "true" },- client: { location: "." }-})-const waits: string[] = []--function process(identity: string, name: string | null, ready = true, service = true) {- const waiters = new Set<() => void>()- const server = { ready, service }- return {- identity,- name,- reference: `${identity}-reference`,- program,- launch: {- server: { service },- client: { service }- },- server,- client: { service },- waitReady(endpoint: "server" | "client", notify: () => void) {-- waits.push(endpoint)- if (endpoint === "client" || server.ready) notify()- else waiters.add(notify)- return () => { waiters.delete(notify) }- },- becomeReady() {- server.ready = true- for (const notify of waiters) notify()- waiters.clear()- }- } as unknown as Process & { becomeReady(): void }-}--let provider = process("0b231437-513b-4907-8041-c497279c07fa", "main")--const services = new EndpointServices(key => {- if (key.program !== undefined && key.program !== program.identity) return null- if (key.program === undefined && key.process !== provider.identity) return null- if (key.process !== provider.identity && key.process !== provider.name) return null- if ((key.endpoint === "server" ? provider.server?.service : provider.client?.service) !== true) return null- return { process: provider, endpoint: key.endpoint }-})--const key = { program: "program", process: "main", endpoint: "server" } satisfies ServiceKey-const clientKey = { ...key, endpoint: "client" } satisfies ServiceKey-const exact = { ...key, process: provider.identity }-const global = { process: provider.identity, endpoint: "server" } satisfies ServiceKey-const lifecycle: string[] = []-const publications: unknown[] = []--await assert.rejects(() => services.waitReady(key, -1), /non-negative finite number/)--services.follow(key, "lifecycle", null, event => lifecycle.push(event))-services.follow(key, "events", "change", (_event, payload) => publications.push(payload))--await services.started(provider, "server")-assert.equal(services.exists(key), true)-assert.equal(services.exists(global), true)-assert.deepEqual(lifecycle, ["start"])-await services.waitReady(key, 0)-await services.waitReady(clientKey, 0)-assert.deepEqual(waits, ["server", "client"])--await services.emit(provider, "server", "ignored", 1)-await services.emit(provider, "server", "change", 2)-assert.deepEqual(publications, [2])--provider.server = null-await services.stopped(provider, "server", true)-assert.equal(services.exists(key), false)-assert.deepEqual(lifecycle, ["start", "stop"])-await assert.rejects(() => services.waitReady(key, 0), /timeout/)--// A name address follows a replacement, while an identity address does not.-provider = process("234448b9-4661-4bda-8028-ae75438bf5be", "main", false)-await services.started(provider, "server")-assert.equal(services.exists(key), true)-assert.equal(services.exists(exact), false)-assert.equal(services.exists(global), false)--const ready = services.waitReady(key, 100)-provider.becomeReady()-await ready--// Server and Client remain distinct coordinates for the same Process.-assert.equal(services.exists(clientKey), true)--const unconfiguredProgram = new Program({- identity: "unconfigured",- server: { location: ".", startCommand: "true" }-})-assert.equal(unconfiguredProgram.server?.service, false)--// One incarnation can override the Program default without changing the Program.-provider = process("2c6f42b0-7847-4f80-8373-0cba3f48636b", "main", true, false)-await services.started(provider, "server")-assert.equal(services.exists(key), false)diff --git a/scripts/contracts/gateway-address.ts b/scripts/contracts/gateway-address.tsdeleted file mode 100644index a5043e4..0000000--- a/scripts/contracts/gateway-address.ts+++ /dev/null@@ -1,12 +0,0 @@-import assert from "node:assert/strict"-import { join } from "node:path"-import gatewayAddress from "@server/view/gateway/address"--const first = gatewayAddress("C:\\Users\\Person\\.phreshos", "win32")--assert.match(first, /^\\\\\.\\pipe\\phreshos-[a-f0-9]{32}-gateway$/)-assert.equal(first, gatewayAddress("c:/users/person/.phreshos/", "win32"))-assert.notEqual(first, gatewayAddress("C:\\Users\\Other\\.phreshos", "win32"))-assert.equal(gatewayAddress("/home/person/.phreshos", "linux"), join("/home/person/.phreshos", "gateway.sock"))--console.log("gateway address verified")diff --git a/scripts/contracts/gateway.ts b/scripts/contracts/gateway.tsdeleted file mode 100644index 4fcd61f..0000000--- a/scripts/contracts/gateway.ts+++ /dev/null@@ -1,62 +0,0 @@-import assert from "node:assert/strict"-import { mkdtemp, rm } from "node:fs/promises"-import { resolve } from "node:path"-import { SocketClient } from "@the-link/ipc/socket-client"-import messagepack from "@the-link/messagepack"-import gatewayAddress from "@server/view/gateway/address"-import gateway from "@server/view/gateway/gateway"-import type LinkManager from "@server/core/link-manager/link-manager"--const directory = await mkdtemp(resolve(".verify-gateway-"))-const path = gatewayAddress(directory)-const received: unknown[][] = []-let removed = false-const session = {- authorization: "owner",- linkManager: { appearance: { key: "appearance", value: {} } },- authManager: {- programManager: { programs: [] },- processManager: { processes: [] }- }-}-const linkManager = {- addConnection() {- return {- async publish(event: string, ...values: unknown[]) {- received.push([event, ...values])- return [{ event, values }]- }- }- },- async addSession(_connection: unknown, owner: boolean) {- assert.equal(owner, true)- return session- },- async removeConnection() { removed = true }-}-const listener = await gateway(linkManager as unknown as LinkManager, path)-const client = new SocketClient(path)--client.setSerialize(messagepack.serialize)-client.setDeserialize(messagepack.deserialize)--const ready = client.$inbound.waitFirst("/gateway/ready")--try {- await client.connect()-- assert.deepEqual(await ready, session)- assert.deepEqual(- await client.$outbound.publishFirst("/auth/example", "authorization", { binary: new Uint8Array([1, 2, 3]) }),- { event: "/auth/example", values: ["authorization", { binary: new Uint8Array([1, 2, 3]) }] }- )- assert.deepEqual(received, [["/auth/example", "authorization", { binary: new Uint8Array([1, 2, 3]) }]])-} finally {- await client.disconnect()- await listener.close()- await rm(directory, { recursive: true, force: true })-}--assert.equal(removed, true)--console.log("gateway boundary verified")diff --git a/scripts/contracts/host-traffic.ts b/scripts/contracts/host-traffic.tsdeleted file mode 100644index a76212a..0000000--- a/scripts/contracts/host-traffic.ts+++ /dev/null@@ -1,30 +0,0 @@-import assert from "node:assert/strict"-import HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"--const traffic = new HostTraffic()-const hostProgram: unknown[][] = []-const ownProgram: unknown[][] = []-const hostProcess: unknown[][] = []-const programProcess: unknown[][] = []--traffic.observe("program", "uninstall", null, (_delivery, event, ...values) => hostProgram.push([event, ...values]))-traffic.observe("program", "uninstall", "program-reference", (_delivery, event, ...values) => ownProgram.push([event, ...values]))-traffic.observe("process", "create", null, (_delivery, event, ...values) => hostProcess.push([event, ...values]))-traffic.observe("process", "create", "program-reference", (_delivery, event, ...values) => programProcess.push([event, ...values]))--const program = { identity: "counter", reference: "program-reference" }-const process = { identity: "worker", reference: "process-reference" }--await traffic.emitHost("program", "uninstall", program.identity, program, true)--assert.deepEqual(hostProgram, [["uninstall", program.identity, program, true]])-assert.deepEqual(ownProgram, [])--await traffic.emitSubject("program", "uninstall", program.reference, true)--assert.deepEqual(ownProgram, [["uninstall", program.reference, true]])--await traffic.emit("process", "create", program.identity, program.reference, process)--assert.deepEqual(hostProcess, [["create", program.identity, process]])-assert.deepEqual(programProcess, [["create", program.reference, process]])diff --git a/scripts/contracts/panel.tsx b/scripts/contracts/panel.tsxdeleted file mode 100644index ffc5726..0000000--- a/scripts/contracts/panel.tsx+++ /dev/null@@ -1,67 +0,0 @@-import assert from "node:assert/strict"-import type { ReactNode } from "react"-import { renderToStaticMarkup } from "react-dom/server"-import { defaultAppearance } from "@phreshos/core"-import { AppearanceProvider } from "@phreshos/react-ui"-import CredentialsForm from "@client/view/structure/authentication/credentials-form"-import TaskbarSurface, { taskbarSurfaceClassName } from "@client/view/structure/desktop/taskbar/taskbar-surface"-import Launcher from "@client/view/structure/desktop/taskbar/launcher/launcher"-import Window from "@client/view/structure/desktop/windows/window"-import StartMenuPanel from "@client/view/structure/desktop/taskbar/launcher/start-menu-panel"--function markup(children: ReactNode) {- return renderToStaticMarkup(<AppearanceProvider appearance={defaultAppearance} theme="light">{children}</AppearanceProvider>)-}--function panel(html: string) {- assert.equal(html.match(/data-material=""/g)?.length, 2)- assert.match(html, /grid-template-rows:auto minmax\(0, 1fr\)/)- assert.match(html, /margin:6px;margin-top:0/)-}--const taskbar = markup(<TaskbarSurface label="Title" labelId="title"><button>Action</button></TaskbarSurface>)-panel(taskbar)-assert.match(taskbar, /<h2 id="title"/)-assert.match(taskbar, /<button>Action<\/button>/)--const window = markup(<Window icon="/icon.svg" title="Window"><iframe title="Content" /></Window>)-assert.equal(window.match(/data-material=""/g)?.length, 1)-assert.match(window, /grid-template-rows:auto minmax\(0, 1fr\)/)-assert.match(window, /data-window-content="true"/)-assert.doesNotMatch(window, /border-top:1px solid yellow/)-assert.doesNotMatch(window, /margin:6px;margin-top:0/)-assert.match(window, /data-window-container/)-assert.match(window, /<iframe title="Content"/)-assert.doesNotMatch(window, /class="p-px"/)--const bare = markup(<Window bare icon="/icon.svg" title="Bare"><iframe title="Content" /></Window>)-assert.doesNotMatch(bare, /data-material/)-assert.doesNotMatch(bare, /grid-template-rows:auto minmax\(0, 1fr\)/)--const authentication = markup(<CredentialsForm title="Sign in" description="Welcome" submitLabel="Continue" passwordAutocomplete="current-password" pending={false} onSubmit={() => {}} />)-panel(authentication)-assert.equal(authentication.match(/<form\b/g)?.length, 1)-assert.match(authentication, /name="username"/)-assert.match(authentication, /name="password"/)-assert.match(authentication, /type="submit"/)--const launcher = markup(<Launcher label="Example System" trigger="Open">{(_close, labelId) => <StartMenuPanel labelId={labelId} name="Example System" version="1.2.3" left={<button>Programs</button>} right={<p>Processes</p>} footer={<input type="search" aria-label="Search Programs and Processes" />} />}</Launcher>)-assert.equal(launcher.match(/data-material=""/g)?.length, 4)-assert.match(launcher, /grid-cols-2/)-assert.match(launcher, /grid-template-rows:auto minmax\(0, 1fr\);min-height:0/)-assert.match(launcher, /grid-template-rows:minmax\(0, 1fr\) auto;gap:8px;padding:8px;padding-top:0/)-assert.match(launcher, /grid-cols-2" style="gap:inherit"/)-assert.match(launcher, /<button>Programs<\/button>/)-assert.match(launcher, /<p>Processes<\/p>/)-assert.match(launcher, /<h2[^>]*>Example System<\/h2>/)-assert.match(launcher, /System version 1.2.3/)-assert.match(launcher, /type="search"/)-assert.doesNotMatch(launcher, /<(?:main|section|article|aside|nav|header|footer)\b/)-assert.match(launcher, /size-4 rounded-sm object-contain/)-// Native popover visibility belongs to the outer host, not Panel's grid.-const popover = launcher.match(/<div[^>]*popover="auto"[^>]*>/)?.[0]-assert(popover)-assert.match(popover, /overflow-visible/)-assert.doesNotMatch(popover, /\bgrid\b/)-// Popovers and native dialogs share a non-clipping host for independently owned outer effects.-assert(taskbarSurfaceClassName.split(" ").includes("overflow-visible"))diff --git a/scripts/contracts/permission-requests.ts b/scripts/contracts/permission-requests.tsdeleted file mode 100644index 9e2d08a..0000000--- a/scripts/contracts/permission-requests.ts+++ /dev/null@@ -1,98 +0,0 @@-import assert from "node:assert/strict"-import { mkdtempSync, rmSync } from "node:fs"-import { tmpdir } from "node:os"-import { join } from "node:path"-import type { PermissionName, PermissionRequest } from "@phreshos/core"-import Program from "@server/core/link-manager/auth-manager/program-manager/program"-import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"-import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"-import Process from "@server/core/link-manager/auth-manager/process-manager/process"-import Window from "@server/core/link-manager/auth-manager/process-manager/window"-import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"-import { readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"--const temporary = mkdtempSync(join(tmpdir(), "phresh-permission-requests-"))--try {- const program = new Program({ identity: "example", storage: temporary, client: { location: "." } })- let dialogs = 0- let choice: boolean | null = null- let whilePending: (() => void) | undefined- let accessUpdates = 0-- const process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, false)- process.startClient(new Window({ title: "Client", layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false), false)-- const authManager = {- dialogManager: {- async requestPermission() {- dialogs++- whilePending?.()- return choice- }- }- }- const programManager = Object.assign(Object.create(ProgramManager.prototype), { authManager }) as ProgramManager- const processManager = Object.assign(Object.create(ProcessManager.prototype), {- authManager,- processes: new Map([["process", process]]),- $outbound: { async publish(event: string) {- assert.equal(event, "/client-access")- accessUpdates++- } }- }) as ProcessManager- Object.assign(authManager, { programManager, processManager })-- const request = <Name extends PermissionName>(name: Name, value: PermissionRequest<Name> = true) => (- processManager.requestPermission("process", "request", name, value)- )- // Stored authority never bypasses approval, even for a narrower request.- writePermissions(program, { services: ["browser", "editor"] })- assert.equal(await request("services", ["browser"]), null)- assert.equal(dialogs, 1)- assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })-- choice = false- assert.equal(await request("services", ["browser"]), false)- assert.equal(dialogs, 2)- assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })-- // Approval replaces the exact permission instead of widening or merging it.- choice = true- assert.deepEqual(await request("services", ["browser"]), ["browser"])- assert.equal(dialogs, 3)- assert.deepEqual(readPermissions(program), { services: ["browser"] })-- // A concurrent edit cannot turn one approved request into a broader grant.- whilePending = () => writePermissions(program, { services: ["editor"] })- assert.deepEqual(await request("services", ["browser"]), ["browser"])- assert.deepEqual(readPermissions(program), { services: ["browser"] })- whilePending = undefined-- // An exact assignment restricts a broader fallback grant. Otherwise an- // approved narrowing request would change the file without changing authority.- writePermissions(program, { all: [] })- assert.deepEqual(await request("network", ["https://api.example.com"]), ["https://api.example.com"])- assert(programManager.grantsPermission(program, "network", ["https://api.example.com/v1"]))- assert(!programManager.grantsPermission(program, "network", ["https://other.example.com"]))-- // Program declarations are installation input, never a second live source.- const declared = new Program({ identity: "declared", storage: temporary, client: { location: ".", permissions: { programs: ["browser"] } } })- writePermissions(declared, { services: ["editor"] })- assert(!programManager.grantsPermission(declared, "services", ["browser"]))- assert(programManager.grantsPermission(declared, "services", ["editor"]))-- // The iframe policy is synchronized independently of permission request results.- writePermissions(program, {})- assert.deepEqual(await request("all"), [])- assert.equal(process.hosted().client?.sameOrigin, true)- assert.equal(accessUpdates, 1)- await programManager.setPermission(program, "all", [])- assert.equal(accessUpdates, 1)- await programManager.deletePermission(program, "all")- assert.equal(process.hosted().client?.sameOrigin, false)- assert.equal(accessUpdates, 2)-}-finally {- rmSync(temporary, { recursive: true, force: true })-}diff --git a/scripts/contracts/permissions.ts b/scripts/contracts/permissions.tsdeleted file mode 100644index 363f4ac..0000000--- a/scripts/contracts/permissions.ts+++ /dev/null@@ -1,161 +0,0 @@-import assert from "node:assert/strict"-import { parsePermissionName } from "@phreshos/core"-import { PermissionCatalog, permissionCatalog } from "@server/core/permissions"--const catalog = new PermissionCatalog({- all: {- default: [],- title: "All permissions",- description: "Grant every available Client permission."- },- services: {- default: [],- title: "Services",- description: "Access Services belonging to every Program or selected Programs."- },- programs: {- default: [],- title: "Programs",- description: "Access every Program or selected Programs and their Services."- },- network: {- default: [],- title: "Network",- description: "Use System networking with every request target or selected target scopes."- },- storage: {- default: [],- title: "Storage",- description: "Use every native filesystem path or selected operation-and-path scopes."- },- uploads: {- default: [],- title: "Uploads",- description: "Create values in the System uploads collection."- },- appearance: {- default: [],- title: "Appearance",- description: "Change the System Appearance."- },- desktopPreferences: {- default: [],- title: "Desktop preferences",- description: "Change this Desktop's preferences."- }-})--assert.deepEqual(catalog.definition("all"), {- valueDomain: "none",- default: [],- title: "All permissions",- description: "Grant every available Client permission."-})-assert.deepEqual(catalog.definition("programs"), {- valueDomain: "program",- default: [],- title: "Programs",- description: "Access every Program or selected Programs and their Services."-})-assert.deepEqual(catalog.definition("network"), {- valueDomain: "network",- default: [],- title: "Network",- description: "Use System networking with every request target or selected target scopes."-})-assert.deepEqual(catalog.definition("storage"), {- valueDomain: "storage",- default: [],- title: "Storage",- description: "Use every native filesystem path or selected operation-and-path scopes."-})-assert.deepEqual(catalog.definition("uploads"), {- valueDomain: "none",- default: [],- title: "Uploads",- description: "Create values in the System uploads collection."-})-assert.deepEqual(catalog.resolve("all", true), [])-assert.deepEqual(catalog.resolve("all", []), [])-assert.deepEqual(catalog.resolve("services", true), [])-assert.deepEqual(catalog.resolve("services", ["flambo", "terminal", "flambo"]), ["flambo", "terminal"])-assert.deepEqual(catalog.resolve("network", ["HTTPS://API.Example.com:443/v1/**"]), ["https://api.example.com/v1/**"])-assert.deepEqual(catalog.resolve("storage", ["delete,read:Documents/**"]), ["read,delete:Documents/**"])-assert.deepEqual(catalog.resolve("uploads", true), [])-assert.equal(catalog.resolve("all", false), false)-assert.equal(catalog.resolve("all", null), null)--assert.deepEqual(catalog.declarations({ all: true, services: ["flambo"] }), { all: [], services: ["flambo"] })-assert(Object.isFrozen(catalog.declarations({})))-assert(Object.isFrozen(catalog.declarations({ all: true }).all))--assert(catalog.grants("all", [], []))-assert(!catalog.grants("all", false, []))-assert(!catalog.grants("all", null, []))-assert(catalog.grants("services", [], []))-assert(catalog.grants("services", [], ["flambo"]))-assert(catalog.grants("services", ["flambo"], ["flambo"]))-assert(!catalog.grants("services", ["flambo"], ["terminal"]))-assert(!catalog.grants("services", ["flambo"], []))-assert(catalog.grants("network", ["https://api.example.com"], ["https://api.example.com/v1/users"]))-assert(catalog.grants("network", ["https://*.example.com/v1/**"], ["https://eu.example.com/v1/users"]))-assert(!catalog.grants("network", ["https://*.example.com/v1/**"], ["https://example.com/v1/users"]))-assert(!catalog.grants("network", ["https://api.example.com/v1/**"], ["https://api.example.com/v2/users"]))-assert(catalog.grants("storage", ["Documents/**"], ["read:Documents/report.txt"]))-assert(catalog.grants("storage", ["read,delete:Documents/**"], ["delete:Documents/old.txt"]))-assert(!catalog.grants("storage", ["read:Documents/**"], ["write:Documents/report.txt"]))-assert(!catalog.grants("storage", ["Documents/report.txt"], ["read:Documents/**"]))-assert(catalog.allows("all", [], { all: [] }))-assert(!catalog.allows("all", [], {}))-assert(catalog.allows("services", ["browser"], { all: [] }))-assert(catalog.allows("services", ["browser"], { services: ["browser"] }))-assert(catalog.allows("services", ["browser"], { programs: [] }))-assert(catalog.allows("services", [], { programs: [] }))-assert(catalog.allows("services", ["browser"], { programs: ["browser"] }))-assert(!catalog.allows("services", ["browser", "editor"], { programs: ["browser"], services: ["editor"] }))-assert(catalog.allows("services", ["editor"], { programs: ["browser"], services: ["editor"] }))-assert(!catalog.allows("services", ["editor"], { programs: ["browser"] }))-assert(!catalog.allows("services", [], { programs: ["browser"] }))-assert(!catalog.allows("programs", ["browser"], { services: [] }))-assert(!catalog.allows("services", ["browser"], { programs: [], services: false }))-assert(!catalog.allows("network", ["https://elsewhere.example"], { all: [], network: ["https://api.example.com"] }))-assert(catalog.allows("network", ["https://api.example.com/v1"], { all: [], network: ["https://api.example.com"] }))-assert(catalog.allowsStorage([], null, "Documents/report.txt", "read"))-assert(catalog.allowsStorage([], ["read:Documents/**"], "Documents/report.txt", "read"))-assert(!catalog.allowsStorage([], ["read:Documents/**"], "Pictures/photo.png", "read"))-assert(!catalog.allowsStorage([], false, "Documents/report.txt", "read"))-assert(!catalog.changed([], []))-assert(!catalog.changed(["flambo", "terminal"], ["terminal", "flambo"]))-assert(catalog.changed(["flambo"], []))--assert.throws(() => parsePermissionName("files"), /does not know/)-assert.throws(() => catalog.resolve("all", ["unknown"]), /unknown value/)-assert.throws(() => catalog.resolve("appearance", ["flambo"]), /unknown value/)-assert.throws(() => catalog.resolve("services", ["Not a Program"]), /unknown value/)-assert.throws(() => catalog.resolve("network", ["api.example.com"]), /unknown value/)-assert.throws(() => catalog.resolve("storage", ["all:Documents"]), /unknown value/)-assert.throws(() => catalog.resolve("storage", ["all,read:Documents"]), /unknown value/)-assert.throws(() => catalog.declarations({ all: ["unknown"] }), /unknown value/)-assert.throws(() => catalog.stored({ all: true }), /unresolved shorthand/)-assert.throws(() => new PermissionCatalog({} as never), /needs a definition/)-assert.throws(() => new PermissionCatalog({- all: {- default: ["unknown"],- title: "All permissions",- description: "Invalid default."- },- services: catalog.definition("services"),- programs: catalog.definition("programs"),- network: catalog.definition("network"),- storage: catalog.definition("storage"),- uploads: catalog.definition("uploads"),- appearance: catalog.definition("appearance"),- desktopPreferences: catalog.definition("desktopPreferences")-} as never), /invalid default/)--assert.deepEqual(permissionCatalog.resolve("all", true), [])-assert.deepEqual(permissionCatalog.declarations({ all: true }), { all: [] })-assert.deepEqual(permissionCatalog.declarations({ programs: true }), { programs: [] })-assert(permissionCatalog.granted([]))-assert(!permissionCatalog.granted(null))-assert.throws(() => permissionCatalog.definition("files" as never), /does not know/)diff --git a/scripts/contracts/ports.ts b/scripts/contracts/ports.tsdeleted file mode 100644index 2df94b7..0000000--- a/scripts/contracts/ports.ts+++ /dev/null@@ -1,60 +0,0 @@-import { strict as assert } from "node:assert"-import { createServer } from "node:http"-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"-import { homedir, tmpdir } from "node:os"-import { join, resolve } from "node:path"-import { defaultHome, defaultPorts, environmentPorts, listenOnPorts, parsePorts, portRange, requestedPorts } from "@server/view/configuration"--assert.equal(environmentPorts("phreshos", {}), undefined)-assert.deepEqual(environmentPorts("phreshos", { PHRESHOS_PORT: "4305" }), [4305])-assert.deepEqual(- environmentPorts("phreshos", { PHRESHOS_PORT: "4196,4234,5000-5002,4234" }),- [4196, 4234, 5000, 5001, 5002]-)-assert.deepEqual(portRange(4300, 4399), Array.from({ length: 100 }, (_, index) => 4300 + index))-assert.deepEqual(defaultPorts(false), portRange(4300, 4399))-assert.deepEqual(defaultPorts(true), portRange(5300, 5399))-assert.equal(defaultHome(false), resolve(homedir(), ".phreshos"))-assert.equal(defaultHome(true), resolve("storage"))--for (const value of ["", "0", "65536", "43.12", "port", "4300-", "4301-4300", "4300,,4301"]) {-- assert.throws(() => parsePorts(value, "PHRESHOS_PORT"), /PHRESHOS_PORT must contain ports or inclusive ranges/)-}--const occupied = createServer()-const available = createServer()--const occupiedPort = await listenOnPorts(occupied, "127.0.0.1")-const availablePort = await listenOnPorts(available, "127.0.0.1")--await close(available)--const selected = createServer()--assert.equal(await listenOnPorts(selected, "127.0.0.1", [occupiedPort, availablePort]), availablePort)--await assert.rejects(- listenOnPorts(createServer(), "127.0.0.1", [occupiedPort, availablePort]),- /No configured System port is available/-)--await Promise.all([close(occupied), close(selected)])--const temporary = await mkdtemp(join(tmpdir(), "phreshos-port-request-"))-const request = join(temporary, "next-port")--try {-- await writeFile(request, "4400,4500-4502\n")-- assert.deepEqual(await requestedPorts(["node", "main.js", "--port-request", request]), [4400, 4500, 4501, 4502])- await assert.rejects(readFile(request), error => (error as NodeJS.ErrnoException).code === "ENOENT")-}--finally { await rm(temporary, { recursive: true, force: true }) }--function close(server: ReturnType<typeof createServer>) {-- return new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))-}diff --git a/scripts/contracts/process-find-or-create.ts b/scripts/contracts/process-find-or-create.tsdeleted file mode 100644index a7e45a5..0000000--- a/scripts/contracts/process-find-or-create.ts+++ /dev/null@@ -1,116 +0,0 @@-import assert from "node:assert/strict"-import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"-import type { Launch } from "@phreshos/core"-import type Program from "@server/core/link-manager/auth-manager/program-manager/program"--interface FixtureProcess {- identity: string- name: string | null- program: Program- launch: unknown-}--interface FixtureManager {- start(owner: Program, launch: Launch, watching?: unknown, parent?: unknown, transition?: boolean, prepared?: { intent: unknown }): Promise<`${string}-${string}-${string}-${string}-${string}`>- resolveLaunch(owner: Program, launch: Launch): { intent: { server: { service: boolean } | null, client: { position: unknown, size: unknown, service: boolean } | null } }-}--const processes = new Map<string, FixtureProcess>()-const program = {- identity: "example",- reference: "example-reference",- server: { start: true },- client: {- start: true,- position: undefined,- size: undefined,- layer: undefined,- minimize: undefined- },- title: "Example",- async validate() {}-} as unknown as Program--let starts = 0--const manager = Object.assign(Object.create(ProgramManager.prototype), {- authManager: { processManager: { processes } },- creating: new Map(),- $outbound: { async publish() {} },- reach: (identity: string) => identity === program.identity ? program : null-}) as ProgramManager-const fixture = manager as unknown as FixtureManager--fixture.start = async (owner, launch, _watching, _parent, _transition, prepared) => {- await Promise.resolve()-- const existing = [...processes.values()].find(process => process.program === owner && process.name === launch.name)- if (existing) throw new Error("This program already has a process with that name")-- const identity = `00000000-0000-0000-0000-${String(++starts).padStart(12, "0")}` as `${string}-${string}-${string}-${string}-${string}`- processes.set(identity, {- identity,- name: launch.name ?? null,- program: owner,- launch: (prepared ?? fixture.resolveLaunch(owner, launch)).intent- })- return identity-}--const launch = {- name: "shared",- server: true,- client: false,- options: { beta: "2", alpha: "1" }-}--const [first, second] = await Promise.all([- manager.findOrCreateProcess(program, launch),- manager.findOrCreateProcess(program, {- name: "shared",- server: true,- client: false,- options: { alpha: "1", beta: "2" }- })-])--assert.equal(first, second)-assert.equal(starts, 1)--await assert.rejects(- manager.findOrCreateProcess(program, {- name: "shared",- server: false,- client: true,- options: { alpha: "1", beta: "2" }- }),- /different launch/-)--const omitted = fixture.resolveLaunch(program, { name: "defaults" }).intent-processes.set("unrelated", { identity: "unrelated", name: null, program, launch: null })-const explicit = fixture.resolveLaunch(program, {- name: "defaults",- server: true,- client: true-}).intent--assert.deepEqual(omitted, explicit)-assert(omitted.client)-assert.deepEqual(omitted.server, { service: false })-assert.equal(omitted.client.service, false)-assert.equal(omitted.client.position, null)-assert.equal(omitted.client.size, null)--const activated = fixture.resolveLaunch(program, {- server: { service: true },- client: { service: true }-}).intent--assert.equal(activated.server?.service, true)-assert.equal(activated.client?.service, true)--const stale = { identity: program.identity, reference: "replaced-program-reference" } as unknown as Program--await assert.rejects(manager.createProcess(stale), /represented by this handle does not exist/)-await assert.rejects(manager.findOrCreateProcess(stale, { name: "stale" }), /represented by this handle does not exist/)diff --git a/scripts/contracts/process-lifecycle.ts b/scripts/contracts/process-lifecycle.tsdeleted file mode 100644index cb59a59..0000000--- a/scripts/contracts/process-lifecycle.ts+++ /dev/null@@ -1,294 +0,0 @@-import assert from "node:assert/strict"-import { TheLink } from "@the-link/core"-import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"-import Program from "@server/core/link-manager/auth-manager/program-manager/program"-import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"-import type Process from "@server/core/link-manager/auth-manager/process-manager/process"-import type ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"-import type { ServerRuntime } from "@server/core/server-runtime"--const launch = { server: null, client: null, options: {} } as const--function processManager() {-- const authManager = new TheLink() as unknown as AuthManager- const manager = new ProcessManager(authManager)-- Object.assign(authManager, {- programManager: {- permission() { return null }- },- linkManager: {- application: {- system: {- holdProcess(value: unknown, fallback?: Process) {-- if (value === undefined || value === null) return fallback- if (typeof value !== "object" || value === null) throw new Error("Invalid Process handle")-- const handle = value as { identity?: string, reference?: string }- const process = handle.identity ? manager.processes.get(handle.identity) : null-- if (!process || process.reference !== handle.reference) throw new Error("The Process represented by this handle does not exist")-- return process- }- }- }- }- })-- return manager-}--function program(identity: string) {-- return new Program({ identity, server: { location: ".", startCommand: "true" } })-}--async function register(manager: ProcessManager, identity: string) {-- return await manager.register(identity, null, program(identity), {}, launch, null, false, null, null)-}--// Parentage retains the exact Process entity after it exits. Absence and-// ended lineage therefore remain distinct states at every System boundary.-{- const manager = processManager()- const parent = await register(manager, "parent")- const child = await manager.register("child", null, parent.program, {}, launch, null, false, null, parent)- const boundary = manager as unknown as {- parent(value: unknown): Promise<{ identity: string } | null>- endHost(process: Process, server: ServerProcessBoundary, args: unknown[]): Promise<unknown[]>- }-- await manager.remove(parent.identity)-- assert.equal((await boundary.parent({ identity: child.identity, reference: child.reference }))?.identity, parent.identity)-- const retained = (await boundary.endHost(child, {} as ServerProcessBoundary, ["parent"]))[0] as { identity: string }-- assert.equal(retained.identity, parent.identity)-}--// A failed configuration cannot leave either its Process identity or an-// unattached runtime behind in the registry.-{- const manager = processManager()- let stops = 0- const runtime = { stop() { stops++ } } as unknown as ServerRuntime-- await assert.rejects(manager.register(- "failed-registration",- null,- program("failed-registration"),- {},- launch,- runtime,- false,- null,- null,- { prepare() { throw new Error("configuration failed") } }- ), /configuration failed/)-- assert.equal(manager.processes.has("failed-registration"), false)- assert.equal(stops, 1)-}--// Failure after an endpoint has been activated still retracts the partially-// announced Process and its client state.-{- const manager = processManager()- const client = new Program({ identity: "partial-registration", client: { location: "https://example.test/" } })-- manager.$outbound.subscribe("/created", () => {-- throw new Error("creation publication failed")- })-- await assert.rejects(manager.register(- "partial-registration",- null,- client,- {},- { ...launch, client: { title: "Partial", position: null, size: null, layer: "window", minimize: false, maximize: false, service: false } },- null,- true,- { title: "Partial", position: { x: 0, y: 0 }, size: { width: 320, height: 240 }, layer: "window", minimize: false, maximize: false },- null- ), /creation publication failed/)-- assert.equal(manager.processes.has("partial-registration"), false)-}--// A launcher can only receive a started Process after the authoritative-// representation has received that Process's creation snapshot.-{- const manager = processManager()- const order: string[] = []-- manager.$outbound.subscribe("/created", () => { order.push("published") })-- await manager.register(- "ordered-registration",- null,- program("ordered-registration"),- {},- launch,- null,- false,- null,- null,- { created() { order.push("reported") } }- )-- assert.deepEqual(order, ["published", "reported"])-}--// A failing observer is not allowed to stop the authoritative teardown or-// prevent later terminal publications from running.-{- const manager = processManager()- await register(manager, "teardown")- let exited = false-- manager.$outbound.subscribe("/exited", () => { exited = true })-- const stop = manager.observeHost("process", "exit", null, () => {-- throw new Error("exit observer failed")- })-- await assert.rejects(manager.remove("teardown"), /exit observer failed/)-- stop()-- assert.equal(manager.processes.has("teardown"), false)- assert.equal(exited, true)-}--interface BoundaryProbe {-- boundary: ServerProcessBoundary-- deliveries: unknown[][]-- cancel(question: string): void-}--function boundaryProbe(): BoundaryProbe {-- const deliveries: unknown[][] = []- const requests = new Map<string, () => void>()-- const boundary = {- retain(question: string, cancel: () => void) {-- requests.get(question)?.()-- requests.set(question, cancel)- },- async deliver(event: string, ...values: unknown[]) {-- if (values[0] === "answer" && typeof values[1] === "string") requests.delete(values[1])-- deliveries.push([event, ...values])- }- } as unknown as ServerProcessBoundary-- return {- boundary,- deliveries,- cancel(question) {-- const cancel = requests.get(question)-- requests.delete(question)-- cancel?.()- }- }-}--type HostWait = {-- endHostWait(process: Process, server: ServerProcessBoundary, question: string, args: unknown[]): Promise<void>-}--// Readiness listeners and their cancellation belong to the exact Server-// incarnation that asked. A replacement must neither inherit the answer nor-// retain the target listeners.-{- const manager = processManager()- const requester = await register(manager, "requester")- const target = await register(manager, "target")- const original = boundaryProbe()- const replacement = boundaryProbe()- let readyListeners = 0- let exitListeners = 0- let becomeReady: () => void = () => undefined-- target.waitReady = (_endpoint, notify) => {-- let active = true-- readyListeners++- becomeReady = notify-- return () => {-- if (!active) return-- active = false- readyListeners--- }- }-- target.onExit = () => {-- let active = true-- exitListeners++-- return () => {-- if (!active) return-- active = false- exitListeners--- }- }-- requester.server = original.boundary-- await (manager as unknown as HostWait).endHostWait(- requester,- original.boundary,- "ready",- ["wait-ready", { identity: target.identity, reference: target.reference }, "server", false]- )-- requester.server = replacement.boundary- becomeReady()-- assert.equal(readyListeners, 0)- assert.equal(exitListeners, 0)- assert.deepEqual(original.deliveries, [["host-end", "answer", "ready", { success: true, result: [] }]])- assert.deepEqual(replacement.deliveries, [])-- await (manager as unknown as HostWait).endHostWait(- requester,- original.boundary,- "cancelled",- ["wait-ready", { identity: target.identity, reference: target.reference }, "server", false]- )-- assert.equal(readyListeners, 1)- assert.equal(exitListeners, 1)-- original.cancel("cancelled")-- assert.equal(readyListeners, 0)- assert.equal(exitListeners, 0)- assert.equal(original.deliveries.length, 1)-}diff --git a/scripts/contracts/program-development.ts b/scripts/contracts/program-development.tsdeleted file mode 100644index 3281516..0000000--- a/scripts/contracts/program-development.ts+++ /dev/null@@ -1,28 +0,0 @@-import assert from "node:assert/strict"-import Program from "@server/core/link-manager/auth-manager/program-manager/program"-import { developmentTarget } from "@server/view/http/program/development"--const development = new Program({-- identity: "example",-- client: { location: "http://localhost:5173/start" }-})--const target = developmentTarget(-- development,-- `http://localhost:4300/program/${development.assetId}/assets/main.ts?direct`-)--assert.equal(target?.href, `http://localhost:5173/program/${development.assetId}/assets/main.ts?direct`)--const production = new Program({-- identity: "example",-- client: { location: "dist/client" }-})--assert.equal(developmentTarget(production, `http://localhost:4300/program/${production.assetId}/assets/`), null)diff --git a/scripts/contracts/program-frame.tsx b/scripts/contracts/program-frame.tsxdeleted file mode 100644index e31e3fa..0000000--- a/scripts/contracts/program-frame.tsx+++ /dev/null@@ -1,31 +0,0 @@-import assert from "node:assert/strict"-import { renderToStaticMarkup } from "react-dom/server"-import ProgramFrame from "@client/view/components/program-frame"-import type Process from "@client/core/link-manager/auth-manager/process-manager/process"-import type ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"--const record = { identity: "process", program: "program" } as Process-const client = { sameOrigin: false, window: {} } as ClientState-const common = {- record,- assetId: "00000000-0000-4000-8000-000000000000",- client,- title: "Program",- door: "/program",- access: "available" as const,- onFrame() {},- onLoad() {}-}--const dark = renderToStaticMarkup(<ProgramFrame {...common} theme="dark" />)-const light = renderToStaticMarkup(<ProgramFrame {...common} theme="light" />)--client.sameOrigin = true--const fullAccess = renderToStaticMarkup(<ProgramFrame {...common} theme="light" />)--assert.match(dark, /style="color-scheme:dark"/)-assert.match(light, /style="color-scheme:light"/)-assert.match(dark, /sandbox="allow-scripts allow-forms"/)-assert.match(fullAccess, /sandbox="allow-scripts allow-forms allow-same-origin"/)-assert.match(fullAccess, /src="\/program\/00000000-0000-4000-8000-000000000000\/assets\/"/)diff --git a/scripts/contracts/program-install.ts b/scripts/contracts/program-install.tsdeleted file mode 100644index b1297f8..0000000--- a/scripts/contracts/program-install.ts+++ /dev/null@@ -1,76 +0,0 @@-import assert from "node:assert/strict"-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"-import { tmpdir } from "node:os"-import { join } from "node:path"-import Program from "@server/core/link-manager/auth-manager/program-manager/program"-import { copyProgram } from "@server/core/link-manager/auth-manager/program-manager/program-manager"-import { installPermissions, readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"-import type { ProgramCommandChunk } from "@phreshos/core"--const temporary = mkdtempSync(join(tmpdir(), "phresh-program-install-"))-const source = join(temporary, "source")-const installed = join(temporary, "installed")--try {- mkdirSync(join(source, "server"), { recursive: true })- mkdirSync(join(source, "client"), { recursive: true })- writeFileSync(join(source, "client", "index.html"), "<!doctype html>")- writeFileSync(join(source, "operating-guide.md"), "Program operating knowledge")- mkdirSync(installed)-- const program = new Program({- identity: "documented-program",- agent: join(source, "operating-guide.md"),- categories: ["Development"],- keywords: ["example"],- website: "https://example.test/program",- server: {- location: join(source, "server"),- installCommand: `node -e "process.stdout.write('install-out'); process.stderr.write('install-err')"`,- uninstallCommand: `node -e "process.stdout.write('uninstall-out'); process.stderr.write('uninstall-err')"`,- startCommand: "true"- },- client: {- location: join(source, "client"),- permissions: { network: ["https://api.example.test/**"] }- }- })-- await program.validate()- copyProgram(program, installed)-- const declaration = JSON.parse(readFileSync(join(installed, "program.json"), "utf8"))-- assert.equal(declaration.agent, "agent.md")- assert.deepEqual(declaration.categories, ["Development"])- assert.deepEqual(declaration.keywords, ["example"])- assert.equal(declaration.website, "https://example.test/program")- assert(program.config.server)- assert.equal(declaration.server.uninstallCommand, program.config.server.uninstallCommand)- assert.equal(readFileSync(join(installed, "agent.md"), "utf8"), "Program operating knowledge")-- const installedProgram = new Program(join(installed, "program.json"))- writePermissions(installedProgram, { network: ["https://old.example.test/**"], appearance: [] })- const rollbackPermissions = installPermissions(installedProgram)- assert.deepEqual(readPermissions(installedProgram), { network: ["https://api.example.test"] })- rollbackPermissions()- assert.deepEqual(readPermissions(installedProgram), { network: ["https://old.example.test"], appearance: [] })- installPermissions(installedProgram)- const installation: ProgramCommandChunk[] = []- const uninstallation: ProgramCommandChunk[] = []-- await installedProgram.installServer(chunk => { installation.push(chunk) })- await installedProgram.uninstallServer(chunk => { uninstallation.push(chunk) })-- assert.deepEqual(Object.fromEntries(installation.map(chunk => [chunk.stream, chunk.text])), {- stdout: "install-out",- stderr: "install-err"- })- assert.deepEqual(Object.fromEntries(uninstallation.map(chunk => [chunk.stream, chunk.text])), {- stdout: "uninstall-out",- stderr: "uninstall-err"- })-}-finally {- rmSync(temporary, { recursive: true, force: true })-}diff --git a/scripts/contracts/readiness.tsx b/scripts/contracts/readiness.tsxdeleted file mode 100644index c463332..0000000--- a/scripts/contracts/readiness.tsx+++ /dev/null@@ -1,67 +0,0 @@-import assert from "node:assert/strict"-import { renderToStaticMarkup } from "react-dom/server"-import Readiness, { ReadinessState } from "@libs/readiness"--const startup = ReadinessState.start(["connection", "session", "wallpaper"])--assert.deepEqual(startup.pending, ["connection", "session", "wallpaper"])--const connected = startup.ready("connection")-const extended = connected.require("programs")-const session = extended.ready("session")-const wallpaper = session.ready("wallpaper")-const complete = wallpaper.ready("programs")--assert.deepEqual(connected.pending, ["session", "wallpaper"])-assert.deepEqual(extended.pending, ["session", "wallpaper", "programs"])-assert.deepEqual(complete.pending, [])-assert.equal(complete.ready("programs"), complete)--const recomposed = complete.require("wallpaper").require("connection").require("session")--assert.deepEqual(recomposed.pending, ["connection", "session", "wallpaper"])-assert.deepEqual(recomposed.ready("connection").ready("session").ready("wallpaper").pending, [])-assert.equal(recomposed.require("connection"), recomposed)--const late = complete.require("late")--assert.deepEqual(late.requirements, ["connection", "session", "wallpaper", "programs", "late"])-assert.deepEqual(late.pending, ["late"])--assert.throws(() => startup.ready("unknown"), /does not know/)-assert.throws(() => ReadinessState.start(["connection", "connection"]), /already knows/)-assert.throws(() => ReadinessState.start([""]), /must have a name/)--const pendingMarkup = renderToStaticMarkup(- <Readiness requirements={["connection"]}>- <Readiness.Pending><span>Loading</span></Readiness.Pending>- <p>Prepared content</p>- </Readiness>-)--const readyMarkup = renderToStaticMarkup(- <Readiness requirements={[]}>- <Readiness.Pending><span>Loading</span></Readiness.Pending>- <p>Prepared content</p>- </Readiness>-)--assert.match(pendingMarkup, /Loading/)-assert.match(pendingMarkup, /Prepared content/)-assert.doesNotMatch(readyMarkup, /Loading/)-assert.match(readyMarkup, /Prepared content/)--const observedPendingMarkup = renderToStaticMarkup(- <Readiness requirements={["connection", "session"]}>- <Readiness.Pending>{pending => <span>{pending.join(",")}</span>}</Readiness.Pending>- </Readiness>-)--const observedReadyMarkup = renderToStaticMarkup(- <Readiness requirements={[]}>- <Readiness.Pending>{pending => <span>{pending.length}</span>}</Readiness.Pending>- </Readiness>-)--assert.match(observedPendingMarkup, /connection,session/)-assert.match(observedReadyMarkup, />0</)diff --git a/scripts/contracts/shell.ts b/scripts/contracts/shell.tsdeleted file mode 100644index 7c35ae3..0000000--- a/scripts/contracts/shell.ts+++ /dev/null@@ -1,36 +0,0 @@-import assert from "node:assert/strict"-import shell from "@server/core/shell"--const executable = `"${process.execPath}"`-const script = JSON.stringify("process.stdout.write(process.env.PHRESHOS_SHELL_TEST); process.stderr.write('error'); process.exitCode = 7")-const events = []--for await (const event of shell(`${executable} -e ${script}`, { env: { PHRESHOS_SHELL_TEST: "output" } })) events.push(event)--assert.equal(events[0]?.event, "started")-assert.equal(events.flatMap(event => event.event === "output" && event.stream === "stdout" ? [event.text] : []).join(""), "output", JSON.stringify(events))-assert.equal(events.flatMap(event => event.event === "output" && event.stream === "stderr" ? [event.text] : []).join(""), "error", JSON.stringify(events))-assert.deepEqual(events.at(-1), {- event: "exited",- exit: { status: "exited", code: 7, signal: null }-})--const running = shell(`${executable} -e ${JSON.stringify("setInterval(() => {}, 1_000)")}`)-const started = await running.next()-const startedEvent = started.value--assert.equal(startedEvent?.event, "started")-await running.return(undefined)--if (startedEvent?.event === "started") assert.throws(() => process.kill(startedEvent.pid, 0), { code: "ESRCH" })--const controller = new AbortController()-const aborted = shell(`${executable} -e ${JSON.stringify("setInterval(() => {}, 1_000)")}`, { signal: controller.signal })-const abortedStart = (await aborted.next()).value-const reason = new Error("test cancellation")--controller.abort(reason)--await assert.rejects(aborted.next(), error => error === reason)--if (abortedStart?.event === "started") assert.throws(() => process.kill(abortedStart.pid, 0), { code: "ESRCH" })diff --git a/scripts/contracts/start-menu-search.tsx b/scripts/contracts/start-menu-search.tsxdeleted file mode 100644index fd8a815..0000000--- a/scripts/contracts/start-menu-search.tsx+++ /dev/null@@ -1,47 +0,0 @@-import assert from "node:assert/strict"-import { renderToStaticMarkup } from "react-dom/server"-import { AppearanceProvider } from "@phreshos/react-ui"-import { defaultAppearance } from "@phreshos/core"-import Program from "@server/core/link-manager/auth-manager/program-manager/program"-import SearchBar from "@client/view/structure/desktop/taskbar/launcher/search-bar"-import { matchesProcess, matchesProgram, searchTerms } from "@client/view/structure/desktop/taskbar/launcher/search"--const program = new Program({- identity: "test-editor",- name: "Note Studio",- description: "Write and organize documents",- categories: ["Productivity"],- keywords: ["markdown", "notes"],- client: { location: "." }-}).record()--assert.deepEqual(program.categories, ["Productivity"])-assert.deepEqual(program.keywords, ["markdown", "notes"])-const empty = new Program({ identity: "empty", client: { location: "." } }).record()--assert.deepEqual(empty.categories, [])-assert.deepEqual(empty.keywords, [])-assert.deepEqual(searchTerms(" NOTE\tstudio "), ["note", "studio"])--for (const query of ["", " ", "NOTE", "productivity", "markdown", "documents", "studio productivity markdown"]) {- assert(matchesProgram(program, searchTerms(query)), query)-}--assert(!matchesProgram(program, searchTerms("missing")))-assert(!matchesProgram(program, searchTerms("studio missing")))-assert(matchesProcess("daily draft", undefined, searchTerms("DAILY draft")))-assert(matchesProcess(null, program, searchTerms("markdown productivity")))-assert(matchesProcess("daily draft", program, searchTerms("documents")))-assert(matchesProcess(null, undefined, searchTerms("")))-assert(!matchesProcess(null, undefined, searchTerms("notes")))-assert(!matchesProcess("daily draft", program, searchTerms("missing")))--const footer = renderToStaticMarkup(<AppearanceProvider appearance={defaultAppearance} theme="light"><SearchBar query="notes" onChange={() => {}} /></AppearanceProvider>)--assert.match(footer, /<div class="react-aria-TextField"/)-assert.match(footer, /<input\b/)-assert.match(footer, /value="notes"/)-assert.match(footer, /aria-label="Search Programs and Processes"/)-assert.equal(footer.match(/data-material=""/g)?.length, 1)-assert.doesNotMatch(footer, /<(?:main|section|article|aside|nav|header|footer)\b/)-assert.doesNotMatch(footer, /Signed in as/)diff --git a/scripts/contracts/storage.ts b/scripts/contracts/storage.tsdeleted file mode 100644index d106b8b..0000000--- a/scripts/contracts/storage.ts+++ /dev/null@@ -1,79 +0,0 @@-import assert from "node:assert/strict"-import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"-import { tmpdir } from "node:os"-import { join, resolve } from "node:path"-import FileArea, { FileSystem } from "@libs/file-area"-import AuthManager from "@server/core/link-manager/auth-manager/auth-manager"--const fixture = mkdtempSync(join(tmpdir(), "phreshos-storage-"))-const root = join(fixture, "configured")-const outside = join(fixture, "outside")--try {- const storage = new FileArea(root)- const home = new FileSystem(resolve(fixture, "home"))- const authManager = Object.assign(Object.create(AuthManager.prototype), {- linkManager: { application: { home, storage: { path: root } } },- $outbound: { async publish() {} }- }) as AuthManager- const systemStorage = (AuthManager.prototype as unknown as {- storage(operation: unknown, values: unknown): Promise<unknown>- }).storage-- assert.equal(await systemStorage.call(authManager, "path", []), home.path)- assert.equal(await systemStorage.call(authManager, "path", ["..", "outside"]), outside)-- mkdirSync(join(root, "kept"), { recursive: true })- mkdirSync(join(root, "nested"), { recursive: true })- writeFileSync(join(root, "kept", "value.txt"), "kept")- writeFileSync(join(root, "nested", "value.txt"), "removed")-- storage.clear(["nested"])-- assert.deepEqual(readdirSync(join(root, "nested")), [])- assert.deepEqual(readdirSync(join(root, "kept")), ["value.txt"])-- storage.create(["created"])- await storage.write(["created", "value.txt"], new Blob(["storage"]).stream(), undefined, false)- await storage.append(["created", "value.txt"], new Blob([" file"]).stream())- assert.equal(readFileSync(join(root, "created", "value.txt"), "utf8"), "storage file")- assert.equal(await new Response(storage.stream(["created", "value.txt"], [8, 4])).text(), "file")- assert.deepEqual(storage.list([], [true]), [- { kind: "storage", path: ["created"] },- { kind: "file", path: ["created", "value.txt"] },- { kind: "storage", path: ["kept"] },- { kind: "file", path: ["kept", "value.txt"] },- { kind: "storage", path: ["nested"] }- ])- assert.ok(storage.space().capacity > 0)-- const changes = storage.watch(["created"])- const changed = changes.next()- await new Promise(resolve => setTimeout(resolve, 10))- writeFileSync(join(root, "created", "watched.txt"), "changed")- assert.match((await changed).value?.event ?? "", /^(change|rename)$/)- await changes.return(undefined)- assert.throws(() => storage.resolve(["..", "outside"]), /configured directory/)-- mkdirSync(outside, { recursive: true })- writeFileSync(join(outside, "value.txt"), "outside")- symlinkSync(outside, join(root, "escape"), "dir")- symlinkSync(outside, join(home.path, "escape"), "dir")-- assert.equal(home.resolve(["escape", "value.txt"]), join(home.path, "escape", "value.txt"))- assert.equal(home.stat(["escape", "value.txt"])?.kind, "file")-- assert.throws(() => storage.stat(["escape", "value.txt"]), /symbolic link/)- assert.throws(() => storage.list(["escape"]), /symbolic link/)- assert.throws(() => storage.stream(["escape", "value.txt"]), /symbolic link/)- assert.throws(() => storage.delete(["escape", "value.txt"]), /symbolic link/)- assert.throws(() => storage.clear(["escape"]), /symbolic link/)- await assert.rejects(- storage.write(["escape", "written.txt"], new Blob(["outside"]).stream()),- /symbolic link/- )- assert.deepEqual(readdirSync(outside), ["value.txt"])-}-finally {- rmSync(fixture, { recursive: true, force: true })-}diff --git a/scripts/contracts/uploads.ts b/scripts/contracts/uploads.tsdeleted file mode 100644index 8c3d125..0000000--- a/scripts/contracts/uploads.ts+++ /dev/null@@ -1,73 +0,0 @@-import assert from "node:assert/strict"-import { mkdtemp, readFile, rm } from "node:fs/promises"-import { resolve } from "node:path"-import FileManager from "@libs/file-manager"-import UploadManager from "@server/core/upload-manager"-import uploadView from "@server/view/http/uploads"-import type Application from "@server/core/application"-import { Hono } from "hono"--const directory = await mkdtemp(resolve(".verify-uploads-"))-const uploads = new UploadManager(new FileManager(directory))--try {- const file = await uploads.write("txt", new Blob(["hello uploads"]).stream())- const upload = uploads.stat(file)-- assert(upload)- assert.equal(upload.size, 13)- assert.equal(typeof upload.modifiedAt, "number")- assert.equal(await readFile(uploads.path(file), "utf8"), "hello uploads")- assert.equal(uploads.stat("00000000-0000-0000-0000-000000000000.txt"), null)- assert.throws(() => uploads.stat("../outside.txt"), /not an upload file/)-- const view = new Hono()-- const application = {- uploads,- linkManager: {- authManager: {- verify(value: unknown) {- if (value !== "allowed") throw new Error("Unauthorized")- },- async upload(authorization: unknown, content: ReadableStream<Uint8Array> | null, extension: string, signal?: AbortSignal) {- this.verify(authorization)- const written = await uploads.write(extension, content, signal)- const upload = uploads.stat(written)- assert(upload)- return { file: written, ...upload }- }- }- }- } as unknown as Application-- view.route("/uploads", uploadView(application))- const response = await view.request("http://system/uploads", {- method: "POST",- headers: {- authorization: "allowed",- "content-disposition": "attachment; filename=value.json",- "content-type": "application/json"- },- body: JSON.stringify({ ready: true })- })- assert.equal(response.status, 200)- const created = await response.json()-- assert.equal(created.file.endsWith(".json"), true)- assert.equal(created.size, 14)- assert.equal(typeof created.modifiedAt, "number")- const described = await view.request(`http://system/uploads/${created.file}/stat`)- const downloaded = await view.request(`http://system/uploads/${created.file}`)-- assert.equal(described.status, 200)- assert.equal(downloaded.status, 200)- assert.deepEqual(await described.json(), { size: created.size, modifiedAt: created.modifiedAt })- assert.deepEqual(JSON.parse(await downloaded.text()), { ready: true })- assert.equal((await view.request("http://system/uploads/not-a-key")).status, 400)- assert.equal((await view.request("http://system/uploads/00000000-0000-0000-0000-000000000000.txt")).status, 404)-} finally {- await rm(directory, { recursive: true, force: true })-}--console.log("uploads verified")diff --git a/scripts/contracts/window-geometry.ts b/scripts/contracts/window-geometry.tsdeleted file mode 100644index db2e73f..0000000--- a/scripts/contracts/window-geometry.ts+++ /dev/null@@ -1,88 +0,0 @@-import assert from "node:assert/strict"-import ClientWindow from "@client/core/link-manager/auth-manager/process-manager/window"-import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"-import ServerWindow from "@server/core/link-manager/auth-manager/process-manager/window"-import type ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"--const initial = {- position: { x: 10, y: 20 },- size: { width: 300, height: 200 }-}--const authority = new ServerWindow(- { title: "Geometry", layer: "window" },- initial.position,- initial.size,- 1,- false-)--assert.throws(() => authority.setGeometry({- position: { x: 40, y: 50 },- size: { width: Number.NaN, height: 240 }-}), /width/)-assert.deepEqual(authority.position, initial.position)-assert.deepEqual(authority.size, initial.size)--const next = {- position: { x: "1/4", y: 30 },- size: { width: "1/2", height: 240 }-}-const events: unknown[][] = []-const echoes: unknown[][] = []-const manager = {- $outbound: {- async publish(...echo: unknown[]) {- echoes.push(echo)- return []- }- },- mutableWindowOf(identity: string) {- assert.equal(identity, "process")- return authority- },- said(...event: unknown[]) {- events.push(event)- }-}--const echo = await ProcessManager.prototype.setGeometry.call(manager as unknown as ProcessManager, "process", next)--assert.deepEqual(authority.position, next.position)-assert.deepEqual(authority.size, next.size)-assert.deepEqual(events, [- ["process", "geometry", next],- ["process", "move", next.position],- ["process", "resize", next.size]-])-assert.deepEqual(echoes, [["/geometry", { identity: "process", window: authority }]])-assert.equal(echo.identity, "process")-assert.equal(echo.window, authority)--const publications: unknown[][] = []-const counterpart = new ClientWindow(- { $outbound: { async publish(...publication: unknown[]) { publications.push(publication); return [] } } } as unknown as ClientProcessManager,- "process",- authority.toJSON()-)-await counterpart.setGeometry(next)-assert.deepEqual(publications, [["/geometry", "process", next]])--authority.minimized = true-await ProcessManager.prototype.maximize.call(manager as unknown as ProcessManager, "process", true)-assert.equal(authority.maximized, true)-assert.equal(authority.minimized, true)-assert.deepEqual(authority.position, next.position)-assert.deepEqual(authority.size, next.size)-assert.deepEqual(events.at(-1), ["process", "maximize", true])-const stored = { position: { x: 44, y: 55 }, size: { width: 440, height: 550 } }-authority.setGeometry(stored)-await ProcessManager.prototype.maximize.call(manager as unknown as ProcessManager, "process", false)-assert.equal(authority.minimized, true)-assert.equal(authority.maximized, false)-assert.deepEqual(authority.position, stored.position)-assert.deepEqual(authority.size, stored.size)-await counterpart.maximize(true)-assert.deepEqual(publications.at(-1), ["/maximize", "process", true])-counterpart.follow(authority.toJSON())-assert.equal(counterpart.maximized, false)diff --git a/scripts/contracts/worker-runtime.ts b/scripts/contracts/worker-runtime.tsdeleted file mode 100644index 856eb0c..0000000--- a/scripts/contracts/worker-runtime.ts+++ /dev/null@@ -1,115 +0,0 @@-import assert from "node:assert/strict"-import { mkdtemp, rm, writeFile } from "node:fs/promises"-import { createRequire } from "node:module"-import { tmpdir } from "node:os"-import { delimiter, join } from "node:path"-import { pathToFileURL } from "node:url"-import CommandServerRuntime, { commandServerEnvironment } from "@server/view/server-runtime/command"-import WorkerServerRuntime from "@server/view/server-runtime/worker"-import Program from "@server/core/link-manager/auth-manager/program-manager/program"-import type { ProgramConfig } from "@server/core/link-manager/auth-manager/program-manager/config"--const directory = await mkdtemp(join(tmpdir(), "phresh-worker-runtime-"))-const entry = join(directory, "server.mjs")-const commandEntry = join(directory, "command.mjs")-const codec = pathToFileURL(createRequire(import.meta.url).resolve("@the-link/messagepack")).href--assert.equal(- commandServerEnvironment(directory, { Path: "/native/bin" }).Path,- `${join(directory, "node_modules", ".bin")}${delimiter}/native/bin`-)--await writeFile(entry, `-import { parentPort } from "node:worker_threads"-import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}--console.log("worker output")-parentPort.postMessage(encode(["boundary", "ready"]))-parentPort.on("message", message => {- const [event, value] = decode(message)- if (event === "probe") parentPort.postMessage(encode(["probe-result", value]))-})-`)--await writeFile(commandEntry, `-import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}--console.log("command output")-process.send?.(encode(["boundary", "ready"]))-process.on("message", message => {- const [event, value] = decode(bytes(message))- if (event === "probe") process.send?.(encode(["probe-result", value]))-})--function bytes(value) {- if (value instanceof Uint8Array) return value- const record = value- const result = new Uint8Array(Object.keys(record).length)- for (let index = 0; index < result.length; index++) result[index] = record[index]- return result-}-`)--try {- const program = new Program({ identity: "worker-verification", server: { location: directory, entryFile: "server.mjs" } })-- await program.validate()-- assert.equal(program.serverEntryPath, entry)-- assert.throws(() => new Program({ identity: "worker-conflict", server: { location: directory, startCommand: "node main.js", entryFile: "server.mjs" } } as unknown as ProgramConfig))- assert.throws(() => new Program({ identity: "worker-escape", server: { location: directory, entryFile: "../server.mjs" } }))-- const runtime = new WorkerServerRuntime(entry)- const messages: unknown[][] = []- const output: ["out" | "err", string][] = []-- runtime.onMessage((event, ...values) => messages.push([event, ...values]))- runtime.onOutput((stream, text) => output.push([stream, text]))-- await until(() => messages.some(message => message[0] === "boundary" && message[1] === "ready"))-- runtime.send("probe", 42)-- await until(() => messages.some(message => message[0] === "probe-result"))- await until(() => output.some(([stream, text]) => stream === "out" && text.includes("worker output")))-- assert.deepEqual(messages.find(message => message[0] === "probe-result"), ["probe-result", 42])-- runtime.stop()-- const ending = await runtime.finished-- assert.equal(ending.signal, null)-- const command = new CommandServerRuntime(`node ${JSON.stringify(commandEntry)}`, directory)- const commandMessages: unknown[][] = []- const commandOutput: ["out" | "err", string][] = []-- command.onMessage((event, ...values) => commandMessages.push([event, ...values]))- command.onOutput((stream, text) => commandOutput.push([stream, text]))-- await until(() => commandMessages.some(message => message[0] === "boundary" && message[1] === "ready"))-- command.send("probe", 42)-- await until(() => commandMessages.some(message => message[0] === "probe-result"))- await until(() => commandOutput.some(([stream, text]) => stream === "out" && text.includes("command output")))-- assert.deepEqual(commandMessages.find(message => message[0] === "probe-result"), ["probe-result", 42])-- command.stop()-- await command.finished-} finally {- await rm(directory, { recursive: true, force: true })-}--async function until(condition: () => boolean, timeout = 2_000) {- const began = Date.now()-- while (!condition()) {- if (Date.now() - began >= timeout) throw new Error(`Worker verification timed out after ${timeout}ms`)- await new Promise(resolve => setTimeout(resolve, 10))- }-}diff --git a/scripts/verify-contracts.ts b/scripts/verify-contracts.tsdeleted file mode 100644index 9f7b510..0000000--- a/scripts/verify-contracts.ts+++ /dev/null@@ -1,8 +0,0 @@-import { readdir } from "node:fs/promises"--const directory = new URL("./contracts/", import.meta.url)--for (const file of (await readdir(directory)).filter(file => /\.tsx?$/.test(file)).sort()) {-- await import(new URL(file, directory).href)-}diff --git a/scripts/verify-distribution.mjs b/scripts/verify-distribution.mjsdeleted file mode 100644index 428cf28..0000000--- a/scripts/verify-distribution.mjs+++ /dev/null@@ -1,143 +0,0 @@-import assert from "node:assert/strict"-import { execFileSync, spawn } from "node:child_process"-import { createHash } from "node:crypto"-import { mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs"-import { createServer } from "node:net"-import { tmpdir } from "node:os"-import { dirname, join, resolve } from "node:path"-import { fileURLToPath } from "node:url"-import AdmZip from "adm-zip"-import manifest from "../package.json" with { type: "json" }--const repository = resolve(dirname(fileURLToPath(import.meta.url)), "..")-const temporary = mkdtempSync(join(tmpdir(), "system-distribution-"))-const archive = join(repository, `${manifest.name}@${manifest.version}.zip`)-const checksum = `${archive}.sha256`-const installation = join(temporary, "installation")-const npm = process.platform === "win32"-- ? { command: process.execPath, prefix: [join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js")] }-- : { command: "npm", prefix: [] }-const portVariable = `${manifest.name.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase()}_PORT`--let runtime--try {- execFileSync(- process.execPath,- ["--run", "pack"],- { cwd: repository, stdio: "inherit" }- )-- const zip = new AdmZip(archive)- const expectedChecksum = readFileSync(checksum, "utf8").trim()- const actualChecksum = createHash("sha256").update(readFileSync(archive)).digest("hex")-- assert.equal(expectedChecksum, `${actualChecksum} ${archive.slice(repository.length + 1)}`)-- const paths = new Set(zip.getEntries().filter(entry => !entry.isDirectory).map(entry => entry.entryName))-- for (const required of [- "package.json",- "server/main.js",- "client/index.html",- "assets/default-icon.png"- ]) {- assert(paths.has(required), `the distribution has no ${required}`)- }-- for (const path of paths) {- assert(!path.startsWith("source/"), `TypeScript source entered the distribution: ${path}`)- assert(!path.startsWith("storage/"), `runtime storage entered the distribution: ${path}`)- assert(!path.startsWith("node_modules/"), `development dependencies entered the distribution: ${path}`)- assert(!path.startsWith(".git"), `repository state entered the distribution: ${path}`)- }-- mkdirSync(installation)- zip.extractAllTo(installation)-- const installedManifest = JSON.parse(readFileSync(join(installation, "package.json"), "utf8"))-- assert.deepEqual(installedManifest.scripts, { start: "node server/main.js" })- assert.deepEqual(installedManifest.engines, { node: ">=24.15.0" })- assert.deepEqual(- installedManifest.dependencies,- Object.fromEntries(["cfonts", "sharp"].map(name => [name, manifest.dependencies[name]]))- )-- execFileSync(- npm.command,- [...npm.prefix, "install", "--omit=dev", "--no-audit", "--no-fund", "--no-package-lock"],- { cwd: installation, stdio: "inherit" }- )-- execFileSync(process.execPath, ["--check", "server/main.js"], { cwd: installation })-- if (process.env.CI === "true") await boot(installation)-} finally {- if (runtime && runtime.exitCode === null) {- runtime.kill()- await new Promise(resolve => runtime.once("exit", resolve))- }-- rmSync(archive, { force: true })- rmSync(checksum, { force: true })- rmSync(temporary, { recursive: true, force: true })-}--async function availablePort() {- const server = createServer()-- await new Promise((resolve, reject) => {- server.once("error", reject)- server.listen(0, "127.0.0.1", resolve)- })-- const address = server.address()-- assert(address && typeof address === "object")-- await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()))-- return address.port-}--async function boot(directory) {- const port = await availablePort()- const output = []-- runtime = spawn(process.execPath, ["server/main.js"], {- cwd: directory,- env: { ...process.env, [portVariable]: String(port) },- stdio: ["ignore", "pipe", "pipe"]- })-- runtime.stdout.on("data", data => output.push(data.toString()))- runtime.stderr.on("data", data => output.push(data.toString()))-- await waitForDesktop(port, runtime, output)-}--async function waitForDesktop(port, child, output) {- const deadline = Date.now() + 20_000- const url = `http://localhost:${port}/`-- while (Date.now() < deadline) {- if (child.exitCode !== null) throw new Error(`the installed system exited before serving the desktop\n${output.join("")}`)-- try {- const response = await fetch(url)- const body = await response.text()-- assert.equal(response.status, 200)- assert.match(body, /<html/i)-- return- } catch {- await new Promise(resolve => setTimeout(resolve, 100))- }- }-- throw new Error(`the installed system did not serve the desktop\n${output.join("")}`)-}diff --git a/tests/appearance.test.ts b/tests/appearance.test.tsnew file mode 100644index 0000000..088e0d5--- /dev/null+++ b/tests/appearance.test.ts@@ -0,0 +1,96 @@+import assert from "node:assert/strict"+import Keyv from "keyv"+import { defaultAppearance, parseAppearance } from "@phreshos/core"+import AppearanceManager from "@server/core/appearance-manager"+import FileManager from "@libs/file-manager"+import UploadManager from "@server/core/upload-manager"+import { mkdtemp, rm } from "node:fs/promises"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { test } from "vitest"++test("appearance contract", async () => {+ assert.deepEqual(parseAppearance(defaultAppearance), defaultAppearance)+ assert.throws(() => parseAppearance({}))+ assert.throws(() => parseAppearance({+ ...defaultAppearance,+ colors: { ...defaultAppearance.colors, accent: defaultAppearance.colors.light.primary }+ }))+ assert.throws(() => parseAppearance({ ...defaultAppearance, spacing: { light: 12, dark: 12 } }))+ assert.throws(() => parseAppearance({+ ...defaultAppearance,+ material: {+ ...defaultAppearance.material,+ dark: { ...defaultAppearance.material.dark, grain: 1.01 }+ }+ }))+ assert.throws(() => parseAppearance({+ ...defaultAppearance,+ transaction: { duration: 120 }+ }))++ const store = new Keyv()+ const directory = await mkdtemp(join(tmpdir(), "phresh-appearance-"))+ const uploads = new UploadManager(new FileManager(directory))+ const manager = await AppearanceManager.open(store, uploads)++ assert.deepEqual(manager.value, defaultAppearance)+ assert(Object.isFrozen(manager.value))+ assert.deepEqual(await store.get("appearance"), defaultAppearance)++ for (const theme of ["light", "dark"] as const) {+ for (const role of ["background", "foreground", "primary", "secondary", "success", "warning", "danger", "info"] as const) {+ const color = "oklch(60% 0.2 260)"+ const colors = {+ ...manager.value.colors,+ [theme]: { ...manager.value.colors[theme], [role]: color }+ }++ await manager.update({ ...manager.value, colors })+ assert.equal(manager.value.colors[theme][role], color)+ assert.equal((await store.get("appearance")).colors[theme][role], color)+ assert(Object.isFrozen(manager.value.colors[theme]))++ const current = manager.value+ const invalidColors = {+ ...current.colors,+ [theme]: { ...current.colors[theme], [role]: "" }+ }++ await assert.rejects(manager.update({ ...current, colors: invalidColors }))+ assert.equal(manager.value, current)+ assert.deepEqual(await store.get("appearance"), current)+ }+ }++ const reopened = await AppearanceManager.open(store, uploads)+ assert.deepEqual(reopened.value, manager.value)++ const shadow = {+ light: { x: -3, y: 12, blur: 30, spread: 2, opacity: 0.25 },+ dark: { x: 2, y: 6, blur: 18, spread: -1, opacity: 0.12 }+ }+ await manager.update({ ...manager.value, shadow })+ assert.deepEqual(manager.value.shadow, shadow)+ assert.deepEqual((await store.get("appearance")).shadow, shadow)+ assert.deepEqual((await AppearanceManager.open(store, uploads)).value.shadow, shadow)++ for (const invalid of [{ ...shadow.light, blur: -1 }, { ...shadow.light, opacity: 1.1 }, { ...shadow.light, x: Infinity }]) {+ await assert.rejects(manager.update({ ...manager.value, shadow: { ...shadow, light: invalid } }))+ assert.deepEqual(manager.value.shadow, shadow)+ }++ const updated = {+ ...manager.value,+ transaction: { duration: 180, easing: [0.25, 0.1, 0.25, 1] as const }+ }++ await manager.update(updated)++ assert.deepEqual(manager.value, updated)+ assert.deepEqual(await store.get("appearance"), updated)+ assert.equal(await store.get("appearance:colors"), undefined)+ assert.equal(await store.get("appearance:theme"), undefined)++ await rm(directory, { recursive: true, force: true })+}, 120_000)diff --git a/tests/client-launch.test.ts b/tests/client-launch.test.tsnew file mode 100644index 0000000..e1eb0d3--- /dev/null+++ b/tests/client-launch.test.ts@@ -0,0 +1,30 @@+import assert from "node:assert/strict"+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"+import type { ClientLaunch } from "@phreshos/core"+import type Program from "@server/core/link-manager/auth-manager/program-manager/program"+import { test } from "vitest"++test("client launch contract", async () => {+ const manager = {+ authManager: {+ processManager: {+ processes: new Map()+ }+ }+ }++ const program = {+ client: {},+ title: "Declared title"+ }++ const shape = (overrides: ClientLaunch) => ProgramManager.prototype.clientShape.call(+ manager as unknown as ProgramManager,+ program as unknown as Program,+ overrides+ )++ assert.equal(shape({ title: "Fetched title" }).title, "Fetched title")+ assert.equal(shape({}).title, "Declared title")+ assert.throws(() => shape({ title: 42 } as unknown as ClientLaunch), /title must be text/)+}, 120_000)diff --git a/tests/client-sandbox.test.ts b/tests/client-sandbox.test.tsnew file mode 100644index 0000000..ed96193--- /dev/null+++ b/tests/client-sandbox.test.ts@@ -0,0 +1,47 @@+import assert from "node:assert/strict"+import Process from "@server/core/link-manager/auth-manager/process-manager/process"+import Window from "@server/core/link-manager/auth-manager/process-manager/window"+import type Program from "@server/core/link-manager/auth-manager/program-manager/program"+import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"+import { test } from "vitest"++test("client sandbox contract", async () => {+ const process = new Process(++ "process",++ null,++ { identity: "program" } as Program,++ {},++ { server: null, client: null, options: {} },++ null,++ {} as HostTraffic,++ false+ )++ process.startClient(new Window(++ { title: "Client", layer: "window" },++ { x: 0, y: 0 },++ { width: 640, height: 480 },++ 1,++ false+ ), false)++ assert.equal(process.hosted().client?.sameOrigin, false)++ assert.equal(process.setClientSameOrigin(true), true)+ assert.equal(process.setClientSameOrigin(true), false)++ assert.equal(process.hosted().client?.sameOrigin, true)+}, 120_000)diff --git a/tests/client-surface.test.ts b/tests/client-surface.test.tsnew file mode 100644index 0000000..c6f169e--- /dev/null+++ b/tests/client-surface.test.ts@@ -0,0 +1,329 @@+import assert from "node:assert/strict"+import ClientProcessBoundary from "@client/view/components/desktop-host/client-process-boundary"+import ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"+import { parseLocalWindowTransaction } from "@client/view/components/desktop-host/local-window"+import host from "@client/view/components/desktop-host/host"+import LocalWindows from "@client/view/components/window-manager/local-windows"+import type { LocalWindowEntry } from "@client/view/components/window-manager/local-windows"+import ServerWindow from "@server/core/link-manager/auth-manager/process-manager/window"+import type { LocalWindowState } from "@client/view/components/desktop-host/local-window"+import type { AppearanceTransaction, WaitedTransaction, WindowLayer } from "@phreshos/core"+import { test } from "vitest"++test("client surface contract", async () => {+ type RequestedTransaction = AppearanceTransaction | WaitedTransaction++ const authoritativeWindow = new ServerWindow(+ { title: "Target", layer: "over" },+ { x: 0, y: 0 },+ { width: 100, height: 100 },+ 1,+ false+ )++ assert.equal("surface" in authoritativeWindow, false)+ assert.equal("surface" in authoritativeWindow.toJSON(), false)++ const transaction = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })+ const visibility = parseLocalWindowTransaction({ duration: 240, easing: "ease-out", wait: true })!++ assert.throws(() => parseLocalWindowTransaction({}), /must provide duration and easing/)+ assert.throws(() => parseLocalWindowTransaction({ wait: true }), /must provide duration and easing/)+ assert.throws(() => parseLocalWindowTransaction({ duration: 60_001, easing: "linear" }), /0 to 60000/)+ assert.throws(() => parseLocalWindowTransaction({ duration: 120 }), /must provide duration and easing/)+ assert.throws(() => parseLocalWindowTransaction({ duration: 120, easing: "linear", wait: false }), /must be true/)+ assert.throws(() => parseLocalWindowTransaction({ unknown: true }), /no "unknown" field/)++ const ordinary = client("window")+ const bare = client("over")+ const clients = new Map([+ ["ordinary", { identity: "ordinary:0", client: ordinary }],+ ["bare", { identity: "bare:0", client: bare }]+ ]) as unknown as ReadonlyMap<string, LocalWindowEntry>+ const byProcess = new Map([["ordinary", ordinary], ["bare", bare]])+ const first = new LocalWindows(clients, identity => byProcess.get(identity) as never ?? null)+ const second = new LocalWindows(clients, identity => byProcess.get(identity) as never ?? null)++ await first.move("ordinary", { x: 40, y: 50 })+ await first.move("bare", { x: 60, y: 70 })++ assert.deepEqual(first.state("ordinary").position, { x: 40, y: 50 })+ assert.deepEqual(first.state("bare").position, { x: 60, y: 70 })+ assert.deepEqual(second.state("ordinary").position, { x: 0, y: 0 })+ assert.deepEqual(ordinary.window.position, { x: 0, y: 0 })++ // A reader reports the rectangle currently painted by the browser. Policy+ // such as fill/restore still needs the underlying projection, because a+ // relative full-surface value and its measured pixels are not equivalent.+ first.represent("ordinary", () => ({ position: { x: 0, y: 0 }, size: { width: 1200, height: 800 } }))+ assert.deepEqual(first.state("ordinary").size, { width: 1200, height: 800 })+ assert.deepEqual(first.projection("ordinary").size, { width: 300, height: 200 })+ first.represent("ordinary", null)++ first.represent("bare", () => ({ position: { x: 65, y: 75 }, size: { width: 290, height: 190 } }))+ assert.deepEqual(first.state("bare").position, { x: 65, y: 75 })+ assert.deepEqual(first.state("bare").size, { width: 290, height: 190 })+ first.represent("bare", null)++ // An unrelated full snapshot is not a Window change and must not erase a+ // local ordinary-window command.+ first.reconcile(clients)+ assert.deepEqual(first.state("ordinary").position, { x: 40, y: 50 })++ ordinary.window.position = { x: 15, y: 25 }+ bare.window.position = { x: 20, y: 30 }+ first.reconcile(clients)++ assert.deepEqual(first.state("ordinary").position, { x: 15, y: 25 })+ assert.deepEqual(first.state("bare").position, { x: 60, y: 70 })++ const matchingAuthority = first.move("ordinary", { x: 30, y: 40 }, { duration: 120, easing: "ease-out", wait: true })+ const matchingRevision = represented(first, "ordinary:0").geometryAnimation!.revision+ ordinary.window.position = { x: 30, y: 40 }+ first.reconcile(clients)+ assert.equal(represented(first, "ordinary:0").geometryAnimation!.revision, matchingRevision)+ first.complete("ordinary", "geometry", matchingRevision)+ await matchingAuthority++ const waiting = first.geometry("bare", {+ position: { x: 80, y: 90 },+ size: { width: 320, height: 240 }+ }, transaction)+ const geometryRevision = represented(first, "bare:0").geometryAnimation!.revision+ first.complete("bare", "geometry", geometryRevision)+ await waiting+ assert.equal(represented(first, "bare:0").geometryAnimation, null)++ const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, easing: "ease-out", wait: true })+ await first.move("bare", { x: 120, y: 130 })+ await assert.rejects(interrupted, /interrupted/)++ const following = first.follow("bare", "ordinary", transaction)+ const followRevision = represented(first, "bare:0").geometryAnimation!.revision+ first.reconcile(clients)+ assert.equal(represented(first, "bare:0").geometryAnimation!.revision, followRevision)+ first.complete("bare", "geometry", followRevision)+ await following+ assert.deepEqual(first.state("bare").position, first.state("ordinary").position)++ // Following reads authority, never another Desktop-local representation.+ await first.move("ordinary", { x: 150, y: 160 })+ assert.deepEqual(first.state("bare").position, ordinary.window.position)+ ordinary.window.position = { x: 170, y: 180 }+ first.reconcile(clients)+ assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })++ await first.unfollow("bare", transaction)+ assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })+ ordinary.window.position = { x: 190, y: 200 }+ first.reconcile(clients)+ assert.deepEqual(first.state("bare").position, { x: 170, y: 180 })++ // Default following can be disabled on ordinary windows and enabled on bare ones.+ await first.unfollow("ordinary")+ ordinary.window.position = { x: 210, y: 220 }+ first.reconcile(clients)+ assert.deepEqual(first.state("ordinary").position, { x: 190, y: 200 })+ await first.follow("ordinary", "ordinary")+ assert.deepEqual(first.state("ordinary").position, { x: 210, y: 220 })+ await first.follow("bare", "ordinary")+ await first.move("bare", { x: 125, y: 135 })+ ordinary.window.title = "Renamed"+ first.reconcile(clients)+ assert.equal(first.state("bare").title, "Renamed")+ assert.deepEqual(first.state("bare").position, { x: 125, y: 135 })+ ordinary.window.position = { x: 230, y: 240 }+ first.reconcile(clients)+ assert.deepEqual(first.state("bare").position, ordinary.window.position)++ // Stored geometry cannot cancel an in-progress maximize presentation.+ const maximizing = first.maximize("bare", true, transaction)+ const maximizeRevision = represented(first, "bare:0").geometryAnimation!.revision+ await first.move("bare", { x: 9, y: 10 }, transaction)+ assert.equal(represented(first, "bare:0").geometryAnimation!.revision, maximizeRevision)+ first.complete("bare", "geometry", maximizeRevision)+ await maximizing+ await first.maximize("bare", false)+ const toInterrupt = first.maximize("bare", true, transaction)+ await first.minimize("bare", true)+ await assert.rejects(toInterrupt, /was minimized/)+ await first.minimize("bare", false)+ await first.maximize("bare", false)++ // Minimize and maximize never overwrite the retained geometry or each other.+ await first.maximize("bare", true)+ await first.minimize("bare", true)+ await first.geometry("bare", { position: { x: 11, y: 12 }, size: { width: 111, height: 112 } }, transaction)+ assert.equal(first.projection("bare").geometryAnimation, null)+ assert.equal(first.state("bare").maximized, true)+ assert.equal(first.state("bare").minimized, true)+ await first.minimize("bare", false)+ assert.equal(first.state("bare").maximized, true)+ await first.maximize("bare", false)+ assert.deepEqual(first.state("bare").position, { x: 11, y: 12 })+ assert.deepEqual(first.state("bare").size, { width: 111, height: 112 })+ await first.follow("bare", "ordinary")+ ordinary.window.maximized = true+ ordinary.window.minimized = true+ first.reconcile(clients)+ assert.equal(first.state("bare").maximized, true)+ assert.equal(first.state("bare").minimized, true)+ ordinary.window.maximized = false+ ordinary.window.minimized = false+ first.reconcile(clients)++ const surfaceWaiting = first.addSurface("bare", visibility)+ const surfaceRevision = surface(first, "bare:0").transition!.revision+ first.complete("bare", "surface", surfaceRevision)+ await surfaceWaiting+ assert.equal(surface(first, "bare:0").transition, null)+ assert.equal(surface(first, "bare:0").visible, true)++ const surfaceRemoval = first.removeSurface("bare", visibility)+ const removalRevision = surface(first, "bare:0").transition!.revision+ assert.equal(surface(first, "bare:0").visible, false)+ first.complete("bare", "surface", removalRevision)+ await surfaceRemoval+ assert.equal(represented(first, "bare:0").surface, null)++ assert.equal(represented(second, "bare:0").surface, null)++ first.release("bare")+ assert.deepEqual(first.state("bare").position, bare.window.position)+ assert.equal(represented(first, "bare:0").surface, null)++ const removed = first.move("bare", { x: 140, y: 150 }, { duration: 200, easing: "ease-out", wait: true })+ const remaining = clients.get("ordinary")+ assert(remaining)+ first.reconcile(new Map([["ordinary", remaining]]))+ await assert.rejects(removed, /representation was removed/)++ const parent = {+ identity: "parent",+ reference: "parent-reference",+ name: "manager",+ program: "program",+ options: {},+ startedAt: new Date(),+ server: null,+ client: null+ }+ const requester = {+ identity: "requester",+ reference: "requester-reference",+ program: "program",+ parent,+ client: { window: { process: "requester", layer: "over" } }+ }+ const target = {+ identity: "target",+ reference: "target-reference",+ program: "program",+ client: { window: { process: "target", layer: "over", position: { x: 10, y: 20 } } }+ }+ const processes = new Map<string, object>([[parent.identity, parent], [requester.identity, requester], [target.identity, target]])+ const calls: unknown[][] = []+ const localWindow = {+ state(identity: string) { return { position: identity === "target" ? { x: 70, y: 80 } : { x: 0, y: 0 } } },+ move(identity: string, value: unknown, motion: RequestedTransaction | undefined) { calls.push(["move", identity, value, motion]) },+ follow(identity: string, followed: string, motion: RequestedTransaction | undefined) { calls.push(["follow", identity, followed, motion]) },+ unfollow(identity: string, motion: RequestedTransaction | undefined) { calls.push(["unfollow", identity, motion]) },+ addSurface(identity: string, motion: RequestedTransaction) { calls.push(["add", identity, motion]) },+ removeSurface(identity: string, motion: RequestedTransaction) { calls.push(["remove", identity, motion]) }+ }+ const processManager = {+ processes,+ front: ClientProcessManager.prototype.front,+ async ownFrame() {},+ async releaseFrame() {},+ async unsubscribeFrame() {}+ }+ const authManager = {+ processManager,+ programManager: { programs: new Map([["program", {+ reference: "program-reference",+ identity: "program",+ assetId: "00000000-0000-4000-8000-000000000000",+ installed: true,+ name: "Program",+ version: null,+ description: null,+ hasAgent: false,+ server: null,+ client: null+ }]]) },+ }+ const request = host(authManager as never, requester.identity, () => ({ size: { width: 1, height: 1 } }), () => "owner", localWindow as never)++ assert.deepEqual(await request("desktopViewport"), [{ size: { width: 1, height: 1 } }])+ const targetAddress = { identity: target.identity, reference: target.reference }+ const requesterAddress = { identity: requester.identity, reference: requester.reference }+ processes.delete(parent.identity)+ const parentAnswer = await request("parent", requesterAddress)+ assert(Array.isArray(parentAnswer))+ const retainedParent = parentAnswer[0] as { identity: string }+ assert.equal(retainedParent.identity, parent.identity)+ await request("windowLocalMove", requesterAddress, { x: 70, y: 80 })+ await request("windowLocalFollow", requesterAddress, targetAddress, visibility)+ await request("windowLocalUnfollow", requesterAddress, visibility)+ await request("windowLocalSurfaceAdd", requesterAddress, undefined, visibility)+ await request("windowLocalSurfaceRemove", requesterAddress, undefined, visibility)++ assert.deepEqual(calls, [+ ["move", "requester", { x: 70, y: 80 }, undefined],+ ["follow", "requester", "target", visibility],+ ["unfollow", "requester", visibility],+ ["add", "requester", visibility],+ ["remove", "requester", visibility]+ ])+ assert.deepEqual(target.client.window.position, { x: 10, y: 20 })+ await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress, undefined, { identity: "unexpected" }), /no "identity" field/)+ await assert.rejects(request("windowLocalSurfaceAdd", targetAddress), /current Client Context/)+ await assert.rejects(request("windowLocalSurfaceAdd", { ...requesterAddress, reference: "wrong" }), /represented by this handle does not exist/)+ requester.client.window.layer = "window"+ await request("windowLocalMove", requesterAddress, { x: 0, y: 0 })+ await assert.rejects(request("windowLocalSurfaceAdd", requesterAddress), /already owns its host Surface/)+ await assert.rejects(request("windowLocalSurfaceRemove", requesterAddress), /already owns its host Surface/)+ requester.client.window.layer = "over"++ const lifecycle: string[] = []+ const boundary = new ClientProcessBoundary(+ "requester",+ { contentWindow: null } as unknown as HTMLIFrameElement,+ authManager as never,+ () => ({ size: { width: 1, height: 1 } }),+ {} as never,+ { release(identity: string) { lifecycle.push(identity) } } as never+ )++ await boundary.own("first-owner")+ await boundary.own("second-owner")+ await boundary.release()++ assert.deepEqual(lifecycle, ["requester", "requester"])++ function client(layer: WindowLayer) {+ return {+ window: {+ title: "Window",+ position: { x: 0, y: 0 },+ size: { width: 300, height: 200 },+ minimized: false, maximized: false,+ layer,+ depth: 1+ }+ }+ }++ function represented(windows: LocalWindows, identity: string): LocalWindowState {+ const value = windows.windows.get(identity)+ assert(value)+ return value+ }++ function surface(windows: LocalWindows, identity: string) {+ const value = represented(windows, identity).surface+ assert(value)+ return value+ }+}, 120_000)diff --git a/tests/client-system-access.test.ts b/tests/client-system-access.test.tsnew file mode 100644index 0000000..da17f75--- /dev/null+++ b/tests/client-system-access.test.ts@@ -0,0 +1,131 @@+import assert from "node:assert/strict"+import { homedir } from "node:os"+import { resolve } from "node:path"+import type AuthManager from "@client/core/link-manager/auth-manager/auth-manager"+import SystemAccess from "@client/view/components/desktop-host/system-access"+import { permissionCatalog } from "@server/core/permissions"+import type { PermissionName, Permissions } from "@phreshos/core"+import { test } from "vitest"++test("client system access contract", async () => {+ const owner = { identity: "process:owner", program: "owner" }+ const sibling = { identity: "process:sibling", program: "owner" }+ const outside = { identity: "process:outside", program: "outside" }+ let permissions: Permissions = {}++ const authManager = {+ processManager: { processes: new Map([+ [owner.identity, owner],+ [sibling.identity, sibling],+ [outside.identity, outside]+ ]) },+ async grantsPermission(process: string, name: PermissionName, values: readonly string[]) {++ assert.equal(process, owner.identity)++ return permissionCatalog.allows(name, values as never, permissions)+ },+ async grantsStorage(process: string, path: string, operation?: "read" | "write" | "delete") {++ assert.equal(process, owner.identity)++ return permissionCatalog.allowsStorage(permissions.all ?? null, permissions.storage ?? null, path, operation)+ }+ } as unknown as AuthManager++ const access = new SystemAccess(authManager, owner.identity)+ const ownProgram = { identity: "owner" }+ const outsideProgram = { identity: "outside" }+ const ownService = { program: "owner", process: "main", endpoint: "server" } as const+ const ownExactService = { process: sibling.identity, endpoint: "client" } as const+ const outsideService = { program: "outside", process: "main", endpoint: "server" } as const++ assert(access.ownsProgram(ownProgram))+ assert(!access.ownsProgram(outsideProgram))+ assert(access.ownsProcess(sibling))+ assert(!access.ownsProcess(outside))+ assert(access.ownsService(ownService))+ assert(access.ownsService(ownExactService))+ assert(!access.ownsService(outsideService))+ assert.equal(await access.program(ownProgram as never), ownProgram)+ assert.equal(await access.service(ownService), ownService)+ assert.equal(await access.service(ownExactService), ownExactService)+ await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)+ await assert.rejects(access.process(outside), /Execution is not permitted/)+ await assert.rejects(access.service(outsideService), /Execution is not permitted/)+ await assert.rejects(access.requirePrograms(), /Execution is not permitted/)+ await assert.rejects(access.requireNetwork("https://api.example.com/v1/users"), /Execution is not permitted/)+ await assert.rejects(access.requireStorage("/Users/person/Documents/report.txt", "read"), /Execution is not permitted/)+ await assert.rejects(access.require("uploads", []), /Execution is not permitted/)+ await assert.rejects(access.require("appearance", []), /Execution is not permitted/)+ await assert.rejects(access.require("desktopPreferences", []), /Execution is not permitted/)++ permissions = { services: ["outside"] }++ assert.equal(await access.service(outsideService), outsideService)+ await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)+ await assert.rejects(access.process(outside), /Execution is not permitted/)+ await assert.rejects(access.requirePrograms(), /Execution is not permitted/)++ permissions = { services: [] }++ assert.equal(await access.service(outsideService), outsideService)+ await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)+ await assert.rejects(access.requirePrograms(), /Execution is not permitted/)++ permissions = { programs: ["outside"] }++ assert.equal(await access.program(outsideProgram as never), outsideProgram)+ assert.equal(await access.process(outside), outside)+ assert.equal(await access.service(outsideService), outsideService)+ await assert.rejects(access.requirePrograms(), /Execution is not permitted/)++ permissions = { programs: [] }++ await access.requirePrograms()+ assert.equal(await access.program(outsideProgram as never), outsideProgram)+ assert.equal(await access.service(outsideService), outsideService)++ permissions = { appearance: [], desktopPreferences: [] }++ await access.require("appearance", [])+ await access.require("desktopPreferences", [])+ await assert.rejects(access.program(outsideProgram as never), /Execution is not permitted/)++ permissions = { uploads: [] }++ await access.require("uploads", [])+ await assert.rejects(access.requireAll(), /Execution is not permitted/)++ permissions = { network: ["https://*.example.com/v1/**"] }++ await access.requireNetwork("https://api.example.com/v1/users")+ await assert.rejects(access.requireNetwork("https://example.com/v1/users"), /Execution is not permitted/)+ await assert.rejects(access.requireNetwork("https://api.example.com/v2/users"), /Execution is not permitted/)++ permissions = { storage: ["read:Documents/**", "write:Documents/report.txt"] }++ await access.requireStorage(resolve(homedir(), "Documents/report.txt"))+ await access.requireStorage(resolve(homedir(), "Documents/report.txt"), "read")+ await access.requireStorage(resolve(homedir(), "Documents/report.txt"), "write")+ await assert.rejects(access.requireStorage(resolve(homedir(), "Documents/other.txt"), "write"), /Execution is not permitted/)+ await assert.rejects(access.requireStorage(resolve(homedir(), "Documents/report.txt"), "delete"), /Execution is not permitted/)+ await assert.rejects(access.requireStorage(homedir()), /Execution is not permitted/)++ permissions = { storage: [] }++ await access.requireStorage(homedir())++ permissions = { all: [] }++ assert.equal((await access.program(outsideProgram as never)).identity, "outside")+ assert.equal((await access.process(outside)).identity, outside.identity)+ assert.equal(await access.service(outsideService), outsideService)+ await access.requirePrograms()+ await access.require("appearance", [])+ await access.require("desktopPreferences", [])+ await access.requireNetwork("wss://events.example.com/socket")+ await access.requireStorage("/any/native/path", "delete")+ await access.require("uploads", [])+ await access.requireAll()+}, 120_000)diff --git a/tests/distribution.test.mjs b/tests/distribution.test.mjsnew file mode 100644index 0000000..b4d5d03--- /dev/null+++ b/tests/distribution.test.mjs@@ -0,0 +1,146 @@+import assert from "node:assert/strict"+import { execFileSync, spawn } from "node:child_process"+import { createHash } from "node:crypto"+import { mkdtempSync, mkdirSync, readFileSync, rmSync } from "node:fs"+import { createServer } from "node:net"+import { tmpdir } from "node:os"+import { dirname, join, resolve } from "node:path"+import { fileURLToPath } from "node:url"+import AdmZip from "adm-zip"+import manifest from "../package.json" with { type: "json" }+import { test } from "vitest"++test("distribution contract", async () => {+ const repository = resolve(dirname(fileURLToPath(import.meta.url)), "..")+ const temporary = mkdtempSync(join(tmpdir(), "system-distribution-"))+ const archive = join(repository, `${manifest.name}@${manifest.version}.zip`)+ const checksum = `${archive}.sha256`+ const installation = join(temporary, "installation")+ const npm = process.platform === "win32"++ ? { command: process.execPath, prefix: [join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js")] }++ : { command: "npm", prefix: [] }+ const portVariable = `${manifest.name.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase()}_PORT`++ let runtime++ try {+ execFileSync(+ process.execPath,+ ["--run", "pack"],+ { cwd: repository, stdio: "inherit" }+ )++ const zip = new AdmZip(archive)+ const expectedChecksum = readFileSync(checksum, "utf8").trim()+ const actualChecksum = createHash("sha256").update(readFileSync(archive)).digest("hex")++ assert.equal(expectedChecksum, `${actualChecksum} ${archive.slice(repository.length + 1)}`)++ const paths = new Set(zip.getEntries().filter(entry => !entry.isDirectory).map(entry => entry.entryName))++ for (const required of [+ "package.json",+ "server/main.js",+ "client/index.html",+ "assets/default-icon.png"+ ]) {+ assert(paths.has(required), `the distribution has no ${required}`)+ }++ for (const path of paths) {+ assert(!path.startsWith("source/"), `TypeScript source entered the distribution: ${path}`)+ assert(!path.startsWith("storage/"), `runtime storage entered the distribution: ${path}`)+ assert(!path.startsWith("node_modules/"), `development dependencies entered the distribution: ${path}`)+ assert(!path.startsWith(".git"), `repository state entered the distribution: ${path}`)+ }++ mkdirSync(installation)+ zip.extractAllTo(installation)++ const installedManifest = JSON.parse(readFileSync(join(installation, "package.json"), "utf8"))++ assert.deepEqual(installedManifest.scripts, { start: "node server/main.js" })+ assert.deepEqual(installedManifest.engines, { node: ">=24.15.0" })+ assert.deepEqual(+ installedManifest.dependencies,+ Object.fromEntries(["cfonts", "sharp"].map(name => [name, manifest.dependencies[name]]))+ )++ execFileSync(+ npm.command,+ [...npm.prefix, "install", "--omit=dev", "--no-audit", "--no-fund", "--no-package-lock"],+ { cwd: installation, stdio: "inherit" }+ )++ execFileSync(process.execPath, ["--check", "server/main.js"], { cwd: installation })++ await boot(installation)+ } finally {+ if (runtime && runtime.exitCode === null) {+ runtime.kill()+ await new Promise(resolve => runtime.once("exit", resolve))+ }++ rmSync(archive, { force: true })+ rmSync(checksum, { force: true })+ rmSync(temporary, { recursive: true, force: true })+ }++ async function availablePort() {+ const server = createServer()++ await new Promise((resolve, reject) => {+ server.once("error", reject)+ server.listen(0, "127.0.0.1", resolve)+ })++ const address = server.address()++ assert(address && typeof address === "object")++ await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()))++ return address.port+ }++ async function boot(directory) {+ const port = await availablePort()+ const output = []++ runtime = spawn(process.execPath, ["server/main.js"], {+ cwd: directory,+ env: { ...process.env, PHRESHOS_HOME: join(temporary, "home"), [portVariable]: String(port) },+ stdio: ["ignore", "pipe", "pipe"]+ })++ runtime.stdout.on("data", data => output.push(data.toString()))+ runtime.stderr.on("data", data => output.push(data.toString()))++ await waitForDesktop(port, runtime, output)+ }++ async function waitForDesktop(port, child, output) {+ const deadline = Date.now() + 20_000+ const url = `http://localhost:${port}/`++ while (Date.now() < deadline) {+ if (child.exitCode !== null) throw new Error(`the installed system exited before serving the desktop\n${output.join("")}`)++ try {+ const response = await fetch(url)+ const body = await response.text()++ assert.equal(response.status, 200)+ assert.match(body, /<html/i)++ return+ } catch {+ await new Promise(resolve => setTimeout(resolve, 100))+ }+ }++ throw new Error(`the installed system did not serve the desktop\n${output.join("")}`)+ }+}, 120_000)diff --git a/tests/endpoint-services.test.ts b/tests/endpoint-services.test.tsnew file mode 100644index 0000000..c64cb12--- /dev/null+++ b/tests/endpoint-services.test.ts@@ -0,0 +1,128 @@+import assert from "node:assert/strict"+import EndpointServices from "@server/core/link-manager/auth-manager/process-manager/endpoint-services"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import type Process from "@server/core/link-manager/auth-manager/process-manager/process"+import type { ServiceKey } from "@phreshos/core"+import { test } from "vitest"++test("endpoint services contract", async () => {+ const privateProgram = new Program({+ identity: "private-program",+ server: { location: ".", startCommand: "true" }+ })+ const documentedProgram = new Program({+ identity: "documented-program",+ agent: "agent.md",+ server: { location: ".", startCommand: "true" },+ client: { location: "." }+ })++ assert.equal(privateProgram.record().hasAgent, false)+ assert.equal(documentedProgram.record().hasAgent, true)+ assert.throws(() => new Program({+ identity: "invalid-program",+ agent: "",+ server: { location: ".", startCommand: "true" }+ }), /agent documentation/)++ const program = new Program({+ identity: "program",+ server: { location: ".", startCommand: "true" },+ client: { location: "." }+ })+ const waits: string[] = []++ function process(identity: string, name: string | null, ready = true, service = true) {+ const waiters = new Set<() => void>()+ const server = { ready, service }+ return {+ identity,+ name,+ reference: `${identity}-reference`,+ program,+ launch: {+ server: { service },+ client: { service }+ },+ server,+ client: { service },+ waitReady(endpoint: "server" | "client", notify: () => void) {++ waits.push(endpoint)+ if (endpoint === "client" || server.ready) notify()+ else waiters.add(notify)+ return () => { waiters.delete(notify) }+ },+ becomeReady() {+ server.ready = true+ for (const notify of waiters) notify()+ waiters.clear()+ }+ } as unknown as Process & { becomeReady(): void }+ }++ let provider = process("0b231437-513b-4907-8041-c497279c07fa", "main")++ const services = new EndpointServices(key => {+ if (key.program !== undefined && key.program !== program.identity) return null+ if (key.program === undefined && key.process !== provider.identity) return null+ if (key.process !== provider.identity && key.process !== provider.name) return null+ if ((key.endpoint === "server" ? provider.server?.service : provider.client?.service) !== true) return null+ return { process: provider, endpoint: key.endpoint }+ })++ const key = { program: "program", process: "main", endpoint: "server" } satisfies ServiceKey+ const clientKey = { ...key, endpoint: "client" } satisfies ServiceKey+ const exact = { ...key, process: provider.identity }+ const global = { process: provider.identity, endpoint: "server" } satisfies ServiceKey+ const lifecycle: string[] = []+ const publications: unknown[] = []++ await assert.rejects(() => services.waitReady(key, -1), /non-negative finite number/)++ services.follow(key, "lifecycle", null, event => lifecycle.push(event))+ services.follow(key, "events", "change", (_event, payload) => publications.push(payload))++ await services.started(provider, "server")+ assert.equal(services.exists(key), true)+ assert.equal(services.exists(global), true)+ assert.deepEqual(lifecycle, ["start"])+ await services.waitReady(key, 0)+ await services.waitReady(clientKey, 0)+ assert.deepEqual(waits, ["server", "client"])++ await services.emit(provider, "server", "ignored", 1)+ await services.emit(provider, "server", "change", 2)+ assert.deepEqual(publications, [2])++ provider.server = null+ await services.stopped(provider, "server", true)+ assert.equal(services.exists(key), false)+ assert.deepEqual(lifecycle, ["start", "stop"])+ await assert.rejects(() => services.waitReady(key, 0), /timeout/)++ // A name address follows a replacement, while an identity address does not.+ provider = process("234448b9-4661-4bda-8028-ae75438bf5be", "main", false)+ await services.started(provider, "server")+ assert.equal(services.exists(key), true)+ assert.equal(services.exists(exact), false)+ assert.equal(services.exists(global), false)++ const ready = services.waitReady(key, 100)+ provider.becomeReady()+ await ready++ // Server and Client remain distinct coordinates for the same Process.+ assert.equal(services.exists(clientKey), true)++ const unconfiguredProgram = new Program({+ identity: "unconfigured",+ server: { location: ".", startCommand: "true" }+ })+ assert.equal(unconfiguredProgram.server?.service, false)++ // One incarnation can override the Program default without changing the Program.+ provider = process("2c6f42b0-7847-4f80-8373-0cba3f48636b", "main", true, false)+ await services.started(provider, "server")+ assert.equal(services.exists(key), false)+}, 120_000)diff --git a/tests/gateway-address.test.ts b/tests/gateway-address.test.tsnew file mode 100644index 0000000..3a2519a--- /dev/null+++ b/tests/gateway-address.test.ts@@ -0,0 +1,15 @@+import assert from "node:assert/strict"+import { join } from "node:path"+import gatewayAddress from "@server/view/gateway/address"+import { test } from "vitest"++test("gateway address contract", async () => {+ const first = gatewayAddress("C:\\Users\\Person\\.phreshos", "win32")++ assert.match(first, /^\\\\\.\\pipe\\phreshos-[a-f0-9]{32}-gateway$/)+ assert.equal(first, gatewayAddress("c:/users/person/.phreshos/", "win32"))+ assert.notEqual(first, gatewayAddress("C:\\Users\\Other\\.phreshos", "win32"))+ assert.equal(gatewayAddress("/home/person/.phreshos", "linux"), join("/home/person/.phreshos", "gateway.sock"))++ console.log("gateway address verified")+}, 120_000)diff --git a/tests/gateway.test.ts b/tests/gateway.test.tsnew file mode 100644index 0000000..f384f50--- /dev/null+++ b/tests/gateway.test.ts@@ -0,0 +1,65 @@+import assert from "node:assert/strict"+import { mkdtemp, rm } from "node:fs/promises"+import { resolve } from "node:path"+import { SocketClient } from "@the-link/ipc/socket-client"+import messagepack from "@the-link/messagepack"+import gatewayAddress from "@server/view/gateway/address"+import gateway from "@server/view/gateway/gateway"+import type LinkManager from "@server/core/link-manager/link-manager"+import { test } from "vitest"++test("gateway contract", async () => {+ const directory = await mkdtemp(resolve(".verify-gateway-"))+ const path = gatewayAddress(directory)+ const received: unknown[][] = []+ let removed = false+ const session = {+ authorization: "owner",+ linkManager: { appearance: { key: "appearance", value: {} } },+ authManager: {+ programManager: { programs: [] },+ processManager: { processes: [] }+ }+ }+ const linkManager = {+ addConnection() {+ return {+ async publish(event: string, ...values: unknown[]) {+ received.push([event, ...values])+ return [{ event, values }]+ }+ }+ },+ async addSession(_connection: unknown, owner: boolean) {+ assert.equal(owner, true)+ return session+ },+ async removeConnection() { removed = true }+ }+ const listener = await gateway(linkManager as unknown as LinkManager, path)+ const client = new SocketClient(path)++ client.setSerialize(messagepack.serialize)+ client.setDeserialize(messagepack.deserialize)++ const ready = client.$inbound.waitFirst("/gateway/ready")++ try {+ await client.connect()++ assert.deepEqual(await ready, session)+ assert.deepEqual(+ await client.$outbound.publishFirst("/auth/example", "authorization", { binary: new Uint8Array([1, 2, 3]) }),+ { event: "/auth/example", values: ["authorization", { binary: new Uint8Array([1, 2, 3]) }] }+ )+ assert.deepEqual(received, [["/auth/example", "authorization", { binary: new Uint8Array([1, 2, 3]) }]])+ } finally {+ await client.disconnect()+ await listener.close()+ await rm(directory, { recursive: true, force: true })+ }++ assert.equal(removed, true)++ console.log("gateway boundary verified")+}, 120_000)diff --git a/tests/host-traffic.test.ts b/tests/host-traffic.test.tsnew file mode 100644index 0000000..f522471--- /dev/null+++ b/tests/host-traffic.test.ts@@ -0,0 +1,33 @@+import assert from "node:assert/strict"+import HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"+import { test } from "vitest"++test("host traffic contract", async () => {+ const traffic = new HostTraffic()+ const hostProgram: unknown[][] = []+ const ownProgram: unknown[][] = []+ const hostProcess: unknown[][] = []+ const programProcess: unknown[][] = []++ traffic.observe("program", "uninstall", null, (_delivery, event, ...values) => hostProgram.push([event, ...values]))+ traffic.observe("program", "uninstall", "program-reference", (_delivery, event, ...values) => ownProgram.push([event, ...values]))+ traffic.observe("process", "create", null, (_delivery, event, ...values) => hostProcess.push([event, ...values]))+ traffic.observe("process", "create", "program-reference", (_delivery, event, ...values) => programProcess.push([event, ...values]))++ const program = { identity: "counter", reference: "program-reference" }+ const process = { identity: "worker", reference: "process-reference" }++ await traffic.emitHost("program", "uninstall", program.identity, program, true)++ assert.deepEqual(hostProgram, [["uninstall", program.identity, program, true]])+ assert.deepEqual(ownProgram, [])++ await traffic.emitSubject("program", "uninstall", program.reference, true)++ assert.deepEqual(ownProgram, [["uninstall", program.reference, true]])++ await traffic.emit("process", "create", program.identity, program.reference, process)++ assert.deepEqual(hostProcess, [["create", program.identity, process]])+ assert.deepEqual(programProcess, [["create", program.reference, process]])+}, 120_000)diff --git a/tests/panel.test.tsx b/tests/panel.test.tsxnew file mode 100644index 0000000..7f45647--- /dev/null+++ b/tests/panel.test.tsx@@ -0,0 +1,70 @@+import assert from "node:assert/strict"+import type { ReactNode } from "react"+import { renderToStaticMarkup } from "react-dom/server"+import { defaultAppearance } from "@phreshos/core"+import { AppearanceProvider } from "@phreshos/react-ui"+import CredentialsForm from "@client/view/structure/authentication/credentials-form"+import TaskbarSurface, { taskbarSurfaceClassName } from "@client/view/structure/desktop/taskbar/taskbar-surface"+import Launcher from "@client/view/structure/desktop/taskbar/launcher/launcher"+import Window from "@client/view/structure/desktop/windows/window"+import StartMenuPanel from "@client/view/structure/desktop/taskbar/launcher/start-menu-panel"+import { test } from "vitest"++test("panel contract", async () => {+ function markup(children: ReactNode) {+ return renderToStaticMarkup(<AppearanceProvider appearance={defaultAppearance} theme="light">{children}</AppearanceProvider>)+ }++ function panel(html: string) {+ assert.equal(html.match(/data-material=""/g)?.length, 2)+ assert.match(html, /grid-template-rows:auto minmax\(0, 1fr\)/)+ assert.match(html, /margin:6px;margin-top:0/)+ }++ const taskbar = markup(<TaskbarSurface label="Title" labelId="title"><button>Action</button></TaskbarSurface>)+ panel(taskbar)+ assert.match(taskbar, /<h2 id="title"/)+ assert.match(taskbar, /<button>Action<\/button>/)++ const window = markup(<Window icon="/icon.svg" title="Window"><iframe title="Content" /></Window>)+ assert.equal(window.match(/data-material=""/g)?.length, 1)+ assert.match(window, /grid-template-rows:auto minmax\(0, 1fr\)/)+ assert.match(window, /data-window-content="true"/)+ assert.doesNotMatch(window, /border-top:1px solid yellow/)+ assert.doesNotMatch(window, /margin:6px;margin-top:0/)+ assert.match(window, /data-window-container/)+ assert.match(window, /<iframe title="Content"/)+ assert.doesNotMatch(window, /class="p-px"/)++ const bare = markup(<Window bare icon="/icon.svg" title="Bare"><iframe title="Content" /></Window>)+ assert.doesNotMatch(bare, /data-material/)+ assert.doesNotMatch(bare, /grid-template-rows:auto minmax\(0, 1fr\)/)++ const authentication = markup(<CredentialsForm title="Sign in" description="Welcome" submitLabel="Continue" passwordAutocomplete="current-password" pending={false} onSubmit={() => {}} />)+ panel(authentication)+ assert.equal(authentication.match(/<form\b/g)?.length, 1)+ assert.match(authentication, /name="username"/)+ assert.match(authentication, /name="password"/)+ assert.match(authentication, /type="submit"/)++ const launcher = markup(<Launcher label="Example System" trigger="Open">{(_close, labelId) => <StartMenuPanel labelId={labelId} name="Example System" version="1.2.3" left={<button>Programs</button>} right={<p>Processes</p>} footer={<input type="search" aria-label="Search Programs and Processes" />} />}</Launcher>)+ assert.equal(launcher.match(/data-material=""/g)?.length, 4)+ assert.match(launcher, /grid-cols-2/)+ assert.match(launcher, /grid-template-rows:auto minmax\(0, 1fr\);min-height:0/)+ assert.match(launcher, /grid-template-rows:minmax\(0, 1fr\) auto;gap:8px;padding:8px;padding-top:0/)+ assert.match(launcher, /grid-cols-2" style="gap:inherit"/)+ assert.match(launcher, /<button>Programs<\/button>/)+ assert.match(launcher, /<p>Processes<\/p>/)+ assert.match(launcher, /<h2[^>]*>Example System<\/h2>/)+ assert.match(launcher, /System version 1.2.3/)+ assert.match(launcher, /type="search"/)+ assert.doesNotMatch(launcher, /<(?:main|section|article|aside|nav|header|footer)\b/)+ assert.match(launcher, /size-4 rounded-sm object-contain/)+ // Native popover visibility belongs to the outer host, not Panel's grid.+ const popover = launcher.match(/<div[^>]*popover="auto"[^>]*>/)?.[0]+ assert(popover)+ assert.match(popover, /overflow-visible/)+ assert.doesNotMatch(popover, /\bgrid\b/)+ // Popovers and native dialogs share a non-clipping host for independently owned outer effects.+ assert(taskbarSurfaceClassName.split(" ").includes("overflow-visible"))+}, 120_000)diff --git a/tests/permission-requests.test.ts b/tests/permission-requests.test.tsnew file mode 100644index 0000000..5890c18--- /dev/null+++ b/tests/permission-requests.test.ts@@ -0,0 +1,101 @@+import assert from "node:assert/strict"+import { mkdtempSync, rmSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"+import type { PermissionName, PermissionRequest } from "@phreshos/core"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"+import Process from "@server/core/link-manager/auth-manager/process-manager/process"+import Window from "@server/core/link-manager/auth-manager/process-manager/window"+import type HostTraffic from "@server/core/link-manager/auth-manager/process-manager/host-traffic"+import { readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"+import { test } from "vitest"++test("permission requests contract", async () => {+ const temporary = mkdtempSync(join(tmpdir(), "phresh-permission-requests-"))++ try {+ const program = new Program({ identity: "example", storage: temporary, client: { location: "." } })+ let dialogs = 0+ let choice: boolean | null = null+ let whilePending: (() => void) | undefined+ let accessUpdates = 0++ const process = new Process("process", null, program, {}, { server: null, client: null, options: {} }, null, {} as HostTraffic, false)+ process.startClient(new Window({ title: "Client", layer: "window" }, { x: 0, y: 0 }, { width: 640, height: 480 }, 1, false), false)++ const authManager = {+ dialogManager: {+ async requestPermission() {+ dialogs+++ whilePending?.()+ return choice+ }+ }+ }+ const programManager = Object.assign(Object.create(ProgramManager.prototype), { authManager }) as ProgramManager+ const processManager = Object.assign(Object.create(ProcessManager.prototype), {+ authManager,+ processes: new Map([["process", process]]),+ $outbound: { async publish(event: string) {+ assert.equal(event, "/client-access")+ accessUpdates+++ } }+ }) as ProcessManager+ Object.assign(authManager, { programManager, processManager })++ const request = <Name extends PermissionName>(name: Name, value: PermissionRequest<Name> = true) => (+ processManager.requestPermission("process", "request", name, value)+ )+ // Stored authority never bypasses approval, even for a narrower request.+ writePermissions(program, { services: ["browser", "editor"] })+ assert.equal(await request("services", ["browser"]), null)+ assert.equal(dialogs, 1)+ assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })++ choice = false+ assert.equal(await request("services", ["browser"]), false)+ assert.equal(dialogs, 2)+ assert.deepEqual(readPermissions(program), { services: ["browser", "editor"] })++ // Approval replaces the exact permission instead of widening or merging it.+ choice = true+ assert.deepEqual(await request("services", ["browser"]), ["browser"])+ assert.equal(dialogs, 3)+ assert.deepEqual(readPermissions(program), { services: ["browser"] })++ // A concurrent edit cannot turn one approved request into a broader grant.+ whilePending = () => writePermissions(program, { services: ["editor"] })+ assert.deepEqual(await request("services", ["browser"]), ["browser"])+ assert.deepEqual(readPermissions(program), { services: ["browser"] })+ whilePending = undefined++ // An exact assignment restricts a broader fallback grant. Otherwise an+ // approved narrowing request would change the file without changing authority.+ writePermissions(program, { all: [] })+ assert.deepEqual(await request("network", ["https://api.example.com"]), ["https://api.example.com"])+ assert(programManager.grantsPermission(program, "network", ["https://api.example.com/v1"]))+ assert(!programManager.grantsPermission(program, "network", ["https://other.example.com"]))++ // Program declarations are installation input, never a second live source.+ const declared = new Program({ identity: "declared", storage: temporary, client: { location: ".", permissions: { programs: ["browser"] } } })+ writePermissions(declared, { services: ["editor"] })+ assert(!programManager.grantsPermission(declared, "services", ["browser"]))+ assert(programManager.grantsPermission(declared, "services", ["editor"]))++ // The iframe policy is synchronized independently of permission request results.+ writePermissions(program, {})+ assert.deepEqual(await request("all"), [])+ assert.equal(process.hosted().client?.sameOrigin, true)+ assert.equal(accessUpdates, 1)+ await programManager.setPermission(program, "all", [])+ assert.equal(accessUpdates, 1)+ await programManager.deletePermission(program, "all")+ assert.equal(process.hosted().client?.sameOrigin, false)+ assert.equal(accessUpdates, 2)+ }+ finally {+ rmSync(temporary, { recursive: true, force: true })+ }+}, 120_000)diff --git a/tests/permissions.test.ts b/tests/permissions.test.tsnew file mode 100644index 0000000..d0ed771--- /dev/null+++ b/tests/permissions.test.ts@@ -0,0 +1,164 @@+import assert from "node:assert/strict"+import { parsePermissionName } from "@phreshos/core"+import { PermissionCatalog, permissionCatalog } from "@server/core/permissions"+import { test } from "vitest"++test("permissions contract", async () => {+ const catalog = new PermissionCatalog({+ all: {+ default: [],+ title: "All permissions",+ description: "Grant every available Client permission."+ },+ services: {+ default: [],+ title: "Services",+ description: "Access Services belonging to every Program or selected Programs."+ },+ programs: {+ default: [],+ title: "Programs",+ description: "Access every Program or selected Programs and their Services."+ },+ network: {+ default: [],+ title: "Network",+ description: "Use System networking with every request target or selected target scopes."+ },+ storage: {+ default: [],+ title: "Storage",+ description: "Use every native filesystem path or selected operation-and-path scopes."+ },+ uploads: {+ default: [],+ title: "Uploads",+ description: "Create values in the System uploads collection."+ },+ appearance: {+ default: [],+ title: "Appearance",+ description: "Change the System Appearance."+ },+ desktopPreferences: {+ default: [],+ title: "Desktop preferences",+ description: "Change this Desktop's preferences."+ }+ })++ assert.deepEqual(catalog.definition("all"), {+ valueDomain: "none",+ default: [],+ title: "All permissions",+ description: "Grant every available Client permission."+ })+ assert.deepEqual(catalog.definition("programs"), {+ valueDomain: "program",+ default: [],+ title: "Programs",+ description: "Access every Program or selected Programs and their Services."+ })+ assert.deepEqual(catalog.definition("network"), {+ valueDomain: "network",+ default: [],+ title: "Network",+ description: "Use System networking with every request target or selected target scopes."+ })+ assert.deepEqual(catalog.definition("storage"), {+ valueDomain: "storage",+ default: [],+ title: "Storage",+ description: "Use every native filesystem path or selected operation-and-path scopes."+ })+ assert.deepEqual(catalog.definition("uploads"), {+ valueDomain: "none",+ default: [],+ title: "Uploads",+ description: "Create values in the System uploads collection."+ })+ assert.deepEqual(catalog.resolve("all", true), [])+ assert.deepEqual(catalog.resolve("all", []), [])+ assert.deepEqual(catalog.resolve("services", true), [])+ assert.deepEqual(catalog.resolve("services", ["flambo", "terminal", "flambo"]), ["flambo", "terminal"])+ assert.deepEqual(catalog.resolve("network", ["HTTPS://API.Example.com:443/v1/**"]), ["https://api.example.com/v1/**"])+ assert.deepEqual(catalog.resolve("storage", ["delete,read:Documents/**"]), ["read,delete:Documents/**"])+ assert.deepEqual(catalog.resolve("uploads", true), [])+ assert.equal(catalog.resolve("all", false), false)+ assert.equal(catalog.resolve("all", null), null)++ assert.deepEqual(catalog.declarations({ all: true, services: ["flambo"] }), { all: [], services: ["flambo"] })+ assert(Object.isFrozen(catalog.declarations({})))+ assert(Object.isFrozen(catalog.declarations({ all: true }).all))++ assert(catalog.grants("all", [], []))+ assert(!catalog.grants("all", false, []))+ assert(!catalog.grants("all", null, []))+ assert(catalog.grants("services", [], []))+ assert(catalog.grants("services", [], ["flambo"]))+ assert(catalog.grants("services", ["flambo"], ["flambo"]))+ assert(!catalog.grants("services", ["flambo"], ["terminal"]))+ assert(!catalog.grants("services", ["flambo"], []))+ assert(catalog.grants("network", ["https://api.example.com"], ["https://api.example.com/v1/users"]))+ assert(catalog.grants("network", ["https://*.example.com/v1/**"], ["https://eu.example.com/v1/users"]))+ assert(!catalog.grants("network", ["https://*.example.com/v1/**"], ["https://example.com/v1/users"]))+ assert(!catalog.grants("network", ["https://api.example.com/v1/**"], ["https://api.example.com/v2/users"]))+ assert(catalog.grants("storage", ["Documents/**"], ["read:Documents/report.txt"]))+ assert(catalog.grants("storage", ["read,delete:Documents/**"], ["delete:Documents/old.txt"]))+ assert(!catalog.grants("storage", ["read:Documents/**"], ["write:Documents/report.txt"]))+ assert(!catalog.grants("storage", ["Documents/report.txt"], ["read:Documents/**"]))+ assert(catalog.allows("all", [], { all: [] }))+ assert(!catalog.allows("all", [], {}))+ assert(catalog.allows("services", ["browser"], { all: [] }))+ assert(catalog.allows("services", ["browser"], { services: ["browser"] }))+ assert(catalog.allows("services", ["browser"], { programs: [] }))+ assert(catalog.allows("services", [], { programs: [] }))+ assert(catalog.allows("services", ["browser"], { programs: ["browser"] }))+ assert(!catalog.allows("services", ["browser", "editor"], { programs: ["browser"], services: ["editor"] }))+ assert(catalog.allows("services", ["editor"], { programs: ["browser"], services: ["editor"] }))+ assert(!catalog.allows("services", ["editor"], { programs: ["browser"] }))+ assert(!catalog.allows("services", [], { programs: ["browser"] }))+ assert(!catalog.allows("programs", ["browser"], { services: [] }))+ assert(!catalog.allows("services", ["browser"], { programs: [], services: false }))+ assert(!catalog.allows("network", ["https://elsewhere.example"], { all: [], network: ["https://api.example.com"] }))+ assert(catalog.allows("network", ["https://api.example.com/v1"], { all: [], network: ["https://api.example.com"] }))+ assert(catalog.allowsStorage([], null, "Documents/report.txt", "read"))+ assert(catalog.allowsStorage([], ["read:Documents/**"], "Documents/report.txt", "read"))+ assert(!catalog.allowsStorage([], ["read:Documents/**"], "Pictures/photo.png", "read"))+ assert(!catalog.allowsStorage([], false, "Documents/report.txt", "read"))+ assert(!catalog.changed([], []))+ assert(!catalog.changed(["flambo", "terminal"], ["terminal", "flambo"]))+ assert(catalog.changed(["flambo"], []))++ assert.throws(() => parsePermissionName("files"), /does not know/)+ assert.throws(() => catalog.resolve("all", ["unknown"]), /unknown value/)+ assert.throws(() => catalog.resolve("appearance", ["flambo"]), /unknown value/)+ assert.throws(() => catalog.resolve("services", ["Not a Program"]), /unknown value/)+ assert.throws(() => catalog.resolve("network", ["api.example.com"]), /unknown value/)+ assert.throws(() => catalog.resolve("storage", ["all:Documents"]), /unknown value/)+ assert.throws(() => catalog.resolve("storage", ["all,read:Documents"]), /unknown value/)+ assert.throws(() => catalog.declarations({ all: ["unknown"] }), /unknown value/)+ assert.throws(() => catalog.stored({ all: true }), /unresolved shorthand/)+ assert.throws(() => new PermissionCatalog({} as never), /needs a definition/)+ assert.throws(() => new PermissionCatalog({+ all: {+ default: ["unknown"],+ title: "All permissions",+ description: "Invalid default."+ },+ services: catalog.definition("services"),+ programs: catalog.definition("programs"),+ network: catalog.definition("network"),+ storage: catalog.definition("storage"),+ uploads: catalog.definition("uploads"),+ appearance: catalog.definition("appearance"),+ desktopPreferences: catalog.definition("desktopPreferences")+ } as never), /invalid default/)++ assert.deepEqual(permissionCatalog.resolve("all", true), [])+ assert.deepEqual(permissionCatalog.declarations({ all: true }), { all: [] })+ assert.deepEqual(permissionCatalog.declarations({ programs: true }), { programs: [] })+ assert(permissionCatalog.granted([]))+ assert(!permissionCatalog.granted(null))+ assert.throws(() => permissionCatalog.definition("files" as never), /does not know/)+}, 120_000)diff --git a/tests/ports.test.ts b/tests/ports.test.tsnew file mode 100644index 0000000..b8c0a6c--- /dev/null+++ b/tests/ports.test.ts@@ -0,0 +1,63 @@+import { strict as assert } from "node:assert"+import { createServer } from "node:http"+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"+import { homedir, tmpdir } from "node:os"+import { join, resolve } from "node:path"+import { defaultHome, defaultPorts, environmentPorts, listenOnPorts, parsePorts, portRange, requestedPorts } from "@server/view/configuration"+import { test } from "vitest"++test("ports contract", async () => {+ assert.equal(environmentPorts("phreshos", {}), undefined)+ assert.deepEqual(environmentPorts("phreshos", { PHRESHOS_PORT: "4305" }), [4305])+ assert.deepEqual(+ environmentPorts("phreshos", { PHRESHOS_PORT: "4196,4234,5000-5002,4234" }),+ [4196, 4234, 5000, 5001, 5002]+ )+ assert.deepEqual(portRange(4300, 4399), Array.from({ length: 100 }, (_, index) => 4300 + index))+ assert.deepEqual(defaultPorts(false), portRange(4300, 4399))+ assert.deepEqual(defaultPorts(true), portRange(5300, 5399))+ assert.equal(defaultHome(false), resolve(homedir(), ".phreshos"))+ assert.equal(defaultHome(true), resolve("storage"))++ for (const value of ["", "0", "65536", "43.12", "port", "4300-", "4301-4300", "4300,,4301"]) {++ assert.throws(() => parsePorts(value, "PHRESHOS_PORT"), /PHRESHOS_PORT must contain ports or inclusive ranges/)+ }++ const occupied = createServer()+ const available = createServer()++ const occupiedPort = await listenOnPorts(occupied, "127.0.0.1")+ const availablePort = await listenOnPorts(available, "127.0.0.1")++ await close(available)++ const selected = createServer()++ assert.equal(await listenOnPorts(selected, "127.0.0.1", [occupiedPort, availablePort]), availablePort)++ await assert.rejects(+ listenOnPorts(createServer(), "127.0.0.1", [occupiedPort, availablePort]),+ /No configured System port is available/+ )++ await Promise.all([close(occupied), close(selected)])++ const temporary = await mkdtemp(join(tmpdir(), "phreshos-port-request-"))+ const request = join(temporary, "next-port")++ try {++ await writeFile(request, "4400,4500-4502\n")++ assert.deepEqual(await requestedPorts(["node", "main.js", "--port-request", request]), [4400, 4500, 4501, 4502])+ await assert.rejects(readFile(request), error => (error as NodeJS.ErrnoException).code === "ENOENT")+ }++ finally { await rm(temporary, { recursive: true, force: true }) }++ function close(server: ReturnType<typeof createServer>) {++ return new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))+ }+}, 120_000)diff --git a/tests/process-find-or-create.test.ts b/tests/process-find-or-create.test.tsnew file mode 100644index 0000000..d4ca909--- /dev/null+++ b/tests/process-find-or-create.test.ts@@ -0,0 +1,119 @@+import assert from "node:assert/strict"+import ProgramManager from "@server/core/link-manager/auth-manager/program-manager/program-manager"+import type { Launch } from "@phreshos/core"+import type Program from "@server/core/link-manager/auth-manager/program-manager/program"+import { test } from "vitest"++test("process find or create contract", async () => {+ interface FixtureProcess {+ identity: string+ name: string | null+ program: Program+ launch: unknown+ }++ interface FixtureManager {+ start(owner: Program, launch: Launch, watching?: unknown, parent?: unknown, transition?: boolean, prepared?: { intent: unknown }): Promise<`${string}-${string}-${string}-${string}-${string}`>+ resolveLaunch(owner: Program, launch: Launch): { intent: { server: { service: boolean } | null, client: { position: unknown, size: unknown, service: boolean } | null } }+ }++ const processes = new Map<string, FixtureProcess>()+ const program = {+ identity: "example",+ reference: "example-reference",+ server: { start: true },+ client: {+ start: true,+ position: undefined,+ size: undefined,+ layer: undefined,+ minimize: undefined+ },+ title: "Example",+ async validate() {}+ } as unknown as Program++ let starts = 0++ const manager = Object.assign(Object.create(ProgramManager.prototype), {+ authManager: { processManager: { processes } },+ creating: new Map(),+ $outbound: { async publish() {} },+ reach: (identity: string) => identity === program.identity ? program : null+ }) as ProgramManager+ const fixture = manager as unknown as FixtureManager++ fixture.start = async (owner, launch, _watching, _parent, _transition, prepared) => {+ await Promise.resolve()++ const existing = [...processes.values()].find(process => process.program === owner && process.name === launch.name)+ if (existing) throw new Error("This program already has a process with that name")++ const identity = `00000000-0000-0000-0000-${String(++starts).padStart(12, "0")}` as `${string}-${string}-${string}-${string}-${string}`+ processes.set(identity, {+ identity,+ name: launch.name ?? null,+ program: owner,+ launch: (prepared ?? fixture.resolveLaunch(owner, launch)).intent+ })+ return identity+ }++ const launch = {+ name: "shared",+ server: true,+ client: false,+ options: { beta: "2", alpha: "1" }+ }++ const [first, second] = await Promise.all([+ manager.findOrCreateProcess(program, launch),+ manager.findOrCreateProcess(program, {+ name: "shared",+ server: true,+ client: false,+ options: { alpha: "1", beta: "2" }+ })+ ])++ assert.equal(first, second)+ assert.equal(starts, 1)++ await assert.rejects(+ manager.findOrCreateProcess(program, {+ name: "shared",+ server: false,+ client: true,+ options: { alpha: "1", beta: "2" }+ }),+ /different launch/+ )++ const omitted = fixture.resolveLaunch(program, { name: "defaults" }).intent+ processes.set("unrelated", { identity: "unrelated", name: null, program, launch: null })+ const explicit = fixture.resolveLaunch(program, {+ name: "defaults",+ server: true,+ client: true+ }).intent++ assert.deepEqual(omitted, explicit)+ assert(omitted.client)+ assert.deepEqual(omitted.server, { service: false })+ assert.equal(omitted.client.service, false)+ assert.equal(omitted.client.position, null)+ assert.equal(omitted.client.size, null)++ const activated = fixture.resolveLaunch(program, {+ server: { service: true },+ client: { service: true }+ }).intent++ assert.equal(activated.server?.service, true)+ assert.equal(activated.client?.service, true)++ const stale = { identity: program.identity, reference: "replaced-program-reference" } as unknown as Program++ await assert.rejects(manager.createProcess(stale), /represented by this handle does not exist/)+ await assert.rejects(manager.findOrCreateProcess(stale, { name: "stale" }), /represented by this handle does not exist/)+}, 120_000)diff --git a/tests/process-lifecycle.test.ts b/tests/process-lifecycle.test.tsnew file mode 100644index 0000000..a844250--- /dev/null+++ b/tests/process-lifecycle.test.ts@@ -0,0 +1,297 @@+import assert from "node:assert/strict"+import { TheLink } from "@the-link/core"+import type AuthManager from "@server/core/link-manager/auth-manager/auth-manager"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"+import type Process from "@server/core/link-manager/auth-manager/process-manager/process"+import type ServerProcessBoundary from "@server/core/link-manager/auth-manager/process-manager/server-process-boundary"+import type { ServerRuntime } from "@server/core/server-runtime"+import { test } from "vitest"++test("process lifecycle contract", async () => {+ const launch = { server: null, client: null, options: {} } as const++ function processManager() {++ const authManager = new TheLink() as unknown as AuthManager+ const manager = new ProcessManager(authManager)++ Object.assign(authManager, {+ programManager: {+ permission() { return null }+ },+ linkManager: {+ application: {+ system: {+ holdProcess(value: unknown, fallback?: Process) {++ if (value === undefined || value === null) return fallback+ if (typeof value !== "object" || value === null) throw new Error("Invalid Process handle")++ const handle = value as { identity?: string, reference?: string }+ const process = handle.identity ? manager.processes.get(handle.identity) : null++ if (!process || process.reference !== handle.reference) throw new Error("The Process represented by this handle does not exist")++ return process+ }+ }+ }+ }+ })++ return manager+ }++ function program(identity: string) {++ return new Program({ identity, server: { location: ".", startCommand: "true" } })+ }++ async function register(manager: ProcessManager, identity: string) {++ return await manager.register(identity, null, program(identity), {}, launch, null, false, null, null)+ }++ // Parentage retains the exact Process entity after it exits. Absence and+ // ended lineage therefore remain distinct states at every System boundary.+ {+ const manager = processManager()+ const parent = await register(manager, "parent")+ const child = await manager.register("child", null, parent.program, {}, launch, null, false, null, parent)+ const boundary = manager as unknown as {+ parent(value: unknown): Promise<{ identity: string } | null>+ endHost(process: Process, server: ServerProcessBoundary, args: unknown[]): Promise<unknown[]>+ }++ await manager.remove(parent.identity)++ assert.equal((await boundary.parent({ identity: child.identity, reference: child.reference }))?.identity, parent.identity)++ const retained = (await boundary.endHost(child, {} as ServerProcessBoundary, ["parent"]))[0] as { identity: string }++ assert.equal(retained.identity, parent.identity)+ }++ // A failed configuration cannot leave either its Process identity or an+ // unattached runtime behind in the registry.+ {+ const manager = processManager()+ let stops = 0+ const runtime = { stop() { stops++ } } as unknown as ServerRuntime++ await assert.rejects(manager.register(+ "failed-registration",+ null,+ program("failed-registration"),+ {},+ launch,+ runtime,+ false,+ null,+ null,+ { prepare() { throw new Error("configuration failed") } }+ ), /configuration failed/)++ assert.equal(manager.processes.has("failed-registration"), false)+ assert.equal(stops, 1)+ }++ // Failure after an endpoint has been activated still retracts the partially+ // announced Process and its client state.+ {+ const manager = processManager()+ const client = new Program({ identity: "partial-registration", client: { location: "https://example.test/" } })++ manager.$outbound.subscribe("/created", () => {++ throw new Error("creation publication failed")+ })++ await assert.rejects(manager.register(+ "partial-registration",+ null,+ client,+ {},+ { ...launch, client: { title: "Partial", position: null, size: null, layer: "window", minimize: false, maximize: false, service: false } },+ null,+ true,+ { title: "Partial", position: { x: 0, y: 0 }, size: { width: 320, height: 240 }, layer: "window", minimize: false, maximize: false },+ null+ ), /creation publication failed/)++ assert.equal(manager.processes.has("partial-registration"), false)+ }++ // A launcher can only receive a started Process after the authoritative+ // representation has received that Process's creation snapshot.+ {+ const manager = processManager()+ const order: string[] = []++ manager.$outbound.subscribe("/created", () => { order.push("published") })++ await manager.register(+ "ordered-registration",+ null,+ program("ordered-registration"),+ {},+ launch,+ null,+ false,+ null,+ null,+ { created() { order.push("reported") } }+ )++ assert.deepEqual(order, ["published", "reported"])+ }++ // A failing observer is not allowed to stop the authoritative teardown or+ // prevent later terminal publications from running.+ {+ const manager = processManager()+ await register(manager, "teardown")+ let exited = false++ manager.$outbound.subscribe("/exited", () => { exited = true })++ const stop = manager.observeHost("process", "exit", null, () => {++ throw new Error("exit observer failed")+ })++ await assert.rejects(manager.remove("teardown"), /exit observer failed/)++ stop()++ assert.equal(manager.processes.has("teardown"), false)+ assert.equal(exited, true)+ }++ interface BoundaryProbe {++ boundary: ServerProcessBoundary++ deliveries: unknown[][]++ cancel(question: string): void+ }++ function boundaryProbe(): BoundaryProbe {++ const deliveries: unknown[][] = []+ const requests = new Map<string, () => void>()++ const boundary = {+ retain(question: string, cancel: () => void) {++ requests.get(question)?.()++ requests.set(question, cancel)+ },+ async deliver(event: string, ...values: unknown[]) {++ if (values[0] === "answer" && typeof values[1] === "string") requests.delete(values[1])++ deliveries.push([event, ...values])+ }+ } as unknown as ServerProcessBoundary++ return {+ boundary,+ deliveries,+ cancel(question) {++ const cancel = requests.get(question)++ requests.delete(question)++ cancel?.()+ }+ }+ }++ type HostWait = {++ endHostWait(process: Process, server: ServerProcessBoundary, question: string, args: unknown[]): Promise<void>+ }++ // Readiness listeners and their cancellation belong to the exact Server+ // incarnation that asked. A replacement must neither inherit the answer nor+ // retain the target listeners.+ {+ const manager = processManager()+ const requester = await register(manager, "requester")+ const target = await register(manager, "target")+ const original = boundaryProbe()+ const replacement = boundaryProbe()+ let readyListeners = 0+ let exitListeners = 0+ let becomeReady: () => void = () => undefined++ target.waitReady = (_endpoint, notify) => {++ let active = true++ readyListeners+++ becomeReady = notify++ return () => {++ if (!active) return++ active = false+ readyListeners--+ }+ }++ target.onExit = () => {++ let active = true++ exitListeners++++ return () => {++ if (!active) return++ active = false+ exitListeners--+ }+ }++ requester.server = original.boundary++ await (manager as unknown as HostWait).endHostWait(+ requester,+ original.boundary,+ "ready",+ ["wait-ready", { identity: target.identity, reference: target.reference }, "server", false]+ )++ requester.server = replacement.boundary+ becomeReady()++ assert.equal(readyListeners, 0)+ assert.equal(exitListeners, 0)+ assert.deepEqual(original.deliveries, [["host-end", "answer", "ready", { success: true, result: [] }]])+ assert.deepEqual(replacement.deliveries, [])++ await (manager as unknown as HostWait).endHostWait(+ requester,+ original.boundary,+ "cancelled",+ ["wait-ready", { identity: target.identity, reference: target.reference }, "server", false]+ )++ assert.equal(readyListeners, 1)+ assert.equal(exitListeners, 1)++ original.cancel("cancelled")++ assert.equal(readyListeners, 0)+ assert.equal(exitListeners, 0)+ assert.equal(original.deliveries.length, 1)+ }+}, 120_000)diff --git a/tests/program-development.test.ts b/tests/program-development.test.tsnew file mode 100644index 0000000..56b33bf--- /dev/null+++ b/tests/program-development.test.ts@@ -0,0 +1,31 @@+import assert from "node:assert/strict"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import { developmentTarget } from "@server/view/http/program/development"+import { test } from "vitest"++test("program development contract", async () => {+ const development = new Program({++ identity: "example",++ client: { location: "http://localhost:5173/start" }+ })++ const target = developmentTarget(++ development,++ `http://localhost:4300/program/${development.assetId}/assets/main.ts?direct`+ )++ assert.equal(target?.href, `http://localhost:5173/program/${development.assetId}/assets/main.ts?direct`)++ const production = new Program({++ identity: "example",++ client: { location: "dist/client" }+ })++ assert.equal(developmentTarget(production, `http://localhost:4300/program/${production.assetId}/assets/`), null)+}, 120_000)diff --git a/tests/program-frame.test.tsx b/tests/program-frame.test.tsxnew file mode 100644index 0000000..d37dd5f--- /dev/null+++ b/tests/program-frame.test.tsx@@ -0,0 +1,34 @@+import assert from "node:assert/strict"+import { renderToStaticMarkup } from "react-dom/server"+import ProgramFrame from "@client/view/components/program-frame"+import type Process from "@client/core/link-manager/auth-manager/process-manager/process"+import type ClientState from "@client/core/link-manager/auth-manager/process-manager/client-state"+import { test } from "vitest"++test("program frame contract", async () => {+ const record = { identity: "process", program: "program" } as Process+ const client = { sameOrigin: false, window: {} } as ClientState+ const common = {+ record,+ assetId: "00000000-0000-4000-8000-000000000000",+ client,+ title: "Program",+ door: "/program",+ access: "available" as const,+ onFrame() {},+ onLoad() {}+ }++ const dark = renderToStaticMarkup(<ProgramFrame {...common} theme="dark" />)+ const light = renderToStaticMarkup(<ProgramFrame {...common} theme="light" />)++ client.sameOrigin = true++ const fullAccess = renderToStaticMarkup(<ProgramFrame {...common} theme="light" />)++ assert.match(dark, /style="color-scheme:dark"/)+ assert.match(light, /style="color-scheme:light"/)+ assert.match(dark, /sandbox="allow-scripts allow-forms"/)+ assert.match(fullAccess, /sandbox="allow-scripts allow-forms allow-same-origin"/)+ assert.match(fullAccess, /src="\/program\/00000000-0000-4000-8000-000000000000\/assets\/"/)+}, 120_000)diff --git a/tests/program-install.test.ts b/tests/program-install.test.tsnew file mode 100644index 0000000..a9115ca--- /dev/null+++ b/tests/program-install.test.ts@@ -0,0 +1,79 @@+import assert from "node:assert/strict"+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { join } from "node:path"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import { copyProgram } from "@server/core/link-manager/auth-manager/program-manager/program-manager"+import { installPermissions, readPermissions, writePermissions } from "@server/core/link-manager/auth-manager/program-manager/permissions"+import type { ProgramCommandChunk } from "@phreshos/core"+import { test } from "vitest"++test("program install contract", async () => {+ const temporary = mkdtempSync(join(tmpdir(), "phresh-program-install-"))+ const source = join(temporary, "source")+ const installed = join(temporary, "installed")++ try {+ mkdirSync(join(source, "server"), { recursive: true })+ mkdirSync(join(source, "client"), { recursive: true })+ writeFileSync(join(source, "client", "index.html"), "<!doctype html>")+ writeFileSync(join(source, "operating-guide.md"), "Program operating knowledge")+ mkdirSync(installed)++ const program = new Program({+ identity: "documented-program",+ agent: join(source, "operating-guide.md"),+ categories: ["Development"],+ keywords: ["example"],+ website: "https://example.test/program",+ server: {+ location: join(source, "server"),+ installCommand: `node -e "process.stdout.write('install-out'); process.stderr.write('install-err')"`,+ uninstallCommand: `node -e "process.stdout.write('uninstall-out'); process.stderr.write('uninstall-err')"`,+ startCommand: "true"+ },+ client: {+ location: join(source, "client"),+ permissions: { network: ["https://api.example.test/**"] }+ }+ })++ await program.validate()+ copyProgram(program, installed)++ const declaration = JSON.parse(readFileSync(join(installed, "program.json"), "utf8"))++ assert.equal(declaration.agent, "agent.md")+ assert.deepEqual(declaration.categories, ["Development"])+ assert.deepEqual(declaration.keywords, ["example"])+ assert.equal(declaration.website, "https://example.test/program")+ assert(program.config.server)+ assert.equal(declaration.server.uninstallCommand, program.config.server.uninstallCommand)+ assert.equal(readFileSync(join(installed, "agent.md"), "utf8"), "Program operating knowledge")++ const installedProgram = new Program(join(installed, "program.json"))+ writePermissions(installedProgram, { network: ["https://old.example.test/**"], appearance: [] })+ const rollbackPermissions = installPermissions(installedProgram)+ assert.deepEqual(readPermissions(installedProgram), { network: ["https://api.example.test"] })+ rollbackPermissions()+ assert.deepEqual(readPermissions(installedProgram), { network: ["https://old.example.test"], appearance: [] })+ installPermissions(installedProgram)+ const installation: ProgramCommandChunk[] = []+ const uninstallation: ProgramCommandChunk[] = []++ await installedProgram.installServer(chunk => { installation.push(chunk) })+ await installedProgram.uninstallServer(chunk => { uninstallation.push(chunk) })++ assert.deepEqual(Object.fromEntries(installation.map(chunk => [chunk.stream, chunk.text])), {+ stdout: "install-out",+ stderr: "install-err"+ })+ assert.deepEqual(Object.fromEntries(uninstallation.map(chunk => [chunk.stream, chunk.text])), {+ stdout: "uninstall-out",+ stderr: "uninstall-err"+ })+ }+ finally {+ rmSync(temporary, { recursive: true, force: true })+ }+}, 120_000)diff --git a/tests/readiness.test.tsx b/tests/readiness.test.tsxnew file mode 100644index 0000000..bb9a2aa--- /dev/null+++ b/tests/readiness.test.tsx@@ -0,0 +1,70 @@+import assert from "node:assert/strict"+import { renderToStaticMarkup } from "react-dom/server"+import Readiness, { ReadinessState } from "@libs/readiness"+import { test } from "vitest"++test("readiness contract", async () => {+ const startup = ReadinessState.start(["connection", "session", "wallpaper"])++ assert.deepEqual(startup.pending, ["connection", "session", "wallpaper"])++ const connected = startup.ready("connection")+ const extended = connected.require("programs")+ const session = extended.ready("session")+ const wallpaper = session.ready("wallpaper")+ const complete = wallpaper.ready("programs")++ assert.deepEqual(connected.pending, ["session", "wallpaper"])+ assert.deepEqual(extended.pending, ["session", "wallpaper", "programs"])+ assert.deepEqual(complete.pending, [])+ assert.equal(complete.ready("programs"), complete)++ const recomposed = complete.require("wallpaper").require("connection").require("session")++ assert.deepEqual(recomposed.pending, ["connection", "session", "wallpaper"])+ assert.deepEqual(recomposed.ready("connection").ready("session").ready("wallpaper").pending, [])+ assert.equal(recomposed.require("connection"), recomposed)++ const late = complete.require("late")++ assert.deepEqual(late.requirements, ["connection", "session", "wallpaper", "programs", "late"])+ assert.deepEqual(late.pending, ["late"])++ assert.throws(() => startup.ready("unknown"), /does not know/)+ assert.throws(() => ReadinessState.start(["connection", "connection"]), /already knows/)+ assert.throws(() => ReadinessState.start([""]), /must have a name/)++ const pendingMarkup = renderToStaticMarkup(+ <Readiness requirements={["connection"]}>+ <Readiness.Pending><span>Loading</span></Readiness.Pending>+ <p>Prepared content</p>+ </Readiness>+ )++ const readyMarkup = renderToStaticMarkup(+ <Readiness requirements={[]}>+ <Readiness.Pending><span>Loading</span></Readiness.Pending>+ <p>Prepared content</p>+ </Readiness>+ )++ assert.match(pendingMarkup, /Loading/)+ assert.match(pendingMarkup, /Prepared content/)+ assert.doesNotMatch(readyMarkup, /Loading/)+ assert.match(readyMarkup, /Prepared content/)++ const observedPendingMarkup = renderToStaticMarkup(+ <Readiness requirements={["connection", "session"]}>+ <Readiness.Pending>{pending => <span>{pending.join(",")}</span>}</Readiness.Pending>+ </Readiness>+ )++ const observedReadyMarkup = renderToStaticMarkup(+ <Readiness requirements={[]}>+ <Readiness.Pending>{pending => <span>{pending.length}</span>}</Readiness.Pending>+ </Readiness>+ )++ assert.match(observedPendingMarkup, /connection,session/)+ assert.match(observedReadyMarkup, />0</)+}, 120_000)diff --git a/tests/shell.test.ts b/tests/shell.test.tsnew file mode 100644index 0000000..a20fe03--- /dev/null+++ b/tests/shell.test.ts@@ -0,0 +1,39 @@+import assert from "node:assert/strict"+import shell from "@server/core/shell"+import { test } from "vitest"++test("shell contract", async () => {+ const executable = `"${process.execPath}"`+ const script = JSON.stringify("process.stdout.write(process.env.PHRESHOS_SHELL_TEST); process.stderr.write('error'); process.exitCode = 7")+ const events = []++ for await (const event of shell(`${executable} -e ${script}`, { env: { PHRESHOS_SHELL_TEST: "output" } })) events.push(event)++ assert.equal(events[0]?.event, "started")+ assert.equal(events.flatMap(event => event.event === "output" && event.stream === "stdout" ? [event.text] : []).join(""), "output", JSON.stringify(events))+ assert.equal(events.flatMap(event => event.event === "output" && event.stream === "stderr" ? [event.text] : []).join(""), "error", JSON.stringify(events))+ assert.deepEqual(events.at(-1), {+ event: "exited",+ exit: { status: "exited", code: 7, signal: null }+ })++ const running = shell(`${executable} -e ${JSON.stringify("setInterval(() => {}, 1_000)")}`)+ const started = await running.next()+ const startedEvent = started.value++ assert.equal(startedEvent?.event, "started")+ await running.return(undefined)++ if (startedEvent?.event === "started") assert.throws(() => process.kill(startedEvent.pid, 0), { code: "ESRCH" })++ const controller = new AbortController()+ const aborted = shell(`${executable} -e ${JSON.stringify("setInterval(() => {}, 1_000)")}`, { signal: controller.signal })+ const abortedStart = (await aborted.next()).value+ const reason = new Error("test cancellation")++ controller.abort(reason)++ await assert.rejects(aborted.next(), error => error === reason)++ if (abortedStart?.event === "started") assert.throws(() => process.kill(abortedStart.pid, 0), { code: "ESRCH" })+}, 120_000)diff --git a/tests/start-menu-search.test.tsx b/tests/start-menu-search.test.tsxnew file mode 100644index 0000000..f7944a1--- /dev/null+++ b/tests/start-menu-search.test.tsx@@ -0,0 +1,50 @@+import assert from "node:assert/strict"+import { renderToStaticMarkup } from "react-dom/server"+import { AppearanceProvider } from "@phreshos/react-ui"+import { defaultAppearance } from "@phreshos/core"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import SearchBar from "@client/view/structure/desktop/taskbar/launcher/search-bar"+import { matchesProcess, matchesProgram, searchTerms } from "@client/view/structure/desktop/taskbar/launcher/search"+import { test } from "vitest"++test("start menu search contract", async () => {+ const program = new Program({+ identity: "test-editor",+ name: "Note Studio",+ description: "Write and organize documents",+ categories: ["Productivity"],+ keywords: ["markdown", "notes"],+ client: { location: "." }+ }).record()++ assert.deepEqual(program.categories, ["Productivity"])+ assert.deepEqual(program.keywords, ["markdown", "notes"])+ const empty = new Program({ identity: "empty", client: { location: "." } }).record()++ assert.deepEqual(empty.categories, [])+ assert.deepEqual(empty.keywords, [])+ assert.deepEqual(searchTerms(" NOTE\tstudio "), ["note", "studio"])++ for (const query of ["", " ", "NOTE", "productivity", "markdown", "documents", "studio productivity markdown"]) {+ assert(matchesProgram(program, searchTerms(query)), query)+ }++ assert(!matchesProgram(program, searchTerms("missing")))+ assert(!matchesProgram(program, searchTerms("studio missing")))+ assert(matchesProcess("daily draft", undefined, searchTerms("DAILY draft")))+ assert(matchesProcess(null, program, searchTerms("markdown productivity")))+ assert(matchesProcess("daily draft", program, searchTerms("documents")))+ assert(matchesProcess(null, undefined, searchTerms("")))+ assert(!matchesProcess(null, undefined, searchTerms("notes")))+ assert(!matchesProcess("daily draft", program, searchTerms("missing")))++ const footer = renderToStaticMarkup(<AppearanceProvider appearance={defaultAppearance} theme="light"><SearchBar query="notes" onChange={() => {}} /></AppearanceProvider>)++ assert.match(footer, /<div class="react-aria-TextField"/)+ assert.match(footer, /<input\b/)+ assert.match(footer, /value="notes"/)+ assert.match(footer, /aria-label="Search Programs and Processes"/)+ assert.equal(footer.match(/data-material=""/g)?.length, 1)+ assert.doesNotMatch(footer, /<(?:main|section|article|aside|nav|header|footer)\b/)+ assert.doesNotMatch(footer, /Signed in as/)+}, 120_000)diff --git a/tests/storage.test.ts b/tests/storage.test.tsnew file mode 100644index 0000000..663f635--- /dev/null+++ b/tests/storage.test.ts@@ -0,0 +1,82 @@+import assert from "node:assert/strict"+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"+import { tmpdir } from "node:os"+import { join, resolve } from "node:path"+import FileArea, { FileSystem } from "@libs/file-area"+import AuthManager from "@server/core/link-manager/auth-manager/auth-manager"+import { test } from "vitest"++test("storage contract", async () => {+ const fixture = mkdtempSync(join(tmpdir(), "phreshos-storage-"))+ const root = join(fixture, "configured")+ const outside = join(fixture, "outside")++ try {+ const storage = new FileArea(root)+ const home = new FileSystem(resolve(fixture, "home"))+ const authManager = Object.assign(Object.create(AuthManager.prototype), {+ linkManager: { application: { home, storage: { path: root } } },+ $outbound: { async publish() {} }+ }) as AuthManager+ const systemStorage = (AuthManager.prototype as unknown as {+ storage(operation: unknown, values: unknown): Promise<unknown>+ }).storage++ assert.equal(await systemStorage.call(authManager, "path", []), home.path)+ assert.equal(await systemStorage.call(authManager, "path", ["..", "outside"]), outside)++ mkdirSync(join(root, "kept"), { recursive: true })+ mkdirSync(join(root, "nested"), { recursive: true })+ writeFileSync(join(root, "kept", "value.txt"), "kept")+ writeFileSync(join(root, "nested", "value.txt"), "removed")++ storage.clear(["nested"])++ assert.deepEqual(readdirSync(join(root, "nested")), [])+ assert.deepEqual(readdirSync(join(root, "kept")), ["value.txt"])++ storage.create(["created"])+ await storage.write(["created", "value.txt"], new Blob(["storage"]).stream(), undefined, false)+ await storage.append(["created", "value.txt"], new Blob([" file"]).stream())+ assert.equal(readFileSync(join(root, "created", "value.txt"), "utf8"), "storage file")+ assert.equal(await new Response(storage.stream(["created", "value.txt"], [8, 4])).text(), "file")+ assert.deepEqual(storage.list([], [true]), [+ { kind: "storage", path: ["created"] },+ { kind: "file", path: ["created", "value.txt"] },+ { kind: "storage", path: ["kept"] },+ { kind: "file", path: ["kept", "value.txt"] },+ { kind: "storage", path: ["nested"] }+ ])+ assert.ok(storage.space().capacity > 0)++ const changes = storage.watch(["created"])+ const changed = changes.next()+ await new Promise(resolve => setTimeout(resolve, 10))+ writeFileSync(join(root, "created", "watched.txt"), "changed")+ assert.match((await changed).value?.event ?? "", /^(change|rename)$/)+ await changes.return(undefined)+ assert.throws(() => storage.resolve(["..", "outside"]), /configured directory/)++ mkdirSync(outside, { recursive: true })+ writeFileSync(join(outside, "value.txt"), "outside")+ symlinkSync(outside, join(root, "escape"), "dir")+ symlinkSync(outside, join(home.path, "escape"), "dir")++ assert.equal(home.resolve(["escape", "value.txt"]), join(home.path, "escape", "value.txt"))+ assert.equal(home.stat(["escape", "value.txt"])?.kind, "file")++ assert.throws(() => storage.stat(["escape", "value.txt"]), /symbolic link/)+ assert.throws(() => storage.list(["escape"]), /symbolic link/)+ assert.throws(() => storage.stream(["escape", "value.txt"]), /symbolic link/)+ assert.throws(() => storage.delete(["escape", "value.txt"]), /symbolic link/)+ assert.throws(() => storage.clear(["escape"]), /symbolic link/)+ await assert.rejects(+ storage.write(["escape", "written.txt"], new Blob(["outside"]).stream()),+ /symbolic link/+ )+ assert.deepEqual(readdirSync(outside), ["value.txt"])+ }+ finally {+ rmSync(fixture, { recursive: true, force: true })+ }+}, 120_000)diff --git a/tests/uploads.test.ts b/tests/uploads.test.tsnew file mode 100644index 0000000..5d53e29--- /dev/null+++ b/tests/uploads.test.ts@@ -0,0 +1,76 @@+import assert from "node:assert/strict"+import { mkdtemp, readFile, rm } from "node:fs/promises"+import { resolve } from "node:path"+import FileManager from "@libs/file-manager"+import UploadManager from "@server/core/upload-manager"+import uploadView from "@server/view/http/uploads"+import type Application from "@server/core/application"+import { Hono } from "hono"+import { test } from "vitest"++test("uploads contract", async () => {+ const directory = await mkdtemp(resolve(".verify-uploads-"))+ const uploads = new UploadManager(new FileManager(directory))++ try {+ const file = await uploads.write("txt", new Blob(["hello uploads"]).stream())+ const upload = uploads.stat(file)++ assert(upload)+ assert.equal(upload.size, 13)+ assert.equal(typeof upload.modifiedAt, "number")+ assert.equal(await readFile(uploads.path(file), "utf8"), "hello uploads")+ assert.equal(uploads.stat("00000000-0000-0000-0000-000000000000.txt"), null)+ assert.throws(() => uploads.stat("../outside.txt"), /not an upload file/)++ const view = new Hono()++ const application = {+ uploads,+ linkManager: {+ authManager: {+ verify(value: unknown) {+ if (value !== "allowed") throw new Error("Unauthorized")+ },+ async upload(authorization: unknown, content: ReadableStream<Uint8Array> | null, extension: string, signal?: AbortSignal) {+ this.verify(authorization)+ const written = await uploads.write(extension, content, signal)+ const upload = uploads.stat(written)+ assert(upload)+ return { file: written, ...upload }+ }+ }+ }+ } as unknown as Application++ view.route("/uploads", uploadView(application))+ const response = await view.request("http://system/uploads", {+ method: "POST",+ headers: {+ authorization: "allowed",+ "content-disposition": "attachment; filename=value.json",+ "content-type": "application/json"+ },+ body: JSON.stringify({ ready: true })+ })+ assert.equal(response.status, 200)+ const created = await response.json()++ assert.equal(created.file.endsWith(".json"), true)+ assert.equal(created.size, 14)+ assert.equal(typeof created.modifiedAt, "number")+ const described = await view.request(`http://system/uploads/${created.file}/stat`)+ const downloaded = await view.request(`http://system/uploads/${created.file}`)++ assert.equal(described.status, 200)+ assert.equal(downloaded.status, 200)+ assert.deepEqual(await described.json(), { size: created.size, modifiedAt: created.modifiedAt })+ assert.deepEqual(JSON.parse(await downloaded.text()), { ready: true })+ assert.equal((await view.request("http://system/uploads/not-a-key")).status, 400)+ assert.equal((await view.request("http://system/uploads/00000000-0000-0000-0000-000000000000.txt")).status, 404)+ } finally {+ await rm(directory, { recursive: true, force: true })+ }++ console.log("uploads verified")+}, 120_000)diff --git a/tests/window-geometry.test.ts b/tests/window-geometry.test.tsnew file mode 100644index 0000000..b71194a--- /dev/null+++ b/tests/window-geometry.test.ts@@ -0,0 +1,91 @@+import assert from "node:assert/strict"+import ClientWindow from "@client/core/link-manager/auth-manager/process-manager/window"+import ProcessManager from "@server/core/link-manager/auth-manager/process-manager/process-manager"+import ServerWindow from "@server/core/link-manager/auth-manager/process-manager/window"+import type ClientProcessManager from "@client/core/link-manager/auth-manager/process-manager/process-manager"+import { test } from "vitest"++test("window geometry contract", async () => {+ const initial = {+ position: { x: 10, y: 20 },+ size: { width: 300, height: 200 }+ }++ const authority = new ServerWindow(+ { title: "Geometry", layer: "window" },+ initial.position,+ initial.size,+ 1,+ false+ )++ assert.throws(() => authority.setGeometry({+ position: { x: 40, y: 50 },+ size: { width: Number.NaN, height: 240 }+ }), /width/)+ assert.deepEqual(authority.position, initial.position)+ assert.deepEqual(authority.size, initial.size)++ const next = {+ position: { x: "1/4", y: 30 },+ size: { width: "1/2", height: 240 }+ }+ const events: unknown[][] = []+ const echoes: unknown[][] = []+ const manager = {+ $outbound: {+ async publish(...echo: unknown[]) {+ echoes.push(echo)+ return []+ }+ },+ mutableWindowOf(identity: string) {+ assert.equal(identity, "process")+ return authority+ },+ said(...event: unknown[]) {+ events.push(event)+ }+ }++ const echo = await ProcessManager.prototype.setGeometry.call(manager as unknown as ProcessManager, "process", next)++ assert.deepEqual(authority.position, next.position)+ assert.deepEqual(authority.size, next.size)+ assert.deepEqual(events, [+ ["process", "geometry", next],+ ["process", "move", next.position],+ ["process", "resize", next.size]+ ])+ assert.deepEqual(echoes, [["/geometry", { identity: "process", window: authority }]])+ assert.equal(echo.identity, "process")+ assert.equal(echo.window, authority)++ const publications: unknown[][] = []+ const counterpart = new ClientWindow(+ { $outbound: { async publish(...publication: unknown[]) { publications.push(publication); return [] } } } as unknown as ClientProcessManager,+ "process",+ authority.toJSON()+ )+ await counterpart.setGeometry(next)+ assert.deepEqual(publications, [["/geometry", "process", next]])++ authority.minimized = true+ await ProcessManager.prototype.maximize.call(manager as unknown as ProcessManager, "process", true)+ assert.equal(authority.maximized, true)+ assert.equal(authority.minimized, true)+ assert.deepEqual(authority.position, next.position)+ assert.deepEqual(authority.size, next.size)+ assert.deepEqual(events.at(-1), ["process", "maximize", true])+ const stored = { position: { x: 44, y: 55 }, size: { width: 440, height: 550 } }+ authority.setGeometry(stored)+ await ProcessManager.prototype.maximize.call(manager as unknown as ProcessManager, "process", false)+ assert.equal(authority.minimized, true)+ assert.equal(authority.maximized, false)+ assert.deepEqual(authority.position, stored.position)+ assert.deepEqual(authority.size, stored.size)+ await counterpart.maximize(true)+ assert.deepEqual(publications.at(-1), ["/maximize", "process", true])+ counterpart.follow(authority.toJSON())+ assert.equal(counterpart.maximized, false)+}, 120_000)diff --git a/tests/worker-runtime.test.ts b/tests/worker-runtime.test.tsnew file mode 100644index 0000000..365d8f3--- /dev/null+++ b/tests/worker-runtime.test.ts@@ -0,0 +1,118 @@+import assert from "node:assert/strict"+import { mkdtemp, rm, writeFile } from "node:fs/promises"+import { createRequire } from "node:module"+import { tmpdir } from "node:os"+import { delimiter, join } from "node:path"+import { pathToFileURL } from "node:url"+import CommandServerRuntime, { commandServerEnvironment } from "@server/view/server-runtime/command"+import WorkerServerRuntime from "@server/view/server-runtime/worker"+import Program from "@server/core/link-manager/auth-manager/program-manager/program"+import type { ProgramConfig } from "@server/core/link-manager/auth-manager/program-manager/config"+import { test } from "vitest"++test("worker runtime contract", async () => {+ const directory = await mkdtemp(join(tmpdir(), "phresh-worker-runtime-"))+ const entry = join(directory, "server.mjs")+ const commandEntry = join(directory, "command.mjs")+ const codec = pathToFileURL(createRequire(import.meta.url).resolve("@the-link/messagepack")).href++ assert.equal(+ commandServerEnvironment(directory, { Path: "/native/bin" }).Path,+ `${join(directory, "node_modules", ".bin")}${delimiter}/native/bin`+ )++ await writeFile(entry, `+ import { parentPort } from "node:worker_threads"+ import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}++ console.log("worker output")+ parentPort.postMessage(encode(["boundary", "ready"]))+ parentPort.on("message", message => {+ const [event, value] = decode(message)+ if (event === "probe") parentPort.postMessage(encode(["probe-result", value]))+ })+ `)++ await writeFile(commandEntry, `+ import { deserialize as decode, serialize as encode } from ${JSON.stringify(codec)}++ console.log("command output")+ process.send?.(encode(["boundary", "ready"]))+ process.on("message", message => {+ const [event, value] = decode(bytes(message))+ if (event === "probe") process.send?.(encode(["probe-result", value]))+ })++ function bytes(value) {+ if (value instanceof Uint8Array) return value+ const record = value+ const result = new Uint8Array(Object.keys(record).length)+ for (let index = 0; index < result.length; index++) result[index] = record[index]+ return result+ }+ `)++ try {+ const program = new Program({ identity: "worker-verification", server: { location: directory, entryFile: "server.mjs" } })++ await program.validate()++ assert.equal(program.serverEntryPath, entry)++ assert.throws(() => new Program({ identity: "worker-conflict", server: { location: directory, startCommand: "node main.js", entryFile: "server.mjs" } } as unknown as ProgramConfig))+ assert.throws(() => new Program({ identity: "worker-escape", server: { location: directory, entryFile: "../server.mjs" } }))++ const runtime = new WorkerServerRuntime(entry)+ const messages: unknown[][] = []+ const output: ["out" | "err", string][] = []++ runtime.onMessage((event, ...values) => messages.push([event, ...values]))+ runtime.onOutput((stream, text) => output.push([stream, text]))++ await until(() => messages.some(message => message[0] === "boundary" && message[1] === "ready"))++ runtime.send("probe", 42)++ await until(() => messages.some(message => message[0] === "probe-result"))+ await until(() => output.some(([stream, text]) => stream === "out" && text.includes("worker output")))++ assert.deepEqual(messages.find(message => message[0] === "probe-result"), ["probe-result", 42])++ runtime.stop()++ const ending = await runtime.finished++ assert.equal(ending.signal, null)++ const command = new CommandServerRuntime(`node ${JSON.stringify(commandEntry)}`, directory)+ const commandMessages: unknown[][] = []+ const commandOutput: ["out" | "err", string][] = []++ command.onMessage((event, ...values) => commandMessages.push([event, ...values]))+ command.onOutput((stream, text) => commandOutput.push([stream, text]))++ await until(() => commandMessages.some(message => message[0] === "boundary" && message[1] === "ready"))++ command.send("probe", 42)++ await until(() => commandMessages.some(message => message[0] === "probe-result"))+ await until(() => commandOutput.some(([stream, text]) => stream === "out" && text.includes("command output")))++ assert.deepEqual(commandMessages.find(message => message[0] === "probe-result"), ["probe-result", 42])++ command.stop()++ await command.finished+ } finally {+ await rm(directory, { recursive: true, force: true })+ }++ async function until(condition: () => boolean, timeout = 2_000) {+ const began = Date.now()++ while (!condition()) {+ if (Date.now() - began >= timeout) throw new Error(`Worker verification timed out after ${timeout}ms`)+ await new Promise(resolve => setTimeout(resolve, 10))+ }+ }+}, 120_000)diff --git a/vitest.config.ts b/vitest.config.tsnew file mode 100644index 0000000..086ca9b--- /dev/null+++ b/vitest.config.ts@@ -0,0 +1,28 @@+import { defineConfig } from "vitest/config"+import decoratorPlugin from "./source/libs/decorator-plugin.js"++export default defineConfig({+ plugins: [decoratorPlugin()],+ resolve: { tsconfigPaths: true },+ test: {+ pool: "forks",+ maxWorkers: 2,+ projects: [+ {+ extends: true,+ test: {+ name: "default",+ include: [+ "tests/**/*.test.{ts,tsx,mjs}"+ ],+ exclude: [+ "tests/**/*.platform.test.*",+ "tests/**/*.live.test.*"+ ],+ environment: "node",+ testTimeout: 30000+ }+ }+ ]+ }+})